Open History to see the last commit
1import * as NodeChildProcess from "node:child_process";
2import * as NodeEvents from "node:events";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import * as NodeVM from "node:vm";
7
8import { assert, describe, it } from "vite-plus/test";
9
10import {
11 makeDevelopmentEnvironmentScript,
12 makeDevelopmentLauncherScript,
13 resolveElectronBinaryPath,
14 resolveMacBundleInfoPlistStrings,
15 resolveMacCodeSignArguments,
16 resolveMacLauncherIconPaths,
17 resolveMacLauncherPaths,
18 writeDevelopmentLauncherScript,
19} from "./electron-launcher.mjs";
20
21describe("electron development launcher", () => {
22 it("uses captured values only as fallbacks for a live runner environment", () => {
23 const environmentScript = makeDevelopmentEnvironmentScript({
24 VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
25 T3CODE_PORT: "16566",
26 T3CODE_HOME: "/tmp/t3",
27 T3CODE_OTLP_PROTOCOL: "http/protobuf",
28 });
29
30 assert.include(
31 environmentScript,
32 "if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
33 );
34 assert.include(
35 environmentScript,
36 "if [ -z \"${T3CODE_OTLP_PROTOCOL:-}\" ]; then export T3CODE_OTLP_PROTOCOL='http/protobuf'; fi",
37 );
38 assert.notInclude(environmentScript, "\nexport VITE_DEV_SERVER_URL=");
39 });
40
41 it("keeps the launcher script free of volatile environment values", () => {
42 const script = makeDevelopmentLauncherScript({
43 electronBinaryPath: "/repo/node_modules/electron/Electron",
44 mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
45 desktopRoot: "/repo/apps/desktop",
46 environmentFilePath: "/repo/apps/desktop/.electron-runtime/dev-environment.sh",
47 });
48
49 assert.include(
50 script,
51 "if [ -f '/repo/apps/desktop/.electron-runtime/dev-environment.sh' ]; then . '/repo/apps/desktop/.electron-runtime/dev-environment.sh'; fi",
52 );
53 assert.notInclude(script, "VITE_DEV_SERVER_URL");
54 assert.include(
55 script,
56 "exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
57 );
58 });
59
60 it("repairs Electron before loading the package entrypoint", () => {
61 const calls = [];
62 const electronPath = resolveElectronBinaryPath({
63 ensureRuntime: () => {
64 calls.push("ensure");
65 },
66 createRequire: () => (specifier) => {
67 calls.push(`require:${specifier}`);
68 return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
69 },
70 moduleUrl: import.meta.url,
71 });
72
73 assert.equal(
74 electronPath,
75 "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
76 );
77 assert.deepEqual(calls, ["ensure", "require:electron"]);
78 });
79
80 it("keeps the native Electron executable name inside the branded macOS bundle", () => {
81 const paths = resolveMacLauncherPaths(
82 "/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
83 "T3 Code (Dev)",
84 );
85
86 assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
87 assert.equal(
88 paths.launcherBinaryPath,
89 "/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
90 );
91 assert.equal(
92 paths.runtimeElectronBinaryPath,
93 "/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
94 );
95
96 const script = makeDevelopmentLauncherScript({
97 electronBinaryPath: paths.runtimeElectronBinaryPath,
98 mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
99 desktopRoot: "/repo/apps/desktop",
100 environmentFilePath: "/repo/apps/desktop/.electron-runtime/dev-environment.sh",
101 });
102 assert.include(
103 script,
104 "exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
105 );
106 assert.notInclude(script, "node_modules/electron");
107 });
108
109 it("declares why the macOS app needs protected access", () => {
110 const values = resolveMacBundleInfoPlistStrings("T3 Code (Dev) Launcher");
111
112 assert.equal(
113 values.NSScreenCaptureUsageDescription,
114 "T3 Code captures the active window when you use the snapshot shortcut.",
115 );
116 assert.equal(
117 values.NSDocumentsFolderUsageDescription,
118 "T3 Code reads project files you open in the desktop app.",
119 );
120 });
121
122 it("ad-hoc signs the complete development app bundle", () => {
123 assert.deepEqual(resolveMacCodeSignArguments("/runtime/T3 Code (Dev).app"), [
124 "--force",
125 "--deep",
126 "--sign",
127 "-",
128 "--timestamp=none",
129 "/runtime/T3 Code (Dev).app",
130 ]);
131 });
132
133 it("restores execute permissions on an unchanged launcher", () => {
134 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-launcher-"));
135 const launcherPath = NodePath.join(directory, "launcher");
136 try {
137 writeDevelopmentLauncherScript(launcherPath, "/runtime/Electron");
138 NodeFS.chmodSync(launcherPath, 0o644);
139
140 assert.isFalse(writeDevelopmentLauncherScript(launcherPath, "/runtime/Electron"));
141 assert.equal(NodeFS.statSync(launcherPath).mode & 0o777, 0o755);
142 } finally {
143 NodeFS.rmSync(directory, { recursive: true, force: true });
144 }
145 });
146
147 it("derives launcher icons from canonical development and production assets", () => {
148 const development = resolveMacLauncherIconPaths("/runtime", true);
149 const production = resolveMacLauncherIconPaths("/runtime", false);
150
151 assert.match(development.sourceIconPath, /assets[\\/]dev[\\/]blueprint-macos-1024\.png$/);
152 assert.equal(development.generatedIconPath, "/runtime/icon-dev.icns");
153 assert.match(production.sourceIconPath, /assets[\\/]prod[\\/]black-macos-1024\.png$/);
154 assert.equal(production.generatedIconPath, "/runtime/icon-prod.icns");
155 });
156});
157
158async function startupCleanupPattern(desktopDir) {
159 const source = NodeFS.readFileSync(new URL("./dev-electron.mjs", import.meta.url), "utf8");
160 let pattern;
161 // Supply inert imports so the real startup runs without launching Electron or signalling processes.
162 await NodeVM.runInNewContext(
163 `(async () => { ${source.replace(/^import\s[\s\S]*?;\n/gm, "")} })()`,
164 {
165 NodeChildProcess: {
166 execFileSync: () => undefined,
167 spawnSync: (command, args) => {
168 if (command === "pkill" && args.includes("-f")) pattern = args.at(-1);
169 },
170 spawn: () => new NodeEvents.EventEmitter(),
171 },
172 NodeFS: { watch: () => ({ close: () => undefined }) },
173 NodeOS: { platform: () => "linux" },
174 NodePath,
175 desktopDir,
176 resolveDevProtocolClient: () => null,
177 resolveElectronLaunchCommand: (args) => ({ electronPath: "electron", args }),
178 waitForResources: async () => undefined,
179 URL,
180 process: {
181 env: { VITE_DEV_SERVER_URL: "http://localhost:1234" },
182 execPath: "node",
183 once: () => undefined,
184 },
185 },
186 );
187 assert.isString(pattern);
188 return pattern;
189}
190
191it
192 // oxlint-disable-next-line t3code/no-global-process-runtime -- Native pgrep is unavailable on Windows.
193 .skipIf(NodeOS.platform() === "win32")
194 .each([
195 "/tmp/t3-feature.one/apps/desktop",
196 "/tmp/t3-feature.one [two](three)+?^${four}|back\\slash*/apps/desktop",
197 ])("dev cleanup matches only the literal root argument: %s", async (desktopDir) => {
198 const pattern = await startupCleanupPattern(desktopDir);
199 const flag = `--t3code-dev-root=${desktopDir}`;
200 const argvCases = [
201 [flag],
202 [flag, "main.cjs"],
203 [flag.replace(".one", "Xone")],
204 [`${flag}-two`],
205 [`prefix${flag}`],
206 [`--t3code-dev-root=/other${desktopDir}`],
207 ];
208 const children = [];
209 try {
210 for (const args of argvCases) {
211 const child = NodeChildProcess.spawn(
212 process.execPath,
213 ["-e", "process.send('ready'); setInterval(() => {}, 1000)", "--", ...args],
214 { stdio: ["ignore", "ignore", "inherit", "ipc"] },
215 );
216 children.push(child);
217 await Promise.race([
218 NodeEvents.once(child, "message"),
219 NodeEvents.once(child, "exit").then(() => {
220 throw new Error("Fixture exited before readiness");
221 }),
222 ]);
223 }
224 // Use the native ERE engine, but never execute the launcher's signal-producing command.
225 const result = NodeChildProcess.spawnSync(
226 "pgrep",
227 ["-P", String(process.pid), "-f", "--", pattern],
228 { encoding: "utf8" },
229 );
230 assert.equal(result.status, 0, result.stderr);
231 const matches = result.stdout.trim().split(/\s+/).map(Number);
232 assert.sameMembers(
233 matches,
234 children.slice(0, 2).map((child) => child.pid),
235 );
236 } finally {
237 await Promise.all(
238 children.map(async (child) => {
239 if (child.exitCode !== null || child.signalCode !== null) return;
240 const exited = NodeEvents.once(child, "exit");
241 child.kill("SIGTERM");
242 await exited;
243 }),
244 );
245 }
246});