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