Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

main.ts

1,288 lines39.1 KB

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