Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(desktop): own dev and smoke Electron processes instead of pkill (#182)
Leo1d175152137b
diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjsindex c28d5ec35..28c468d63 100644--- a/apps/desktop/scripts/dev-electron.mjs+++ b/apps/desktop/scripts/dev-electron.mjs@@ -32,7 +32,6 @@ const watchedDirectories = [];const forcedShutdownTimeoutMs = 1_500;const restartDebounceMs = 120;-const childTreeGracePeriodMs = 1_200;const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime.const hostPlatform = NodeOS.platform();@@ -59,22 +58,35 @@ let restartQueue = Promise.resolve();const expectedExits = new WeakSet();const watchers = [];-function killChildTreeByPid(pid, signal) {- if (hostPlatform === "win32" || typeof pid !== "number") {+const ownedProcessGroups = new Map();++function signalApp(app, signal) {+ if (hostPlatform === "win32") {+ app.kill(signal);return;}- NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });-}--function cleanupStaleDevApps() {- if (hostPlatform === "win32") {+ const pid = ownedProcessGroups.get(app);+ if (pid === undefined) {return;}- NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], {- stdio: "ignore",- });+ try {+ process.kill(-pid, signal);+ } catch (error) {+ if (error.code !== "ESRCH") {+ throw error;+ }+ ownedProcessGroups.delete(app);+ }+}++function releaseApp(app) {+ // The group can outlive its leader. Clean it before releasing ownership.+ if (hostPlatform !== "win32") {+ signalApp(app, "SIGKILL");+ ownedProcessGroups.delete(app);+ }}function startApp() {@@ -83,7 +95,7 @@ function startApp() {}const electronArgs = remoteDebuggingPort- ? [`--remote-debugging-port=${remoteDebuggingPort}`]+ ? ["--remote-debugging-address=127.0.0.1", `--remote-debugging-port=${remoteDebuggingPort}`]: [];const launchArgs = devProtocolClient? electronArgs@@ -93,11 +105,16 @@ function startApp() {cwd: desktopDir,env: childEnv,stdio: "inherit",+ detached: hostPlatform !== "win32",});+ if (hostPlatform !== "win32" && Number.isInteger(app.pid) && app.pid > 0) {+ ownedProcessGroups.set(app, app.pid);+ }currentApp = app;app.once("error", () => {+ releaseApp(app);if (currentApp === app) {currentApp = null;}@@ -108,6 +125,7 @@ function startApp() {});app.once("exit", (code, signal) => {+ releaseApp(app);if (currentApp === app) {currentApp = null;}@@ -137,24 +155,19 @@ async function stopApp() {}settled = true;+ clearTimeout(forceTimer);+ app.removeListener("exit", finish);resolve();};- app.once("exit", finish);- app.kill("SIGTERM");- killChildTreeByPid(app.pid, "TERM");- cleanupStaleDevApps();-- setTimeout(() => {- if (settled) {- return;- }-- app.kill("SIGKILL");- killChildTreeByPid(app.pid, "KILL");- cleanupStaleDevApps();+ const forceTimer = setTimeout(() => {+ signalApp(app, "SIGKILL");+ ownedProcessGroups.delete(app);finish();- }, forcedShutdownTimeoutMs).unref();+ }, forcedShutdownTimeoutMs);++ app.once("exit", finish);+ signalApp(app, "SIGTERM");});}@@ -198,17 +211,6 @@ function startWatchers() {}}-function killChildTree(signal) {- if (hostPlatform === "win32") {- return;- }-- // Kill direct children as a final fallback in case normal shutdown leaves stragglers.- NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], {- stdio: "ignore",- });-}-async function shutdown(exitCode) {if (shuttingDown) return;shuttingDown = true;@@ -222,18 +224,13 @@ async function shutdown(exitCode) {watcher.close();}+ await restartQueue.catch(() => undefined);await stopApp();- killChildTree("TERM");- await new Promise((resolve) => {- setTimeout(resolve, childTreeGracePeriodMs);- });- killChildTree("KILL");process.exit(exitCode);}startWatchers();-cleanupStaleDevApps();startApp();process.once("SIGINT", () => {diff --git a/apps/desktop/scripts/dev-electron.test.mjs b/apps/desktop/scripts/dev-electron.test.mjsnew file mode 100644index 000000000..0b1e28f9b--- /dev/null+++ b/apps/desktop/scripts/dev-electron.test.mjs@@ -0,0 +1,319 @@+import * as NodeEvents from "node:events";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({+ spawn: vi.fn(),+ spawnSync: vi.fn(),+ watch: vi.fn(),+ platform: vi.fn(),+ resolveDevProtocolClient: vi.fn(),+ resolveElectronLaunchCommand: vi.fn(),+ waitForResources: vi.fn(),+}));++vi.mock("node:child_process", () => ({ spawn: mocks.spawn, spawnSync: mocks.spawnSync }));+vi.mock("node:fs", () => ({ watch: mocks.watch }));+vi.mock("node:os", () => ({ platform: mocks.platform }));+vi.mock("./electron-launcher.mjs", () => ({+ desktopDir: "/repo/apps/desktop",+ resolveDevProtocolClient: mocks.resolveDevProtocolClient,+ resolveElectronLaunchCommand: mocks.resolveElectronLaunchCommand,+}));+vi.mock("./wait-for-resources.mjs", () => ({ waitForResources: mocks.waitForResources }));++const killProcess = process.kill.bind(process);++let apps;+let watchers;+let signals;+let kill;+let exit;++async function launch(platform = "darwin") {+ mocks.platform.mockReturnValue(platform);+ await import("./dev-electron.mjs");+}++async function changeBuild() {+ watchers[0].onChange("change", "main.cjs");+ await vi.advanceTimersByTimeAsync(120);+}++describe("desktop development process ownership", () => {+ beforeEach(() => {+ vi.resetModules();+ vi.resetAllMocks();+ vi.useFakeTimers();+ vi.stubEnv("VITE_DEV_SERVER_URL", "http://localhost:5173");+ vi.stubEnv("T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT", "");+ apps = [];+ watchers = [];+ signals = new Map();+ kill = vi.spyOn(process, "kill").mockReturnValue(true);+ exit = vi.spyOn(process, "exit").mockImplementation(() => undefined);+ vi.spyOn(process, "once").mockImplementation((signal, listener) => {+ signals.set(signal, listener);+ return process;+ });+ mocks.resolveElectronLaunchCommand.mockImplementation((args) => ({+ electronPath: "/runtime/Electron",+ args,+ }));+ mocks.spawn.mockImplementation(() => {+ const app = new NodeEvents.EventEmitter();+ app.pid = 4100 + apps.length;+ app.kill = vi.fn();+ apps.push(app);+ return app;+ });+ mocks.watch.mockImplementation((_directory, _options, onChange) => {+ const watcher = { onChange, close: vi.fn() };+ watchers.push(watcher);+ return watcher;+ });+ });++ afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ });++ it.each(["darwin", "linux"])(+ "starts an isolated group on %s without cleaning pre-existing processes",+ async (platform) => {+ await launch(platform);++ expect(mocks.spawn).toHaveBeenCalledExactlyOnceWith(+ "/runtime/Electron",+ ["--t3code-dev-root=/repo/apps/desktop", "dist-electron/main.cjs"],+ expect.objectContaining({ detached: true, stdio: "inherit" }),+ );+ expect(kill).not.toHaveBeenCalled();+ expect(mocks.spawnSync).not.toHaveBeenCalled();+ },+ );++ it.each([undefined, { appBundleId: "dev.akeru.test" }])(+ "binds enabled remote debugging to loopback with protocol client %j",+ async (protocolClient) => {+ vi.stubEnv("T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT", " 9222 ");+ mocks.resolveDevProtocolClient.mockReturnValue(protocolClient);+ await launch();++ expect(mocks.resolveElectronLaunchCommand).toHaveBeenCalledExactlyOnceWith(+ expect.arrayContaining([+ "--remote-debugging-address=127.0.0.1",+ "--remote-debugging-port=9222",+ ]),+ );+ },+ );++ it("stops only the captured group and waits for exit before restarting", async () => {+ await launch();+ const app = apps[0];+ app.pid = 9999;+ await changeBuild();++ expect(kill.mock.calls).toEqual([[-4100, "SIGTERM"]]);+ expect(mocks.spawn).toHaveBeenCalledTimes(1);+ app.emit("exit", 0, null);+ await vi.advanceTimersByTimeAsync(0);++ expect(kill.mock.calls).toEqual([+ [-4100, "SIGTERM"],+ [-4100, "SIGKILL"],+ ]);+ expect(app.kill).not.toHaveBeenCalled();+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1500);+ expect(kill).toHaveBeenCalledTimes(2);+ expect(mocks.spawnSync).not.toHaveBeenCalled();+ });++ it("forces only the owned group and does not signal it again on a late exit", async () => {+ await launch();+ await changeBuild();+ await vi.advanceTimersByTimeAsync(1500);++ expect(kill.mock.calls).toEqual([+ [-4100, "SIGTERM"],+ [-4100, "SIGKILL"],+ ]);+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ apps[0].emit("exit", null, "SIGKILL");+ await vi.advanceTimersByTimeAsync(1500);+ expect(kill).toHaveBeenCalledTimes(2);+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ });++ it("cleans remaining group members after a crash and restarts", async () => {+ await launch();+ apps[0].emit("exit", 1, null);+ expect(kill.mock.calls).toEqual([[-4100, "SIGKILL"]]);+ await vi.advanceTimersByTimeAsync(120);+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ });++ it("cleans remaining group members after a normal exit without restarting", async () => {+ await launch();+ apps[0].emit("exit", 0, null);+ await vi.advanceTimersByTimeAsync(2000);+ expect(kill.mock.calls).toEqual([[-4100, "SIGKILL"]]);+ expect(mocks.spawn).toHaveBeenCalledTimes(1);+ });++ it("retries a failed spawn without signaling an unknown PID", async () => {+ mocks.spawn.mockImplementationOnce(() => {+ const app = new NodeEvents.EventEmitter();+ apps.push(app);+ return app;+ });+ await launch();+ apps[0].emit("error", new Error("spawn failed"));+ await vi.advanceTimersByTimeAsync(120);+ expect(kill).not.toHaveBeenCalled();+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ });++ it("releases a missing group without retrying its PID", async () => {+ await launch();+ kill.mockImplementationOnce(() => {+ throw Object.assign(new Error("missing group"), { code: "ESRCH" });+ });+ await changeBuild();+ apps[0].emit("exit", 0, null);+ await vi.advanceTimersByTimeAsync(1500);+ expect(kill.mock.calls).toEqual([[-4100, "SIGTERM"]]);+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ });++ it.each([+ ["SIGINT", 130],+ ["SIGTERM", 143],+ ["SIGHUP", 129],+ ])("waits for an active restart cleanup on %s without spawning again", async (signal, code) => {+ await launch();+ await changeBuild();+ signals.get(signal)();+ expect(exit).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1500);++ expect(exit).toHaveBeenCalledExactlyOnceWith(code);+ expect(mocks.spawn).toHaveBeenCalledTimes(1);+ expect(kill.mock.calls).toEqual([+ [-4100, "SIGTERM"],+ [-4100, "SIGKILL"],+ ]);+ expect(watchers[0].close).toHaveBeenCalledOnce();+ expect(watchers[1].close).toHaveBeenCalledOnce();+ expect(mocks.spawnSync).not.toHaveBeenCalled();+ });++ it("cancels a pending restart during shutdown", async () => {+ await launch();+ watchers[0].onChange("change", "main.cjs");+ signals.get("SIGTERM")();+ await vi.advanceTimersByTimeAsync(0);+ apps[0].emit("exit", 0, null);+ await vi.advanceTimersByTimeAsync(2000);+ expect(mocks.spawn).toHaveBeenCalledTimes(1);+ expect(exit).toHaveBeenCalledExactlyOnceWith(143);+ });++ // oxlint-disable-next-line t3code/no-global-process-runtime -- Process-group smoke tests require POSIX signals.+ it.skipIf(process.platform === "win32").each([false, true])(+ "cleans a real owned child and grandchild, with forced shutdown %s",+ async (forceShutdown) => {+ const { spawn } = await vi.importActual("node:child_process");+ const grandchildScript = `+ process.on("SIGTERM", () => {});+ process.send("ready");+ setInterval(() => {}, 1000);+ `;+ const childScript = `+ const { spawn } = require("node:child_process");+ process.on("SIGTERM", () => { ${forceShutdown ? "" : "process.exit(0);"} });+ const grandchild = spawn(process.execPath, ["-e", ${JSON.stringify(grandchildScript)}], {+ stdio: ["ignore", "inherit", "inherit", "ipc"],+ });+ grandchild.once("message", () => process.send("ready"));+ setInterval(() => {}, 1000);+ `;+ const unrelated = spawn(+ process.execPath,+ [+ "-e",+ `+ process.on("message", () => process.send("alive"));+ process.send("ready");+ `,+ ],+ { stdio: ["ignore", "ignore", "ignore", "ipc"] },+ );+ const unrelatedExit = NodeEvents.once(unrelated, "exit");+ let app;+ let ready;+ let closed;+ let appClosed = false;+ try {+ await NodeEvents.once(unrelated, "message");+ mocks.spawn.mockImplementationOnce(() => {+ app = spawn(process.execPath, ["-e", childScript], {+ detached: true,+ stdio: ["ignore", "pipe", "pipe", "ipc"],+ });+ ready = NodeEvents.once(app, "message");+ // Inherited pipes close only after both processes release them.+ closed = NodeEvents.once(app, "close").then(() => {+ appClosed = true;+ });+ return app;+ });+ kill.mockImplementation(killProcess);+ await launch();+ await ready;+ signals.get("SIGTERM")();+ await vi.advanceTimersByTimeAsync(0);+ expect(kill).toHaveBeenCalledWith(-app.pid, "SIGTERM");+ if (!forceShutdown) {+ await closed;+ }+ await vi.advanceTimersByTimeAsync(1500);+ await closed;+ await vi.advanceTimersByTimeAsync(0);++ expect(kill.mock.calls).toEqual([+ [-app.pid, "SIGTERM"],+ [-app.pid, "SIGKILL"],+ ]);+ expect(exit).toHaveBeenCalledExactlyOnceWith(143);+ expect(mocks.spawn).toHaveBeenCalledTimes(1);+ const reply = NodeEvents.once(unrelated, "message");+ unrelated.send("ping");+ expect(await reply).toEqual(["alive", undefined]);+ } finally {+ if (app && !appClosed) {+ killProcess(-app.pid, "SIGKILL");+ await closed;+ }+ unrelated.kill("SIGKILL");+ await unrelatedExit;+ }+ },+ );++ it("uses only the spawned child on Windows", async () => {+ await launch("win32");+ expect(mocks.spawn.mock.calls[0][2].detached).toBe(false);+ await changeBuild();+ expect(apps[0].kill).toHaveBeenCalledExactlyOnceWith("SIGTERM");+ await vi.advanceTimersByTimeAsync(1500);+ expect(apps[0].kill.mock.calls).toEqual([["SIGTERM"], ["SIGKILL"]]);+ expect(kill).not.toHaveBeenCalled();+ expect(mocks.spawnSync).not.toHaveBeenCalled();+ expect(mocks.spawn).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/scripts/smoke-test.mjs b/apps/desktop/scripts/smoke-test.mjsindex fea5f0a12..9255d0776 100644--- a/apps/desktop/scripts/smoke-test.mjs+++ b/apps/desktop/scripts/smoke-test.mjs@@ -1,58 +1,206 @@import * as NodeChildProcess from "node:child_process";+import * as NodeFS from "node:fs";+import * as NodeModule from "node:module";+import * as NodeOS from "node:os";import * as NodePath from "node:path";import * as NodeURL from "node:url";-import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";-const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));-const desktopDir = NodePath.resolve(__dirname, "..");-const mainJs = NodePath.resolve(desktopDir, "dist-electron/main.cjs");+const desktopDir = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");+const fatalPattern =+ /Cannot find module|MODULE_NOT_FOUND|Refused to execute|Uncaught\b|fatal startup error|render-process-gone|main window render process gone|main window failed to load|renderer process crashed|Failed to load URL/i;+const readinessMarkers = ["backend ready", "main window created"];-console.log("\nLaunching Electron smoke test...");+export function resolveSmokeElectronPath() {+ const require = NodeModule.createRequire(import.meta.url);+ const packageDir = NodePath.dirname(require.resolve("electron/package.json"));+ // Read the installed runtime directly; the branded launcher registers OS URL schemes.+ const relativePath = NodeFS.readFileSync(NodePath.join(packageDir, "path.txt"), "utf8").trim();+ const distDir = NodePath.join(packageDir, "dist");+ const executable = NodePath.resolve(distDir, relativePath);+ if (!relativePath || !executable.startsWith(`${distDir}${NodePath.sep}`)) {+ throw new Error("Invalid installed Electron executable path.");+ }+ NodeFS.accessSync(executable, NodeFS.constants.X_OK);+ return executable;+}-const electronCommand = resolveElectronLaunchCommand([mainJs]);-const child = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, {- stdio: ["pipe", "pipe", "pipe"],- env: {- ...process.env,- VITE_DEV_SERVER_URL: "",+export function createSmokeEnvironment(root, inherited = process.env) {+ const env = Object.fromEntries(+ Object.entries(inherited).filter(+ ([key]) =>+ !/^(T3CODE_|AKERU_|VITE_|ELECTRON_|NODE_OPTIONS$|NODE_PATH$|APPIMAGE$|APPDIR$|HOME$|USERPROFILE$|HOMEDRIVE$|HOMEPATH$|APPDATA$|LOCALAPPDATA$|XDG_(CONFIG|DATA|CACHE|STATE)_HOME$|TMPDIR$|TMP$|TEMP$)/i.test(+ key,+ ),+ ),+ );+ const home = NodePath.join(root, "home");+ return {+ ...env,+ HOME: home,+ USERPROFILE: home,+ TMPDIR: NodePath.join(root, "tmp"),+ TMP: NodePath.join(root, "tmp"),+ TEMP: NodePath.join(root, "tmp"),+ HOMEDRIVE: NodePath.parse(home).root.replace(/[\\/]$/, ""),+ HOMEPATH: home.slice(NodePath.parse(home).root.length - 1),+ APPDATA: NodePath.join(home, "AppData", "Roaming"),+ LOCALAPPDATA: NodePath.join(home, "AppData", "Local"),+ XDG_CONFIG_HOME: NodePath.join(home, ".config"),+ XDG_DATA_HOME: NodePath.join(home, ".local", "share"),+ XDG_CACHE_HOME: NodePath.join(home, ".cache"),+ XDG_STATE_HOME: NodePath.join(home, ".local", "state"),+ T3CODE_HOME: NodePath.join(root, "akeru"),+ AKERU_HOME: NodePath.join(root, "akeru"),+ T3CODE_DISABLE_AUTO_UPDATE: "true",ELECTRON_ENABLE_LOGGING: "1",- },-});--let output = "";-child.stdout.on("data", (chunk) => {- output += chunk.toString();-});-child.stderr.on("data", (chunk) => {- output += chunk.toString();-});--const timeout = setTimeout(() => {- child.kill();-}, 8_000);--child.on("exit", () => {- clearTimeout(timeout);+ };+}- const fatalPatterns = [- "Cannot find module",- "MODULE_NOT_FOUND",- "Refused to execute",- "Uncaught Error",- "Uncaught TypeError",- "Uncaught ReferenceError",- ];- const failures = fatalPatterns.filter((pattern) => output.includes(pattern));-- if (failures.length > 0) {- console.error("\nDesktop smoke test failed:");- for (const failure of failures) {- console.error(` - ${failure}`);+export async function runSmokeTest({ timeoutMs = 30_000, shutdownMs = 1_500 } = {}) {+ const electronPath = resolveSmokeElectronPath();+ const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "akeru-desktop-smoke-"));+ let child;+ let pid;+ let closed = false;+ let exited = false;+ let output = "";+ let timer;+ let closePromise;+ const signals = new Map();+ // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone smoke script has no Effect runtime.+ const grouped = NodeOS.platform() !== "win32";+ const signalChild = (signal) => {+ if (!pid) return;+ try {+ if (grouped) process.kill(-pid, signal);+ else {+ // Kill the captured tree so a spawned backend cannot outlive cleanup.+ NodeChildProcess.spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"]);+ if (!closed) child.kill(signal);+ }+ } catch (error) {+ if (error.code !== "ESRCH") throw error;+ pid = undefined;+ }+ };+ const cleanup = async () => {+ if (pid) {+ const waitForClose = async () => {+ let deadline;+ try {+ await Promise.race([+ closePromise,+ new Promise((resolve) => {+ deadline = setTimeout(resolve, shutdownMs);+ }),+ ]);+ } finally {+ clearTimeout(deadline);+ }+ };+ signalChild("SIGTERM");+ await waitForClose();+ // A stopped parent can leave backend or renderer children in its group.+ signalChild("SIGKILL");+ if (!closed) await waitForClose();+ if (!closed) throw new Error(`Desktop did not close; retained smoke directory at ${root}.`);+ }+ NodeFS.rmSync(root, { recursive: true, force: true });+ };+ try {+ const env = createSmokeEnvironment(root);+ for (const directory of [+ env.HOME,+ env.TMPDIR,+ env.APPDATA,+ env.LOCALAPPDATA,+ env.XDG_CONFIG_HOME,+ env.XDG_DATA_HOME,+ env.XDG_CACHE_HOME,+ env.XDG_STATE_HOME,+ env.T3CODE_HOME,+ ]) {+ NodeFS.mkdirSync(directory, { recursive: true });+ }+ child = NodeChildProcess.spawn(+ electronPath,+ [+ "--no-default-browser-check",+ "--no-default-protocol-client",+ `--user-data-dir=${NodePath.join(root, "chromium")}`,+ NodePath.join(desktopDir, "dist-electron/main.cjs"),+ ],+ { cwd: desktopDir, detached: grouped, stdio: ["ignore", "pipe", "pipe"], env },+ );+ pid = child.pid;+ closePromise = new Promise((resolve) =>+ child.once("close", () => {+ closed = true;+ resolve();+ }),+ );+ await new Promise((resolve, reject) => {+ const capture = (chunk) => {+ output = (output + chunk.toString()).slice(-1_000_000);+ if (fatalPattern.test(output)) reject(new Error("Fatal desktop startup error."));+ };+ child.stdout.on("data", capture);+ child.stderr.on("data", capture);+ child.once("error", reject);+ child.once("exit", (code, signal) => {+ exited = true;+ reject(+ new Error(+ `Desktop exited before the observation period ended (code ${code}, signal ${signal}).`,+ ),+ );+ });+ child.once("close", () =>+ reject(new Error("Desktop closed before startup verification completed.")),+ );+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {+ const listener = () => reject(new Error(`Desktop smoke test interrupted by ${signal}.`));+ signals.set(signal, listener);+ process.once(signal, listener);+ }+ timer = setTimeout(() => {+ const missing = readinessMarkers.filter((marker) => !output.includes(marker));+ if (exited || closed || missing.length > 0) {+ reject(+ new Error(+ `Desktop startup readiness timed out. Missing: ${missing.join(", ") || "live process"}.`,+ ),+ );+ } else {+ resolve();+ }+ }, timeoutMs);+ });+ return "Desktop startup smoke test passed: backend ready and main window created. Renderer content and interaction were not verified.";+ } catch (error) {+ throw new Error(`${error.message}${output ? `\nDesktop output:\n${output}` : ""}`, {+ cause: error,+ });+ } finally {+ clearTimeout(timer);+ // Keep signal handlers installed until the owned process group has stopped.+ try {+ await cleanup();+ } finally {+ for (const [signal, listener] of signals) process.removeListener(signal, listener);}- console.error("\nFull output:\n" + output);- process.exit(1);}+}- console.log("Desktop smoke test passed.");- process.exit(0);-});+if (+ process.argv[1] &&+ NodeURL.pathToFileURL(NodePath.resolve(process.argv[1])).href === import.meta.url+) {+ runSmokeTest().then(+ (message) => console.log(message),+ (error) => {+ console.error(error.message);+ process.exitCode = 1;+ },+ );+}diff --git a/apps/desktop/scripts/smoke-test.test.mjs b/apps/desktop/scripts/smoke-test.test.mjsnew file mode 100644index 000000000..1f9c6db31--- /dev/null+++ b/apps/desktop/scripts/smoke-test.test.mjs@@ -0,0 +1,321 @@+import * as NodeEvents from "node:events";+import * as NodePath from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ spawn: vi.fn(),+ spawnSync: vi.fn(() => ({ status: 0 })),+ mkdtempSync: vi.fn(),+ mkdirSync: vi.fn(),+ rmSync: vi.fn(),+ readFileSync: vi.fn(),+ accessSync: vi.fn(),+ platform: vi.fn(),+ resolve: vi.fn(),+}));+vi.mock("node:child_process", () => ({ spawn: mocks.spawn, spawnSync: mocks.spawnSync }));+vi.mock("node:fs", () => ({ ...mocks, constants: { X_OK: 1 } }));+vi.mock("node:os", () => ({ platform: mocks.platform, tmpdir: () => "/tmp" }));+vi.mock("node:module", () => ({ createRequire: () => ({ resolve: mocks.resolve }) }));++import { createSmokeEnvironment, resolveSmokeElectronPath, runSmokeTest } from "./smoke-test.mjs";++const root = "/tmp/akeru-desktop-smoke-owned";+const ready = "[desktop-window] backend ready\n[desktop-window] main window created\n";+let app;+let kill;+let signals;++function launch() {+ // Attach rejection handling before advancing fake time.+ return runSmokeTest({ timeoutMs: 100, shutdownMs: 10 }).then(+ (message) => ({ message }),+ (error) => ({ error }),+ );+}++function close() {+ app.emit("exit", 0, null);+ app.emit("close", 0, null);+}++beforeEach(() => {+ vi.resetAllMocks();+ vi.useFakeTimers();+ mocks.platform.mockReturnValue("darwin");+ mocks.resolve.mockReturnValue("/installed/electron/package.json");+ mocks.readFileSync.mockReturnValue("Electron.app/Contents/MacOS/Electron\n");+ mocks.mkdtempSync.mockReturnValue(root);+ app = new NodeEvents.EventEmitter();+ app.pid = 4100;+ app.stdout = new NodeEvents.EventEmitter();+ app.stderr = new NodeEvents.EventEmitter();+ app.kill = vi.fn(() => {+ close();+ return true;+ });+ mocks.spawn.mockReturnValue(app);+ kill = vi.spyOn(process, "kill").mockImplementation(() => {+ close();+ return true;+ });+ signals = new Map();+ vi.spyOn(process, "once").mockImplementation((signal, listener) => {+ signals.set(signal, listener);+ return process;+ });+ vi.spyOn(process, "removeListener").mockReturnValue(process);+});++afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+});++describe("desktop smoke isolation", () => {+ it("replaces both homes and every persistent OS profile path and removes inherited launch context", () => {+ const inherited = {+ HOME: "/live",+ USERPROFILE: "/live",+ UserProfile: "/live-case-insensitive",+ TMPDIR: "/live/tmp",+ TEMP: "/live/tmp",+ TMP: "/live/tmp",+ APPDATA: "/live",+ LOCALAPPDATA: "/live",+ XDG_CONFIG_HOME: "/live",+ XDG_DATA_HOME: "/live",+ XDG_CACHE_HOME: "/live",+ T3CODE_HOME: "/live",+ AKERU_HOME: "/live",+ T3CODE_PORT: "3773",+ T3CODE_DESKTOP_LAN_HOST: "0.0.0.0",+ T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH: "/live/server",+ VITE_DEV_SERVER_URL: "http://live",+ VITE_WS_URL: "ws://live",+ ELECTRON_RUN_AS_NODE: "1",+ ELECTRON_OVERRIDE_DIST_PATH: "/branded",+ NODE_OPTIONS: "--require /live/hook",+ NODE_PATH: "/live/modules",+ PATH: "/bin",+ };+ const env = createSmokeEnvironment(root, inherited);+ for (const key of [+ "HOME",+ "USERPROFILE",+ "TMPDIR",+ "TMP",+ "TEMP",+ "APPDATA",+ "LOCALAPPDATA",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_STATE_HOME",+ "T3CODE_HOME",+ "AKERU_HOME",+ ]) {+ expect(env[key].startsWith(`${root}/`)).toBe(true);+ }+ for (const key of [+ "T3CODE_PORT",+ "T3CODE_DESKTOP_LAN_HOST",+ "T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH",+ "VITE_DEV_SERVER_URL",+ "VITE_WS_URL",+ "ELECTRON_RUN_AS_NODE",+ "ELECTRON_OVERRIDE_DIST_PATH",+ "NODE_OPTIONS",+ "NODE_PATH",+ ])+ expect(env).not.toHaveProperty(key);+ expect(env).not.toHaveProperty("UserProfile");+ expect(env.PATH).toBe("/bin");+ expect(inherited.HOME).toBe("/live");+ });++ it("uses only the installed raw runtime, without the launcher or an inherited override", async () => {+ vi.stubEnv("ELECTRON_OVERRIDE_DIST_PATH", "/branded");+ const result = launch();+ expect(mocks.spawn).toHaveBeenCalledWith(+ "/installed/electron/dist/Electron.app/Contents/MacOS/Electron",+ expect.arrayContaining(["--no-default-protocol-client", `--user-data-dir=${root}/chromium`]),+ expect.objectContaining({+ detached: true,+ env: expect.objectContaining({ HOME: `${root}/home` }),+ }),+ );+ close();+ await result;+ expect(mocks.rmSync).toHaveBeenCalledExactlyOnceWith(root, { recursive: true, force: true });+ });++ it.each(["", "../../launcher", "/branded/Electron"])(+ "rejects invalid runtime path %j before creating state",+ (path) => {+ mocks.readFileSync.mockReturnValue(path);+ expect(() => resolveSmokeElectronPath()).toThrow("Invalid installed");+ expect(mocks.mkdtempSync).not.toHaveBeenCalled();+ expect(mocks.spawn).not.toHaveBeenCalled();+ },+ );++ it("does not install a missing runtime", async () => {+ mocks.accessSync.mockImplementation(() => {+ throw new Error("runtime missing");+ });+ expect((await launch()).error.message).toContain("runtime missing");+ expect(mocks.spawn).not.toHaveBeenCalled();+ expect(mocks.rmSync).not.toHaveBeenCalled();+ });+});++describe("desktop startup evidence and cleanup", () => {+ it.each([0, 1, null])(+ "rejects an early exit with code %j, even with readiness logs",+ async (code) => {+ const result = launch();+ app.stdout.emit("data", ready);+ app.emit("exit", code, code === null ? "SIGSEGV" : null);+ expect((await result).error.message).toContain("exited before");+ expect(kill.mock.calls).toEqual([+ [-4100, "SIGTERM"],+ [-4100, "SIGKILL"],+ ]);+ },+ );++ it.each(["", "app ready", "backend ready", "main window created"])(+ "fails at the deadline without both readiness markers: %j",+ async (output) => {+ const result = launch();+ app.stdout.emit("data", output);+ await vi.advanceTimersByTimeAsync(100);+ expect((await result).error.message).toContain("readiness timed out");+ expect(mocks.rmSync).toHaveBeenCalledOnce();+ },+ );++ it("requires the full observation period and reports startup evidence, not renderer verification", async () => {+ const result = launch();+ app.stdout.emit("data", "backend rea");+ app.stdout.emit("data", "dy\nmain window created");+ await vi.advanceTimersByTimeAsync(99);+ expect(kill).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect((await result).message).toContain("Renderer content and interaction were not verified");+ expect(mocks.rmSync).toHaveBeenCalledExactlyOnceWith(root, { recursive: true, force: true });+ expect(process.removeListener).toHaveBeenCalledTimes(3);+ });++ it.each([+ "Cannot find module",+ "MODULE_NOT_FOUND",+ "Refused to execute",+ "Uncaught TypeError",+ "fatal startup error",+ "render-process-gone",+ "main window render process gone",+ "main window failed to load",+ "Failed to load URL",+ ])("fails immediately on %s after readiness", async (failure) => {+ const result = launch();+ app.stdout.emit("data", ready);+ app.stderr.emit("data", failure.slice(0, 4));+ app.stderr.emit("data", failure.slice(4));+ expect((await result).error.message).toContain("Fatal desktop startup error");+ });++ it("cleans the exact directory after a synchronous spawn failure without signaling", async () => {+ mocks.spawn.mockImplementation(() => {+ throw new Error("spawn failed");+ });+ expect((await launch()).error.message).toContain("spawn failed");+ expect(kill).not.toHaveBeenCalled();+ expect(mocks.rmSync).toHaveBeenCalledExactlyOnceWith(root, { recursive: true, force: true });+ });++ it("handles an asynchronous spawn error without a PID", async () => {+ app.pid = undefined;+ const result = launch();+ app.emit("error", new Error("ENOENT"));+ expect((await result).error.message).toContain("ENOENT");+ expect(kill).not.toHaveBeenCalled();+ expect(mocks.rmSync).toHaveBeenCalledOnce();+ });++ it("escalates only the captured group and waits for close before deleting state", async () => {+ kill.mockImplementation((_pid, signal) => {+ if (signal === "SIGKILL") close();+ return true;+ });+ const result = launch();+ app.pid = 9999;+ signals.get("SIGTERM")();+ await vi.advanceTimersByTimeAsync(0);+ expect(kill.mock.calls).toEqual([[-4100, "SIGTERM"]]);+ expect(mocks.rmSync).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(10);+ expect((await result).error.message).toContain("interrupted by SIGTERM");+ expect(kill.mock.calls).toEqual([+ [-4100, "SIGTERM"],+ [-4100, "SIGKILL"],+ ]);+ expect(mocks.rmSync).toHaveBeenCalledOnce();+ });++ it("retains state when the owned process does not close", async () => {+ kill.mockReturnValue(true);+ const result = launch();+ signals.get("SIGINT")();+ await vi.advanceTimersByTimeAsync(20);+ expect((await result).error.message).toContain(`retained smoke directory at ${root}`);+ expect(mocks.rmSync).not.toHaveBeenCalled();+ });++ it("does not retry a missing process group", async () => {+ kill.mockImplementation(() => {+ close();+ throw Object.assign(new Error("missing"), { code: "ESRCH" });+ });+ const result = launch();+ close();+ await result;+ expect(kill).toHaveBeenCalledExactlyOnceWith(-4100, "SIGTERM");+ expect(mocks.rmSync).toHaveBeenCalledOnce();+ });++ it("terminates the captured tree on Windows so a backend cannot outlive cleanup", async () => {+ mocks.platform.mockReturnValue("win32");+ const result = launch();+ app.stderr.emit("data", "fatal startup error");+ await result;+ expect(mocks.spawn.mock.calls[0][2].detached).toBe(false);+ expect(app.kill).toHaveBeenCalledExactlyOnceWith("SIGTERM");+ expect(mocks.spawnSync).toHaveBeenCalledWith("taskkill", ["/pid", "4100", "/T", "/F"]);+ expect(kill).not.toHaveBeenCalled();+ });++ it("kills the Windows tree even after the direct child closed", async () => {+ mocks.platform.mockReturnValue("win32");+ const result = launch();+ app.stdout.emit("data", ready);+ close();+ await result;+ // The tree kill still runs against the captured PID after close.+ expect(mocks.spawnSync).toHaveBeenCalledWith("taskkill", ["/pid", "4100", "/T", "/F"]);+ expect(app.kill).not.toHaveBeenCalled();+ expect(mocks.rmSync).toHaveBeenCalledOnce();+ });++ it("cleans state if directory setup fails", async () => {+ mocks.mkdirSync.mockImplementation(() => {+ throw new Error("mkdir failed");+ });+ expect((await launch()).error.message).toContain("mkdir failed");+ expect(mocks.spawn).not.toHaveBeenCalled();+ expect(mocks.rmSync.mock.calls[0][0]).toBe(NodePath.resolve(root));+ });+});