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 = 12;
24const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
25const developmentMacIconPngPath = NodePath.join(
26 repoRoot,
27 "assets",
28 "dev",
29 "blueprint-macos-1024.png",
30);
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
103function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
104 const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
105 const envEntries = [
106 ["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
107 ["T3CODE_PORT", process.env.T3CODE_PORT],
108 ["T3CODE_HOME", process.env.T3CODE_HOME],
109 ["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
110 ["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
111 ["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
112 ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
113 ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
114 NodeFS.writeFileSync(
115 targetBinaryPath,
116 [
117 "#!/bin/sh",
118 ...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
119 `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
120 "",
121 ].join("\n"),
122 );
123 NodeFS.chmodSync(targetBinaryPath, 0o755);
124}
125
126function registerMacLauncherBundle(appBundlePath) {
127 runChecked(
128 "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
129 ["-f", appBundlePath],
130 );
131
132 if (!isDevelopment) {
133 return;
134 }
135
136 for (const scheme of APP_PROTOCOL_SCHEMES) {
137 runChecked("osascript", [
138 "-l",
139 "JavaScript",
140 "-e",
141 [
142 'ObjC.import("CoreServices");',
143 `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
144 `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
145 "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
146 "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
147 ].join(" "),
148 ]);
149 }
150}
151
152function ensureDevelopmentIconIcns(runtimeDir) {
153 const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
154 NodeFS.mkdirSync(runtimeDir, { recursive: true });
155
156 if (!NodeFS.existsSync(developmentMacIconPngPath)) {
157 return defaultIconPath;
158 }
159
160 const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
161 if (
162 NodeFS.existsSync(generatedIconPath) &&
163 NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
164 ) {
165 return generatedIconPath;
166 }
167
168 const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
169 const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
170 NodeFS.mkdirSync(iconsetDir, { recursive: true });
171
172 try {
173 for (const size of [16, 32, 128, 256, 512]) {
174 runChecked("sips", [
175 "-z",
176 String(size),
177 String(size),
178 developmentMacIconPngPath,
179 "--out",
180 NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
181 ]);
182
183 const retinaSize = size * 2;
184 runChecked("sips", [
185 "-z",
186 String(retinaSize),
187 String(retinaSize),
188 developmentMacIconPngPath,
189 "--out",
190 NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
191 ]);
192 }
193
194 runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
195 return generatedIconPath;
196 } catch (error) {
197 console.warn(
198 "[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
199 error,
200 );
201 return defaultIconPath;
202 } finally {
203 NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
204 }
205}
206
207function patchMainBundleInfoPlist(appBundlePath, iconPath) {
208 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
209 setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
210 setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
211 setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
212 setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
213 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
214 {
215 CFBundleURLName: APP_BUNDLE_ID,
216 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
217 },
218 ]);
219
220 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
221 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
222 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
223}
224
225function patchHelperBundleInfoPlists(appBundlePath) {
226 const helperBundleNames = [
227 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
228 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
229 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
230 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
231 ];
232
233 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
234 const infoPlistPath = NodePath.join(
235 appBundlePath,
236 "Contents",
237 "Frameworks",
238 bundleName,
239 "Contents",
240 "Info.plist",
241 );
242 if (!NodeFS.existsSync(infoPlistPath)) {
243 continue;
244 }
245
246 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
247 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
248 setPlistString(
249 infoPlistPath,
250 "CFBundleIdentifier",
251 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
252 );
253 }
254}
255
256function readJson(path) {
257 try {
258 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
259 } catch {
260 return null;
261 }
262}
263
264function buildMacLauncher(electronBinaryPath) {
265 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
266 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
267 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
268 const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
269 const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
270 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
271
272 NodeFS.mkdirSync(runtimeDir, { recursive: true });
273
274 const expectedMetadata = {
275 launcherVersion: LAUNCHER_VERSION,
276 sourceAppBundlePath,
277 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
278 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
279 appBundleId: APP_BUNDLE_ID,
280 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
281 };
282
283 const currentMetadata = readJson(metadataPath);
284 if (
285 NodeFS.existsSync(targetBinaryPath) &&
286 currentMetadata &&
287 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
288 ) {
289 registerMacLauncherBundle(targetAppBundlePath);
290 return targetBinaryPath;
291 }
292
293 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
294 // verbatimSymlinks keeps the framework's relative symlinks intact
295 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
296 // rewrites them to absolute paths into node_modules, which escape the
297 // bundle and crash sandboxed helper processes (icudtl.dat not found).
298 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
299 recursive: true,
300 verbatimSymlinks: true,
301 });
302 patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
303 patchHelperBundleInfoPlists(targetAppBundlePath);
304 if (isDevelopment) {
305 writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
306 }
307 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
308 registerMacLauncherBundle(targetAppBundlePath);
309
310 return targetBinaryPath;
311}
312
313function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
314 if (hostPlatform !== "linux") {
315 return true;
316 }
317
318 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
319 try {
320 const sandboxStat = NodeFS.statSync(sandboxPath);
321 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
322 } catch {
323 return false;
324 }
325}
326
327function resolveLinuxSandboxArgs(electronBinaryPath) {
328 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
329 return [];
330 }
331
332 console.warn(
333 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
334 );
335 return ["--no-sandbox"];
336}
337
338export function resolveElectronPath() {
339 ensureElectronRuntime();
340
341 const require = NodeModule.createRequire(import.meta.url);
342 const electronBinaryPath = require("electron");
343
344 if (hostPlatform !== "darwin") {
345 return electronBinaryPath;
346 }
347
348 return buildMacLauncher(electronBinaryPath);
349}
350
351export function resolveElectronLaunchCommand(args = []) {
352 const electronPath = resolveElectronPath();
353 return {
354 electronPath,
355 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
356 };
357}
358
359export function resolveDevProtocolClient() {
360 if (hostPlatform !== "darwin" || !isDevelopment) {
361 return null;
362 }
363
364 const require = NodeModule.createRequire(import.meta.url);
365 const electronBinaryPath = require("electron");
366 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
367 return {
368 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
369 appBundleId: APP_BUNDLE_ID,
370 };
371}