Open History to see the last commit
1import * as ChildProcess from "node:child_process";
2import * as Crypto from "node:crypto";
3import * as FS from "node:fs";
4import * as OS from "node:os";
5import * as Path from "node:path";
6
7import {
8 app,
9 BrowserWindow,
10 dialog,
11 ipcMain,
12 Menu,
13 nativeImage,
14 nativeTheme,
15 protocol,
16 shell,
17} from "electron";
18import type { MenuItemConstructorOptions } from "electron";
19import * as Effect from "effect/Effect";
20import type {
21 DesktopTheme,
22 DesktopUpdateActionResult,
23 DesktopUpdateCheckResult,
24 DesktopUpdateState,
25} from "@t3tools/contracts";
26import { autoUpdater } from "electron-updater";
27
28import type { ContextMenuItem } from "@t3tools/contracts";
29import { NetService } from "@t3tools/shared/Net";
30import { RotatingFileSink } from "@t3tools/shared/logging";
31import { showDesktopConfirmDialog } from "./confirmDialog";
32import { syncShellEnvironment } from "./syncShellEnvironment";
33import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
34import {
35 createInitialDesktopUpdateState,
36 reduceDesktopUpdateStateOnCheckFailure,
37 reduceDesktopUpdateStateOnCheckStart,
38 reduceDesktopUpdateStateOnDownloadComplete,
39 reduceDesktopUpdateStateOnDownloadFailure,
40 reduceDesktopUpdateStateOnDownloadProgress,
41 reduceDesktopUpdateStateOnDownloadStart,
42 reduceDesktopUpdateStateOnInstallFailure,
43 reduceDesktopUpdateStateOnNoUpdate,
44 reduceDesktopUpdateStateOnUpdateAvailable,
45} from "./updateMachine";
46import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
47
48syncShellEnvironment();
49
50const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
51const CONFIRM_CHANNEL = "desktop:confirm";
52const SET_THEME_CHANNEL = "desktop:set-theme";
53const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
54const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
55const MENU_ACTION_CHANNEL = "desktop:menu-action";
56const UPDATE_STATE_CHANNEL = "desktop:update-state";
57const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
58const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
59const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
60const UPDATE_CHECK_CHANNEL = "desktop:update-check";
61const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
62const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
63const STATE_DIR = Path.join(BASE_DIR, "userdata");
64const DESKTOP_SCHEME = "t3";
65const ROOT_DIR = Path.resolve(__dirname, "../../..");
66const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
67const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
68const APP_USER_MODEL_ID = "com.t3tools.t3code";
69const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
70const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
71const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
72const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
73const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
74const COMMIT_HASH_DISPLAY_LENGTH = 12;
75const LOG_DIR = Path.join(STATE_DIR, "logs");
76const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
77const LOG_FILE_MAX_FILES = 10;
78const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
79const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
80const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
81const DESKTOP_UPDATE_CHANNEL = "latest";
82const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
83
84type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
85type LinuxDesktopNamedApp = Electron.App & {
86 setDesktopName?: (desktopName: string) => void;
87};
88
89let mainWindow: BrowserWindow | null = null;
90let backendProcess: ChildProcess.ChildProcess | null = null;
91let backendPort = 0;
92let backendAuthToken = "";
93let backendWsUrl = "";
94let restartAttempt = 0;
95let restartTimer: ReturnType<typeof setTimeout> | null = null;
96let isQuitting = false;
97let desktopProtocolRegistered = false;
98let aboutCommitHashCache: string | null | undefined;
99let desktopLogSink: RotatingFileSink | null = null;
100let backendLogSink: RotatingFileSink | null = null;
101let restoreStdIoCapture: (() => void) | null = null;
102
103let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
104const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
105 platform: process.platform,
106 processArch: process.arch,
107 runningUnderArm64Translation: app.runningUnderARM64Translation === true,
108});
109const initialUpdateState = (): DesktopUpdateState =>
110 createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
111
112function logTimestamp(): string {
113 return new Date().toISOString();
114}
115
116function logScope(scope: string): string {
117 return `${scope} run=${APP_RUN_ID}`;
118}
119
120function sanitizeLogValue(value: string): string {
121 return value.replace(/\s+/g, " ").trim();
122}
123
124function backendChildEnv(): NodeJS.ProcessEnv {
125 const env = { ...process.env };
126 delete env.T3CODE_PORT;
127 delete env.T3CODE_AUTH_TOKEN;
128 delete env.T3CODE_MODE;
129 delete env.T3CODE_NO_BROWSER;
130 delete env.T3CODE_HOST;
131 delete env.T3CODE_DESKTOP_WS_URL;
132 return env;
133}
134
135function writeDesktopLogHeader(message: string): void {
136 if (!desktopLogSink) return;
137 desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
138}
139
140function writeBackendSessionBoundary(phase: "START" | "END", details: string): void {
141 if (!backendLogSink) return;
142 const normalizedDetails = sanitizeLogValue(details);
143 backendLogSink.write(
144 `[${logTimestamp()}] ---- APP SESSION ${phase} run=${APP_RUN_ID} ${normalizedDetails} ----\n`,
145 );
146}
147
148function formatErrorMessage(error: unknown): string {
149 if (error instanceof Error) {
150 return error.message;
151 }
152 return String(error);
153}
154
155function getSafeExternalUrl(rawUrl: unknown): string | null {
156 if (typeof rawUrl !== "string" || rawUrl.length === 0) {
157 return null;
158 }
159
160 let parsedUrl: URL;
161 try {
162 parsedUrl = new URL(rawUrl);
163 } catch {
164 return null;
165 }
166
167 if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
168 return null;
169 }
170
171 return parsedUrl.toString();
172}
173
174function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
175 if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") {
176 return rawTheme;
177 }
178
179 return null;
180}
181
182function writeDesktopStreamChunk(
183 streamName: "stdout" | "stderr",
184 chunk: unknown,
185 encoding: BufferEncoding | undefined,
186): void {
187 if (!desktopLogSink) return;
188 const buffer = Buffer.isBuffer(chunk)
189 ? chunk
190 : Buffer.from(String(chunk), typeof chunk === "string" ? encoding : undefined);
191 desktopLogSink.write(`[${logTimestamp()}] [${logScope(streamName)}] `);
192 desktopLogSink.write(buffer);
193 if (buffer.length === 0 || buffer[buffer.length - 1] !== 0x0a) {
194 desktopLogSink.write("\n");
195 }
196}
197
198function installStdIoCapture(): void {
199 if (!app.isPackaged || desktopLogSink === null || restoreStdIoCapture !== null) {
200 return;
201 }
202
203 const originalStdoutWrite = process.stdout.write.bind(process.stdout);
204 const originalStderrWrite = process.stderr.write.bind(process.stderr);
205
206 const patchWrite =
207 (streamName: "stdout" | "stderr", originalWrite: typeof process.stdout.write) =>
208 (
209 chunk: string | Uint8Array,
210 encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),
211 callback?: (error?: Error | null) => void,
212 ): boolean => {
213 const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined;
214 writeDesktopStreamChunk(streamName, chunk, encoding);
215 if (typeof encodingOrCallback === "function") {
216 return originalWrite(chunk, encodingOrCallback);
217 }
218 if (callback !== undefined) {
219 return originalWrite(chunk, encoding, callback);
220 }
221 if (encoding !== undefined) {
222 return originalWrite(chunk, encoding);
223 }
224 return originalWrite(chunk);
225 };
226
227 process.stdout.write = patchWrite("stdout", originalStdoutWrite);
228 process.stderr.write = patchWrite("stderr", originalStderrWrite);
229
230 restoreStdIoCapture = () => {
231 process.stdout.write = originalStdoutWrite;
232 process.stderr.write = originalStderrWrite;
233 restoreStdIoCapture = null;
234 };
235}
236
237function initializePackagedLogging(): void {
238 if (!app.isPackaged) return;
239 try {
240 desktopLogSink = new RotatingFileSink({
241 filePath: Path.join(LOG_DIR, "desktop-main.log"),
242 maxBytes: LOG_FILE_MAX_BYTES,
243 maxFiles: LOG_FILE_MAX_FILES,
244 });
245 backendLogSink = new RotatingFileSink({
246 filePath: Path.join(LOG_DIR, "server-child.log"),
247 maxBytes: LOG_FILE_MAX_BYTES,
248 maxFiles: LOG_FILE_MAX_FILES,
249 });
250 installStdIoCapture();
251 writeDesktopLogHeader(`runtime log capture enabled logDir=${LOG_DIR}`);
252 } catch (error) {
253 // Logging setup should never block app startup.
254 console.error("[desktop] failed to initialize packaged logging", error);
255 }
256}
257
258function captureBackendOutput(child: ChildProcess.ChildProcess): void {
259 if (!app.isPackaged || backendLogSink === null) return;
260 const writeChunk = (chunk: unknown): void => {
261 if (!backendLogSink) return;
262 const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
263 backendLogSink.write(buffer);
264 };
265 child.stdout?.on("data", writeChunk);
266 child.stderr?.on("data", writeChunk);
267}
268
269initializePackagedLogging();
270
271if (process.platform === "linux") {
272 app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
273}
274
275function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
276 if (process.platform !== "darwin") return undefined;
277 if (destructiveMenuIconCache !== undefined) {
278 return destructiveMenuIconCache ?? undefined;
279 }
280 try {
281 const icon = nativeImage.createFromNamedImage("trash").resize({
282 width: 14,
283 height: 14,
284 });
285 if (icon.isEmpty()) {
286 destructiveMenuIconCache = null;
287 return undefined;
288 }
289 icon.setTemplateImage(true);
290 destructiveMenuIconCache = icon;
291 return icon;
292 } catch {
293 destructiveMenuIconCache = null;
294 return undefined;
295 }
296}
297let updatePollTimer: ReturnType<typeof setInterval> | null = null;
298let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
299let updateCheckInFlight = false;
300let updateDownloadInFlight = false;
301let updateInstallInFlight = false;
302let updaterConfigured = false;
303let updateState: DesktopUpdateState = initialUpdateState();
304
305function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
306 if (updateInstallInFlight) return "install";
307 if (updateDownloadInFlight) return "download";
308 if (updateCheckInFlight) return "check";
309 return updateState.errorContext;
310}
311
312protocol.registerSchemesAsPrivileged([
313 {
314 scheme: DESKTOP_SCHEME,
315 privileges: {
316 standard: true,
317 secure: true,
318 supportFetchAPI: true,
319 corsEnabled: true,
320 },
321 },
322]);
323
324function resolveAppRoot(): string {
325 if (!app.isPackaged) {
326 return ROOT_DIR;
327 }
328 return app.getAppPath();
329}
330
331/** Read the baked-in app-update.yml config (if applicable). */
332function readAppUpdateYml(): Record<string, string> | null {
333 try {
334 // electron-updater reads from process.resourcesPath in packaged builds,
335 // or dev-app-update.yml via app.getAppPath() in dev.
336 const ymlPath = app.isPackaged
337 ? Path.join(process.resourcesPath, "app-update.yml")
338 : Path.join(app.getAppPath(), "dev-app-update.yml");
339 const raw = FS.readFileSync(ymlPath, "utf-8");
340 // The YAML is simple key-value pairs — avoid pulling in a YAML parser by
341 // doing a line-based parse (fields: provider, owner, repo, releaseType, …).
342 const entries: Record<string, string> = {};
343 for (const line of raw.split("\n")) {
344 const match = line.match(/^(\w+):\s*(.+)$/);
345 if (match?.[1] && match[2]) entries[match[1]] = match[2].trim();
346 }
347 return entries.provider ? entries : null;
348 } catch {
349 return null;
350 }
351}
352
353function normalizeCommitHash(value: unknown): string | null {
354 if (typeof value !== "string") {
355 return null;
356 }
357 const trimmed = value.trim();
358 if (!COMMIT_HASH_PATTERN.test(trimmed)) {
359 return null;
360 }
361 return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase();
362}
363
364function resolveEmbeddedCommitHash(): string | null {
365 const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
366 if (!FS.existsSync(packageJsonPath)) {
367 return null;
368 }
369
370 try {
371 const raw = FS.readFileSync(packageJsonPath, "utf8");
372 const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
373 return normalizeCommitHash(parsed.t3codeCommitHash);
374 } catch {
375 return null;
376 }
377}
378
379function resolveAboutCommitHash(): string | null {
380 if (aboutCommitHashCache !== undefined) {
381 return aboutCommitHashCache;
382 }
383
384 const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH);
385 if (envCommitHash) {
386 aboutCommitHashCache = envCommitHash;
387 return aboutCommitHashCache;
388 }
389
390 // Only packaged builds are required to expose commit metadata.
391 if (!app.isPackaged) {
392 aboutCommitHashCache = null;
393 return aboutCommitHashCache;
394 }
395
396 aboutCommitHashCache = resolveEmbeddedCommitHash();
397
398 return aboutCommitHashCache;
399}
400
401function resolveBackendEntry(): string {
402 return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
403}
404
405function resolveBackendCwd(): string {
406 if (!app.isPackaged) {
407 return resolveAppRoot();
408 }
409 return OS.homedir();
410}
411
412function resolveDesktopStaticDir(): string | null {
413 const appRoot = resolveAppRoot();
414 const candidates = [
415 Path.join(appRoot, "apps/server/dist/client"),
416 Path.join(appRoot, "apps/web/dist"),
417 ];
418
419 for (const candidate of candidates) {
420 if (FS.existsSync(Path.join(candidate, "index.html"))) {
421 return candidate;
422 }
423 }
424
425 return null;
426}
427
428function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
429 const url = new URL(requestUrl);
430 const rawPath = decodeURIComponent(url.pathname);
431 const normalizedPath = Path.posix.normalize(rawPath).replace(/^\/+/, "");
432 if (normalizedPath.includes("..")) {
433 return Path.join(staticRoot, "index.html");
434 }
435
436 const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
437 const resolvedPath = Path.join(staticRoot, requestedPath);
438
439 if (Path.extname(resolvedPath)) {
440 return resolvedPath;
441 }
442
443 const nestedIndex = Path.join(resolvedPath, "index.html");
444 if (FS.existsSync(nestedIndex)) {
445 return nestedIndex;
446 }
447
448 return Path.join(staticRoot, "index.html");
449}
450
451function isStaticAssetRequest(requestUrl: string): boolean {
452 try {
453 const url = new URL(requestUrl);
454 return Path.extname(url.pathname).length > 0;
455 } catch {
456 return false;
457 }
458}
459
460function handleFatalStartupError(stage: string, error: unknown): void {
461 const message = formatErrorMessage(error);
462 const detail =
463 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
464 writeDesktopLogHeader(`fatal startup error stage=${stage} message=${message}`);
465 console.error(`[desktop] fatal startup error (${stage})`, error);
466 if (!isQuitting) {
467 isQuitting = true;
468 dialog.showErrorBox("T3 Code failed to start", `Stage: ${stage}\n${message}${detail}`);
469 }
470 stopBackend();
471 restoreStdIoCapture?.();
472 app.quit();
473}
474
475function registerDesktopProtocol(): void {
476 if (isDevelopment || desktopProtocolRegistered) return;
477
478 const staticRoot = resolveDesktopStaticDir();
479 if (!staticRoot) {
480 throw new Error(
481 "Desktop static bundle missing. Build apps/server (with bundled client) first.",
482 );
483 }
484
485 const staticRootResolved = Path.resolve(staticRoot);
486 const staticRootPrefix = `${staticRootResolved}${Path.sep}`;
487 const fallbackIndex = Path.join(staticRootResolved, "index.html");
488
489 protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
490 try {
491 const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
492 const resolvedCandidate = Path.resolve(candidate);
493 const isInRoot =
494 resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
495 const isAssetRequest = isStaticAssetRequest(request.url);
496
497 if (!isInRoot || !FS.existsSync(resolvedCandidate)) {
498 if (isAssetRequest) {
499 callback({ error: -6 });
500 return;
501 }
502 callback({ path: fallbackIndex });
503 return;
504 }
505
506 callback({ path: resolvedCandidate });
507 } catch {
508 callback({ path: fallbackIndex });
509 }
510 });
511
512 desktopProtocolRegistered = true;
513}
514
515function dispatchMenuAction(action: string): void {
516 const existingWindow =
517 BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
518 const targetWindow = existingWindow ?? createWindow();
519 if (!existingWindow) {
520 mainWindow = targetWindow;
521 }
522
523 const send = () => {
524 if (targetWindow.isDestroyed()) return;
525 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
526 if (!targetWindow.isVisible()) {
527 targetWindow.show();
528 }
529 targetWindow.focus();
530 };
531
532 if (targetWindow.webContents.isLoadingMainFrame()) {
533 targetWindow.webContents.once("did-finish-load", send);
534 return;
535 }
536
537 send();
538}
539
540function handleCheckForUpdatesMenuClick(): void {
541 const disabledReason = getAutoUpdateDisabledReason({
542 isDevelopment,
543 isPackaged: app.isPackaged,
544 platform: process.platform,
545 appImage: process.env.APPIMAGE,
546 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
547 });
548 if (disabledReason) {
549 console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
550 void dialog.showMessageBox({
551 type: "info",
552 title: "Updates unavailable",
553 message: "Automatic updates are not available right now.",
554 detail: disabledReason,
555 buttons: ["OK"],
556 });
557 return;
558 }
559
560 if (!BrowserWindow.getAllWindows().length) {
561 mainWindow = createWindow();
562 }
563 void checkForUpdatesFromMenu();
564}
565
566async function checkForUpdatesFromMenu(): Promise<void> {
567 await checkForUpdates("menu");
568
569 if (updateState.status === "up-to-date") {
570 void dialog.showMessageBox({
571 type: "info",
572 title: "You're up to date!",
573 message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
574 buttons: ["OK"],
575 });
576 } else if (updateState.status === "error") {
577 void dialog.showMessageBox({
578 type: "warning",
579 title: "Update check failed",
580 message: "Could not check for updates.",
581 detail: updateState.message ?? "An unknown error occurred. Please try again later.",
582 buttons: ["OK"],
583 });
584 }
585}
586
587function configureApplicationMenu(): void {
588 const template: MenuItemConstructorOptions[] = [];
589
590 if (process.platform === "darwin") {
591 template.push({
592 label: app.name,
593 submenu: [
594 { role: "about" },
595 {
596 label: "Check for Updates...",
597 click: () => handleCheckForUpdatesMenuClick(),
598 },
599 { type: "separator" },
600 {
601 label: "Settings...",
602 accelerator: "CmdOrCtrl+,",
603 click: () => dispatchMenuAction("open-settings"),
604 },
605 { type: "separator" },
606 { role: "services" },
607 { type: "separator" },
608 { role: "hide" },
609 { role: "hideOthers" },
610 { role: "unhide" },
611 { type: "separator" },
612 { role: "quit" },
613 ],
614 });
615 }
616
617 template.push(
618 {
619 label: "File",
620 submenu: [
621 ...(process.platform === "darwin"
622 ? []
623 : [
624 {
625 label: "Settings...",
626 accelerator: "CmdOrCtrl+,",
627 click: () => dispatchMenuAction("open-settings"),
628 },
629 { type: "separator" as const },
630 ]),
631 { role: process.platform === "darwin" ? "close" : "quit" },
632 ],
633 },
634 { role: "editMenu" },
635 {
636 label: "View",
637 submenu: [
638 { role: "reload" },
639 { role: "forceReload" },
640 { role: "toggleDevTools" },
641 { type: "separator" },
642 { role: "resetZoom" },
643 { role: "zoomIn", accelerator: "CmdOrCtrl+=" },
644 { role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
645 { role: "zoomOut" },
646 { type: "separator" },
647 { role: "togglefullscreen" },
648 ],
649 },
650 { role: "windowMenu" },
651 {
652 role: "help",
653 submenu: [
654 {
655 label: "Check for Updates...",
656 click: () => handleCheckForUpdatesMenuClick(),
657 },
658 ],
659 },
660 );
661
662 Menu.setApplicationMenu(Menu.buildFromTemplate(template));
663}
664
665function resolveResourcePath(fileName: string): string | null {
666 const candidates = [
667 Path.join(__dirname, "../resources", fileName),
668 Path.join(__dirname, "../prod-resources", fileName),
669 Path.join(process.resourcesPath, "resources", fileName),
670 Path.join(process.resourcesPath, fileName),
671 ];
672
673 for (const candidate of candidates) {
674 if (FS.existsSync(candidate)) {
675 return candidate;
676 }
677 }
678
679 return null;
680}
681
682function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
683 return resolveResourcePath(`icon.${ext}`);
684}
685
686/**
687 * Resolve the Electron userData directory path.
688 *
689 * Electron derives the default userData path from `productName` in
690 * package.json, which currently produces directories with spaces and
691 * parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is
692 * unfriendly for shell usage and violates Linux naming conventions.
693 *
694 * We override it to a clean lowercase name (`t3code`). If the legacy
695 * directory already exists we keep using it so existing users don't
696 * lose their Chromium profile data (localStorage, cookies, sessions).
697 */
698function resolveUserDataPath(): string {
699 const appDataBase =
700 process.platform === "win32"
701 ? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming")
702 : process.platform === "darwin"
703 ? Path.join(OS.homedir(), "Library", "Application Support")
704 : process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config");
705
706 const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME);
707 if (FS.existsSync(legacyPath)) {
708 return legacyPath;
709 }
710
711 return Path.join(appDataBase, USER_DATA_DIR_NAME);
712}
713
714function configureAppIdentity(): void {
715 app.setName(APP_DISPLAY_NAME);
716 const commitHash = resolveAboutCommitHash();
717 app.setAboutPanelOptions({
718 applicationName: APP_DISPLAY_NAME,
719 applicationVersion: app.getVersion(),
720 version: commitHash ?? "unknown",
721 });
722
723 if (process.platform === "win32") {
724 app.setAppUserModelId(APP_USER_MODEL_ID);
725 }
726
727 if (process.platform === "linux") {
728 (app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME);
729 }
730
731 if (process.platform === "darwin" && app.dock) {
732 const iconPath = resolveIconPath("png");
733 if (iconPath) {
734 app.dock.setIcon(iconPath);
735 }
736 }
737}
738
739function clearUpdatePollTimer(): void {
740 if (updateStartupTimer) {
741 clearTimeout(updateStartupTimer);
742 updateStartupTimer = null;
743 }
744 if (updatePollTimer) {
745 clearInterval(updatePollTimer);
746 updatePollTimer = null;
747 }
748}
749
750function emitUpdateState(): void {
751 for (const window of BrowserWindow.getAllWindows()) {
752 if (window.isDestroyed()) continue;
753 window.webContents.send(UPDATE_STATE_CHANNEL, updateState);
754 }
755}
756
757function setUpdateState(patch: Partial<DesktopUpdateState>): void {
758 updateState = { ...updateState, ...patch };
759 emitUpdateState();
760}
761
762function shouldEnableAutoUpdates(): boolean {
763 return (
764 getAutoUpdateDisabledReason({
765 isDevelopment,
766 isPackaged: app.isPackaged,
767 platform: process.platform,
768 appImage: process.env.APPIMAGE,
769 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
770 }) === null
771 );
772}
773
774async function checkForUpdates(reason: string): Promise<boolean> {
775 if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
776 if (updateState.status === "downloading" || updateState.status === "downloaded") {
777 console.info(
778 `[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
779 );
780 return false;
781 }
782 updateCheckInFlight = true;
783 setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
784 console.info(`[desktop-updater] Checking for updates (${reason})...`);
785
786 try {
787 await autoUpdater.checkForUpdates();
788 return true;
789 } catch (error: unknown) {
790 const message = error instanceof Error ? error.message : String(error);
791 setUpdateState(
792 reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
793 );
794 console.error(`[desktop-updater] Failed to check for updates: ${message}`);
795 return true;
796 } finally {
797 updateCheckInFlight = false;
798 }
799}
800
801async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
802 if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
803 return { accepted: false, completed: false };
804 }
805 updateDownloadInFlight = true;
806 setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
807 autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
808 console.info("[desktop-updater] Downloading update...");
809
810 try {
811 await autoUpdater.downloadUpdate();
812 return { accepted: true, completed: true };
813 } catch (error: unknown) {
814 const message = error instanceof Error ? error.message : String(error);
815 setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message));
816 console.error(`[desktop-updater] Failed to download update: ${message}`);
817 return { accepted: true, completed: false };
818 } finally {
819 updateDownloadInFlight = false;
820 }
821}
822
823async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
824 if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
825 return { accepted: false, completed: false };
826 }
827
828 isQuitting = true;
829 updateInstallInFlight = true;
830 clearUpdatePollTimer();
831 try {
832 await stopBackendAndWaitForExit();
833 // Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
834 for (const win of BrowserWindow.getAllWindows()) {
835 win.destroy();
836 }
837 // `quitAndInstall()` only starts the handoff to the updater. The actual
838 // install may still fail asynchronously, so keep the action incomplete
839 // until we either quit or receive an updater error.
840 autoUpdater.quitAndInstall(true, true);
841 return { accepted: true, completed: false };
842 } catch (error: unknown) {
843 const message = formatErrorMessage(error);
844 updateInstallInFlight = false;
845 isQuitting = false;
846 setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
847 console.error(`[desktop-updater] Failed to install update: ${message}`);
848 return { accepted: true, completed: false };
849 }
850}
851
852function configureAutoUpdater(): void {
853 const enabled = shouldEnableAutoUpdates();
854 setUpdateState({
855 ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
856 enabled,
857 status: enabled ? "idle" : "disabled",
858 });
859 if (!enabled) {
860 return;
861 }
862 updaterConfigured = true;
863
864 const githubToken =
865 process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
866 if (githubToken) {
867 // When a token is provided, re-configure the feed with `private: true` so
868 // electron-updater uses the GitHub API (api.github.com) instead of the
869 // public Atom feed (github.com/…/releases.atom) which rejects Bearer auth.
870 const appUpdateYml = readAppUpdateYml();
871 if (appUpdateYml?.provider === "github") {
872 autoUpdater.setFeedURL({
873 ...appUpdateYml,
874 provider: "github" as const,
875 private: true,
876 token: githubToken,
877 });
878 }
879 }
880
881 if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
882 autoUpdater.setFeedURL({
883 provider: "generic",
884 url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
885 });
886 }
887
888 autoUpdater.autoDownload = false;
889 autoUpdater.autoInstallOnAppQuit = false;
890 // Keep alpha branding, but force all installs onto the stable update track.
891 autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
892 autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
893 autoUpdater.allowDowngrade = false;
894 autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
895 let lastLoggedDownloadMilestone = -1;
896
897 if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
898 console.info(
899 "[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.",
900 );
901 }
902
903 autoUpdater.on("checking-for-update", () => {
904 console.info("[desktop-updater] Looking for updates...");
905 });
906 autoUpdater.on("update-available", (info) => {
907 setUpdateState(
908 reduceDesktopUpdateStateOnUpdateAvailable(
909 updateState,
910 info.version,
911 new Date().toISOString(),
912 ),
913 );
914 lastLoggedDownloadMilestone = -1;
915 console.info(`[desktop-updater] Update available: ${info.version}`);
916 });
917 autoUpdater.on("update-not-available", () => {
918 setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
919 lastLoggedDownloadMilestone = -1;
920 console.info("[desktop-updater] No updates available.");
921 });
922 autoUpdater.on("error", (error) => {
923 const message = formatErrorMessage(error);
924 if (updateInstallInFlight) {
925 updateInstallInFlight = false;
926 isQuitting = false;
927 setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
928 console.error(`[desktop-updater] Updater error: ${message}`);
929 return;
930 }
931 if (!updateCheckInFlight && !updateDownloadInFlight) {
932 setUpdateState({
933 status: "error",
934 message,
935 checkedAt: new Date().toISOString(),
936 downloadPercent: null,
937 errorContext: resolveUpdaterErrorContext(),
938 canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null,
939 });
940 }
941 console.error(`[desktop-updater] Updater error: ${message}`);
942 });
943 autoUpdater.on("download-progress", (progress) => {
944 const percent = Math.floor(progress.percent);
945 if (
946 shouldBroadcastDownloadProgress(updateState, progress.percent) ||
947 updateState.message !== null
948 ) {
949 setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent));
950 }
951 const milestone = percent - (percent % 10);
952 if (milestone > lastLoggedDownloadMilestone) {
953 lastLoggedDownloadMilestone = milestone;
954 console.info(`[desktop-updater] Download progress: ${percent}%`);
955 }
956 });
957 autoUpdater.on("update-downloaded", (info) => {
958 setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version));
959 console.info(`[desktop-updater] Update downloaded: ${info.version}`);
960 });
961
962 clearUpdatePollTimer();
963
964 updateStartupTimer = setTimeout(() => {
965 updateStartupTimer = null;
966 void checkForUpdates("startup");
967 }, AUTO_UPDATE_STARTUP_DELAY_MS);
968 updateStartupTimer.unref();
969
970 updatePollTimer = setInterval(() => {
971 void checkForUpdates("poll");
972 }, AUTO_UPDATE_POLL_INTERVAL_MS);
973 updatePollTimer.unref();
974}
975function scheduleBackendRestart(reason: string): void {
976 if (isQuitting || restartTimer) return;
977
978 const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
979 restartAttempt += 1;
980 console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
981
982 restartTimer = setTimeout(() => {
983 restartTimer = null;
984 startBackend();
985 }, delayMs);
986}
987
988function startBackend(): void {
989 if (isQuitting || backendProcess) return;
990
991 const backendEntry = resolveBackendEntry();
992 if (!FS.existsSync(backendEntry)) {
993 scheduleBackendRestart(`missing server entry at ${backendEntry}`);
994 return;
995 }
996
997 const captureBackendLogs = app.isPackaged && backendLogSink !== null;
998 const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
999 cwd: resolveBackendCwd(),
1000 // In Electron main, process.execPath points to the Electron binary.
1001 // Run the child in Node mode so this backend process does not become a GUI app instance.
1002 env: {
1003 ...backendChildEnv(),
1004 ELECTRON_RUN_AS_NODE: "1",
1005 },
1006 stdio: captureBackendLogs
1007 ? ["ignore", "pipe", "pipe", "pipe"]
1008 : ["ignore", "inherit", "inherit", "pipe"],
1009 });
1010 const bootstrapStream = child.stdio[3];
1011 if (bootstrapStream && "write" in bootstrapStream) {
1012 bootstrapStream.write(
1013 `${JSON.stringify({
1014 mode: "desktop",
1015 noBrowser: true,
1016 port: backendPort,
1017 t3Home: BASE_DIR,
1018 authToken: backendAuthToken,
1019 })}\n`,
1020 );
1021 bootstrapStream.end();
1022 } else {
1023 child.kill("SIGTERM");
1024 scheduleBackendRestart("missing desktop bootstrap pipe");
1025 return;
1026 }
1027 backendProcess = child;
1028 let backendSessionClosed = false;
1029 const closeBackendSession = (details: string) => {
1030 if (backendSessionClosed) return;
1031 backendSessionClosed = true;
1032 writeBackendSessionBoundary("END", details);
1033 };
1034 writeBackendSessionBoundary(
1035 "START",
1036 `pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`,
1037 );
1038 captureBackendOutput(child);
1039
1040 child.once("spawn", () => {
1041 restartAttempt = 0;
1042 });
1043
1044 child.on("error", (error) => {
1045 if (backendProcess === child) {
1046 backendProcess = null;
1047 }
1048 closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
1049 scheduleBackendRestart(error.message);
1050 });
1051
1052 child.on("exit", (code, signal) => {
1053 if (backendProcess === child) {
1054 backendProcess = null;
1055 }
1056 closeBackendSession(
1057 `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
1058 );
1059 if (isQuitting) return;
1060 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
1061 scheduleBackendRestart(reason);
1062 });
1063}
1064
1065function stopBackend(): void {
1066 if (restartTimer) {
1067 clearTimeout(restartTimer);
1068 restartTimer = null;
1069 }
1070
1071 const child = backendProcess;
1072 backendProcess = null;
1073 if (!child) return;
1074
1075 if (child.exitCode === null && child.signalCode === null) {
1076 child.kill("SIGTERM");
1077 setTimeout(() => {
1078 if (child.exitCode === null && child.signalCode === null) {
1079 child.kill("SIGKILL");
1080 }
1081 }, 2_000).unref();
1082 }
1083}
1084
1085async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
1086 if (restartTimer) {
1087 clearTimeout(restartTimer);
1088 restartTimer = null;
1089 }
1090
1091 const child = backendProcess;
1092 backendProcess = null;
1093 if (!child) return;
1094 const backendChild = child;
1095 if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
1096
1097 await new Promise<void>((resolve) => {
1098 let settled = false;
1099 let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
1100 let exitTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
1101
1102 function settle(): void {
1103 if (settled) return;
1104 settled = true;
1105 backendChild.off("exit", onExit);
1106 if (forceKillTimer) {
1107 clearTimeout(forceKillTimer);
1108 }
1109 if (exitTimeoutTimer) {
1110 clearTimeout(exitTimeoutTimer);
1111 }
1112 resolve();
1113 }
1114
1115 function onExit(): void {
1116 settle();
1117 }
1118
1119 backendChild.once("exit", onExit);
1120 backendChild.kill("SIGTERM");
1121
1122 forceKillTimer = setTimeout(() => {
1123 if (backendChild.exitCode === null && backendChild.signalCode === null) {
1124 backendChild.kill("SIGKILL");
1125 }
1126 }, 2_000);
1127 forceKillTimer.unref();
1128
1129 exitTimeoutTimer = setTimeout(() => {
1130 settle();
1131 }, timeoutMs);
1132 exitTimeoutTimer.unref();
1133 });
1134}
1135
1136function registerIpcHandlers(): void {
1137 ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
1138 ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
1139 event.returnValue = backendWsUrl;
1140 });
1141
1142 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
1143 ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
1144 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
1145 const result = owner
1146 ? await dialog.showOpenDialog(owner, {
1147 properties: ["openDirectory", "createDirectory"],
1148 })
1149 : await dialog.showOpenDialog({
1150 properties: ["openDirectory", "createDirectory"],
1151 });
1152 if (result.canceled) return null;
1153 return result.filePaths[0] ?? null;
1154 });
1155
1156 ipcMain.removeHandler(CONFIRM_CHANNEL);
1157 ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
1158 if (typeof message !== "string") {
1159 return false;
1160 }
1161
1162 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
1163 return showDesktopConfirmDialog(message, owner);
1164 });
1165
1166 ipcMain.removeHandler(SET_THEME_CHANNEL);
1167 ipcMain.handle(SET_THEME_CHANNEL, async (_event, rawTheme: unknown) => {
1168 const theme = getSafeTheme(rawTheme);
1169 if (!theme) {
1170 return;
1171 }
1172
1173 nativeTheme.themeSource = theme;
1174 });
1175
1176 ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
1177 ipcMain.handle(
1178 CONTEXT_MENU_CHANNEL,
1179 async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
1180 const normalizedItems = items
1181 .filter((item) => typeof item.id === "string" && typeof item.label === "string")
1182 .map((item) => ({
1183 id: item.id,
1184 label: item.label,
1185 destructive: item.destructive === true,
1186 disabled: item.disabled === true,
1187 }));
1188 if (normalizedItems.length === 0) {
1189 return null;
1190 }
1191
1192 const popupPosition =
1193 position &&
1194 Number.isFinite(position.x) &&
1195 Number.isFinite(position.y) &&
1196 position.x >= 0 &&
1197 position.y >= 0
1198 ? {
1199 x: Math.floor(position.x),
1200 y: Math.floor(position.y),
1201 }
1202 : null;
1203
1204 const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
1205 if (!window) return null;
1206
1207 return new Promise<string | null>((resolve) => {
1208 const template: MenuItemConstructorOptions[] = [];
1209 let hasInsertedDestructiveSeparator = false;
1210 for (const item of normalizedItems) {
1211 if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
1212 template.push({ type: "separator" });
1213 hasInsertedDestructiveSeparator = true;
1214 }
1215 const itemOption: MenuItemConstructorOptions = {
1216 label: item.label,
1217 enabled: !item.disabled,
1218 click: () => resolve(item.id),
1219 };
1220 if (item.destructive) {
1221 const destructiveIcon = getDestructiveMenuIcon();
1222 if (destructiveIcon) {
1223 itemOption.icon = destructiveIcon;
1224 }
1225 }
1226 template.push(itemOption);
1227 }
1228
1229 const menu = Menu.buildFromTemplate(template);
1230 menu.popup({
1231 window,
1232 ...popupPosition,
1233 callback: () => resolve(null),
1234 });
1235 });
1236 },
1237 );
1238
1239 ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
1240 ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
1241 const externalUrl = getSafeExternalUrl(rawUrl);
1242 if (!externalUrl) {
1243 return false;
1244 }
1245
1246 try {
1247 await shell.openExternal(externalUrl);
1248 return true;
1249 } catch {
1250 return false;
1251 }
1252 });
1253
1254 ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
1255 ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
1256
1257 ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
1258 ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
1259 const result = await downloadAvailableUpdate();
1260 return {
1261 accepted: result.accepted,
1262 completed: result.completed,
1263 state: updateState,
1264 } satisfies DesktopUpdateActionResult;
1265 });
1266
1267 ipcMain.removeHandler(UPDATE_INSTALL_CHANNEL);
1268 ipcMain.handle(UPDATE_INSTALL_CHANNEL, async () => {
1269 if (isQuitting) {
1270 return {
1271 accepted: false,
1272 completed: false,
1273 state: updateState,
1274 } satisfies DesktopUpdateActionResult;
1275 }
1276 const result = await installDownloadedUpdate();
1277 return {
1278 accepted: result.accepted,
1279 completed: result.completed,
1280 state: updateState,
1281 } satisfies DesktopUpdateActionResult;
1282 });
1283
1284 ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
1285 ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
1286 if (!updaterConfigured) {
1287 return {
1288 checked: false,
1289 state: updateState,
1290 } satisfies DesktopUpdateCheckResult;
1291 }
1292 const checked = await checkForUpdates("web-ui");
1293 return {
1294 checked,
1295 state: updateState,
1296 } satisfies DesktopUpdateCheckResult;
1297 });
1298}
1299
1300function getIconOption(): { icon: string } | Record<string, never> {
1301 if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
1302 const ext = process.platform === "win32" ? "ico" : "png";
1303 const iconPath = resolveIconPath(ext);
1304 return iconPath ? { icon: iconPath } : {};
1305}
1306
1307function createWindow(): BrowserWindow {
1308 const window = new BrowserWindow({
1309 width: 1100,
1310 height: 780,
1311 minWidth: 840,
1312 minHeight: 620,
1313 show: false,
1314 autoHideMenuBar: true,
1315 ...getIconOption(),
1316 title: APP_DISPLAY_NAME,
1317 titleBarStyle: "hiddenInset",
1318 trafficLightPosition: { x: 16, y: 18 },
1319 webPreferences: {
1320 preload: Path.join(__dirname, "preload.js"),
1321 contextIsolation: true,
1322 nodeIntegration: false,
1323 sandbox: true,
1324 },
1325 });
1326
1327 window.webContents.on("context-menu", (event, params) => {
1328 event.preventDefault();
1329
1330 const menuTemplate: MenuItemConstructorOptions[] = [];
1331
1332 if (params.misspelledWord) {
1333 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
1334 menuTemplate.push({
1335 label: suggestion,
1336 click: () => window.webContents.replaceMisspelling(suggestion),
1337 });
1338 }
1339 if (params.dictionarySuggestions.length === 0) {
1340 menuTemplate.push({ label: "No suggestions", enabled: false });
1341 }
1342 menuTemplate.push({ type: "separator" });
1343 }
1344
1345 menuTemplate.push(
1346 { role: "cut", enabled: params.editFlags.canCut },
1347 { role: "copy", enabled: params.editFlags.canCopy },
1348 { role: "paste", enabled: params.editFlags.canPaste },
1349 { role: "selectAll", enabled: params.editFlags.canSelectAll },
1350 );
1351
1352 Menu.buildFromTemplate(menuTemplate).popup({ window });
1353 });
1354
1355 window.webContents.setWindowOpenHandler(({ url }) => {
1356 const externalUrl = getSafeExternalUrl(url);
1357 if (externalUrl) {
1358 void shell.openExternal(externalUrl);
1359 }
1360 return { action: "deny" };
1361 });
1362
1363 window.on("page-title-updated", (event) => {
1364 event.preventDefault();
1365 window.setTitle(APP_DISPLAY_NAME);
1366 });
1367 window.webContents.on("did-finish-load", () => {
1368 window.setTitle(APP_DISPLAY_NAME);
1369 emitUpdateState();
1370 });
1371 window.once("ready-to-show", () => {
1372 window.show();
1373 });
1374
1375 if (isDevelopment) {
1376 void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
1377 window.webContents.openDevTools({ mode: "detach" });
1378 } else {
1379 void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
1380 }
1381
1382 window.on("closed", () => {
1383 if (mainWindow === window) {
1384 mainWindow = null;
1385 }
1386 });
1387
1388 return window;
1389}
1390
1391// Override Electron's userData path before the `ready` event so that
1392// Chromium session data uses a filesystem-friendly directory name.
1393// Must be called synchronously at the top level — before `app.whenReady()`.
1394app.setPath("userData", resolveUserDataPath());
1395
1396configureAppIdentity();
1397
1398async function bootstrap(): Promise<void> {
1399 writeDesktopLogHeader("bootstrap start");
1400 backendPort = await Effect.service(NetService).pipe(
1401 Effect.flatMap((net) => net.reserveLoopbackPort()),
1402 Effect.provide(NetService.layer),
1403 Effect.runPromise,
1404 );
1405 writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
1406 backendAuthToken = Crypto.randomBytes(24).toString("hex");
1407 const baseUrl = `ws://127.0.0.1:${backendPort}`;
1408 backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
1409 writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
1410
1411 registerIpcHandlers();
1412 writeDesktopLogHeader("bootstrap ipc handlers registered");
1413 startBackend();
1414 writeDesktopLogHeader("bootstrap backend start requested");
1415 mainWindow = createWindow();
1416 writeDesktopLogHeader("bootstrap main window created");
1417}
1418
1419app.on("before-quit", () => {
1420 isQuitting = true;
1421 updateInstallInFlight = false;
1422 writeDesktopLogHeader("before-quit received");
1423 clearUpdatePollTimer();
1424 stopBackend();
1425 restoreStdIoCapture?.();
1426});
1427
1428app
1429 .whenReady()
1430 .then(() => {
1431 writeDesktopLogHeader("app ready");
1432 configureAppIdentity();
1433 configureApplicationMenu();
1434 registerDesktopProtocol();
1435 configureAutoUpdater();
1436 void bootstrap().catch((error) => {
1437 handleFatalStartupError("bootstrap", error);
1438 });
1439
1440 app.on("activate", () => {
1441 if (BrowserWindow.getAllWindows().length === 0) {
1442 mainWindow = createWindow();
1443 }
1444 });
1445 })
1446 .catch((error) => {
1447 handleFatalStartupError("whenReady", error);
1448 });
1449
1450app.on("window-all-closed", () => {
1451 if (process.platform !== "darwin" && !isQuitting) {
1452 app.quit();
1453 }
1454});
1455
1456if (process.platform !== "win32") {
1457 process.on("SIGINT", () => {
1458 if (isQuitting) return;
1459 isQuitting = true;
1460 writeDesktopLogHeader("SIGINT received");
1461 clearUpdatePollTimer();
1462 stopBackend();
1463 restoreStdIoCapture?.();
1464 app.quit();
1465 });
1466
1467 process.on("SIGTERM", () => {
1468 if (isQuitting) return;
1469 isQuitting = true;
1470 writeDesktopLogHeader("SIGTERM received");
1471 clearUpdatePollTimer();
1472 stopBackend();
1473 restoreStdIoCapture?.();
1474 app.quit();
1475 });
1476}