Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off
2// Launches a packaged desktop app against a seeded T3 home, opens a thread, and checks its
3// messages render. Release jobs run it so a build whose backend or bundle cannot start fails
4// before it is published.
5import * as NodeChildProcess from "node:child_process";
6import * as NodeFS from "node:fs";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import * as NodeTimersPromises from "node:timers/promises";
10import * as NodeUtil from "node:util";
11import { chromium, type Browser } from "playwright-core";
12
13// A snapshot from an older build on purpose: the packaged server must migrate it forward, as it
14// does for every upgrading user. It holds one project and two threads, nothing else.
15const FIXTURE_DB = NodePath.join(import.meta.dirname, "fixtures/desktop-launch/statev2.sqlite");
16const THREAD_TITLE = "Release launch check";
17const THREAD_MESSAGE = "The release opens and shows this thread.";
18const STEP_TIMEOUT_MS = 60_000;
19
20const { values } = NodeUtil.parseArgs({
21 options: {
22 executable: { type: "string" },
23 // An unpackaged app directory for a plain Electron executable, as PR CI runs it.
24 app: { type: "string" },
25 "artifacts-dir": { type: "string" },
26 },
27});
28const executable = values.executable;
29if (!executable)
30 throw new Error(
31 "Usage: smoke-desktop-app.ts --executable <app> [--app <dir>] [--artifacts-dir <dir>]",
32 );
33const artifactsDir = NodePath.resolve(values["artifacts-dir"] ?? "desktop-launch-check");
34
35const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-desktop-launch-"));
36const t3Home = NodePath.join(home, "t3");
37NodeFS.mkdirSync(NodePath.join(t3Home, "userdata"), { recursive: true });
38NodeFS.copyFileSync(FIXTURE_DB, NodePath.join(t3Home, "userdata/statev2.sqlite"));
39
40// Packaged builds turn off Electron's Node inspector fuse, so Playwright's `_electron.launch`
41// (which attaches through `--inspect`) never connects. Chromium's DevTools port still works.
42const waitForDevToolsEndpoint = (child: NodeChildProcess.ChildProcess) =>
43 new Promise<string>((resolve, reject) => {
44 let output = "";
45 const onData = (chunk: Buffer) => {
46 process.stderr.write(chunk);
47 output += chunk.toString();
48 const match = /DevTools listening on (ws:\/\/\S+)/.exec(output);
49 if (match?.[1]) {
50 clearTimeout(timer);
51 child.off("exit", onExit);
52 resolve(match[1]);
53 }
54 };
55 const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
56 clearTimeout(timer);
57 reject(new Error(`The app exited (code ${code}, signal ${signal}) before DevTools opened.`));
58 };
59 const timer = setTimeout(() => {
60 child.off("exit", onExit);
61 reject(new Error(`DevTools did not open within ${STEP_TIMEOUT_MS}ms.`));
62 }, STEP_TIMEOUT_MS);
63 child.stderr?.on("data", onData);
64 child.once("exit", onExit);
65 });
66
67let step = "launching the app";
68let child: NodeChildProcess.ChildProcess | undefined;
69let browser: Browser | undefined;
70try {
71 child = NodeChildProcess.spawn(
72 executable,
73 [
74 ...(values.app ? [NodePath.resolve(values.app)] : []),
75 // Linux CI runners do not allow the Chromium sandbox's user namespaces.
76 "--no-sandbox",
77 "--remote-debugging-port=0",
78 ],
79 {
80 stdio: ["ignore", "inherit", "pipe"],
81 // HOME stays real: on macOS a fake HOME has no login keychain, and safeStorage blocks the
82 // main process on a keychain dialog. macOS keeps its Electron profile in the runner's HOME.
83 env: {
84 ...process.env,
85 XDG_CONFIG_HOME: NodePath.join(home, ".config"),
86 XDG_DATA_HOME: NodePath.join(home, ".local/share"),
87 T3CODE_HOME: t3Home,
88 T3CODE_TELEMETRY_ENABLED: "false",
89 T3CODE_DISABLE_AUTO_UPDATE: "true",
90 },
91 },
92 );
93 const endpoint = await waitForDevToolsEndpoint(child);
94 browser = await chromium.connectOverCDP(endpoint, { timeout: STEP_TIMEOUT_MS });
95 // A backend that never starts leaves no window, or only the "could not start" window, so the
96 // thread wait below fails either way and its screenshot shows the startup error.
97 step = "waiting for the first window";
98 const context = browser.contexts()[0];
99 if (!context) throw new Error("The app exposed no browser context over DevTools.");
100 const page =
101 context.pages()[0] ?? (await context.waitForEvent("page", { timeout: STEP_TIMEOUT_MS }));
102 try {
103 step = `finding "${THREAD_TITLE}" in the sidebar`;
104 const thread = page.locator("li[data-thread-item]", { hasText: THREAD_TITLE });
105 await thread.waitFor({ timeout: STEP_TIMEOUT_MS });
106 step = "opening the thread";
107 await thread.click();
108 await page.getByText(THREAD_MESSAGE).waitFor({ timeout: STEP_TIMEOUT_MS });
109 } catch (error) {
110 NodeFS.mkdirSync(artifactsDir, { recursive: true });
111 await page
112 .screenshot({ path: NodePath.join(artifactsDir, "window.png"), timeout: 10_000 })
113 .catch(() => {});
114 throw error;
115 }
116 console.log("Desktop launch check passed: the app opened and showed the seeded thread.");
117} catch (error) {
118 console.error(`Desktop launch check failed while ${step}.`);
119 NodeFS.mkdirSync(artifactsDir, { recursive: true });
120 console.error(error instanceof Error ? error.message : error);
121 const logs = NodePath.join(t3Home, "userdata/logs");
122 if (NodeFS.existsSync(logs)) {
123 NodeFS.cpSync(logs, NodePath.join(artifactsDir, "logs"), { recursive: true });
124 const serverLog = NodePath.join(logs, "server-child.log");
125 if (NodeFS.existsSync(serverLog)) {
126 console.error("\nLast backend output (server-child.log):");
127 console.error(NodeFS.readFileSync(serverLog, "utf8").split("\n").slice(-20).join("\n"));
128 }
129 }
130 process.exitCode = 1;
131} finally {
132 await browser?.close().catch(() => {});
133 if (child && child.exitCode === null && child.signalCode === null) {
134 // Let the app quit cleanly, but a hung app never does; kill it so the job does not wait.
135 const exited = new Promise((resolve) => child?.once("exit", resolve));
136 child.kill("SIGTERM");
137 await Promise.race([exited, NodeTimersPromises.setTimeout(10_000, undefined, { ref: false })]);
138 child.kill("SIGKILL");
139 }
140 NodeFS.rmSync(home, { recursive: true, force: true, maxRetries: 5 });
141}