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 = 19;
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 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
284 {
285 CFBundleURLName: APP_BUNDLE_ID,
286 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
287 },
288 ]);
289
290 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
291 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
292 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
293}
294
295function patchHelperBundleInfoPlists(appBundlePath) {
296 const helperBundleNames = [
297 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
298 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
299 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
300 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
301 ];
302
303 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
304 const infoPlistPath = NodePath.join(
305 appBundlePath,
306 "Contents",
307 "Frameworks",
308 bundleName,
309 "Contents",
310 "Info.plist",
311 );
312 if (!NodeFS.existsSync(infoPlistPath)) {
313 continue;
314 }
315
316 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
317 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
318 setPlistString(
319 infoPlistPath,
320 "CFBundleIdentifier",
321 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
322 );
323 }
324}
325
326function readJson(path) {
327 try {
328 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
329 } catch {
330 return null;
331 }
332}
333
334export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
335 const executableDir = NodePath.posix.join(appBundlePath, "Contents", "MacOS");
336 const launcherExecutableName = `${displayName} Launcher`;
337 return {
338 launcherExecutableName,
339 launcherBinaryPath: NodePath.posix.join(executableDir, launcherExecutableName),
340 runtimeElectronBinaryPath: NodePath.posix.join(executableDir, "Electron"),
341 };
342}
343
344function buildMacLauncher(electronBinaryPath) {
345 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
346 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
347 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
348 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
349 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
350 const launcherBinaryPath = isDevelopment
351 ? developmentPaths.launcherBinaryPath
352 : runtimeElectronBinaryPath;
353 const iconPath = ensureMacIconIcns(runtimeDir);
354 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
355
356 NodeFS.mkdirSync(runtimeDir, { recursive: true });
357
358 const expectedMetadata = {
359 launcherVersion: LAUNCHER_VERSION,
360 sourceAppBundlePath,
361 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
362 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
363 appBundleId: APP_BUNDLE_ID,
364 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
365 };
366
367 const currentMetadata = readJson(metadataPath);
368 if (
369 NodeFS.existsSync(launcherBinaryPath) &&
370 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
371 currentMetadata &&
372 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
373 ) {
374 if (isDevelopment) {
375 // The launcher also handles protocol activations outside the dev runner,
376 // so refresh its fallback environment on every launch. Never let a value
377 // captured by an older parent app override the live dev-runner environment.
378 writeDevelopmentEnvironmentScript();
379 if (writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath)) {
380 signMacLauncherBundle(targetAppBundlePath);
381 }
382 }
383 registerMacLauncherBundle(targetAppBundlePath);
384 return launcherBinaryPath;
385 }
386
387 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
388 // verbatimSymlinks keeps the framework's relative symlinks intact
389 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
390 // rewrites them to absolute paths into node_modules, which escape the
391 // bundle and crash sandboxed helper processes (icudtl.dat not found).
392 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
393 recursive: true,
394 verbatimSymlinks: true,
395 });
396 patchMainBundleInfoPlist(
397 targetAppBundlePath,
398 iconPath,
399 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
400 );
401 patchHelperBundleInfoPlists(targetAppBundlePath);
402 if (isDevelopment) {
403 // Keep Electron's native executable inside the branded bundle. Launching the
404 // node_modules copy makes macOS associate the process (and Dock label) with
405 // Electron.app even though this bundle's Info.plist has the T3 Code name.
406 // Its conventional executable name also keeps Electron's default-app runtime
407 // in development mode instead of making app.isPackaged report true.
408 writeDevelopmentEnvironmentScript();
409 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
410 }
411 signMacLauncherBundle(targetAppBundlePath);
412 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
413 registerMacLauncherBundle(targetAppBundlePath);
414
415 return launcherBinaryPath;
416}
417
418function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
419 if (hostPlatform !== "linux") {
420 return true;
421 }
422
423 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
424 try {
425 const sandboxStat = NodeFS.statSync(sandboxPath);
426 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
427 } catch {
428 return false;
429 }
430}
431
432function resolveLinuxSandboxArgs(electronBinaryPath) {
433 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
434 return [];
435 }
436
437 console.warn(
438 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
439 );
440 return ["--no-sandbox"];
441}
442
443function resolveElectronPath() {
444 const electronBinaryPath = resolveElectronBinaryPath();
445
446 if (hostPlatform !== "darwin") {
447 return electronBinaryPath;
448 }
449
450 return buildMacLauncher(electronBinaryPath);
451}
452
453export function resolveElectronLaunchCommand(args = []) {
454 const electronPath = resolveElectronPath();
455 return {
456 electronPath,
457 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
458 };
459}
460
461export function resolveElectronBinaryPath({
462 ensureRuntime = ensureElectronRuntime,
463 createRequire = NodeModule.createRequire,
464 moduleUrl = import.meta.url,
465} = {}) {
466 ensureRuntime();
467
468 const require = createRequire(moduleUrl);
469 return require("electron");
470}
471
472export function resolveDevProtocolClient() {
473 if (hostPlatform !== "darwin" || !isDevelopment) {
474 return null;
475 }
476
477 const electronBinaryPath = resolveElectronBinaryPath();
478 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
479 return {
480 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
481 appBundleId: APP_BUNDLE_ID,
482 };
483}