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