Skip to content

Commit 40a98c2

Browse files
marcuscasteloclaude
andcommitted
fix(desktop): stop the backend when the desktop process dies
When the desktop main process died without running its shutdown (SIGKILL, SIGTRAP, native crash), the backend it spawned was reparented and kept listening on its port. The next launch then found the port taken and moved to the next one, breaking paired remotes and saved MCP URLs. The desktop now passes the primary backend a lifetime pipe on fd 6, which it never writes to or closes, so the OS closes it only when the desktop process exits. The backend watches it and, on EOF, runs its SIGTERM shutdown handler, the same shutdown a normal quit triggers. Emitting the event instead of signalling keeps that graceful on Windows too. Headless, CLI, and WSL servers never receive the descriptor and are unaffected. Fixes #13747 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 5d707bb commit 40a98c2

12 files changed

Lines changed: 190 additions & 0 deletions

‎apps/desktop/src/backend/DesktopBackendConfiguration.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,6 +1426,7 @@ describe("DesktopBackendConfiguration", () => {
14261426
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
14271427
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
14281428
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
1429+
assert.equal(config.bootstrap.desktopLifetimeFd, 6);
14291430
}).pipe(
14301431
Effect.provide(
14311432
DesktopBackendConfiguration.layer.pipe(

‎apps/desktop/src/backend/DesktopBackendConfiguration.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
557557
tailscaleServePort: backendExposure.tailscaleServePort,
558558
desktopTelemetryFd: 4,
559559
desktopTelemetryControlFd: 5,
560+
desktopLifetimeFd: 6,
560561
...Option.match(input.resourceMonitorPath, {
561562
onNone: () => ({}),
562563
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),

‎apps/desktop/src/backend/DesktopBackendManager.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
5454
tailscaleServePort: 443,
5555
desktopTelemetryFd: 4,
5656
desktopTelemetryControlFd: 5,
57+
desktopLifetimeFd: 6,
5758
},
5859
bootstrapDelivery: "fd3",
5960
extendEnv: true,
@@ -260,6 +261,7 @@ describe("DesktopBackendManager", () => {
260261
assert.isDefined(spawnedCommand.options.forceKillAfter);
261262
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
262263
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
264+
assert.equal(spawnedCommand.options.additionalFds?.fd6?.type, "input");
263265
assert.equal(
264266
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
265267
2_000,

‎apps/desktop/src/backend/DesktopBackendManager.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,14 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
472472
type: "output",
473473
};
474474
}
475+
// Nothing writes to or closes this pipe, so the OS closes it only when
476+
// this process exits. The backend shuts down on its EOF, which covers
477+
// crashes and SIGKILL that skip the backend shutdown here.
478+
if (options.bootstrap.desktopLifetimeFd !== undefined) {
479+
additionalFds[`fd${options.bootstrap.desktopLifetimeFd}`] = {
480+
type: "input",
481+
};
482+
}
475483
}
476484
const command = ChildProcess.make(options.executablePath, options.args, {
477485
cwd: options.cwd,

‎apps/server/src/cli/config.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
397397
desktopBootstrapToken: "desktop-token",
398398
desktopTelemetryFd: 4,
399399
desktopTelemetryControlFd: 5,
400+
desktopLifetimeFd: 6,
400401
tailscaleServeEnabled: false,
401402
tailscaleServePort: 443,
402403
otlpTracesUrl: "http://localhost:4318/v1/traces",
@@ -456,6 +457,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
456457
desktopBootstrapToken: "desktop-token",
457458
desktopTelemetryFd: 4,
458459
desktopTelemetryControlFd: 5,
460+
desktopLifetimeFd: 6,
459461
resourceMonitorPath: undefined,
460462
autoBootstrapProjectFromCwd: false,
461463
logWebSocketEvents: false,
@@ -465,6 +467,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
465467
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
466468
assert.equal(resolved.desktopTelemetryFd, 4);
467469
assert.equal(resolved.desktopTelemetryControlFd, 5);
470+
assert.equal(resolved.desktopLifetimeFd, 6);
468471
}),
469472
);
470473

‎apps/server/src/cli/config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@ export const resolveServerConfig = (
348348
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
349349
const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
350350
const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
351+
const desktopLifetimeFd = bootstrap?.desktopLifetimeFd;
351352
const resourceMonitorPath = bootstrap?.resourceMonitorPath;
352353
const autoBootstrapProjectFromCwd = Option.getOrElse(
353354
resolveOptionPrecedence(
@@ -453,6 +454,7 @@ export const resolveServerConfig = (
453454
desktopBootstrapToken,
454455
desktopTelemetryFd,
455456
desktopTelemetryControlFd,
457+
desktopLifetimeFd,
456458
resourceMonitorPath,
457459
autoBootstrapProjectFromCwd,
458460
logWebSocketEvents,

‎apps/server/src/cli/pair.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@ const makePairServerConfig = Effect.fn(function* (input: {
341341
desktopBootstrapToken: undefined,
342342
desktopTelemetryFd: undefined,
343343
desktopTelemetryControlFd: undefined,
344+
desktopLifetimeFd: undefined,
344345
resourceMonitorPath: undefined,
345346
autoBootstrapProjectFromCwd: false,
346347
logWebSocketEvents: false,

‎apps/server/src/config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ export class ServerConfig extends Context.Service<
9696
readonly desktopBootstrapToken: string | undefined;
9797
readonly desktopTelemetryFd?: number | undefined;
9898
readonly desktopTelemetryControlFd?: number | undefined;
99+
readonly desktopLifetimeFd?: number | undefined;
99100
readonly resourceMonitorPath?: string | undefined;
100101
readonly autoBootstrapProjectFromCwd: boolean;
101102
readonly logWebSocketEvents: boolean;
@@ -234,6 +235,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
234235
desktopBootstrapToken: undefined,
235236
desktopTelemetryFd: undefined,
236237
desktopTelemetryControlFd: undefined,
238+
desktopLifetimeFd: undefined,
237239
resourceMonitorPath: undefined,
238240
staticDir: undefined,
239241
devUrl,
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeFS from "node:fs";
4+
import * as NodePath from "node:path";
5+
import * as NodeReadline from "node:readline";
6+
import * as NodeURL from "node:url";
7+
8+
import * as NodeServices from "@effect/platform-node/NodeServices";
9+
import { it } from "@effect/vitest";
10+
import * as Deferred from "effect/Deferred";
11+
import * as Effect from "effect/Effect";
12+
import * as Fiber from "effect/Fiber";
13+
import * as FileSystem from "effect/FileSystem";
14+
import * as Queue from "effect/Queue";
15+
import { describe, expect } from "vite-plus/test";
16+
17+
import * as DesktopLifetime from "./desktopLifetime.ts";
18+
19+
// Stands in for the desktop: spawns a backend with the lifetime pipe on fd 6,
20+
// the way DesktopBackendManager does, then waits to be killed.
21+
const DESKTOP_SCRIPT = `
22+
const backend = require("node:child_process").spawn(
23+
process.execPath,
24+
["--input-type=module", "-e", process.env.T3_TEST_BACKEND_SCRIPT],
25+
{ stdio: ["ignore", "inherit", "inherit", "ignore", "ignore", "ignore", "pipe"] },
26+
);
27+
console.log("backend " + backend.pid);
28+
setInterval(() => {}, 1 << 30);
29+
`;
30+
31+
// Runs the real watcher on fd 6 and reports through the stdout it inherits
32+
// from the desktop, which outlives the desktop.
33+
const BACKEND_SCRIPT = `
34+
import * as Effect from "effect/Effect";
35+
import * as Fiber from "effect/Fiber";
36+
const { watch } = await import(process.env.T3_TEST_DESKTOP_LIFETIME_MODULE);
37+
const onDesktopExit = Effect.sync(() => console.log("desktop exited"));
38+
await Effect.runPromise(Effect.scoped(Effect.flatMap(watch(6, onDesktopExit), Fiber.join)));
39+
`;
40+
41+
const takeLineMatching = (lines: Queue.Dequeue<string>, matches: (line: string) => boolean) =>
42+
Queue.take(lines).pipe(Effect.repeat({ until: matches }));
43+
44+
describe("DesktopLifetime", () => {
45+
it.effect("reports the desktop exit when the desktop dies without cleanup", () =>
46+
Effect.gen(function* () {
47+
const lines = yield* Queue.unbounded<string>();
48+
const desktop = yield* Effect.acquireRelease(
49+
Effect.sync(() => {
50+
const child = NodeChildProcess.spawn(process.execPath, ["-e", DESKTOP_SCRIPT], {
51+
cwd: NodePath.join(import.meta.dirname, ".."),
52+
env: {
53+
...process.env,
54+
T3_TEST_BACKEND_SCRIPT: BACKEND_SCRIPT,
55+
T3_TEST_DESKTOP_LIFETIME_MODULE: NodeURL.pathToFileURL(
56+
NodePath.join(import.meta.dirname, "desktopLifetime.ts"),
57+
).href,
58+
},
59+
stdio: ["ignore", "pipe", "inherit"],
60+
});
61+
NodeReadline.createInterface({ input: child.stdout }).on("line", (line) => {
62+
Queue.offerUnsafe(lines, line);
63+
});
64+
return child;
65+
}),
66+
(child) =>
67+
Effect.sync(() => {
68+
child.kill("SIGKILL");
69+
}),
70+
);
71+
const backendPid = Number(
72+
(yield* takeLineMatching(lines, (line) => line.startsWith("backend "))).slice(8),
73+
);
74+
yield* Effect.addFinalizer(() =>
75+
Effect.sync(() => {
76+
try {
77+
process.kill(backendPid, "SIGKILL");
78+
} catch {
79+
// Already exited.
80+
}
81+
}),
82+
);
83+
84+
desktop.kill("SIGKILL");
85+
expect(yield* takeLineMatching(lines, (line) => line === "desktop exited")).toBe(
86+
"desktop exited",
87+
);
88+
}),
89+
);
90+
91+
it.effect("keeps running when the descriptor cannot be watched", () =>
92+
Effect.gen(function* () {
93+
const fs = yield* FileSystem.FileSystem;
94+
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-lifetime-" });
95+
const filePath = NodePath.join(tempDir, "not-a-pipe");
96+
yield* fs.writeFileString(filePath, "");
97+
const fd = yield* Effect.acquireRelease(
98+
Effect.sync(() => NodeFS.openSync(filePath, "r")),
99+
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
100+
);
101+
102+
const desktopExited = yield* Deferred.make<void>();
103+
const watcher = yield* DesktopLifetime.watch(fd, Deferred.succeed(desktopExited, undefined));
104+
yield* Fiber.join(watcher);
105+
106+
expect(yield* Deferred.isDone(desktopExited)).toBe(false);
107+
}).pipe(Effect.provide(NodeServices.layer)),
108+
);
109+
});

‎apps/server/src/desktopLifetime.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - a net.Socket reads the inherited pipe without holding a threadpool thread.
2+
import * as NodeNet from "node:net";
3+
4+
import * as Effect from "effect/Effect";
5+
import * as Layer from "effect/Layer";
6+
7+
import * as ServerConfig from "./config.ts";
8+
9+
// Runs the shutdown a SIGTERM from the desktop would. Emitting the event rather
10+
// than signalling keeps it graceful on Windows, where a real SIGTERM ends the
11+
// process without running any handler.
12+
const shutDown = Effect.sync(() => {
13+
if (!process.emit("SIGTERM", "SIGTERM")) {
14+
process.kill(process.pid, "SIGTERM");
15+
}
16+
});
17+
18+
/**
19+
* Runs `onDesktopExit` once the desktop app that spawned this server has
20+
* exited. The desktop holds the only write end of `fd` and never writes to or
21+
* closes it, so EOF means its process is gone, including crashes and SIGKILL
22+
* that skip its own backend shutdown. A descriptor that cannot be watched is
23+
* logged and ignored.
24+
*/
25+
export const watch = (fd: number, onDesktopExit: Effect.Effect<void>) =>
26+
Effect.acquireRelease(
27+
Effect.try(() => new NodeNet.Socket({ fd, readable: true, writable: false })),
28+
(socket) => Effect.sync(() => socket.destroy()),
29+
).pipe(
30+
Effect.flatMap((socket) =>
31+
Effect.callback<void, Error>((resume) => {
32+
const onEnd = () => resume(Effect.void);
33+
socket.once("end", onEnd);
34+
// Stays attached for the socket's life, so a late error is never unhandled.
35+
socket.on("error", (error) => resume(Effect.fail(error)));
36+
socket.resume();
37+
return Effect.sync(() => {
38+
socket.off("end", onEnd);
39+
});
40+
}),
41+
),
42+
Effect.andThen(Effect.logInfo("The desktop app exited; shutting down.", { fd })),
43+
Effect.andThen(onDesktopExit),
44+
Effect.catch((cause) =>
45+
Effect.logWarning("Cannot watch the desktop app's lifetime.", { fd, cause }),
46+
),
47+
Effect.forkScoped,
48+
);
49+
50+
/** Shuts the server down when the desktop app that spawned it exits. */
51+
export const layer = Layer.effectDiscard(
52+
Effect.gen(function* () {
53+
const { desktopLifetimeFd } = yield* ServerConfig.ServerConfig;
54+
if (desktopLifetimeFd === undefined) return;
55+
yield* watch(desktopLifetimeFd, shutDown);
56+
}),
57+
);

0 commit comments

Comments
 (0)