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

main.ts

672 lines17.8 KB

1import { spawn, type ChildProcess } from "node:child_process";
2import { randomBytes } from "node:crypto";
3import fs from "node:fs";
4import net from "node:net";
5import os from "node:os";
6import path from "node:path";
7​
8import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
9import type { MenuItemConstructorOptions } from "electron";
10​
11import type { ContextMenuItem } from "@t3tools/contracts";
12import { showDesktopConfirmDialog } from "./confirmDialog";
13import { fixPath } from "./fixPath";
14​
15fixPath();
16​
17const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
18const CONFIRM_CHANNEL = "desktop:confirm";
19const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
20const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
21const MENU_ACTION_CHANNEL = "desktop:menu-action";
22const STATE_DIR =
23 process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
24const DESKTOP_SCHEME = "t3";
25const ROOT_DIR = path.resolve(__dirname, "../../..");
26const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
27const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
28const APP_USER_MODEL_ID = "com.t3tools.t3code";
29const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
30const COMMIT_HASH_DISPLAY_LENGTH = 12;
31​
32let mainWindow: BrowserWindow | null = null;
33let backendProcess: ChildProcess | null = null;
34let backendPort = 0;
35let backendAuthToken = "";
36let backendWsUrl = "";
37let restartAttempt = 0;
38let restartTimer: ReturnType<typeof setTimeout> | null = null;
39let isQuitting = false;
40let desktopProtocolRegistered = false;
41let aboutCommitHashCache: string | null | undefined;
42​
43let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
44​
45function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
46 if (process.platform !== "darwin") return undefined;
47 if (destructiveMenuIconCache !== undefined) {
48 return destructiveMenuIconCache ?? undefined;
49 }
50 try {
51 const icon = nativeImage.createFromNamedImage("trash").resize({
52 width: 14,
53 height: 14,
54 });
55 if (icon.isEmpty()) {
56 destructiveMenuIconCache = null;
57 return undefined;
58 }
59 icon.setTemplateImage(true);
60 destructiveMenuIconCache = icon;
61 return icon;
62 } catch {
63 destructiveMenuIconCache = null;
64 return undefined;
65 }
67​
68protocol.registerSchemesAsPrivileged([
69 {
70 scheme: DESKTOP_SCHEME,
71 privileges: {
72 standard: true,
73 secure: true,
74 supportFetchAPI: true,
75 corsEnabled: true,
76 },
77 },
78]);
79​
80function resolveAppRoot(): string {
81 if (!app.isPackaged) {
82 return ROOT_DIR;
83 }
84 return app.getAppPath();
86​
87function normalizeCommitHash(value: unknown): string | null {
88 if (typeof value !== "string") {
89 return null;
90 }
91 const trimmed = value.trim();
92 if (!COMMIT_HASH_PATTERN.test(trimmed)) {
93 return null;
94 }
95 return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase();
97​
98function resolveEmbeddedCommitHash(): string | null {
99 const packageJsonPath = path.join(resolveAppRoot(), "package.json");
100 if (!fs.existsSync(packageJsonPath)) {
101 return null;
102 }
103​
104 try {
105 const raw = fs.readFileSync(packageJsonPath, "utf8");
106 const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
107 return normalizeCommitHash(parsed.t3codeCommitHash);
108 } catch {
109 return null;
110 }
112​
113function resolveAboutCommitHash(): string | null {
114 if (aboutCommitHashCache !== undefined) {
115 return aboutCommitHashCache;
116 }
117​
118 const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH);
119 if (envCommitHash) {
120 aboutCommitHashCache = envCommitHash;
121 return aboutCommitHashCache;
122 }
123​
124 // Only packaged builds are required to expose commit metadata.
125 if (!app.isPackaged) {
126 aboutCommitHashCache = null;
127 return aboutCommitHashCache;
128 }
129​
130 aboutCommitHashCache = resolveEmbeddedCommitHash();
131​
132 return aboutCommitHashCache;
134​
135function resolveBackendEntry(): string {
136 return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
138​
139function resolveBackendCwd(): string {
140 if (!app.isPackaged) {
141 return resolveAppRoot();
142 }
143 return os.homedir();
145​
146function resolveDesktopStaticDir(): string | null {
147 const appRoot = resolveAppRoot();
148 const candidates = [
149 path.join(appRoot, "apps/server/dist/client"),
150 path.join(appRoot, "apps/web/dist"),
151 ];
152​
153 for (const candidate of candidates) {
154 if (fs.existsSync(path.join(candidate, "index.html"))) {
155 return candidate;
156 }
157 }
158​
159 return null;
161​
162function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
163 const url = new URL(requestUrl);
164 const rawPath = decodeURIComponent(url.pathname);
165 const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
166 if (normalizedPath.includes("..")) {
167 return path.join(staticRoot, "index.html");
168 }
169​
170 const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
171 const resolvedPath = path.join(staticRoot, requestedPath);
172​
173 if (path.extname(resolvedPath)) {
174 return resolvedPath;
175 }
176​
177 const nestedIndex = path.join(resolvedPath, "index.html");
178 if (fs.existsSync(nestedIndex)) {
179 return nestedIndex;
180 }
181​
182 return path.join(staticRoot, "index.html");
184​
185function isStaticAssetRequest(requestUrl: string): boolean {
186 try {
187 const url = new URL(requestUrl);
188 return path.extname(url.pathname).length > 0;
189 } catch {
190 return false;
191 }
193​
194function registerDesktopProtocol(): void {
195 if (isDevelopment || desktopProtocolRegistered) return;
196​
197 const staticRoot = resolveDesktopStaticDir();
198 if (!staticRoot) {
199 throw new Error(
200 "Desktop static bundle missing. Build apps/server (with bundled client) first.",
201 );
202 }
203​
204 const staticRootResolved = path.resolve(staticRoot);
205 const staticRootPrefix = `${staticRootResolved}${path.sep}`;
206 const fallbackIndex = path.join(staticRootResolved, "index.html");
207​
208 protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
209 try {
210 const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
211 const resolvedCandidate = path.resolve(candidate);
212 const isInRoot =
213 resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
214 const isAssetRequest = isStaticAssetRequest(request.url);
215​
216 if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
217 if (isAssetRequest) {
218 callback({ error: -6 });
219 return;
220 }
221 callback({ path: fallbackIndex });
222 return;
223 }
224​
225 callback({ path: resolvedCandidate });
226 } catch {
227 callback({ path: fallbackIndex });
228 }
229 });
230​
231 desktopProtocolRegistered = true;
233​
234function dispatchMenuAction(action: string): void {
235 const existingWindow =
236 BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
237 const targetWindow = existingWindow ?? createWindow();
238 if (!existingWindow) {
239 mainWindow = targetWindow;
240 }
241​
242 const send = () => {
243 if (targetWindow.isDestroyed()) return;
244 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
245 if (!targetWindow.isVisible()) {
246 targetWindow.show();
247 }
248 targetWindow.focus();
249 };
250​
251 if (targetWindow.webContents.isLoadingMainFrame()) {
252 targetWindow.webContents.once("did-finish-load", send);
253 return;
254 }
255​
256 send();
258​
259function configureApplicationMenu(): void {
260 const template: MenuItemConstructorOptions[] = [];
261​
262 if (process.platform === "darwin") {
263 template.push({
264 label: app.name,
265 submenu: [
266 { role: "about" },
267 {
268 label: "Settings...",
269 accelerator: "CmdOrCtrl+,",
270 click: () => dispatchMenuAction("open-settings"),
271 },
272 { type: "separator" },
273 { role: "services" },
274 { type: "separator" },
275 { role: "hide" },
276 { role: "hideOthers" },
277 { role: "unhide" },
278 { type: "separator" },
279 { role: "quit" },
280 ],
281 });
282 }
283​
284 template.push(
285 {
286 label: "File",
287 submenu: [
288 ...(process.platform === "darwin"
289 ? []
290 : [
291 {
292 label: "Settings...",
293 accelerator: "CmdOrCtrl+,",
294 click: () => dispatchMenuAction("open-settings"),
295 },
296 { type: "separator" as const },
297 ]),
298 { role: process.platform === "darwin" ? "close" : "quit" },
299 ],
300 },
301 { role: "editMenu" },
302 { role: "viewMenu" },
303 { role: "windowMenu" },
304 );
305​
306 Menu.setApplicationMenu(Menu.buildFromTemplate(template));
308​
309function resolveResourcePath(fileName: string): string | null {
310 const candidates = [
311 path.join(__dirname, "../resources", fileName),
312 path.join(process.resourcesPath, "resources", fileName),
313 path.join(process.resourcesPath, fileName),
314 ];
315​
316 for (const candidate of candidates) {
317 if (fs.existsSync(candidate)) {
318 return candidate;
319 }
320 }
321​
322 return null;
324​
325function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
326 return resolveResourcePath(`icon.${ext}`);
328​
329function configureAppIdentity(): void {
330 app.setName(APP_DISPLAY_NAME);
331 const commitHash = resolveAboutCommitHash();
332 app.setAboutPanelOptions({
333 applicationName: APP_DISPLAY_NAME,
334 applicationVersion: app.getVersion(),
335 version: commitHash ?? "unknown",
336 });
337​
338 if (process.platform === "win32") {
339 app.setAppUserModelId(APP_USER_MODEL_ID);
340 }
341​
342 if (process.platform === "darwin" && app.dock) {
343 const iconPath = resolveIconPath("png");
344 if (iconPath) {
345 app.dock.setIcon(iconPath);
346 }
347 }
349​
350async function reserveLoopbackPort(): Promise<number> {
351 return new Promise((resolve, reject) => {
352 const probe = net.createServer();
353 probe.listen(0, "127.0.0.1", () => {
354 const address = probe.address();
355 const port = typeof address === "object" && address !== null ? address.port : 0;
356 probe.close(() => {
357 if (port > 0) {
358 resolve(port);
359 return;
360 }
361 reject(new Error("Failed to reserve backend port"));
362 });
363 });
364 probe.on("error", reject);
365 });
367​
368function backendEnv(): NodeJS.ProcessEnv {
369 return {
370 ...process.env,
371 T3CODE_MODE: "desktop",
372 T3CODE_NO_BROWSER: "1",
373 T3CODE_PORT: String(backendPort),
374 T3CODE_STATE_DIR: STATE_DIR,
375 T3CODE_AUTH_TOKEN: backendAuthToken,
376 };
378​
379function scheduleBackendRestart(reason: string): void {
380 if (isQuitting || restartTimer) return;
381​
382 const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
383 restartAttempt += 1;
384 console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
385​
386 restartTimer = setTimeout(() => {
387 restartTimer = null;
388 startBackend();
389 }, delayMs);
391​
392function startBackend(): void {
393 if (isQuitting || backendProcess) return;
394​
395 const backendEntry = resolveBackendEntry();
396 if (!fs.existsSync(backendEntry)) {
397 scheduleBackendRestart(`missing server entry at ${backendEntry}`);
398 return;
399 }
400​
401 const child = spawn(process.execPath, [backendEntry], {
402 cwd: resolveBackendCwd(),
403 // In Electron main, process.execPath points to the Electron binary.
404 // Run the child in Node mode so this backend process does not become a GUI app instance.
405 env: {
406 ...backendEnv(),
407 ELECTRON_RUN_AS_NODE: "1",
408 },
409 stdio: "inherit",
410 });
411 backendProcess = child;
412​
413 child.once("spawn", () => {
414 restartAttempt = 0;
415 });
416​
417 child.on("error", (error) => {
418 if (backendProcess === child) {
419 backendProcess = null;
420 }
421 scheduleBackendRestart(error.message);
422 });
423​
424 child.on("exit", (code, signal) => {
425 if (backendProcess === child) {
426 backendProcess = null;
427 }
428 if (isQuitting) return;
429 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
430 scheduleBackendRestart(reason);
431 });
433​
434function stopBackend(): void {
435 if (restartTimer) {
436 clearTimeout(restartTimer);
437 restartTimer = null;
438 }
439​
440 const child = backendProcess;
441 backendProcess = null;
442 if (!child) return;
443​
444 if (child.exitCode === null && child.signalCode === null) {
445 child.kill("SIGTERM");
446 setTimeout(() => {
447 if (child.exitCode === null && child.signalCode === null) {
448 child.kill("SIGKILL");
449 }
450 }, 2_000).unref();
451 }
453​
454function registerIpcHandlers(): void {
455 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
456 ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
457 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
458 const result = owner
459 ? await dialog.showOpenDialog(owner, {
460 properties: ["openDirectory", "createDirectory"],
461 })
462 : await dialog.showOpenDialog({
463 properties: ["openDirectory", "createDirectory"],
464 });
465 if (result.canceled) return null;
466 return result.filePaths[0] ?? null;
467 });
468​
469 ipcMain.removeHandler(CONFIRM_CHANNEL);
470 ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
471 if (typeof message !== "string") {
472 return false;
473 }
474​
475 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
476 return showDesktopConfirmDialog(message, owner);
477 });
478​
479 ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
480 ipcMain.handle(
481 CONTEXT_MENU_CHANNEL,
482 async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
483 const normalizedItems = items
484 .filter((item) => typeof item.id === "string" && typeof item.label === "string")
485 .map((item) => ({
486 id: item.id,
487 label: item.label,
488 destructive: item.destructive === true,
489 }));
490 if (normalizedItems.length === 0) {
491 return null;
492 }
493​
494 const popupPosition =
495 position &&
496 Number.isFinite(position.x) &&
497 Number.isFinite(position.y) &&
498 position.x >= 0 &&
499 position.y >= 0
500 ? {
501 x: Math.floor(position.x),
502 y: Math.floor(position.y),
503 }
504 : null;
505​
506 const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
507 if (!window) return null;
508​
509 return new Promise<string | null>((resolve) => {
510 const template: MenuItemConstructorOptions[] = [];
511 let hasInsertedDestructiveSeparator = false;
512 for (const item of normalizedItems) {
513 if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
514 template.push({ type: "separator" });
515 hasInsertedDestructiveSeparator = true;
516 }
517 const itemOption: MenuItemConstructorOptions = {
518 label: item.label,
519 click: () => resolve(item.id),
520 };
521 if (item.destructive) {
522 const destructiveIcon = getDestructiveMenuIcon();
523 if (destructiveIcon) {
524 itemOption.icon = destructiveIcon;
525 }
526 }
527 template.push(itemOption);
528 }
529​
530 const menu = Menu.buildFromTemplate(template);
531 menu.popup({
532 window,
533 ...popupPosition,
534 callback: () => resolve(null),
535 });
536 });
537 },
538 );
539​
540 ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
541 ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
542 if (typeof rawUrl !== "string" || rawUrl.length === 0) {
543 return false;
544 }
545​
546 let parsedUrl: URL;
547 try {
548 parsedUrl = new URL(rawUrl);
549 } catch {
550 return false;
551 }
552​
553 if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
554 return false;
555 }
556​
557 try {
558 await shell.openExternal(parsedUrl.toString());
559 return true;
560 } catch {
561 return false;
562 }
563 });
565​
566function getIconOption(): { icon: string } | Record<string, never> {
567 if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
568 const ext = process.platform === "win32" ? "ico" : "png";
569 const iconPath = resolveIconPath(ext);
570 return iconPath ? { icon: iconPath } : {};
572​
573function createWindow(): BrowserWindow {
574 const window = new BrowserWindow({
575 width: 1100,
576 height: 780,
577 minWidth: 840,
578 minHeight: 620,
579 show: false,
580 autoHideMenuBar: true,
581 ...getIconOption(),
582 title: APP_DISPLAY_NAME,
583 titleBarStyle: "hiddenInset",
584 trafficLightPosition: { x: 16, y: 18 },
585 webPreferences: {
586 preload: path.join(__dirname, "preload.js"),
587 contextIsolation: true,
588 nodeIntegration: false,
589 sandbox: true,
590 },
591 });
592​
593 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
594 window.on("page-title-updated", (event) => {
595 event.preventDefault();
596 window.setTitle(APP_DISPLAY_NAME);
597 });
598 window.webContents.on("did-finish-load", () => {
599 window.setTitle(APP_DISPLAY_NAME);
600 });
601 window.once("ready-to-show", () => {
602 window.show();
603 });
604​
605 if (isDevelopment) {
606 void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
607 window.webContents.openDevTools({ mode: "detach" });
608 } else {
609 void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
610 }
611​
612 window.on("closed", () => {
613 if (mainWindow === window) {
614 mainWindow = null;
615 }
616 });
617​
618 return window;
620​
621configureAppIdentity();
622​
623async function bootstrap(): Promise<void> {
624 backendPort = await reserveLoopbackPort();
625 backendAuthToken = randomBytes(24).toString("hex");
626 backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
627 process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
628​
629 registerIpcHandlers();
630 startBackend();
631 mainWindow = createWindow();
633​
634app.on("before-quit", () => {
635 isQuitting = true;
636 stopBackend();
637});
638​
639app.whenReady().then(() => {
640 configureAppIdentity();
641 configureApplicationMenu();
642 registerDesktopProtocol();
643 void bootstrap();
644​
645 app.on("activate", () => {
646 if (BrowserWindow.getAllWindows().length === 0) {
647 mainWindow = createWindow();
648 }
649 });
650});
651​
652app.on("window-all-closed", () => {
653 if (process.platform !== "darwin") {
654 app.quit();
655 }
656});
657​
658if (process.platform !== "win32") {
659 process.on("SIGINT", () => {
660 if (isQuitting) return;
661 isQuitting = true;
662 stopBackend();
663 app.quit();
664 });
665​
666 process.on("SIGTERM", () => {
667 if (isQuitting) return;
668 isQuitting = true;
669 stopBackend();
670 app.quit();
671 });