Skip to content

Commit 5326163

Browse files
Merge branch 'main' into fix/issue-30998
2 parents bfebff2 + 04be2b3 commit 5326163

194 files changed

Lines changed: 8329 additions & 837 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ const childTreeGracePeriodMs = 1_200;
5252
const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
5353
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.
5454
const hostPlatform = NodeOS.platform();
55+
const parentPid = process.ppid;
56+
const parentWatchIntervalMs = 1_000;
5557

5658
NodeChildProcess.execFileSync(
5759
process.execPath,
@@ -271,3 +273,14 @@ process.once("SIGTERM", () => {
271273
process.once("SIGHUP", () => {
272274
void shutdown(129);
273275
});
276+
// A parent killed without forwarding a signal leaves us reparented (to a subreaper on Linux, not
277+
// necessarily PID 1), and nothing else would ever stop the restart loop. This only notices the
278+
// death of our direct parent, so vite.config.ts launches us without a shell in between. Windows
279+
// never reparents, and reading process.ppid there snapshots the process table.
280+
if (hostPlatform !== "win32") {
281+
setInterval(() => {
282+
if (process.ppid !== parentPid) {
283+
void shutdown(129);
284+
}
285+
}, parentWatchIntervalMs).unref();
286+
}

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

Lines changed: 106 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -118,19 +118,21 @@ describe("electron development launcher", () => {
118118
});
119119
});
120120

121-
async function startupCleanupPattern(desktopDir) {
121+
// Supply inert imports so the real startup runs without launching Electron or signalling processes.
122+
async function runDevElectronStartup({
123+
desktopDir = "/repo/apps/desktop",
124+
spawnSync,
125+
spawn,
126+
...context
127+
}) {
122128
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.
125129
await NodeVM.runInNewContext(
126130
`(async () => { ${source.replace(/^import\s[\s\S]*?;\n/gm, "")} })()`,
127131
{
128132
NodeChildProcess: {
129133
execFileSync: () => undefined,
130-
spawnSync: (command, args) => {
131-
if (command === "pkill" && args.includes("-f")) pattern = args.at(-1);
132-
},
133-
spawn: () => new NodeEvents.EventEmitter(),
134+
spawnSync: spawnSync ?? (() => undefined),
135+
spawn: spawn ?? (() => new NodeEvents.EventEmitter()),
134136
},
135137
NodeFS: { watch: () => ({ close: () => undefined }) },
136138
NodeOS: { platform: () => "linux" },
@@ -140,17 +142,114 @@ async function startupCleanupPattern(desktopDir) {
140142
resolveElectronLaunchCommand: (args) => ({ electronPath: "electron", args }),
141143
waitForResources: async () => undefined,
142144
URL,
145+
...makeFakeClock(),
143146
process: {
144147
env: { VITE_DEV_SERVER_URL: "http://localhost:1234" },
145148
execPath: "node",
149+
ppid: 1,
146150
once: () => undefined,
147151
},
152+
...context,
148153
},
149154
);
155+
}
156+
157+
async function startupCleanupPattern(desktopDir) {
158+
let pattern;
159+
await runDevElectronStartup({
160+
desktopDir,
161+
spawnSync: (command, args) => {
162+
if (command === "pkill" && args.includes("-f")) pattern = args.at(-1);
163+
},
164+
});
150165
assert.isString(pattern);
151166
return pattern;
152167
}
153168

169+
function makeFakeClock() {
170+
let now = 0;
171+
let timers = [];
172+
const schedule = (callback, delay, repeat) => {
173+
const timer = { callback, due: now + (delay ?? 0), repeat: repeat ? (delay ?? 0) : null };
174+
timer.handle = { unref: () => timer.handle, ref: () => timer.handle };
175+
timers.push(timer);
176+
return timer.handle;
177+
};
178+
const clear = (handle) => {
179+
timers = timers.filter((timer) => timer.handle !== handle);
180+
};
181+
const flushMicrotasks = async () => {
182+
for (let index = 0; index < 50; index += 1) await Promise.resolve();
183+
};
184+
return {
185+
setTimeout: (callback, delay) => schedule(callback, delay, false),
186+
setInterval: (callback, delay) => schedule(callback, delay, true),
187+
clearTimeout: clear,
188+
clearInterval: clear,
189+
async advance(ms) {
190+
const end = now + ms;
191+
for (;;) {
192+
await flushMicrotasks();
193+
const next = timers
194+
.filter((timer) => timer.due <= end)
195+
.toSorted((a, b) => a.due - b.due)[0];
196+
if (!next) break;
197+
now = next.due;
198+
if (next.repeat === null) clear(next.handle);
199+
else next.due = now + Math.max(next.repeat, 1);
200+
next.callback();
201+
}
202+
now = end;
203+
await flushMicrotasks();
204+
},
205+
};
206+
}
207+
208+
it("dev supervisor stops Electron and exits once its parent process goes away", async () => {
209+
const clock = makeFakeClock();
210+
let ppid = 4242;
211+
const exitCodes = [];
212+
const appSignals = [];
213+
await runDevElectronStartup({
214+
...clock,
215+
spawn: () => {
216+
const app = new NodeEvents.EventEmitter();
217+
app.pid = 5151;
218+
app.kill = (signal) => {
219+
appSignals.push(signal);
220+
app.emit("exit", null, signal);
221+
};
222+
return app;
223+
},
224+
process: {
225+
env: { VITE_DEV_SERVER_URL: "http://localhost:1234" },
226+
execPath: "node",
227+
pid: 4343,
228+
get ppid() {
229+
return ppid;
230+
},
231+
once: () => undefined,
232+
exit: (code) => {
233+
exitCodes.push(code);
234+
},
235+
},
236+
});
237+
238+
await clock.advance(5_000);
239+
assert.deepEqual(appSignals, [], "supervisor stopped Electron while its parent was alive");
240+
241+
// The launching process died without signalling us; the OS reparented the supervisor.
242+
ppid = 1;
243+
await clock.advance(5_000);
244+
245+
assert.include(
246+
appSignals,
247+
"SIGTERM",
248+
"supervisor kept Electron running after its parent process went away",
249+
);
250+
assert.lengthOf(exitCodes, 1, "supervisor did not exit after its parent process went away");
251+
});
252+
154253
it
155254
// oxlint-disable-next-line t3code/no-global-process-runtime -- Native pgrep is unavailable on Windows.
156255
.skipIf(NodeOS.platform() === "win32")

‎apps/desktop/src/app/DesktopApp.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.
5959
import * as DesktopIpc from "../ipc/DesktopIpc.ts";
6060
import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
6161
import * as DesktopManagedPolicy from "./DesktopManagedPolicy.ts";
62+
import * as DesktopPrimaryPaste from "./DesktopPrimaryPaste.ts";
6263
import * as DesktopSshEnvironment from "../ssh/DesktopSshEnvironment.ts";
6364
import * as DesktopSshPasswordPrompts from "../ssh/DesktopSshPasswordPrompts.ts";
6465
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
@@ -222,6 +223,7 @@ it.effect.each([false, true])(
222223
Layer.mock(DesktopIpc.DesktopIpc, {}),
223224
Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, {}),
224225
Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}),
226+
Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }),
225227
Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}),
226228
Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}),
227229
Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}),

‎apps/desktop/src/app/DesktopCliShim.test.ts‎

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@ const run = (shim: string, args: ReadonlyArray<string>, env: NodeJS.ProcessEnv =
4141
const REPORTER =
4242
'#!/bin/sh\necho "node=$ELECTRON_RUN_AS_NODE cli=$T3CODE_CLI_PATH home=$T3CODE_HOME"\nprintf "%s\\n" "$@"\nexit 3\n';
4343

44-
const fakeAppImage = (canMount = true) => {
44+
const fakeAppImage = (canMount = true, app = REPORTER) => {
4545
const root = tempRoot();
4646
const image = NodePath.join(root, "image");
47-
writeExecutable(NodePath.join(image, "t3code"), REPORTER);
47+
writeExecutable(NodePath.join(image, "t3code"), app);
4848
const appImage = NodePath.join(root, "T3 Code.AppImage");
4949
writeExecutable(
5050
appImage,
@@ -53,8 +53,11 @@ const fakeAppImage = (canMount = true) => {
5353
`if [ "$1" = --appimage-extract ]; then cp -R '${image}' squashfs-root; exit 0; fi`,
5454
'[ "$1" = --appimage-mount ] || exit 9',
5555
'[ -n "$APPIMAGE_EXTRACT_AND_RUN" ] && exit 8',
56+
`echo $$ >'${root}/mounter.pid'`,
5657
canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1',
57-
`trap 'touch "${root}/unmounted"; exit 0' TERM`,
58+
// Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open.
59+
`trap 'echo unmounted >&3 2>/dev/null; touch "${root}/unmounted"; exit 0' TERM HUP INT`,
60+
"trap 'echo mounted >&3 2>/dev/null' WINCH",
5861
"while :; do sleep 0.05; done",
5962
"",
6063
].join("\n"),
@@ -63,7 +66,81 @@ const fakeAppImage = (canMount = true) => {
6366
return { root, image, appImage, shim };
6467
};
6568

69+
// Stays up after a signal until the test lets it finish, like a server shutting down.
70+
const SLOW_SERVER = [
71+
"#!/bin/sh",
72+
"trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP",
73+
"echo ready",
74+
"while :; do sleep 0.05; done",
75+
"",
76+
].join("\n");
77+
78+
// The launcher mounts only under setsid, which stock macOS and Windows lack; there it extracts instead.
79+
const hasSetsid = NodeChildProcess.spawnSync("setsid", ["true"]).status === 0;
80+
81+
const lines = (stream: NodeJS.ReadableStream) => {
82+
const seen: Array<string> = [];
83+
const waiters: Array<() => void> = [];
84+
let buffer = "";
85+
stream.setEncoding("utf8");
86+
stream.on("data", (chunk: string) => {
87+
buffer += chunk;
88+
const parts = buffer.split("\n");
89+
buffer = parts.pop()!;
90+
seen.push(...parts);
91+
for (const wake of waiters.splice(0)) wake();
92+
});
93+
const until = async (match: (line: string) => boolean) => {
94+
for (;;) {
95+
const line = seen.find(match);
96+
if (line !== undefined) return line;
97+
await new Promise<void>((resolve) => waiters.push(resolve));
98+
}
99+
};
100+
return { seen, until };
101+
};
102+
66103
describe("renderCliShim", () => {
104+
it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)(
105+
"keeps the AppImage mounted until the server exits after %s to the process group",
106+
async (signal) => {
107+
const { root, shim } = fakeAppImage(true, SLOW_SERVER);
108+
const child = NodeChildProcess.spawn(shim, [], {
109+
detached: true,
110+
env: { PATH: process.env.PATH },
111+
stdio: ["pipe", "pipe", "ignore", "pipe"],
112+
});
113+
let mounter: number | undefined;
114+
try {
115+
const stdout = lines(child.stdout!);
116+
const events = lines(child.stdio[3] as NodeJS.ReadableStream);
117+
const exited = new Promise((resolve) => child.on("close", resolve));
118+
await stdout.until((line) => line === "ready");
119+
mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8"));
120+
121+
// Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group.
122+
process.kill(-child.pid!, signal);
123+
// The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and
124+
// HUP, so a mounter that also got the group signal unmounts before it answers this probe.
125+
process.kill(mounter, "SIGWINCH");
126+
const mount = await events.until((line) => line === "mounted" || line === "unmounted");
127+
expect(mount).toBe("mounted");
128+
129+
await events.until((line) => line === "stopping");
130+
child.stdin!.end("go\n");
131+
await exited;
132+
expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]);
133+
} finally {
134+
for (const pid of [-child.pid!, mounter]) {
135+
if (pid === undefined) continue;
136+
try {
137+
process.kill(pid, "SIGKILL");
138+
} catch {}
139+
}
140+
}
141+
},
142+
);
143+
67144
it("extracts the AppImage where it cannot be mounted", () => {
68145
const { shim } = fakeAppImage(false);
69146
const result = run(shim, ["--version"], { APPIMAGE_EXTRACT_AND_RUN: "1" });

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,13 @@ export const renderCliShim = (input: {
9090
...header,
9191
// Extract-and-run would make the runtime start the app instead of mounting it.
9292
"unset APPIMAGE_EXTRACT_AND_RUN",
93-
// The runtime stays mounted until killed; traps unmount it because background jobs ignore Ctrl-C.
93+
// Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the
94+
// running server; the traps unmount it after. Without setsid the extract fallback runs.
9495
"work=$(mktemp -d) || exit 1",
95-
'"$app" --appimage-mount >"$work/mount" 2>/dev/null &',
96+
'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &',
9697
"mounter=$!",
9798
`trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`,
98-
"trap 'exit 130' INT TERM",
99+
"trap 'exit 130' INT TERM HUP",
99100
"mount=",
100101
'while kill -0 "$mounter" 2>/dev/null; do',
101102
' mount=$(head -n 1 "$work/mount")',

‎apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,11 @@ interface RecordedRegistration {
2626
readonly files: Array<{ readonly path: string; readonly content: string }>;
2727
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
2828
readonly copies: Array<{ readonly source: string; readonly destination: string }>;
29+
readonly icons: Array<{ readonly path: string; readonly bytes: ReadonlyArray<number> }>;
2930
}
3031

32+
const ICON_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
33+
3134
const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
3235
DesktopEnvironment.DesktopEnvironment.of({
3336
platform: "linux",
@@ -69,7 +72,7 @@ const layerHandler = (
6972
readonly writeError?: PlatformError.PlatformError;
7073
readonly existingEntry?: string;
7174
readonly iconSource?: string;
72-
readonly iconCopyError?: PlatformError.PlatformError;
75+
readonly iconWriteError?: PlatformError.PlatformError;
7376
} = {},
7477
) =>
7578
DesktopLinuxUrlHandler.layer.pipe(
@@ -92,10 +95,25 @@ const layerHandler = (
9295
}),
9396
FileSystem.layerNoop({
9497
copyFile: (source, destination) =>
95-
input.iconCopyError
96-
? Effect.fail(input.iconCopyError)
98+
Effect.sync(() => {
99+
recorded.copies.push({ source, destination });
100+
}),
101+
readFile: (path) =>
102+
path === input.iconSource
103+
? Effect.succeed(ICON_BYTES)
104+
: Effect.fail(
105+
PlatformError.systemError({
106+
_tag: "NotFound",
107+
module: "FileSystem",
108+
method: "readFile",
109+
pathOrDescriptor: path,
110+
}),
111+
),
112+
writeFile: (path, bytes) =>
113+
input.iconWriteError
114+
? Effect.fail(input.iconWriteError)
97115
: Effect.sync(() => {
98-
recorded.copies.push({ source, destination });
116+
recorded.icons.push({ path, bytes: [...bytes] });
99117
}),
100118
readFileString: () => Effect.succeed(input.existingEntry ?? ""),
101119
makeDirectory: (path) =>
@@ -162,6 +180,7 @@ const emptyRecording = (): RecordedRegistration => ({
162180
files: [],
163181
commands: [],
164182
copies: [],
183+
icons: [],
165184
});
166185

167186
describe("DesktopLinuxUrlHandler", () => {
@@ -290,22 +309,21 @@ describe("DesktopLinuxUrlHandler", () => {
290309
}),
291310
});
292311
assert.deepEqual(recorded.files, []);
293-
assert.deepEqual(recorded.copies, [
294-
{ source: "/tmp/.mount_T3/resources/icon.png", destination: iconPath },
295-
]);
312+
assert.deepEqual(recorded.copies, [], "icon must not be copied out of the app bundle");
313+
assert.deepEqual(recorded.icons, [{ path: iconPath, bytes: [...ICON_BYTES] }]);
296314
assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
297315
});
298316
});
299317

300-
it.effect("still registers the handler when copying its icon fails", () => {
318+
it.effect("still registers the handler when installing its icon fails", () => {
301319
const recorded = emptyRecording();
302320
return Effect.gen(function* () {
303321
yield* runRegister(recorded, {
304322
iconSource: "/tmp/.mount_T3/resources/icon.png",
305-
iconCopyError: PlatformError.systemError({
323+
iconWriteError: PlatformError.systemError({
306324
_tag: "PermissionDenied",
307325
module: "FileSystem",
308-
method: "copyFile",
326+
method: "writeFile",
309327
description: "read-only icon directory",
310328
}),
311329
});

0 commit comments

Comments
 (0)