Open History to see the last commit
1// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
2
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeModule from "node:module";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeURL from "node:url";
9import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
10
11const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
12const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
13export const desktopDir = NodePath.resolve(__dirname, "..");
14const repoRoot = NodePath.resolve(desktopDir, "..", "..");
15const devBundleIdSuffix = NodePath.basename(repoRoot)
16 .toLowerCase()
17 .replaceAll(/[^a-z0-9]+/g, "");
18const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
19const APP_BUNDLE_ID = isDevelopment
20 ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
21 : "com.t3tools.t3code";
22const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
23const LAUNCHER_VERSION = 20;
24const developmentMacIconPngPath = NodePath.join(
25 repoRoot,
26 "assets",
27 "dev",
28 "blueprint-macos-1024.png",
29);
30const productionMacIconPngPath = NodePath.join(repoRoot, "assets", "prod", "black-macos-1024.png");
31// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
32const hostPlatform = NodeOS.platform();
33
34function setPlistString(plistPath, key, value) {
35 const replaceResult = NodeChildProcess.spawnSync(
36 "plutil",
37 ["-replace", key, "-string", value, plistPath],
38 {
39 encoding: "utf8",
40 },
41 );
42 if (replaceResult.status === 0) {
43 return;
44 }
45
46 const insertResult = NodeChildProcess.spawnSync(
47 "plutil",
48 ["-insert", key, "-string", value, plistPath],
49 {
50 encoding: "utf8",
51 },
52 );
53 if (insertResult.status === 0) {
54 return;
55 }
56
57 const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
58 throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
59}
60
61function setPlistJson(plistPath, key, value) {
62 const serialized = JSON.stringify(value);
63 const replaceResult = NodeChildProcess.spawnSync(
64 "plutil",
65 ["-replace", key, "-json", serialized, plistPath],
66 {
67 encoding: "utf8",
68 },
69 );
70 if (replaceResult.status === 0) {
71 return;
72 }
73
74 const insertResult = NodeChildProcess.spawnSync(
75 "plutil",
76 ["-insert", key, "-json", serialized, plistPath],
77 {
78 encoding: "utf8",
79 },
80 );
81 if (insertResult.status === 0) {
82 return;
83 }
84
85 const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
86 throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
87}
88
89function runChecked(command, args) {
90 const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
91 if (result.status === 0) {
92 return;
93 }
94
95 const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
96 throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
97}
98
99export function resolveMacCodeSignArguments(appBundlePath) {
100 return ["--force", "--deep", "--sign", "-", "--timestamp=none", appBundlePath];
101}
102
103function signMacLauncherBundle(appBundlePath) {
104 runChecked("codesign", resolveMacCodeSignArguments(appBundlePath));
105}
106
107function shellSingleQuote(value) {
108 return `'${value.replaceAll("'", "'\\''")}'`;
109}
110
111export function makeDevelopmentEnvironmentScript(environment) {
112 const envEntries = [
113 ["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
114 ["T3CODE_PORT", environment.T3CODE_PORT],
115 ["T3CODE_HOME", environment.T3CODE_HOME],
116 ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
117 ["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
118 ["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
119 ["T3CODE_OTLP_HEADERS", environment.T3CODE_OTLP_HEADERS],
120 ["T3CODE_OTLP_PROTOCOL", environment.T3CODE_OTLP_PROTOCOL],
121 ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
122 ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
123 return [
124 ...envEntries.map(
125 ([name, value]) =>
126 `if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
127 ),
128 "",
129 ].join("\n");
130}
131
132export function makeDevelopmentLauncherScript({
133 electronBinaryPath,
134 mainEntryPath,
135 desktopRoot,
136 environmentFilePath,
137}) {
138 return [
139 "#!/bin/sh",
140 `if [ -f ${shellSingleQuote(environmentFilePath)} ]; then . ${shellSingleQuote(environmentFilePath)}; fi`,
141 `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
142 "",
143 ].join("\n");
144}
145
146const developmentEnvironmentFilePath = NodePath.join(
147 desktopDir,
148 ".electron-runtime",
149 "dev-environment.sh",
150);
151
152function writeDevelopmentEnvironmentScript() {
153 NodeFS.mkdirSync(NodePath.dirname(developmentEnvironmentFilePath), { recursive: true });
154 NodeFS.writeFileSync(
155 developmentEnvironmentFilePath,
156 makeDevelopmentEnvironmentScript(process.env),
157 );
158}
159
160export function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
161 const script = makeDevelopmentLauncherScript({
162 electronBinaryPath,
163 mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
164 desktopRoot: desktopDir,
165 environmentFilePath: developmentEnvironmentFilePath,
166 });
167 if (
168 NodeFS.existsSync(targetBinaryPath) &&
169 NodeFS.readFileSync(targetBinaryPath, "utf8") === script
170 ) {
171 NodeFS.chmodSync(targetBinaryPath, 0o755);
172 return false;
173 }
174 NodeFS.writeFileSync(targetBinaryPath, script);
175 NodeFS.chmodSync(targetBinaryPath, 0o755);
176 return true;
177}
178
179function registerMacLauncherBundle(appBundlePath) {
180 runChecked(
181 "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
182 ["-f", appBundlePath],
183 );
184
185 if (!isDevelopment) {
186 return;
187 }
188
189 for (const scheme of APP_PROTOCOL_SCHEMES) {
190 runChecked("osascript", [
191 "-l",
192 "JavaScript",
193 "-e",
194 [
195 'ObjC.import("CoreServices");',
196 `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
197 `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
198 "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
199 "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
200 ].join(" "),
201 ]);
202 }
203}
204
205// Bundle-internal paths are macOS paths whatever host builds them.
206export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
207 return {
208 sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
209 generatedIconPath: NodePath.posix.join(
210 runtimeDir,
211 development ? "icon-dev.icns" : "icon-prod.icns",
212 ),
213 };
214}
215
216function ensureMacIconIcns(runtimeDir) {
217 const { sourceIconPath, generatedIconPath } = resolveMacLauncherIconPaths(runtimeDir);
218 NodeFS.mkdirSync(runtimeDir, { recursive: true });
219
220 if (!NodeFS.existsSync(sourceIconPath)) {
221 throw new Error(`Desktop macOS icon source is missing at ${sourceIconPath}`);
222 }
223
224 const sourceMtimeMs = NodeFS.statSync(sourceIconPath).mtimeMs;
225 if (
226 NodeFS.existsSync(generatedIconPath) &&
227 NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
228 ) {
229 return generatedIconPath;
230 }
231
232 const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
233 const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
234 NodeFS.mkdirSync(iconsetDir, { recursive: true });
235
236 try {
237 for (const size of [16, 32, 128, 256, 512]) {
238 runChecked("sips", [
239 "-z",
240 String(size),
241 String(size),
242 sourceIconPath,
243 "--out",
244 NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
245 ]);
246
247 const retinaSize = size * 2;
248 runChecked("sips", [
249 "-z",
250 String(retinaSize),
251 String(retinaSize),
252 sourceIconPath,
253 "--out",
254 NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
255 ]);
256 }
257
258 runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
259 return generatedIconPath;
260 } finally {
261 NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
262 }
263}
264
265export function resolveMacBundleInfoPlistStrings(executableName) {
266 return {
267 CFBundleDisplayName: APP_DISPLAY_NAME,
268 CFBundleName: APP_DISPLAY_NAME,
269 CFBundleIdentifier: APP_BUNDLE_ID,
270 CFBundleExecutable: executableName,
271 CFBundleIconFile: "icon.icns",
272 NSScreenCaptureUsageDescription:
273 "T3 Code captures the active window when you use the snapshot shortcut.",
274 NSDocumentsFolderUsageDescription: "T3 Code reads project files you open in the desktop app.",
275 };
276}
277
278function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
279 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
280 for (const [key, value] of Object.entries(resolveMacBundleInfoPlistStrings(executableName))) {
281 setPlistString(infoPlistPath, key, value);
282 }
283 // macOS 26 offers Messages/Mail codes in every text field unless opted out.
284 setPlistJson(infoPlistPath, "NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac", true);
285 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
286 {
287 CFBundleURLName: APP_BUNDLE_ID,
288 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
289 },
290 ]);
291
292 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
293 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
294 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
295}
296
297function patchHelperBundleInfoPlists(appBundlePath) {
298 const helperBundleNames = [
299 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
300 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
301 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
302 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
303 ];
304
305 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
306 const infoPlistPath = NodePath.join(
307 appBundlePath,
308 "Contents",
309 "Frameworks",
310 bundleName,
311 "Contents",
312 "Info.plist",
313 );
314 if (!NodeFS.existsSync(infoPlistPath)) {
315 continue;
316 }
317
318 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
319 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
320 setPlistString(
321 infoPlistPath,
322 "CFBundleIdentifier",
323 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
324 );
325 }
326}
327
328function readJson(path) {
329 try {
330 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
331 } catch {
332 return null;
333 }
334}
335
336export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
337 const executableDir = NodePath.posix.join(appBundlePath, "Contents", "MacOS");
338 const launcherExecutableName = `${displayName} Launcher`;
339 return {
340 launcherExecutableName,
341 launcherBinaryPath: NodePath.posix.join(executableDir, launcherExecutableName),
342 runtimeElectronBinaryPath: NodePath.posix.join(executableDir, "Electron"),
343 };
344}
345
346function buildMacLauncher(electronBinaryPath) {
347 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
348 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
349 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
350 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
351 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
352 const launcherBinaryPath = isDevelopment
353 ? developmentPaths.launcherBinaryPath
354 : runtimeElectronBinaryPath;
355 const iconPath = ensureMacIconIcns(runtimeDir);
356 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
357
358 NodeFS.mkdirSync(runtimeDir, { recursive: true });
359
360 const expectedMetadata = {
361 launcherVersion: LAUNCHER_VERSION,
362 sourceAppBundlePath,
363 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
364 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
365 appBundleId: APP_BUNDLE_ID,
366 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
367 };
368
369 const currentMetadata = readJson(metadataPath);
370 if (
371 NodeFS.existsSync(launcherBinaryPath) &&
372 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
373 currentMetadata &&
374 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
375 ) {
376 if (isDevelopment) {
377 // The launcher also handles protocol activations outside the dev runner,
378 // so refresh its fallback environment on every launch. Never let a value
379 // captured by an older parent app override the live dev-runner environment.
380 writeDevelopmentEnvironmentScript();
381 if (writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath)) {
382 signMacLauncherBundle(targetAppBundlePath);
383 }
384 }
385 registerMacLauncherBundle(targetAppBundlePath);
386 return launcherBinaryPath;
387 }
388
389 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
390 // verbatimSymlinks keeps the framework's relative symlinks intact
391 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
392 // rewrites them to absolute paths into node_modules, which escape the
393 // bundle and crash sandboxed helper processes (icudtl.dat not found).
394 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
395 recursive: true,
396 verbatimSymlinks: true,
397 });
398 patchMainBundleInfoPlist(
399 targetAppBundlePath,
400 iconPath,
401 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
402 );
403 patchHelperBundleInfoPlists(targetAppBundlePath);
404 if (isDevelopment) {
405 // Keep Electron's native executable inside the branded bundle. Launching the
406 // node_modules copy makes macOS associate the process (and Dock label) with
407 // Electron.app even though this bundle's Info.plist has the T3 Code name.
408 // Its conventional executable name also keeps Electron's default-app runtime
409 // in development mode instead of making app.isPackaged report true.
410 writeDevelopmentEnvironmentScript();
411 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
412 }
413 signMacLauncherBundle(targetAppBundlePath);
414 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
415 registerMacLauncherBundle(targetAppBundlePath);
416
417 return launcherBinaryPath;
418}
419
420function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
421 if (hostPlatform !== "linux") {
422 return true;
423 }
424
425 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
426 try {
427 const sandboxStat = NodeFS.statSync(sandboxPath);
428 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
429 } catch {
430 return false;
431 }
432}
433
434function resolveLinuxSandboxArgs(electronBinaryPath) {
435 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
436 return [];
437 }
438
439 console.warn(
440 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
441 );
442 return ["--no-sandbox"];
443}
444
445function resolveElectronPath() {
446 const electronBinaryPath = resolveElectronBinaryPath();
447
448 if (hostPlatform !== "darwin") {
449 return electronBinaryPath;
450 }
451
452 return buildMacLauncher(electronBinaryPath);
453}
454
455export function resolveElectronLaunchCommand(args = []) {
456 const electronPath = resolveElectronPath();
457 return {
458 electronPath,
459 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
460 };
461}
462
463export function resolveElectronBinaryPath({
464 ensureRuntime = ensureElectronRuntime,
465 createRequire = NodeModule.createRequire,
466 moduleUrl = import.meta.url,
467} = {}) {
468 ensureRuntime();
469
470 const require = createRequire(moduleUrl);
471 return require("electron");
472}
473
474export function resolveDevProtocolClient() {
475 if (hostPlatform !== "darwin" || !isDevelopment) {
476 return null;
477 }
478
479 const electronBinaryPath = resolveElectronBinaryPath();
480 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
481 return {
482 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
483 appBundleId: APP_BUNDLE_ID,
484 };
485}