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

main.ts

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