@@ -8,6 +8,7 @@ export const MANAGED_SERVER_NAME = "coder-studio-server";
88const PM2_RESTART_DELAY_MS = 2000 ;
99const PM2_MIN_UPTIME = "5s" ;
1010const PM2_MAX_RESTARTS = 10 ;
11+ const PM2_DELETE_WAIT_MS = 5000 ;
1112const STARTUP_POLL_INTERVAL_MS = 100 ;
1213const STARTUP_FAILURE_GUIDANCE =
1314 "Run `coder-studio logs` for details or `coder-studio serve --foreground` for interactive debugging." ;
@@ -236,6 +237,26 @@ const waitForManagedServerExit = async (): Promise<void> => {
236237 }
237238} ;
238239
240+ const waitForManagedServerDeletion = async ( waitMs : number ) : Promise < void > => {
241+ const deadline = Date . now ( ) + waitMs ;
242+
243+ while ( Date . now ( ) <= deadline ) {
244+ const processes = await withPm2Connection ( describeManagedServer ) ;
245+ if ( processes . length === 0 ) {
246+ return ;
247+ }
248+
249+ const remainingMs = deadline - Date . now ( ) ;
250+ if ( remainingMs <= 0 ) {
251+ break ;
252+ }
253+
254+ await sleep ( Math . min ( STARTUP_POLL_INTERVAL_MS , remainingMs ) ) ;
255+ }
256+
257+ throw new Error ( `Timed out waiting for the managed server to stop after ${ waitMs } ms.` ) ;
258+ } ;
259+
239260const ensureLogDirectory = ( ) : void => {
240261 mkdirSync ( join ( homedir ( ) , ".coder-studio" , "logs" ) , { recursive : true } ) ;
241262} ;
@@ -286,8 +307,8 @@ export const deleteManagedServer = async ({
286307 ignoreMissing = false ,
287308} : {
288309 ignoreMissing ?: boolean ;
289- } = { } ) : Promise < boolean > =>
290- withPm2Connection ( async ( ) => {
310+ } = { } ) : Promise < boolean > => {
311+ const deleted = await withPm2Connection ( async ( ) => {
291312 const processes = await describeManagedServer ( ) ;
292313 if ( processes . length === 0 ) {
293314 return false ;
@@ -305,6 +326,14 @@ export const deleteManagedServer = async ({
305326 }
306327 } ) ;
307328
329+ if ( ! deleted ) {
330+ return false ;
331+ }
332+
333+ await waitForManagedServerDeletion ( PM2_DELETE_WAIT_MS ) ;
334+ return true ;
335+ } ;
336+
308337export const startManagedServer = async ( {
309338 script,
310339 cwd,
@@ -402,6 +431,14 @@ export const getManagedServerStatus = async (): Promise<ManagedServerStatus> =>
402431 } ;
403432 }
404433
434+ if ( pm2Pid === null || pm2Pid === 0 ) {
435+ return {
436+ status : "stopped" ,
437+ pm2Pid : null ,
438+ restartCount,
439+ } ;
440+ }
441+
405442 return {
406443 status : "errored" ,
407444 pm2Pid,
0 commit comments