@devries-cameron20 / t3code-1 / commits / 8f54d4b1a9
Fork 0

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

fix(desktop): exits that skip quit are recorded in the trace and logs (#35097)

Julius Marminge committed Nov 12, 2026 at 02:40 UTC 8f54d4b1a9a565eff6cf40464fb2dc6801c598df
6 files changed +190 -1
apps/desktop/src/app/DesktopExitChildren.test.ts new
+42
@@ -0,0 +1,42 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Spawns a real process tree for /proc.
2 +import * as NodeChildProcess from "node:child_process";
3 +import * as NodeFS from "node:fs";
4 +import { assert, describe, it } from "@effect/vitest";
5 +
6 +import { stopChildProcessesBeforeExit } from "./DesktopExitChildren.ts";
7 +
8 +const isRunning = (pid: number) => {
9 + try {
10 + const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8");
11 + return !"ZX".includes(stat.charAt(stat.lastIndexOf(")") + 2));
12 + } catch {
13 + return false;
14 + }
15 +};
16 +
17 +describe.runIf(NodeFS.existsSync("/proc/self/task"))("stopChildProcessesBeforeExit", () => {
18 + it("terminates every child of the given process before returning", async () => {
19 + const parent = NodeChildProcess.spawn(
20 + "sh",
21 + ["-c", "sleep 60 & echo $!; sleep 60 & echo $!; wait"],
22 + { stdio: ["ignore", "pipe", "ignore"] },
23 + );
24 + try {
25 + const childPids = await new Promise<Array<number>>((resolve) => {
26 + let output = "";
27 + parent.stdout.on("data", (chunk: Buffer) => {
28 + output += chunk.toString();
29 + const pids = output.split("\n").filter(Boolean).map(Number);
30 + if (pids.length === 2) resolve(pids);
31 + });
32 + });
33 + assert.isTrue(childPids.every(isRunning));
34 +
35 + assert.deepStrictEqual(stopChildProcessesBeforeExit(parent.pid!), []);
36 +
37 + assert.isFalse(childPids.some(isRunning));
38 + } finally {
39 + parent.kill("SIGKILL");
40 + }
41 + });
42 +});
apps/desktop/src/app/DesktopExitChildren.ts new
+70
@@ -0,0 +1,70 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Runs synchronously in the process "exit" event, where nothing async completes.
2 +import * as NodeFS from "node:fs";
3 +
4 +// Matches the backend's quit budget: SIGTERM, 5 s grace, SIGKILL, 1 s wait.
5 +const TERMINATE_GRACE_MS = 5_000;
6 +const KILL_WAIT_MS = 1_000;
7 +
8 +const readProc = (path: string): string | undefined => {
9 + try {
10 + return NodeFS.readFileSync(path, "utf8");
11 + } catch {
12 + return undefined;
13 + }
14 +};
15 +
16 +// Chromium launches helpers from its own threads, so each thread's children file is read.
17 +const childPids = (pid: number): ReadonlyArray<number> => {
18 + let tasks: ReadonlyArray<string>;
19 + try {
20 + tasks = NodeFS.readdirSync(`/proc/${pid}/task`);
21 + } catch {
22 + return [];
23 + }
24 + return tasks.flatMap((task) =>
25 + (readProc(`/proc/${pid}/task/${task}/children`) ?? "")
26 + .split(" ")
27 + .filter((value) => value.trim() !== "")
28 + .map(Number),
29 + );
30 +};
31 +
32 +// A zombie has already released its memory mappings.
33 +const isRunning = (pid: number): boolean => {
34 + const stat = readProc(`/proc/${pid}/stat`);
35 + if (stat === undefined) return false;
36 + const state = stat.charAt(stat.lastIndexOf(")") + 2);
37 + return state !== "Z" && state !== "X";
38 +};
39 +
40 +const signal = (pids: ReadonlyArray<number>, name: NodeJS.Signals) => {
41 + for (const pid of pids) {
42 + try {
43 + process.kill(pid, name);
44 + } catch {}
45 + }
46 +};
47 +
48 +const waitUntilStopped = (pids: ReadonlyArray<number>, maxMs: number): ReadonlyArray<number> => {
49 + const tick = new Int32Array(new SharedArrayBuffer(4));
50 + let running = pids.filter(isRunning);
51 + for (let waited = 0; waited < maxMs && running.length > 0; waited += 10) {
52 + Atomics.wait(tick, 0, 0, 10);
53 + running = running.filter(isRunning);
54 + }
55 + return running;
56 +};
57 +
58 +/**
59 + * Stops the main process's children while it is still alive. On an AppImage the image unmounts
60 + * as soon as main exits, so children left running then die with SIGBUS. Linux only (/proc).
61 + * Returns the pids that needed SIGKILL.
62 + */
63 +export const stopChildProcessesBeforeExit = (pid: number): ReadonlyArray<number> => {
64 + const children = childPids(pid);
65 + signal(children, "SIGTERM");
66 + const survivors = waitUntilStopped(children, TERMINATE_GRACE_MS);
67 + signal(survivors, "SIGKILL");
68 + waitUntilStopped(survivors, KILL_WAIT_MS);
69 + return survivors;
70 +};
apps/desktop/src/app/DesktopLifecycle.ts
+33 -1
@@ -12,6 +12,7 @@ import type * as Electron from "electron";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13
14 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
15 +import { stopChildProcessesBeforeExit } from "./DesktopExitChildren.ts";
16 import { makeComponentLogger } from "./DesktopObservability.ts";
17 import * as DesktopShutdown from "./DesktopShutdown.ts";
18 import * as ElectronApp from "../electron/ElectronApp.ts";
@@ -69,15 +70,18 @@ function addScopedListener<Args extends ReadonlyArray<unknown>>(
70 target: unknown,
71 eventName: string,
72 listener: (...args: Args) => void,
73 + options: { readonly prepend?: boolean } = {},
74 ): Effect.Effect<void, never, Scope.Scope> {
75 const eventTarget = target as {
76 on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
77 + prependListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
78 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown;
79 };
80 const untypedListener = listener as unknown as (...args: Array<unknown>) => void;
81 return Effect.acquireRelease(
82 Effect.sync(() => {
80 - eventTarget.on(eventName, untypedListener);
83 + if (options.prepend) eventTarget.prependListener(eventName, untypedListener);
84 + else eventTarget.on(eventName, untypedListener);
85 }),
86 () =>
87 Effect.sync(() => {
@@ -300,6 +304,34 @@ export const make = DesktopLifecycle.of({
304 );
305 });
306
307 + // Electron can exit without before-quit, e.g. when the X11/Wayland connection drops.
308 + // Children (the backend too) get SIGTERM while main still holds an AppImage mount open.
309 + // Prepended so the record is buffered before the trace sink's own exit flush runs.
310 + yield* addScopedListener(
311 + process,
312 + "exit",
313 + (exitCode: number) => {
314 + Effect.runSyncWith(context)(
315 + Effect.gen(function* () {
316 + const shutdown = yield* DesktopShutdown.DesktopShutdown;
317 + // "allowed" without a finished shutdown is the updater's quit; its relaunched app is a child.
318 + if (quit.phase === "allowed" || (yield* shutdown.isComplete)) return;
319 + const attributes = { exitCode, quitPhase: quit.phase };
320 + yield* Effect.gen(function* () {
321 + yield* logLifecycleError(
322 + "desktop main process exiting before shutdown completed",
323 + attributes,
324 + );
325 + if (environment.platform !== "linux") return;
326 + const killed = stopChildProcessesBeforeExit(process.pid);
327 + yield* Effect.annotateCurrentSpan({ killedChildPids: killed });
328 + }).pipe(Effect.withSpan("desktop.lifecycle.exit", { attributes }));
329 + }),
330 + );
331 + },
332 + { prepend: true },
333 + );
334 +
335 if (environment.platform !== "win32") {
336 yield* addScopedListener(process, "SIGINT", () => {
337 quitFromSignal("SIGINT", runEffect, quit);
apps/desktop/src/app/DesktopObservability.ts
+2
@@ -654,6 +654,8 @@ const layerTelemetry = Layer.unwrap(
654 maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
655 batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
656 });
657 + // Unscoped: Electron can exit without closing the app scope, e.g. when the display drops.
658 + process.once("exit", sink.flushSync);
659 const delegate =
660 endpoints.traces === undefined
661 ? undefined
packages/shared/src/observability.test.ts
+28
@@ -158,6 +158,7 @@ describe("observability", () => {
158 if (record.type === "effect-span") records.push(record);
159 },
160 flush: Effect.void,
161 + flushSync: () => {},
162 close: () => Effect.void,
163 },
164 delegate: Tracer.make({
@@ -306,6 +307,33 @@ describe("observability", () => {
307 ),
308 );
309
310 + it.effect("writes buffered records synchronously for process exit", () =>
311 + Effect.scoped(
312 + Effect.gen(function* () {
313 + const fileSystem = yield* FileSystem.FileSystem;
314 + const path = yield* Path.Path;
315 + const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
316 + const tracePath = path.join(tempDir, "exit.trace.ndjson");
317 + const sink = yield* makeTraceSink({
318 + filePath: tracePath,
319 + maxBytes: 1_000_000,
320 + maxFiles: 2,
321 + batchWindowMs: 10_000,
322 + });
323 +
324 + sink.push(makeRecord("before-exit"));
325 + sink.flushSync();
326 + sink.flushSync();
327 +
328 + const records = yield* readTraceRecords(tracePath);
329 + assert.deepStrictEqual(
330 + records.map((record) => record.name),
331 + ["before-exit"],
332 + );
333 + }),
334 + ),
335 + );
336 +
337 it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
338 Effect.scoped(
339 Effect.gen(function* () {
packages/shared/src/observability.ts
+15
@@ -1,3 +1,5 @@
1 +// @effect-diagnostics-next-line nodeBuiltinImport:off - flushSync must write before the process exits.
2 +import * as NodeFS from "node:fs";
3 import * as Cause from "effect/Cause";
4 import * as Context from "effect/Context";
5 import * as Effect from "effect/Effect";
@@ -173,6 +175,8 @@ export interface TraceSink {
175 readonly filePath: string;
176 push: (record: TraceRecord) => void;
177 flush: Effect.Effect<void>;
178 + /** Appends buffered records synchronously, for process exit where async writes never land. */
179 + flushSync: () => void;
180 close: () => Effect.Effect<void>;
181 }
182
@@ -544,6 +548,17 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac
548 }
549 },
550 flush,
551 + flushSync() {
552 + if (buffer.length === 0) return;
553 + const text = buffer.map((record) => record.text).join("");
554 + buffer = [];
555 + bufferBytes = 0;
556 + try {
557 + NodeFS.appendFileSync(options.filePath, text);
558 + } catch {
559 + return;
560 + }
561 + },
562 close: () => flush,
563 } satisfies TraceSink;
564 });