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