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