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