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, "");
18export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
19export const 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 = 15;
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
99function shellSingleQuote(value) {
100 return `'${value.replaceAll("'", "'\\''")}'`;
101}
102
103export function makeDevelopmentLauncherScript({
104 electronBinaryPath,
105 mainEntryPath,
106 desktopRoot,
107 environment,
108}) {
109 const envEntries = [
110 ["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
111 ["T3CODE_PORT", environment.T3CODE_PORT],
112 ["T3CODE_HOME", environment.T3CODE_HOME],
113 ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
114 ["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
115 ["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
116 ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
117 ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
118 return [
119 "#!/bin/sh",
120 ...envEntries.map(
121 ([name, value]) =>
122 `if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
123 ),
124 `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
125 "",
126 ].join("\n");
127}
128
129function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
130 NodeFS.writeFileSync(
131 targetBinaryPath,
132 makeDevelopmentLauncherScript({
133 electronBinaryPath,
134 mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
135 desktopRoot: desktopDir,
136 environment: process.env,
137 }),
138 );
139 NodeFS.chmodSync(targetBinaryPath, 0o755);
140}
141
142function registerMacLauncherBundle(appBundlePath) {
143 runChecked(
144 "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
145 ["-f", appBundlePath],
146 );
147
148 if (!isDevelopment) {
149 return;
150 }
151
152 for (const scheme of APP_PROTOCOL_SCHEMES) {
153 runChecked("osascript", [
154 "-l",
155 "JavaScript",
156 "-e",
157 [
158 'ObjC.import("CoreServices");',
159 `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
160 `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
161 "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
162 "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
163 ].join(" "),
164 ]);
165 }
166}
167
168// Bundle-internal paths are macOS paths whatever host builds them.
169export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
170 return {
171 sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
172 generatedIconPath: NodePath.posix.join(
173 runtimeDir,
174 development ? "icon-dev.icns" : "icon-prod.icns",
175 ),
176 };
177}
178
179function ensureMacIconIcns(runtimeDir) {
180 const { sourceIconPath, generatedIconPath } = resolveMacLauncherIconPaths(runtimeDir);
181 NodeFS.mkdirSync(runtimeDir, { recursive: true });
182
183 if (!NodeFS.existsSync(sourceIconPath)) {
184 throw new Error(`Desktop macOS icon source is missing at ${sourceIconPath}`);
185 }
186
187 const sourceMtimeMs = NodeFS.statSync(sourceIconPath).mtimeMs;
188 if (
189 NodeFS.existsSync(generatedIconPath) &&
190 NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
191 ) {
192 return generatedIconPath;
193 }
194
195 const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
196 const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
197 NodeFS.mkdirSync(iconsetDir, { recursive: true });
198
199 try {
200 for (const size of [16, 32, 128, 256, 512]) {
201 runChecked("sips", [
202 "-z",
203 String(size),
204 String(size),
205 sourceIconPath,
206 "--out",
207 NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
208 ]);
209
210 const retinaSize = size * 2;
211 runChecked("sips", [
212 "-z",
213 String(retinaSize),
214 String(retinaSize),
215 sourceIconPath,
216 "--out",
217 NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
218 ]);
219 }
220
221 runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
222 return generatedIconPath;
223 } finally {
224 NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
225 }
226}
227
228function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
229 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
230 setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
231 setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
232 setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
233 setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
234 setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
235 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
236 {
237 CFBundleURLName: APP_BUNDLE_ID,
238 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
239 },
240 ]);
241
242 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
243 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
244 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
245}
246
247function patchHelperBundleInfoPlists(appBundlePath) {
248 const helperBundleNames = [
249 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
250 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
251 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
252 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
253 ];
254
255 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
256 const infoPlistPath = NodePath.join(
257 appBundlePath,
258 "Contents",
259 "Frameworks",
260 bundleName,
261 "Contents",
262 "Info.plist",
263 );
264 if (!NodeFS.existsSync(infoPlistPath)) {
265 continue;
266 }
267
268 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
269 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
270 setPlistString(
271 infoPlistPath,
272 "CFBundleIdentifier",
273 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
274 );
275 }
276}
277
278function readJson(path) {
279 try {
280 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
281 } catch {
282 return null;
283 }
284}
285
286export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
287 const executableDir = NodePath.posix.join(appBundlePath, "Contents", "MacOS");
288 const launcherExecutableName = `${displayName} Launcher`;
289 return {
290 launcherExecutableName,
291 launcherBinaryPath: NodePath.posix.join(executableDir, launcherExecutableName),
292 runtimeElectronBinaryPath: NodePath.posix.join(executableDir, "Electron"),
293 };
294}
295
296function buildMacLauncher(electronBinaryPath) {
297 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
298 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
299 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
300 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
301 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
302 const launcherBinaryPath = isDevelopment
303 ? developmentPaths.launcherBinaryPath
304 : runtimeElectronBinaryPath;
305 const iconPath = ensureMacIconIcns(runtimeDir);
306 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
307
308 NodeFS.mkdirSync(runtimeDir, { recursive: true });
309
310 const expectedMetadata = {
311 launcherVersion: LAUNCHER_VERSION,
312 sourceAppBundlePath,
313 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
314 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
315 appBundleId: APP_BUNDLE_ID,
316 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
317 };
318
319 const currentMetadata = readJson(metadataPath);
320 if (
321 NodeFS.existsSync(launcherBinaryPath) &&
322 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
323 currentMetadata &&
324 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
325 ) {
326 if (isDevelopment) {
327 // The launcher also handles protocol activations outside the dev runner,
328 // so refresh its fallback environment on every launch. Never let a value
329 // captured by an older parent app override the live dev-runner environment.
330 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
331 }
332 registerMacLauncherBundle(targetAppBundlePath);
333 return launcherBinaryPath;
334 }
335
336 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
337 // verbatimSymlinks keeps the framework's relative symlinks intact
338 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
339 // rewrites them to absolute paths into node_modules, which escape the
340 // bundle and crash sandboxed helper processes (icudtl.dat not found).
341 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
342 recursive: true,
343 verbatimSymlinks: true,
344 });
345 patchMainBundleInfoPlist(
346 targetAppBundlePath,
347 iconPath,
348 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
349 );
350 patchHelperBundleInfoPlists(targetAppBundlePath);
351 if (isDevelopment) {
352 // Keep Electron's native executable inside the branded bundle. Launching the
353 // node_modules copy makes macOS associate the process (and Dock label) with
354 // Electron.app even though this bundle's Info.plist has the T3 Code name.
355 // Its conventional executable name also keeps Electron's default-app runtime
356 // in development mode instead of making app.isPackaged report true.
357 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
358 }
359 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
360 registerMacLauncherBundle(targetAppBundlePath);
361
362 return launcherBinaryPath;
363}
364
365function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
366 if (hostPlatform !== "linux") {
367 return true;
368 }
369
370 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
371 try {
372 const sandboxStat = NodeFS.statSync(sandboxPath);
373 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
374 } catch {
375 return false;
376 }
377}
378
379function resolveLinuxSandboxArgs(electronBinaryPath) {
380 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
381 return [];
382 }
383
384 console.warn(
385 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
386 );
387 return ["--no-sandbox"];
388}
389
390export function resolveElectronPath() {
391 const electronBinaryPath = resolveElectronBinaryPath();
392
393 if (hostPlatform !== "darwin") {
394 return electronBinaryPath;
395 }
396
397 return buildMacLauncher(electronBinaryPath);
398}
399
400export function resolveElectronLaunchCommand(args = []) {
401 const electronPath = resolveElectronPath();
402 return {
403 electronPath,
404 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
405 };
406}
407
408export function resolveElectronBinaryPath({
409 ensureRuntime = ensureElectronRuntime,
410 createRequire = NodeModule.createRequire,
411 moduleUrl = import.meta.url,
412} = {}) {
413 ensureRuntime();
414
415 const require = createRequire(moduleUrl);
416 return require("electron");
417}
418
419export function resolveDevProtocolClient() {
420 if (hostPlatform !== "darwin" || !isDevelopment) {
421 return null;
422 }
423
424 const electronBinaryPath = resolveElectronBinaryPath();
425 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
426 return {
427 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
428 appBundleId: APP_BUNDLE_ID,
429 };
430}