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