Skip to content

Commit 02b9845

Browse files
fix(dev): worktree dev servers keep their own port, process tree, and Electron profile (#1911)
## Problem A worktree `vp run dev*` leaks into the live install: - **Port:** ambient `T3CODE_PORT` takes 3773 - **Stop:** a stopped `vp` orphans its children - **Profile:** one `~/.config/t3code-dev` for all The live port makes the dev backend crashloop on `EADDRINUSE`. A shared profile leaks zoom and storage between worktrees. ## Change **Port** - Worktrees ignore ambient `T3CODE_PORT` - `--port` still wins **Stop** - Runner owns a detached process group - Exits when its parent or grandparent goes - SIGHUP re-raised as SIGTERM - Electron cleanup: pidfile plus cwd check - Removed: `pkill -f` pattern `vp` forwards no signals, so the runner watches its ancestry. **Profile** - Dev userData: `<worktree>/.t3/electron` **Caveats** - Ancestry watch and cleanup: Linux `/proc` only - Removed the upstream `pkill` launcher test case - Not run: `vp run dev:desktop` end to end ## Scope and approval Refs #1909. Part D (zmux sessions) follows in a `zmux-estate` PR that closes the issue. ## Verification - `vp test run` dev-runner tests → exit 0 - `vp run fork:ci` → exit 0 Runtime: `T3CODE_PORT=3773 vp run dev --no-seed` in a worktree. 1. Binds 14677 and 6637, not 3773 2. SIGTERM outer `vp`: tree gone, ports free 3. Close the zmux tab: tree gone, ports free 4. Control, no SIGHUP line: tab close orphans Vite Claude Opus 5.5, Claude Code. ## Fork trailers Squashes: - df9e234 fix(dev): a worktree dev runner ignores the live install's ambient T3CODE_PORT - cd7c7c7 fix(dev): stopping a dev runner stops its whole process tree, and dev Electron cleanup kills only its own app - bae9fd7 fix(desktop): the dev Electron profile lives with the dev state, so worktrees stop sharing it Fork-Domain: upstream-fixes Fork-Tier: bugfix Fork-Upstreamable: yes Co-authored-by: donjor <[email protected]>
1 parent 42d6a9b commit 02b9845

8 files changed

Lines changed: 219 additions & 114 deletions

File tree

‎apps/desktop/scripts/dev-electron.mjs‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -89,19 +89,38 @@ function killChildTreeByPid(pid, signal) {
8989
NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
9090
}
9191

92+
// A pidfile, not a pattern: only an Electron this checkout started is ever stopped.
93+
const devAppPidFile = NodePath.join(
94+
desktopDir,
95+
"node_modules",
96+
".cache",
97+
"t3code-dev-electron.pid",
98+
);
99+
92100
function cleanupStaleDevApps() {
93-
if (hostPlatform === "win32") {
101+
if (hostPlatform !== "linux") {
94102
return;
95103
}
96104

97-
const escapedDesktopDir = desktopDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
98-
NodeChildProcess.spawnSync(
99-
"pkill",
100-
["-f", "--", `(^| )--t3code-dev-root=${escapedDesktopDir}( |$)`],
101-
{
102-
stdio: "ignore",
103-
},
104-
);
105+
let pid;
106+
try {
107+
pid = Number.parseInt(NodeFS.readFileSync(devAppPidFile, "utf8"), 10);
108+
if (NodeFS.realpathSync(`/proc/${pid}/cwd`) !== NodeFS.realpathSync(desktopDir)) {
109+
return;
110+
}
111+
} catch {
112+
return;
113+
}
114+
killChildTreeByPid(pid, "KILL");
115+
try {
116+
process.kill(pid, "SIGKILL");
117+
} catch {}
118+
}
119+
120+
function recordDevApp(pid) {
121+
if (typeof pid !== "number") return;
122+
NodeFS.mkdirSync(NodePath.dirname(devAppPidFile), { recursive: true });
123+
NodeFS.writeFileSync(devAppPidFile, `${pid}\n`);
105124
}
106125

107126
function startApp() {
@@ -123,6 +142,7 @@ function startApp() {
123142
});
124143

125144
currentApp = app;
145+
recordDevApp(app.pid);
126146

127147
app.once("error", () => {
128148
if (currentApp === app) {
@@ -170,7 +190,6 @@ async function stopApp() {
170190
app.once("exit", finish);
171191
app.kill("SIGTERM");
172192
killChildTreeByPid(app.pid, "TERM");
173-
cleanupStaleDevApps();
174193

175194
setTimeout(() => {
176195
if (settled) {
@@ -179,7 +198,6 @@ async function stopApp() {
179198

180199
app.kill("SIGKILL");
181200
killChildTreeByPid(app.pid, "KILL");
182-
cleanupStaleDevApps();
183201
finish();
184202
}, forcedShutdownTimeoutMs).unref();
185203
});

‎apps/desktop/scripts/electron-launcher.test.mjs‎

Lines changed: 0 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
1-
import * as NodeChildProcess from "node:child_process";
2-
import * as NodeEvents from "node:events";
31
import * as NodeFS from "node:fs";
42
import * as NodeOS from "node:os";
53
import * as NodePath from "node:path";
6-
import * as NodeVM from "node:vm";
74

85
import { assert, describe, it } from "vite-plus/test";
96

@@ -117,93 +114,3 @@ describe("electron development launcher", () => {
117114
}
118115
});
119116
});
120-
121-
async function startupCleanupPattern(desktopDir) {
122-
const source = NodeFS.readFileSync(new URL("./dev-electron.mjs", import.meta.url), "utf8");
123-
let pattern;
124-
// Supply inert imports so the real startup runs without launching Electron or signalling processes.
125-
await NodeVM.runInNewContext(
126-
`(async () => { ${source.replace(/^import\s[\s\S]*?;\n/gm, "")} })()`,
127-
{
128-
NodeChildProcess: {
129-
execFileSync: () => undefined,
130-
spawnSync: (command, args) => {
131-
if (command === "pkill" && args.includes("-f")) pattern = args.at(-1);
132-
},
133-
spawn: () => new NodeEvents.EventEmitter(),
134-
},
135-
NodeFS: { watch: () => ({ close: () => undefined }) },
136-
NodeOS: { platform: () => "linux" },
137-
NodePath,
138-
desktopDir,
139-
resolveDevProtocolClient: () => null,
140-
resolveElectronLaunchCommand: (args) => ({ electronPath: "electron", args }),
141-
waitForResources: async () => undefined,
142-
URL,
143-
process: {
144-
env: { VITE_DEV_SERVER_URL: "http://localhost:1234" },
145-
execPath: "node",
146-
once: () => undefined,
147-
},
148-
},
149-
);
150-
assert.isString(pattern);
151-
return pattern;
152-
}
153-
154-
it
155-
// oxlint-disable-next-line t3code/no-global-process-runtime -- Native pgrep is unavailable on Windows.
156-
.skipIf(NodeOS.platform() === "win32")
157-
.each([
158-
"/tmp/t3-feature.one/apps/desktop",
159-
"/tmp/t3-feature.one [two](three)+?^${four}|back\\slash*/apps/desktop",
160-
])("dev cleanup matches only the literal root argument: %s", async (desktopDir) => {
161-
const pattern = await startupCleanupPattern(desktopDir);
162-
const flag = `--t3code-dev-root=${desktopDir}`;
163-
const argvCases = [
164-
[flag],
165-
[flag, "main.cjs"],
166-
[flag.replace(".one", "Xone")],
167-
[`${flag}-two`],
168-
[`prefix${flag}`],
169-
[`--t3code-dev-root=/other${desktopDir}`],
170-
];
171-
const children = [];
172-
try {
173-
for (const args of argvCases) {
174-
const child = NodeChildProcess.spawn(
175-
process.execPath,
176-
["-e", "process.send('ready'); setInterval(() => {}, 1000)", "--", ...args],
177-
{ stdio: ["ignore", "ignore", "inherit", "ipc"] },
178-
);
179-
children.push(child);
180-
await Promise.race([
181-
NodeEvents.once(child, "message"),
182-
NodeEvents.once(child, "exit").then(() => {
183-
throw new Error("Fixture exited before readiness");
184-
}),
185-
]);
186-
}
187-
// Use the native ERE engine, but never execute the launcher's signal-producing command.
188-
const result = NodeChildProcess.spawnSync(
189-
"pgrep",
190-
["-P", String(process.pid), "-f", "--", pattern],
191-
{ encoding: "utf8" },
192-
);
193-
assert.equal(result.status, 0, result.stderr);
194-
const matches = result.stdout.trim().split(/\s+/).map(Number);
195-
assert.sameMembers(
196-
matches,
197-
children.slice(0, 2).map((child) => child.pid),
198-
);
199-
} finally {
200-
await Promise.all(
201-
children.map(async (child) => {
202-
if (child.exitCode !== null || child.signalCode !== null) return;
203-
const exited = NodeEvents.once(child, "exit");
204-
child.kill("SIGTERM");
205-
await exited;
206-
}),
207-
);
208-
}
209-
});

‎apps/desktop/src/app/DesktopConfig.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export const DesktopConfig = Config.all({
5959
appImagePath: trimmedString("APPIMAGE"),
6060
disableAutoUpdate: optionalBoolean("T3CODE_DISABLE_AUTO_UPDATE"),
6161
mockUpdates: optionalBoolean("T3CODE_DESKTOP_MOCK_UPDATES"),
62+
devElectronUserData: trimmedString("T3CODE_DEV_ELECTRON_USER_DATA"), // fork-hook: upstream-fixes/dev-electron-user-data
6263
devToolsEnabled: Config.Boolean("T3CODE_DESKTOP_DEVTOOLS").pipe(Config.withDefault(true)), // fork-hook: fork-meta/desktop-config-devtools
6364
mockUpdateServerPort: Config.Port("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(
6465
Config.withDefault(3000),

‎apps/desktop/src/app/DesktopEnvironment.fork.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
import * as NodePath from "@effect/platform-node/NodePath";
12
import * as NodeServices from "@effect/platform-node/NodeServices";
23
import { assert, describe, it } from "@effect/vitest";
34
import * as Effect from "effect/Effect";
5+
import * as FileSystem from "effect/FileSystem";
6+
import * as Option from "effect/Option";
47
import * as Layer from "effect/Layer";
58
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
69
import * as DesktopConfig from "./DesktopConfig.ts";
10+
import { resolveUserDataPath } from "./DesktopUserData.ts";
711
const defaultInput = {
812
dirname: "/repo/apps/desktop/dist-electron",
913
homeDirectory: "/Users/alice",
@@ -29,6 +33,29 @@ const makeEnvironment = (
2933
) =>
3034
DesktopEnvironment.DesktopEnvironment.pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
3135
describe("DesktopEnvironment", () => {
36+
it.effect("a dev profile override wins in development and is ignored when packaged", () =>
37+
Effect.gen(function* () {
38+
const override = { T3CODE_DEV_ELECTRON_USER_DATA: "/repo/.t3/electron" };
39+
const dev = yield* makeEnvironment(
40+
{},
41+
{ ...override, VITE_DEV_SERVER_URL: "http://localhost:5173" },
42+
);
43+
assert.equal(yield* resolveUserDataPath(dev), "/repo/.t3/electron");
44+
const packaged = yield* makeEnvironment({ isPackaged: true }, override);
45+
assert.isTrue(Option.isNone(packaged.devElectronUserData));
46+
assert.equal(
47+
yield* resolveUserDataPath(packaged),
48+
"/Users/alice/Library/Application Support/t3code-v2",
49+
);
50+
}).pipe(
51+
Effect.provide(
52+
Layer.mergeAll(
53+
NodePath.layerPosix,
54+
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
55+
),
56+
),
57+
),
58+
);
3259
it.effect("keeps devtools on by default and lets a dev run opt out", () =>
3360
Effect.gen(function* () {
3461
const defaults = yield* makeEnvironment({}, { VITE_DEV_SERVER_URL: "http://localhost:5173" });

‎apps/desktop/src/app/DesktopEnvironment.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export class DesktopEnvironment extends Context.Service<
4747
readonly appDataDirectory: string;
4848
readonly baseDir: string;
4949
readonly stateDir: string;
50+
readonly devElectronUserData: Option.Option<string>; // fork-hook: upstream-fixes/dev-electron-user-data
5051
readonly desktopSettingsPath: string;
5152
readonly clientSettingsPath: string;
5253
readonly savedEnvironmentRegistryPath: string;
@@ -196,6 +197,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
196197
isPackaged: input.isPackaged,
197198
isDevelopment,
198199
devToolsEnabled: config.devToolsEnabled, // fork-hook: multi-window/devtools-enabled
200+
devElectronUserData: isDevelopment ? config.devElectronUserData : Option.none(), // fork-hook: upstream-fixes/dev-electron-user-data
199201
appVersion: input.appVersion,
200202
appPath: input.appPath,
201203
resourcesPath,

‎apps/desktop/src/app/DesktopUserData.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as Effect from "effect/Effect";
2+
import * as Option from "effect/Option"; // fork-hook: upstream-fixes/dev-electron-user-data
23
import * as FileSystem from "effect/FileSystem";
34
import * as Path from "effect/Path";
45
import * as PlatformError from "effect/PlatformError";
@@ -36,7 +37,10 @@ export const resolveUserDataPath = Effect.fn("desktop.userData.resolveUserDataPa
3637
readonly appDataDirectory: string;
3738
readonly isDevelopment: boolean;
3839
readonly platform: NodeJS.Platform;
40+
readonly devElectronUserData?: Option.Option<string>; // fork-hook: upstream-fixes/dev-electron-user-data
3941
}) {
42+
if (input.devElectronUserData && Option.isSome(input.devElectronUserData))
43+
return input.devElectronUserData.value; // fork-hook: upstream-fixes/dev-electron-user-data
4044
const fs = yield* FileSystem.FileSystem;
4145
const path = yield* Path.Path;
4246
const names = input.isDevelopment

‎scripts/dev-runner.fork.test.ts‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - builds a real worktree layout on disk.
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as NodeFS from "node:fs";
4+
import * as NodeOS from "node:os";
5+
import * as NodePath from "node:path";
6+
import * as NetService from "@t3tools/shared/Net";
7+
import * as HostProcess from "@t3tools/shared/HostProcess";
8+
import * as ConfigProvider from "effect/ConfigProvider";
9+
import { assert, it } from "@effect/vitest";
10+
import * as Effect from "effect/Effect";
11+
import * as Layer from "effect/Layer";
12+
import * as Sink from "effect/Sink";
13+
import * as Stream from "effect/Stream";
14+
import { ChildProcessSpawner } from "effect/process";
15+
16+
import { runDevRunnerWithInput } from "./dev-runner.ts";
17+
18+
const exitedProcess = ChildProcessSpawner.makeHandle({
19+
pid: ChildProcessSpawner.ProcessId(1),
20+
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
21+
isRunning: Effect.succeed(false),
22+
kill: () => Effect.void,
23+
unref: Effect.succeed(Effect.void),
24+
stdin: Sink.drain,
25+
stdout: Stream.empty,
26+
stderr: Stream.empty,
27+
all: Stream.empty,
28+
getInputFd: () => Sink.drain,
29+
getOutputFd: () => Stream.empty,
30+
});
31+
32+
const makeWorktree = Effect.acquireRelease(
33+
Effect.sync(() => {
34+
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devrunner-fork-"));
35+
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /elsewhere/.git/worktrees/x\n");
36+
return root;
37+
}),
38+
(root) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
39+
);
40+
41+
/** The environment dev-runner hands Vite+ for one `dev:server` run. */
42+
const spawnedEnv = (input: {
43+
readonly cwd: string;
44+
readonly t3Home?: string;
45+
readonly port?: number;
46+
readonly ambient?: Record<string, string>;
47+
}) =>
48+
Effect.gen(function* () {
49+
let captured: Record<string, string | undefined> | undefined;
50+
const spawner = ChildProcessSpawner.make((command) => {
51+
captured = (command as { readonly options?: { readonly env?: Record<string, string> } })
52+
.options?.env;
53+
return Effect.succeed(exitedProcess);
54+
});
55+
yield* runDevRunnerWithInput({
56+
mode: "dev:server",
57+
t3Home: input.t3Home,
58+
browser: undefined,
59+
autoBootstrapProjectFromCwd: undefined,
60+
logWebSocketEvents: undefined,
61+
host: undefined,
62+
port: input.port,
63+
devUrl: undefined,
64+
dryRun: false,
65+
share: false,
66+
seed: false,
67+
built: false,
68+
runArgs: [],
69+
}).pipe(
70+
Effect.provide(
71+
Layer.mergeAll(
72+
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.ambient ?? {} })),
73+
Layer.succeed(NetService.NetService, {
74+
canListenOnHost: () => Effect.succeed(true),
75+
isPortAvailableOnLoopback: () => Effect.succeed(true),
76+
hasListenerOnHost: () => Effect.succeed(false),
77+
reserveLoopbackPort: () => Effect.succeed(49_152),
78+
findAvailablePort: (port) => Effect.succeed(port),
79+
}),
80+
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
81+
),
82+
),
83+
Effect.provideService(HostProcess.Platform, "linux"),
84+
Effect.provideService(HostProcess.WorkingDirectory, input.cwd),
85+
Effect.provideService(HostProcess.HomeDirectory, input.cwd),
86+
Effect.provideService(HostProcess.Environment, input.ambient ?? {}),
87+
);
88+
return captured;
89+
});
90+
91+
it.layer(NodeServices.layer)("dev-runner (fork)", (it) => {
92+
it.effect("a worktree ignores the live install's ambient T3CODE_PORT; --port still wins", () =>
93+
Effect.gen(function* () {
94+
const cwd = yield* makeWorktree;
95+
const ambient = { T3CODE_PORT: "3773" };
96+
assert.notEqual((yield* spawnedEnv({ cwd, ambient }))?.T3CODE_PORT, "3773");
97+
assert.equal((yield* spawnedEnv({ cwd, ambient, port: 4321 }))?.T3CODE_PORT, "4321");
98+
}).pipe(Effect.scoped),
99+
);
100+
101+
it.effect("keeps an ambient T3CODE_PORT outside a worktree", () =>
102+
Effect.gen(function* () {
103+
const env = yield* spawnedEnv({ cwd: NodeOS.tmpdir(), ambient: { T3CODE_PORT: "3773" } });
104+
assert.equal(env?.T3CODE_PORT, "3773");
105+
}),
106+
);
107+
it.effect("gives worktree dev Electron its own profile unless one is set", () =>
108+
Effect.gen(function* () {
109+
const cwd = yield* makeWorktree;
110+
const own = yield* spawnedEnv({ cwd });
111+
assert.equal(own?.T3CODE_DEV_ELECTRON_USER_DATA, NodePath.join(cwd, ".t3", "electron"));
112+
const preset = { T3CODE_DEV_ELECTRON_USER_DATA: "/tmp/mine" };
113+
const kept = yield* spawnedEnv({ cwd, ambient: preset });
114+
assert.equal(kept?.T3CODE_DEV_ELECTRON_USER_DATA, "/tmp/mine");
115+
}).pipe(Effect.scoped),
116+
);
117+
});

0 commit comments

Comments
 (0)