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

main.ts

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