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