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