@devries-cameron20 / t3code Mirror · read-only / commits / 6e21f81461
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(desktop): wait for the local server to exit when quitting (#22996)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 00:29 UTC 6e21f8146149b2b35c3f301986ed2a2dfc177113
3 files changed +184 -44
apps/desktop/src/backend/DesktopBackendManager.test.ts
+7 -8
@@ -421,7 +421,7 @@ describe("DesktopBackendManager", () => {
421 ),
422 );
423
424 - it.effect("starts the configured backend and closes the scoped process on stop", () =>
424 + it.effect("stops the scoped process with output still pending", () =>
425 Effect.scoped(
426 Effect.gen(function* () {
427 let startCount = 0;
@@ -458,6 +458,7 @@ describe("DesktopBackendManager", () => {
458 yield* Scope.addFinalizer(scope, close);
459
460 return makeProcess({
461 + stdout: Stream.never,
462 exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
463 kill: () => close,
464 });
@@ -721,14 +722,12 @@ describe("DesktopBackendManager", () => {
722 ),
723 );
724
724 - it.effect("the quit stop deadline waits for a backend that only exits at the force kill", () =>
725 + it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () =>
726 Effect.scoped(
727 Effect.gen(function* () {
728 const spawned = yield* Deferred.make<void>();
729 const teardownStarted = yield* Deferred.make<void>();
730 const teardownFinished = yield* Deferred.make<void>();
730 - // The real spawner sends SIGTERM, waits the grace, then SIGKILLs. A backend that
731 - // ignores SIGTERM therefore finishes tearing down just after the grace.
731 const instance = yield* makeTestInstance({
732 spawnerLayer: Layer.succeed(
733 ChildProcessSpawner.ChildProcessSpawner,
@@ -739,7 +738,7 @@ describe("DesktopBackendManager", () => {
738 yield* Scope.addFinalizer(
739 scope,
740 Deferred.succeed(teardownStarted, undefined).pipe(
742 - Effect.andThen(Effect.sleep(Duration.seconds(6))),
741 + Effect.andThen(Effect.sleep(Duration.seconds(10))),
742 Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
743 Effect.asVoid,
744 ),
@@ -764,11 +763,11 @@ describe("DesktopBackendManager", () => {
763 .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
764
765 yield* Deferred.await(teardownStarted);
767 - // Past the SIGTERM grace but before the force kill lands: quit must still be waiting.
768 - yield* TestClock.adjust(Duration.millis(5_500));
766 + // Past the quit deadline, quit must still wait for the backend to exit.
767 + yield* TestClock.adjust(Duration.seconds(9));
768 assert.isFalse(yield* Deferred.isDone(quitDone));
769
771 - yield* TestClock.adjust(Duration.millis(500));
770 + yield* TestClock.adjust(Duration.seconds(1));
771 yield* Fiber.join(quitFiber);
772 assert.isTrue(yield* Deferred.isDone(teardownFinished));
773 }).pipe(Effect.provide(TestClock.layer())),
apps/desktop/src/backend/DesktopBackendManager.ts
+18 -8
@@ -240,6 +240,7 @@ export interface DesktopBackendInstance {
240 readonly id: BackendInstanceId;
241 readonly label: Effect.Effect<string>;
242 readonly start: Effect.Effect<void>;
243 + /** Timeout controls the warning; stop still waits for process teardown and exit. */
244 readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
245 readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
246 readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
@@ -307,7 +308,7 @@ const closeRun = (
308 run: ActiveBackendRun,
309 parentScope: Scope.Scope,
310 options?: { readonly timeout?: Duration.Duration },
310 -): Effect.Effect<boolean> => {
311 +) => {
312 const waitForFiber = Option.match(run.fiber, {
313 onNone: () => Effect.void,
314 onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid),
@@ -319,12 +320,24 @@ const closeRun = (
320 const timeout = options?.timeout;
321
322 if (!timeout) {
322 - return close.pipe(Effect.as(true));
323 + return close;
324 }
325
325 - return Effect.forkIn(close, parentScope).pipe(
326 + return Effect.forkIn(close, parentScope, { startImmediately: true }).pipe(
327 Effect.flatMap((closeFiber) =>
327 - Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)),
328 + Fiber.await(closeFiber).pipe(
329 + Effect.timeoutOption(timeout),
330 + Effect.tap((completed) =>
331 + Option.isNone(completed)
332 + ? logBackendProcessWarning("backend shutdown exceeded timeout; waiting for exit", {
333 + timeoutMs: Duration.toMillis(timeout),
334 + })
335 + : Effect.void,
336 + ),
337 + // Parent-scope interruption still finishes release; do not cancel sibling stops.
338 + Effect.andThen(Fiber.await(closeFiber)),
339 + Effect.asVoid,
340 + ),
341 ),
342 );
343 };
@@ -1099,10 +1112,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1112 onNone: () => Effect.void,
1113 // The enclosing operation owns the span for this inline handler.
1114 onSome: Effect.fnUntraced(function* (run) {
1102 - const closed = yield* closeRun(run, parentScope, options);
1103 - if (!closed) {
1104 - return;
1105 - }
1115 + yield* closeRun(run, parentScope, options);
1116 const cleanup = yield* mutex.withPermits(1)(
1117 SubscriptionRef.modify(
1118 state,
apps/desktop/src/backend/DesktopBackendPool.test.ts
+159 -28
@@ -1,11 +1,17 @@
1 import { assert, describe, it } from "@effect/vitest";
2 +import * as Deferred from "effect/Deferred";
3 +import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 +import * as Fiber from "effect/Fiber";
6 +import * as Queue from "effect/Queue";
7 +import * as TestClock from "effect/testing/TestClock";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Ref from "effect/Ref";
12 +import * as Sink from "effect/Sink";
13 import * as Stream from "effect/Stream";
8 -import { HttpClient } from "effect/http";
14 +import { HttpClient, HttpClientResponse } from "effect/http";
15 import { ChildProcessSpawner } from "effect/process";
16
17 import * as DesktopObservability from "../app/DesktopObservability.ts";
@@ -21,18 +27,105 @@ import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
27 import * as DesktopBackendPool from "./DesktopBackendPool.ts";
28 import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
29
24 -function layerPool(labelRef: Ref.Ref<string>): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
30 +// Models the spawner's release for a backend that ignores SIGTERM, without OS signals.
31 +const makeFakeBackendProcess = Effect.fn("test.makeFakeBackendProcess")(function* () {
32 + const started = yield* Deferred.make<void>();
33 + const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
34 + const signals = yield* Queue.unbounded<"SIGTERM" | "SIGKILL">();
35 + let running = false;
36 + const killWait = Duration.seconds(1);
37 + const exit = Effect.sync(() => {
38 + running = false;
39 + }).pipe(Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0))), Effect.asVoid);
40 + const layer = Layer.succeed(
41 + ChildProcessSpawner.ChildProcessSpawner,
42 + ChildProcessSpawner.make((command) =>
43 + Effect.gen(function* () {
44 + if (command._tag !== "StandardCommand") {
45 + return yield* Effect.die("Expected a standard backend command");
46 + }
47 + const terminateGrace = Duration.fromInputUnsafe(command.options.forceKillAfter ?? 0);
48 + running = true;
49 + yield* Effect.addFinalizer(() =>
50 + Effect.gen(function* () {
51 + yield* Queue.offer(signals, "SIGTERM");
52 + yield* Effect.sleep(terminateGrace);
53 + yield* Queue.offer(signals, "SIGKILL");
54 + yield* Effect.sleep(killWait);
55 + yield* exit;
56 + }),
57 + );
58 + yield* Deferred.succeed(started, undefined);
59 + return ChildProcessSpawner.makeHandle({
60 + pid: ChildProcessSpawner.ProcessId(123),
61 + stdout: Stream.empty,
62 + stderr: Stream.empty,
63 + all: Stream.empty,
64 + stdin: Sink.drain,
65 + getInputFd: () => Sink.drain,
66 + getOutputFd: () => Stream.empty,
67 + exitCode: Deferred.await(exited),
68 + isRunning: Effect.sync(() => running),
69 + kill: () => exit,
70 + unref: Effect.succeed(Effect.void),
71 + });
72 + }),
73 + ),
74 + );
75 + return {
76 + layer,
77 + started: Deferred.await(started),
78 + signals,
79 + isRunning: Effect.sync(() => running),
80 + killWait,
81 + };
82 +});
83 +
84 +const runningConfig = {
85 + executablePath: "/electron",
86 + args: [],
87 + entryPath: "/server/bin.mjs",
88 + cwd: "/server",
89 + env: {},
90 + bootstrap: {
91 + mode: "desktop",
92 + noBrowser: true,
93 + port: 3774,
94 + t3Home: "/tmp/t3",
95 + host: "127.0.0.1",
96 + desktopBootstrapToken: "token",
97 + tailscaleServeEnabled: false,
98 + tailscaleServePort: 443,
99 + },
100 + bootstrapDelivery: "fd3",
101 + extendEnv: true,
102 + httpBaseUrl: new URL("http://127.0.0.1:3774"),
103 + captureOutput: false,
104 + preflightFailure: Option.none(),
105 +} satisfies DesktopBackendStartConfig;
106 +
107 +function layerPool(
108 + labelRef: Ref.Ref<string>,
109 + backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>,
110 +): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
111 return DesktopBackendPool.layer.pipe(
112 Layer.provideMerge(
113 Layer.mergeAll(
28 - FileSystem.layerNoop({}),
29 - Layer.succeed(
30 - ChildProcessSpawner.ChildProcessSpawner,
31 - ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
32 - ),
114 + FileSystem.layerNoop({ exists: () => Effect.succeed(true) }),
115 + backend?.layer ??
116 + Layer.succeed(
117 + ChildProcessSpawner.ChildProcessSpawner,
118 + ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
119 + ),
120 Layer.succeed(
121 HttpClient.HttpClient,
35 - HttpClient.make(() => Effect.die("unexpected HTTP request")),
122 + HttpClient.make((request) =>
123 + backend === undefined
124 + ? Effect.die("unexpected HTTP request")
125 + : Effect.succeed(
126 + HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
127 + ),
128 + ),
129 ),
130 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
131 forInstance: () =>
@@ -90,6 +183,62 @@ function layerPool(labelRef: Ref.Ref<string>): Layer.Layer<DesktopBackendPool.De
183 }
184
185 describe("DesktopBackendPool", () => {
186 + it.effect("unregister during pool quit does not interrupt sibling stops", () =>
187 + Effect.scoped(
188 + Effect.gen(function* () {
189 + const backend = yield* makeFakeBackendProcess();
190 + yield* Effect.gen(function* () {
191 + const pool = yield* DesktopBackendPool.DesktopBackendPool;
192 + const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
193 + const ready = yield* Deferred.make<void>();
194 + const siblingStarted = yield* Deferred.make<void>();
195 + const finishSibling = yield* Deferred.make<void>();
196 + let siblingCompleted = false;
197 + const instance = yield* pool.register({
198 + id,
199 + label: Effect.succeed("WSL (Ubuntu)"),
200 + configResolve: Effect.succeed(runningConfig),
201 + onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
202 + });
203 + yield* instance.start;
204 + yield* backend.started;
205 + yield* Deferred.await(ready);
206 + const quitFiber = yield* Effect.all(
207 + [
208 + instance.stop({ timeout: Duration.seconds(5) }),
209 + Deferred.succeed(siblingStarted, undefined).pipe(
210 + Effect.andThen(Deferred.await(finishSibling)),
211 + Effect.andThen(
212 + Effect.sync(() => {
213 + siblingCompleted = true;
214 + }),
215 + ),
216 + ),
217 + ],
218 + { concurrency: "unbounded" },
219 + ).pipe(Effect.forkChild);
220 + yield* Deferred.await(siblingStarted);
221 + assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
222 + const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
223 + yield* TestClock.adjust(Duration.seconds(5));
224 + assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
225 + assert.isUndefined(quitFiber.pollUnsafe());
226 + assert.isUndefined(unregisterFiber.pollUnsafe());
227 + assert.isTrue(yield* backend.isRunning);
228 + yield* TestClock.adjust(backend.killWait);
229 + yield* Fiber.join(unregisterFiber);
230 + yield* Deferred.succeed(finishSibling, undefined);
231 + yield* Fiber.join(quitFiber);
232 +
233 + assert.isTrue(siblingCompleted);
234 + assert.isFalse(yield* backend.isRunning);
235 + assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
236 + assert.isTrue(Option.isNone(yield* pool.get(id)));
237 + }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), backend)));
238 + }),
239 + ),
240 + );
241 +
242 it.effect("unregister stops the registered instance", () =>
243 Effect.scoped(
244 Effect.gen(function* () {
@@ -99,27 +248,9 @@ describe("DesktopBackendPool", () => {
248 id,
249 label: Effect.succeed("WSL (Ubuntu)"),
250 configResolve: Effect.succeed({
102 - executablePath: "/electron",
103 - args: [],
104 - entryPath: "/server/bin.mjs",
105 - cwd: "/server",
106 - env: {},
107 - bootstrap: {
108 - mode: "desktop",
109 - noBrowser: true,
110 - port: 3774,
111 - t3Home: "/tmp/t3",
112 - host: "127.0.0.1",
113 - desktopBootstrapToken: "token",
114 - tailscaleServeEnabled: false,
115 - tailscaleServePort: 443,
116 - },
117 - bootstrapDelivery: "fd3",
118 - extendEnv: true,
119 - httpBaseUrl: new URL("http://127.0.0.1:3774"),
120 - captureOutput: false,
251 + ...runningConfig,
252 preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
122 - } satisfies DesktopBackendStartConfig),
253 + }),
254 });
255 yield* instance.start;
256 assert.equal((yield* instance.snapshot).restartScheduled, true);