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