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