Open History to see the last commit
1import { spawn, spawnSync } from "node:child_process";
2import { watch } from "node:fs";
3import { join } from "node:path";
4
5import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
6import { waitForResources } from "./wait-for-resources.mjs";
7
8const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
9if (!devServerUrl) {
10 throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
11}
12
13const devServer = new URL(devServerUrl);
14const port = Number.parseInt(devServer.port, 10);
15if (!Number.isInteger(port) || port <= 0) {
16 throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
17}
18
19const requiredFiles = [
20 "dist-electron/main.cjs",
21 "dist-electron/preload.cjs",
22 "../server/dist/bin.mjs",
23];
24const watchedDirectories = [
25 { directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
26 { directory: "../server/dist", files: new Set(["bin.mjs"]) },
27];
28const forcedShutdownTimeoutMs = 1_500;
29const restartDebounceMs = 120;
30const childTreeGracePeriodMs = 1_200;
31const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim();
32
33await waitForResources({
34 baseDir: desktopDir,
35 files: requiredFiles,
36 tcpHost: devServer.hostname,
37 tcpPort: port,
38});
39
40const childEnv = { ...process.env };
41delete childEnv.ELECTRON_RUN_AS_NODE;
42const devProtocolClient = resolveDevProtocolClient();
43if (devProtocolClient) {
44 childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId;
45 childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1";
46}
47
48let shuttingDown = false;
49let restartTimer = null;
50let currentApp = null;
51let restartQueue = Promise.resolve();
52const expectedExits = new WeakSet();
53const watchers = [];
54
55function killChildTreeByPid(pid, signal) {
56 if (process.platform === "win32" || typeof pid !== "number") {
57 return;
58 }
59
60 spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
61}
62
63function cleanupStaleDevApps() {
64 if (process.platform === "win32") {
65 return;
66 }
67
68 spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
69}
70
71function startApp() {
72 if (shuttingDown || currentApp !== null) {
73 return;
74 }
75
76 const electronArgs = remoteDebuggingPort
77 ? [`--remote-debugging-port=${remoteDebuggingPort}`]
78 : [];
79 const launchArgs = devProtocolClient
80 ? electronArgs
81 : [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
82 const app = spawn(resolveElectronPath(), launchArgs, {
83 cwd: desktopDir,
84 env: childEnv,
85 stdio: "inherit",
86 });
87
88 currentApp = app;
89
90 app.once("error", () => {
91 if (currentApp === app) {
92 currentApp = null;
93 }
94
95 if (!shuttingDown) {
96 scheduleRestart();
97 }
98 });
99
100 app.once("exit", (code, signal) => {
101 if (currentApp === app) {
102 currentApp = null;
103 }
104
105 const exitedAbnormally = signal !== null || code !== 0;
106 if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
107 scheduleRestart();
108 }
109 });
110}
111
112async function stopApp() {
113 const app = currentApp;
114 if (!app) {
115 return;
116 }
117
118 currentApp = null;
119 expectedExits.add(app);
120
121 await new Promise((resolve) => {
122 let settled = false;
123
124 const finish = () => {
125 if (settled) {
126 return;
127 }
128
129 settled = true;
130 resolve();
131 };
132
133 app.once("exit", finish);
134 app.kill("SIGTERM");
135 killChildTreeByPid(app.pid, "TERM");
136 cleanupStaleDevApps();
137
138 setTimeout(() => {
139 if (settled) {
140 return;
141 }
142
143 app.kill("SIGKILL");
144 killChildTreeByPid(app.pid, "KILL");
145 cleanupStaleDevApps();
146 finish();
147 }, forcedShutdownTimeoutMs).unref();
148 });
149}
150
151function scheduleRestart() {
152 if (shuttingDown) {
153 return;
154 }
155
156 if (restartTimer) {
157 clearTimeout(restartTimer);
158 }
159
160 restartTimer = setTimeout(() => {
161 restartTimer = null;
162 restartQueue = restartQueue
163 .catch(() => undefined)
164 .then(async () => {
165 await stopApp();
166 if (!shuttingDown) {
167 startApp();
168 }
169 });
170 }, restartDebounceMs);
171}
172
173function startWatchers() {
174 for (const { directory, files } of watchedDirectories) {
175 const watcher = watch(
176 join(desktopDir, directory),
177 { persistent: true },
178 (_eventType, filename) => {
179 if (typeof filename !== "string" || !files.has(filename)) {
180 return;
181 }
182
183 scheduleRestart();
184 },
185 );
186
187 watchers.push(watcher);
188 }
189}
190
191function killChildTree(signal) {
192 if (process.platform === "win32") {
193 return;
194 }
195
196 // Kill direct children as a final fallback in case normal shutdown leaves stragglers.
197 spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
198}
199
200async function shutdown(exitCode) {
201 if (shuttingDown) return;
202 shuttingDown = true;
203
204 if (restartTimer) {
205 clearTimeout(restartTimer);
206 restartTimer = null;
207 }
208
209 for (const watcher of watchers) {
210 watcher.close();
211 }
212
213 await stopApp();
214 killChildTree("TERM");
215 await new Promise((resolve) => {
216 setTimeout(resolve, childTreeGracePeriodMs);
217 });
218 killChildTree("KILL");
219
220 process.exit(exitCode);
221}
222
223startWatchers();
224cleanupStaleDevApps();
225startApp();
226
227process.once("SIGINT", () => {
228 void shutdown(130);
229});
230process.once("SIGTERM", () => {
231 void shutdown(143);
232});
233process.once("SIGHUP", () => {
234 void shutdown(129);
235});