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, shell } from "electron";
9
10import { showDesktopConfirmDialog } from "./confirmDialog";
11import { fixPath } from "./fixPath";
12
13fixPath();
14
15const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
16const CONFIRM_CHANNEL = "desktop:confirm";
17const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
18const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
19const ROOT_DIR = path.resolve(import.meta.dirname, "../../..");
20const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
21const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
22const STATE_DIR =
23 process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
24const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
25const PERF_AUTOMATION_ENABLED = process.env.T3CODE_DESKTOP_PERF_AUTOMATION === "1";
26
27let mainWindow: BrowserWindow | null = null;
28let backendProcess: ChildProcess | null = null;
29let backendPort = 0;
30let backendAuthToken = "";
31let backendWsUrl = "";
32let restartAttempt = 0;
33let restartTimer: ReturnType<typeof setTimeout> | null = null;
34let isQuitting = false;
35
36async function runPerfAutomationIfEnabled(window: BrowserWindow): Promise<void> {
37 if (!PERF_AUTOMATION_ENABLED) return;
38 try {
39 const { runDesktopPerfAutomation } = await import("./desktopPerfAutomation");
40 await runDesktopPerfAutomation(window);
41 } catch (error) {
42 const message = error instanceof Error ? error.message : String(error);
43 console.error("[desktop-perf] failed to load automation module:", message);
44 const doneOutPath = process.env.T3CODE_DESKTOP_PERF_DONE_OUT?.trim() ?? "";
45 if (doneOutPath.length > 0) {
46 fs.mkdirSync(path.dirname(doneOutPath), { recursive: true });
47 fs.writeFileSync(
48 doneOutPath,
49 JSON.stringify(
50 {
51 status: "error",
52 error: `Failed to load desktop perf automation module: ${message}`,
53 },
54 null,
55 2,
56 ),
57 );
58 }
59 }
60}
61
62async function reserveLoopbackPort(): Promise<number> {
63 return new Promise((resolve, reject) => {
64 const probe = net.createServer();
65 probe.listen(0, "127.0.0.1", () => {
66 const address = probe.address();
67 const port = typeof address === "object" && address !== null ? address.port : 0;
68 probe.close(() => {
69 if (port > 0) {
70 resolve(port);
71 return;
72 }
73 reject(new Error("Failed to reserve backend port"));
74 });
75 });
76 probe.on("error", reject);
77 });
78}
79
80function backendEnv(): NodeJS.ProcessEnv {
81 return {
82 ...process.env,
83 T3CODE_MODE: "desktop",
84 T3CODE_NO_BROWSER: "1",
85 T3CODE_PORT: String(backendPort),
86 T3CODE_STATE_DIR: STATE_DIR,
87 T3CODE_AUTH_TOKEN: backendAuthToken,
88 };
89}
90
91function scheduleBackendRestart(reason: string): void {
92 if (isQuitting || restartTimer) return;
93
94 const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);
95 restartAttempt += 1;
96 console.error(`[desktop] backend exited unexpectedly (${reason}); restarting in ${delayMs}ms`);
97
98 restartTimer = setTimeout(() => {
99 restartTimer = null;
100 startBackend();
101 }, delayMs);
102}
103
104function startBackend(): void {
105 if (isQuitting || backendProcess) return;
106
107 if (!fs.existsSync(BACKEND_ENTRY)) {
108 scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
109 return;
110 }
111
112 const child = spawn(process.execPath, [BACKEND_ENTRY], {
113 cwd: ROOT_DIR,
114 // In Electron main, process.execPath points to the Electron binary.
115 // Run the child in Node mode so this backend process does not become a GUI app instance.
116 env: {
117 ...backendEnv(),
118 ELECTRON_RUN_AS_NODE: "1",
119 },
120 stdio: "inherit",
121 });
122 backendProcess = child;
123
124 child.once("spawn", () => {
125 restartAttempt = 0;
126 });
127
128 child.on("error", (error) => {
129 if (backendProcess === child) {
130 backendProcess = null;
131 }
132 scheduleBackendRestart(error.message);
133 });
134
135 child.on("exit", (code, signal) => {
136 if (backendProcess === child) {
137 backendProcess = null;
138 }
139 if (isQuitting) return;
140 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
141 scheduleBackendRestart(reason);
142 });
143}
144
145function stopBackend(): void {
146 if (restartTimer) {
147 clearTimeout(restartTimer);
148 restartTimer = null;
149 }
150
151 const child = backendProcess;
152 backendProcess = null;
153 if (!child) return;
154
155 if (!child.killed) {
156 child.kill("SIGTERM");
157 setTimeout(() => {
158 if (!child.killed) {
159 child.kill("SIGKILL");
160 }
161 }, 2_000).unref();
162 }
163}
164
165function registerIpcHandlers(): void {
166 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
167 ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
168 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
169 const result = owner
170 ? await dialog.showOpenDialog(owner, {
171 properties: ["openDirectory", "createDirectory"],
172 })
173 : await dialog.showOpenDialog({
174 properties: ["openDirectory", "createDirectory"],
175 });
176 if (result.canceled) return null;
177 return result.filePaths[0] ?? null;
178 });
179
180 ipcMain.removeHandler(CONFIRM_CHANNEL);
181 ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
182 if (typeof message !== "string") {
183 return false;
184 }
185
186 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
187 return showDesktopConfirmDialog(message, owner);
188 });
189
190 ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
191 ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
192 const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
193 if (!window) return null;
194
195 return new Promise<string | null>((resolve) => {
196 const menu = Menu.buildFromTemplate(
197 items.map((item) => ({
198 label: item.label,
199 click: () => resolve(item.id),
200 })),
201 );
202 menu.popup({
203 window,
204 callback: () => resolve(null),
205 });
206 });
207 });
208
209 ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
210 ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
211 if (typeof rawUrl !== "string" || rawUrl.length === 0) {
212 return false;
213 }
214
215 let parsedUrl: URL;
216 try {
217 parsedUrl = new URL(rawUrl);
218 } catch {
219 return false;
220 }
221
222 if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
223 return false;
224 }
225
226 try {
227 await shell.openExternal(parsedUrl.toString());
228 return true;
229 } catch {
230 return false;
231 }
232 });
233}
234
235function createWindow(): BrowserWindow {
236 const window = new BrowserWindow({
237 width: 1100,
238 height: 780,
239 minWidth: 840,
240 minHeight: 620,
241 show: false,
242 autoHideMenuBar: true,
243 titleBarStyle: "hiddenInset",
244 trafficLightPosition: { x: 16, y: 18 },
245 webPreferences: {
246 preload: path.join(import.meta.dirname, "preload.cjs"),
247 contextIsolation: true,
248 nodeIntegration: false,
249 sandbox: true,
250 },
251 });
252
253 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
254 window.once("ready-to-show", () => {
255 window.show();
256 });
257
258 if (isDevelopment) {
259 const devUrl = new URL(process.env.VITE_DEV_SERVER_URL as string);
260 if (PERF_AUTOMATION_ENABLED) {
261 devUrl.searchParams.set("t3code_perf_automation", "1");
262 }
263 void window.loadURL(devUrl.toString());
264 if (!PERF_AUTOMATION_ENABLED) {
265 window.webContents.openDevTools({ mode: "detach" });
266 }
267 } else {
268 if (!fs.existsSync(WEB_ENTRY)) {
269 throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
270 }
271 if (PERF_AUTOMATION_ENABLED) {
272 void window.loadFile(WEB_ENTRY, {
273 query: { t3code_perf_automation: "1" },
274 });
275 } else {
276 void window.loadFile(WEB_ENTRY);
277 }
278 }
279
280 window.on("closed", () => {
281 if (mainWindow === window) {
282 mainWindow = null;
283 }
284 });
285
286 return window;
287}
288
289async function bootstrap(): Promise<void> {
290 backendPort = await reserveLoopbackPort();
291 backendAuthToken = randomBytes(24).toString("hex");
292 backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
293 process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
294
295 registerIpcHandlers();
296 startBackend();
297 mainWindow = createWindow();
298 if (mainWindow && PERF_AUTOMATION_ENABLED) {
299 void runPerfAutomationIfEnabled(mainWindow);
300 }
301}
302
303app.on("before-quit", () => {
304 isQuitting = true;
305 stopBackend();
306});
307
308app.whenReady().then(() => {
309 void bootstrap();
310
311 app.on("activate", () => {
312 if (BrowserWindow.getAllWindows().length === 0) {
313 mainWindow = createWindow();
314 }
315 });
316});
317
318app.on("window-all-closed", () => {
319 if (process.platform !== "darwin") {
320 app.quit();
321 }
322});