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

main.ts

1,391 lines41.8 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 checkForUpdatesFromMenu();
540​
541async function checkForUpdatesFromMenu(): Promise<void> {
542 await checkForUpdates("menu");
543​
544 if (updateState.status === "up-to-date") {
545 void dialog.showMessageBox({
546 type: "info",
547 title: "You're up to date!",
548 message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
549 buttons: ["OK"],
550 });
551 } else if (updateState.status === "error") {
552 void dialog.showMessageBox({
553 type: "warning",
554 title: "Update check failed",
555 message: "Could not check for updates.",
556 detail: updateState.message ?? "An unknown error occurred. Please try again later.",
557 buttons: ["OK"],
558 });
559 }
561​
562function configureApplicationMenu(): void {
563 const template: MenuItemConstructorOptions[] = [];
564​
565 if (process.platform === "darwin") {
566 template.push({
567 label: app.name,
568 submenu: [
569 { role: "about" },
570 {
571 label: "Check for Updates...",
572 click: () => handleCheckForUpdatesMenuClick(),
573 },
574 { type: "separator" },
575 {
576 label: "Settings...",
577 accelerator: "CmdOrCtrl+,",
578 click: () => dispatchMenuAction("open-settings"),
579 },
580 { type: "separator" },
581 { role: "services" },
582 { type: "separator" },
583 { role: "hide" },
584 { role: "hideOthers" },
585 { role: "unhide" },
586 { type: "separator" },
587 { role: "quit" },
588 ],
589 });
590 }
591​
592 template.push(
593 {
594 label: "File",
595 submenu: [
596 ...(process.platform === "darwin"
597 ? []
598 : [
599 {
600 label: "Settings...",
601 accelerator: "CmdOrCtrl+,",
602 click: () => dispatchMenuAction("open-settings"),
603 },
604 { type: "separator" as const },
605 ]),
606 { role: process.platform === "darwin" ? "close" : "quit" },
607 ],
608 },
609 { role: "editMenu" },
610 {
611 label: "View",
612 submenu: [
613 { role: "reload" },
614 { role: "forceReload" },
615 { role: "toggleDevTools" },
616 { type: "separator" },
617 { role: "resetZoom" },
618 { role: "zoomIn", accelerator: "CmdOrCtrl+=" },
619 { role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
620 { role: "zoomOut" },
621 { type: "separator" },
622 { role: "togglefullscreen" },
623 ],
624 },
625 { role: "windowMenu" },
626 {
627 role: "help",
628 submenu: [
629 {
630 label: "Check for Updates...",
631 click: () => handleCheckForUpdatesMenuClick(),
632 },
633 ],
634 },
635 );
636​
637 Menu.setApplicationMenu(Menu.buildFromTemplate(template));
639​
640function resolveResourcePath(fileName: string): string | null {
641 const candidates = [
642 Path.join(__dirname, "../resources", fileName),
643 Path.join(__dirname, "../prod-resources", fileName),
644 Path.join(process.resourcesPath, "resources", fileName),
645 Path.join(process.resourcesPath, fileName),
646 ];
647​
648 for (const candidate of candidates) {
649 if (FS.existsSync(candidate)) {
650 return candidate;
651 }
652 }
653​
654 return null;
656​
657function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
658 return resolveResourcePath(`icon.${ext}`);
660​
661/**
662 * Resolve the Electron userData directory path.
663 *
664 * Electron derives the default userData path from `productName` in
665 * package.json, which currently produces directories with spaces and
666 * parentheses (e.g. `~/.config/T3 Code (Alpha)` on Linux). This is
667 * unfriendly for shell usage and violates Linux naming conventions.
668 *
669 * We override it to a clean lowercase name (`t3code`). If the legacy
670 * directory already exists we keep using it so existing users don't
671 * lose their Chromium profile data (localStorage, cookies, sessions).
672 */
673function resolveUserDataPath(): string {
674 const appDataBase =
675 process.platform === "win32"
676 ? process.env.APPDATA || Path.join(OS.homedir(), "AppData", "Roaming")
677 : process.platform === "darwin"
678 ? Path.join(OS.homedir(), "Library", "Application Support")
679 : process.env.XDG_CONFIG_HOME || Path.join(OS.homedir(), ".config");
680​
681 const legacyPath = Path.join(appDataBase, LEGACY_USER_DATA_DIR_NAME);
682 if (FS.existsSync(legacyPath)) {
683 return legacyPath;
684 }
685​
686 return Path.join(appDataBase, USER_DATA_DIR_NAME);
688​
689function configureAppIdentity(): void {
690 app.setName(APP_DISPLAY_NAME);
691 const commitHash = resolveAboutCommitHash();
692 app.setAboutPanelOptions({
693 applicationName: APP_DISPLAY_NAME,
694 applicationVersion: app.getVersion(),
695 version: commitHash ?? "unknown",
696 });
697​
698 if (process.platform === "win32") {
699 app.setAppUserModelId(APP_USER_MODEL_ID);
700 }
701​
702 if (process.platform === "darwin" && app.dock) {
703 const iconPath = resolveIconPath("png");
704 if (iconPath) {
705 app.dock.setIcon(iconPath);
706 }
707 }
709​
710function clearUpdatePollTimer(): void {
711 if (updateStartupTimer) {
712 clearTimeout(updateStartupTimer);
713 updateStartupTimer = null;
714 }
715 if (updatePollTimer) {
716 clearInterval(updatePollTimer);
717 updatePollTimer = null;
718 }
720​
721function emitUpdateState(): void {
722 for (const window of BrowserWindow.getAllWindows()) {
723 if (window.isDestroyed()) continue;
724 window.webContents.send(UPDATE_STATE_CHANNEL, updateState);
725 }
727​
728function setUpdateState(patch: Partial<DesktopUpdateState>): void {
729 updateState = { ...updateState, ...patch };
730 emitUpdateState();
732​
733function shouldEnableAutoUpdates(): boolean {
734 return (
735 getAutoUpdateDisabledReason({
736 isDevelopment,
737 isPackaged: app.isPackaged,
738 platform: process.platform,
739 appImage: process.env.APPIMAGE,
740 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
741 }) === null
742 );
744​
745async function checkForUpdates(reason: string): Promise<void> {
746 if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
747 if (updateState.status === "downloading" || updateState.status === "downloaded") {
748 console.info(
749 `[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
750 );
751 return;
752 }
753 updateCheckInFlight = true;
754 setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
755 console.info(`[desktop-updater] Checking for updates (${reason})...`);
756​
757 try {
758 await autoUpdater.checkForUpdates();
759 } catch (error: unknown) {
760 const message = error instanceof Error ? error.message : String(error);
761 setUpdateState(
762 reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
763 );
764 console.error(`[desktop-updater] Failed to check for updates: ${message}`);
765 } finally {
766 updateCheckInFlight = false;
767 }
769​
770async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
771 if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
772 return { accepted: false, completed: false };
773 }
774 updateDownloadInFlight = true;
775 setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
776 autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
777 console.info("[desktop-updater] Downloading update...");
778​
779 try {
780 await autoUpdater.downloadUpdate();
781 return { accepted: true, completed: true };
782 } catch (error: unknown) {
783 const message = error instanceof Error ? error.message : String(error);
784 setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message));
785 console.error(`[desktop-updater] Failed to download update: ${message}`);
786 return { accepted: true, completed: false };
787 } finally {
788 updateDownloadInFlight = false;
789 }
791​
792async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
793 if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
794 return { accepted: false, completed: false };
795 }
796​
797 isQuitting = true;
798 clearUpdatePollTimer();
799 try {
800 await stopBackendAndWaitForExit();
801 autoUpdater.quitAndInstall();
802 return { accepted: true, completed: true };
803 } catch (error: unknown) {
804 const message = formatErrorMessage(error);
805 isQuitting = false;
806 setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
807 console.error(`[desktop-updater] Failed to install update: ${message}`);
808 return { accepted: true, completed: false };
809 }
811​
812function configureAutoUpdater(): void {
813 const enabled = shouldEnableAutoUpdates();
814 setUpdateState({
815 ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
816 enabled,
817 status: enabled ? "idle" : "disabled",
818 });
819 if (!enabled) {
820 return;
821 }
822 updaterConfigured = true;
823​
824 const githubToken =
825 process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
826 if (githubToken) {
827 // When a token is provided, re-configure the feed with `private: true` so
828 // electron-updater uses the GitHub API (api.github.com) instead of the
829 // public Atom feed (github.com/…/releases.atom) which rejects Bearer auth.
830 const appUpdateYml = readAppUpdateYml();
831 if (appUpdateYml?.provider === "github") {
832 autoUpdater.setFeedURL({
833 ...appUpdateYml,
834 provider: "github" as const,
835 private: true,
836 token: githubToken,
837 });
838 }
839 }
840​
841 autoUpdater.autoDownload = false;
842 autoUpdater.autoInstallOnAppQuit = false;
843 // Keep alpha branding, but force all installs onto the stable update track.
844 autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
845 autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
846 autoUpdater.allowDowngrade = false;
847 autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
848 let lastLoggedDownloadMilestone = -1;
849​
850 if (isArm64HostRunningIntelBuild(desktopRuntimeInfo)) {
851 console.info(
852 "[desktop-updater] Apple Silicon host detected while running Intel build; updates will switch to arm64 packages.",
853 );
854 }
855​
856 autoUpdater.on("checking-for-update", () => {
857 console.info("[desktop-updater] Looking for updates...");
858 });
859 autoUpdater.on("update-available", (info) => {
860 setUpdateState(
861 reduceDesktopUpdateStateOnUpdateAvailable(
862 updateState,
863 info.version,
864 new Date().toISOString(),
865 ),
866 );
867 lastLoggedDownloadMilestone = -1;
868 console.info(`[desktop-updater] Update available: ${info.version}`);
869 });
870 autoUpdater.on("update-not-available", () => {
871 setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
872 lastLoggedDownloadMilestone = -1;
873 console.info("[desktop-updater] No updates available.");
874 });
875 autoUpdater.on("error", (error) => {
876 const message = formatErrorMessage(error);
877 if (!updateCheckInFlight && !updateDownloadInFlight) {
878 setUpdateState({
879 status: "error",
880 message,
881 checkedAt: new Date().toISOString(),
882 downloadPercent: null,
883 errorContext: resolveUpdaterErrorContext(),
884 canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null,
885 });
886 }
887 console.error(`[desktop-updater] Updater error: ${message}`);
888 });
889 autoUpdater.on("download-progress", (progress) => {
890 const percent = Math.floor(progress.percent);
891 if (
892 shouldBroadcastDownloadProgress(updateState, progress.percent) ||
893 updateState.message !== null
894 ) {
895 setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent));
896 }
897 const milestone = percent - (percent % 10);
898 if (milestone > lastLoggedDownloadMilestone) {
899 lastLoggedDownloadMilestone = milestone;
900 console.info(`[desktop-updater] Download progress: ${percent}%`);
901 }
902 });
903 autoUpdater.on("update-downloaded", (info) => {
904 setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version));
905 console.info(`[desktop-updater] Update downloaded: ${info.version}`);
906 });
907​
908 clearUpdatePollTimer();
909​
910 updateStartupTimer = setTimeout(() => {
911 updateStartupTimer = null;
912 void checkForUpdates("startup");
913 }, AUTO_UPDATE_STARTUP_DELAY_MS);
914 updateStartupTimer.unref();
915​
916 updatePollTimer = setInterval(() => {
917 void checkForUpdates("poll");
918 }, AUTO_UPDATE_POLL_INTERVAL_MS);
919 updatePollTimer.unref();
921function backendEnv(): NodeJS.ProcessEnv {
922 return {
923 ...process.env,
924 T3CODE_MODE: "desktop",
925 T3CODE_NO_BROWSER: "1",
926 T3CODE_PORT: String(backendPort),
927 T3CODE_STATE_DIR: STATE_DIR,
928 T3CODE_AUTH_TOKEN: backendAuthToken,
929 };
931​
932function scheduleBackendRestart(reason: string): void {
933 if (isQuitting || restartTimer) return;
934​
935 const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
936 restartAttempt += 1;
937 console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
938​
939 restartTimer = setTimeout(() => {
940 restartTimer = null;
941 startBackend();
942 }, delayMs);
944​
945function startBackend(): void {
946 if (isQuitting || backendProcess) return;
947​
948 const backendEntry = resolveBackendEntry();
949 if (!FS.existsSync(backendEntry)) {
950 scheduleBackendRestart(`missing server entry at ${backendEntry}`);
951 return;
952 }
953​
954 const captureBackendLogs = app.isPackaged && backendLogSink !== null;
955 const child = ChildProcess.spawn(process.execPath, [backendEntry], {
956 cwd: resolveBackendCwd(),
957 // In Electron main, process.execPath points to the Electron binary.
958 // Run the child in Node mode so this backend process does not become a GUI app instance.
959 env: {
960 ...backendEnv(),
961 ELECTRON_RUN_AS_NODE: "1",
962 },
963 stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
964 });
965 backendProcess = child;
966 let backendSessionClosed = false;
967 const closeBackendSession = (details: string) => {
968 if (backendSessionClosed) return;
969 backendSessionClosed = true;
970 writeBackendSessionBoundary("END", details);
971 };
972 writeBackendSessionBoundary(
973 "START",
974 `pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`,
975 );
976 captureBackendOutput(child);
977​
978 child.once("spawn", () => {
979 restartAttempt = 0;
980 });
981​
982 child.on("error", (error) => {
983 if (backendProcess === child) {
984 backendProcess = null;
985 }
986 closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
987 scheduleBackendRestart(error.message);
988 });
989​
990 child.on("exit", (code, signal) => {
991 if (backendProcess === child) {
992 backendProcess = null;
993 }
994 closeBackendSession(
995 `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
996 );
997 if (isQuitting) return;
998 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
999 scheduleBackendRestart(reason);
1000 });
1002​
1003function stopBackend(): void {
1004 if (restartTimer) {
1005 clearTimeout(restartTimer);
1006 restartTimer = null;
1008​
1009 const child = backendProcess;
1010 backendProcess = null;
1011 if (!child) return;
1012​
1013 if (child.exitCode === null && child.signalCode === null) {
1014 child.kill("SIGTERM");
1015 setTimeout(() => {
1016 if (child.exitCode === null && child.signalCode === null) {
1017 child.kill("SIGKILL");
1019 }, 2_000).unref();
1022​
1023async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
1024 if (restartTimer) {
1025 clearTimeout(restartTimer);
1026 restartTimer = null;
1028​
1029 const child = backendProcess;
1030 backendProcess = null;
1031 if (!child) return;
1032 const backendChild = child;
1033 if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
1034​
1035 await new Promise<void>((resolve) => {
1036 let settled = false;
1037 let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
1038 let exitTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
1039​
1040 function settle(): void {
1041 if (settled) return;
1042 settled = true;
1043 backendChild.off("exit", onExit);
1044 if (forceKillTimer) {
1045 clearTimeout(forceKillTimer);
1047 if (exitTimeoutTimer) {
1048 clearTimeout(exitTimeoutTimer);
1050 resolve();
1052​
1053 function onExit(): void {
1054 settle();
1056​
1057 backendChild.once("exit", onExit);
1058 backendChild.kill("SIGTERM");
1059​
1060 forceKillTimer = setTimeout(() => {
1061 if (backendChild.exitCode === null && backendChild.signalCode === null) {
1062 backendChild.kill("SIGKILL");
1064 }, 2_000);
1065 forceKillTimer.unref();
1066​
1067 exitTimeoutTimer = setTimeout(() => {
1068 settle();
1069 }, timeoutMs);
1070 exitTimeoutTimer.unref();
1071 });
1073​
1074function registerIpcHandlers(): void {
1075 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
1076 ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
1077 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
1078 const result = owner
1079 ? await dialog.showOpenDialog(owner, {
1080 properties: ["openDirectory", "createDirectory"],
1081 })
1082 : await dialog.showOpenDialog({
1083 properties: ["openDirectory", "createDirectory"],
1084 });
1085 if (result.canceled) return null;
1086 return result.filePaths[0] ?? null;
1087 });
1088​
1089 ipcMain.removeHandler(CONFIRM_CHANNEL);
1090 ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
1091 if (typeof message !== "string") {
1092 return false;
1094​
1095 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
1096 return showDesktopConfirmDialog(message, owner);
1097 });
1098​
1099 ipcMain.removeHandler(SET_THEME_CHANNEL);
1100 ipcMain.handle(SET_THEME_CHANNEL, async (_event, rawTheme: unknown) => {
1101 const theme = getSafeTheme(rawTheme);
1102 if (!theme) {
1103 return;
1105​
1106 nativeTheme.themeSource = theme;
1107 });
1108​
1109 ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
1110 ipcMain.handle(
1111 CONTEXT_MENU_CHANNEL,
1112 async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
1113 const normalizedItems = items
1114 .filter((item) => typeof item.id === "string" && typeof item.label === "string")
1115 .map((item) => ({
1116 id: item.id,
1117 label: item.label,
1118 destructive: item.destructive === true,
1119 }));
1120 if (normalizedItems.length === 0) {
1121 return null;
1123​
1124 const popupPosition =
1125 position &&
1126 Number.isFinite(position.x) &&
1127 Number.isFinite(position.y) &&
1128 position.x >= 0 &&
1129 position.y >= 0
1130 ? {
1131 x: Math.floor(position.x),
1132 y: Math.floor(position.y),
1134 : null;
1135​
1136 const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
1137 if (!window) return null;
1138​
1139 return new Promise<string | null>((resolve) => {
1140 const template: MenuItemConstructorOptions[] = [];
1141 let hasInsertedDestructiveSeparator = false;
1142 for (const item of normalizedItems) {
1143 if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
1144 template.push({ type: "separator" });
1145 hasInsertedDestructiveSeparator = true;
1147 const itemOption: MenuItemConstructorOptions = {
1148 label: item.label,
1149 click: () => resolve(item.id),
1150 };
1151 if (item.destructive) {
1152 const destructiveIcon = getDestructiveMenuIcon();
1153 if (destructiveIcon) {
1154 itemOption.icon = destructiveIcon;
1157 template.push(itemOption);
1159​
1160 const menu = Menu.buildFromTemplate(template);
1161 menu.popup({
1162 window,
1163 ...popupPosition,
1164 callback: () => resolve(null),
1165 });
1166 });
1167 },
1168 );
1169​
1170 ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
1171 ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
1172 const externalUrl = getSafeExternalUrl(rawUrl);
1173 if (!externalUrl) {
1174 return false;
1176​
1177 try {
1178 await shell.openExternal(externalUrl);
1179 return true;
1180 } catch {
1181 return false;
1183 });
1184​
1185 ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
1186 ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
1187​
1188 ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
1189 ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
1190 const result = await downloadAvailableUpdate();
1191 return {
1192 accepted: result.accepted,
1193 completed: result.completed,
1194 state: updateState,
1195 } satisfies DesktopUpdateActionResult;
1196 });
1197​
1198 ipcMain.removeHandler(UPDATE_INSTALL_CHANNEL);
1199 ipcMain.handle(UPDATE_INSTALL_CHANNEL, async () => {
1200 if (isQuitting) {
1201 return {
1202 accepted: false,
1203 completed: false,
1204 state: updateState,
1205 } satisfies DesktopUpdateActionResult;
1207 const result = await installDownloadedUpdate();
1208 return {
1209 accepted: result.accepted,
1210 completed: result.completed,
1211 state: updateState,
1212 } satisfies DesktopUpdateActionResult;
1213 });
1215​
1216function getIconOption(): { icon: string } | Record<string, never> {
1217 if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
1218 const ext = process.platform === "win32" ? "ico" : "png";
1219 const iconPath = resolveIconPath(ext);
1220 return iconPath ? { icon: iconPath } : {};
1222​
1223function createWindow(): BrowserWindow {
1224 const window = new BrowserWindow({
1225 width: 1100,
1226 height: 780,
1227 minWidth: 840,
1228 minHeight: 620,
1229 show: false,
1230 autoHideMenuBar: true,
1231 ...getIconOption(),
1232 title: APP_DISPLAY_NAME,
1233 titleBarStyle: "hiddenInset",
1234 trafficLightPosition: { x: 16, y: 18 },
1235 webPreferences: {
1236 preload: Path.join(__dirname, "preload.js"),
1237 contextIsolation: true,
1238 nodeIntegration: false,
1239 sandbox: true,
1240 },
1241 });
1242​
1243 window.webContents.on("context-menu", (event, params) => {
1244 event.preventDefault();
1245​
1246 const menuTemplate: MenuItemConstructorOptions[] = [];
1247​
1248 if (params.misspelledWord) {
1249 for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
1250 menuTemplate.push({
1251 label: suggestion,
1252 click: () => window.webContents.replaceMisspelling(suggestion),
1253 });
1255 if (params.dictionarySuggestions.length === 0) {
1256 menuTemplate.push({ label: "No suggestions", enabled: false });
1258 menuTemplate.push({ type: "separator" });
1260​
1261 menuTemplate.push(
1262 { role: "cut", enabled: params.editFlags.canCut },
1263 { role: "copy", enabled: params.editFlags.canCopy },
1264 { role: "paste", enabled: params.editFlags.canPaste },
1265 { role: "selectAll", enabled: params.editFlags.canSelectAll },
1266 );
1267​
1268 Menu.buildFromTemplate(menuTemplate).popup({ window });
1269 });
1270​
1271 window.webContents.setWindowOpenHandler(({ url }) => {
1272 const externalUrl = getSafeExternalUrl(url);
1273 if (externalUrl) {
1274 void shell.openExternal(externalUrl);
1276 return { action: "deny" };
1277 });
1278​
1279 window.on("page-title-updated", (event) => {
1280 event.preventDefault();
1281 window.setTitle(APP_DISPLAY_NAME);
1282 });
1283 window.webContents.on("did-finish-load", () => {
1284 window.setTitle(APP_DISPLAY_NAME);
1285 emitUpdateState();
1286 });
1287 window.once("ready-to-show", () => {
1288 window.show();
1289 });
1290​
1291 if (isDevelopment) {
1292 void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
1293 window.webContents.openDevTools({ mode: "detach" });
1294 } else {
1295 void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
1297​
1298 window.on("closed", () => {
1299 if (mainWindow === window) {
1300 mainWindow = null;
1302 });
1303​
1304 return window;
1306​
1307// Override Electron's userData path before the `ready` event so that
1308// Chromium session data uses a filesystem-friendly directory name.
1309// Must be called synchronously at the top level — before `app.whenReady()`.
1310app.setPath("userData", resolveUserDataPath());
1311​
1312configureAppIdentity();
1313​
1314async function bootstrap(): Promise<void> {
1315 writeDesktopLogHeader("bootstrap start");
1316 backendPort = await Effect.service(NetService).pipe(
1317 Effect.flatMap((net) => net.reserveLoopbackPort()),
1318 Effect.provide(NetService.layer),
1319 Effect.runPromise,
1320 );
1321 writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
1322 backendAuthToken = Crypto.randomBytes(24).toString("hex");
1323 backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
1324 process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
1325 writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
1326​
1327 registerIpcHandlers();
1328 writeDesktopLogHeader("bootstrap ipc handlers registered");
1329 startBackend();
1330 writeDesktopLogHeader("bootstrap backend start requested");
1331 mainWindow = createWindow();
1332 writeDesktopLogHeader("bootstrap main window created");
1334​
1335app.on("before-quit", () => {
1336 isQuitting = true;
1337 writeDesktopLogHeader("before-quit received");
1338 clearUpdatePollTimer();
1339 stopBackend();
1340 restoreStdIoCapture?.();
1341});
1342​
1343app
1344 .whenReady()
1345 .then(() => {
1346 writeDesktopLogHeader("app ready");
1347 configureAppIdentity();
1348 configureApplicationMenu();
1349 registerDesktopProtocol();
1350 configureAutoUpdater();
1351 void bootstrap().catch((error) => {
1352 handleFatalStartupError("bootstrap", error);
1353 });
1354​
1355 app.on("activate", () => {
1356 if (BrowserWindow.getAllWindows().length === 0) {
1357 mainWindow = createWindow();
1359 });
1360 })
1361 .catch((error) => {
1362 handleFatalStartupError("whenReady", error);
1363 });
1364​
1365app.on("window-all-closed", () => {
1366 if (process.platform !== "darwin") {
1367 app.quit();
1369});
1370​
1371if (process.platform !== "win32") {
1372 process.on("SIGINT", () => {
1373 if (isQuitting) return;
1374 isQuitting = true;
1375 writeDesktopLogHeader("SIGINT received");
1376 clearUpdatePollTimer();
1377 stopBackend();
1378 restoreStdIoCapture?.();
1379 app.quit();
1380 });
1381​
1382 process.on("SIGTERM", () => {
1383 if (isQuitting) return;
1384 isQuitting = true;
1385 writeDesktopLogHeader("SIGTERM received");
1386 clearUpdatePollTimer();
1387 stopBackend();
1388 restoreStdIoCapture?.();
1389 app.quit();
1390 });