The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeChildProcess from "node:child_process"; |
| 2 | import * as NodeFS from "node:fs"; |
| 3 | import * as NodeOS from "node:os"; |
| 4 | import * as NodePath from "node:path"; |
| 5 | |
| 6 | import { |
| 7 | desktopDir, |
| 8 | resolveDevProtocolClient, |
| 9 | resolveElectronLaunchCommand, |
| 10 | } from "./electron-launcher.mjs"; |
| 11 | import { waitForResources } from "./wait-for-resources.mjs"; |
| 12 | |
| 13 | const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim(); |
| 14 | if (!devServerUrl) { |
| 15 | throw new Error("VITE_DEV_SERVER_URL is required for desktop development."); |
| 16 | } |
| 17 | |
| 18 | const devServer = new URL(devServerUrl); |
| 19 | const port = Number.parseInt(devServer.port, 10); |
| 20 | if (!Number.isInteger(port) || port <= 0) { |
| 21 | throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`); |
| 22 | } |
| 23 | |
| 24 | const requiredFiles = [ |
| 25 | "dist-electron/main.cjs", |
| 26 | "dist-electron/electron/WindowsForegroundFocusWorker.cjs", |
| 27 | "dist-electron/preload.cjs", |
| 28 | "dist-electron/snapShot/GlobalShiftShortcutWorker.cjs", |
| 29 | "dist-electron/snapShot/RegionSnapShotWorker.cjs", |
| 30 | "dist-electron/snapShot/SnapShotAccessibilityWorker.cjs", |
| 31 | "../server/dist/bin.mjs", |
| 32 | ]; |
| 33 | const watchedDirectories = [ |
| 34 | { directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) }, |
| 35 | { |
| 36 | directory: "dist-electron/electron", |
| 37 | files: new Set(["WindowsForegroundFocusWorker.cjs"]), |
| 38 | }, |
| 39 | { |
| 40 | directory: "dist-electron/snapShot", |
| 41 | files: new Set([ |
| 42 | "GlobalShiftShortcutWorker.cjs", |
| 43 | "RegionSnapShotWorker.cjs", |
| 44 | "SnapShotAccessibilityWorker.cjs", |
| 45 | ]), |
| 46 | }, |
| 47 | { directory: "../server/dist", files: new Set(["bin.mjs"]) }, |
| 48 | ]; |
| 49 | const forcedShutdownTimeoutMs = 1_500; |
| 50 | const restartDebounceMs = 120; |
| 51 | const childTreeGracePeriodMs = 1_200; |
| 52 | const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim(); |
| 53 | // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime. |
| 54 | const hostPlatform = NodeOS.platform(); |
| 55 | const parentPid = process.ppid; |
| 56 | const parentWatchIntervalMs = 1_000; |
| 57 | |
| 58 | NodeChildProcess.execFileSync( |
| 59 | process.execPath, |
| 60 | [NodePath.join(desktopDir, "scripts/build-browser-secret.mjs")], |
| 61 | { stdio: "inherit" }, |
| 62 | ); |
| 63 | NodeChildProcess.execFileSync( |
| 64 | process.execPath, |
| 65 | [NodePath.join(desktopDir, "scripts/build-apple-speech.mjs")], |
| 66 | { stdio: "inherit" }, |
| 67 | ); |
| 68 | |
| 69 | await waitForResources({ |
| 70 | baseDir: desktopDir, |
| 71 | files: requiredFiles, |
| 72 | tcpHost: devServer.hostname, |
| 73 | tcpPort: port, |
| 74 | }); |
| 75 | |
| 76 | const childEnv = { ...process.env }; |
| 77 | delete childEnv.ELECTRON_RUN_AS_NODE; |
| 78 | const devProtocolClient = resolveDevProtocolClient(); |
| 79 | if (devProtocolClient) { |
| 80 | childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId; |
| 81 | childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1"; |
| 82 | } |
| 83 | |
| 84 | let shuttingDown = false; |
| 85 | let restartTimer = null; |
| 86 | let currentApp = null; |
| 87 | let restartQueue = Promise.resolve(); |
| 88 | const expectedExits = new WeakSet(); |
| 89 | const watchers = []; |
| 90 | |
| 91 | function killChildTreeByPid(pid, signal) { |
| 92 | if (hostPlatform === "win32" || typeof pid !== "number") { |
| 93 | return; |
| 94 | } |
| 95 | |
| 96 | NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" }); |
| 97 | } |
| 98 | |
| 99 | function cleanupStaleDevApps() { |
| 100 | if (hostPlatform === "win32") { |
| 101 | return; |
| 102 | } |
| 103 | |
| 104 | const escapedDesktopDir = desktopDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 105 | NodeChildProcess.spawnSync( |
| 106 | "pkill", |
| 107 | ["-f", "--", `(^| )--t3code-dev-root=${escapedDesktopDir}( |$)`], |
| 108 | { |
| 109 | stdio: "ignore", |
| 110 | }, |
| 111 | ); |
| 112 | } |
| 113 | |
| 114 | function startApp() { |
| 115 | if (shuttingDown || currentApp !== null) { |
| 116 | return; |
| 117 | } |
| 118 | |
| 119 | const electronArgs = remoteDebuggingPort |
| 120 | ? [`--remote-debugging-port=${remoteDebuggingPort}`] |
| 121 | : []; |
| 122 | const launchArgs = devProtocolClient |
| 123 | ? electronArgs |
| 124 | : [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"]; |
| 125 | const electronCommand = resolveElectronLaunchCommand(launchArgs); |
| 126 | const app = NodeChildProcess.spawn(electronCommand.electronPath, electronCommand.args, { |
| 127 | cwd: desktopDir, |
| 128 | env: childEnv, |
| 129 | stdio: "inherit", |
| 130 | }); |
| 131 | |
| 132 | currentApp = app; |
| 133 | |
| 134 | app.once("error", () => { |
| 135 | if (currentApp === app) { |
| 136 | currentApp = null; |
| 137 | } |
| 138 | |
| 139 | if (!shuttingDown) { |
| 140 | scheduleRestart(); |
| 141 | } |
| 142 | }); |
| 143 | |
| 144 | app.once("exit", (code, signal) => { |
| 145 | if (currentApp === app) { |
| 146 | currentApp = null; |
| 147 | } |
| 148 | |
| 149 | const exitedAbnormally = signal !== null || code !== 0; |
| 150 | if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) { |
| 151 | scheduleRestart(); |
| 152 | } |
| 153 | }); |
| 154 | } |
| 155 | |
| 156 | async function stopApp() { |
| 157 | const app = currentApp; |
| 158 | if (!app) { |
| 159 | return; |
| 160 | } |
| 161 | |
| 162 | currentApp = null; |
| 163 | expectedExits.add(app); |
| 164 | |
| 165 | await new Promise((resolve) => { |
| 166 | let settled = false; |
| 167 | |
| 168 | const finish = () => { |
| 169 | if (settled) { |
| 170 | return; |
| 171 | } |
| 172 | |
| 173 | settled = true; |
| 174 | resolve(); |
| 175 | }; |
| 176 | |
| 177 | app.once("exit", finish); |
| 178 | app.kill("SIGTERM"); |
| 179 | killChildTreeByPid(app.pid, "TERM"); |
| 180 | cleanupStaleDevApps(); |
| 181 | |
| 182 | setTimeout(() => { |
| 183 | if (settled) { |
| 184 | return; |
| 185 | } |
| 186 | |
| 187 | app.kill("SIGKILL"); |
| 188 | killChildTreeByPid(app.pid, "KILL"); |
| 189 | cleanupStaleDevApps(); |
| 190 | finish(); |
| 191 | }, forcedShutdownTimeoutMs).unref(); |
| 192 | }); |
| 193 | } |
| 194 | |
| 195 | function scheduleRestart() { |
| 196 | if (shuttingDown) { |
| 197 | return; |
| 198 | } |
| 199 | |
| 200 | if (restartTimer) { |
| 201 | clearTimeout(restartTimer); |
| 202 | } |
| 203 | |
| 204 | restartTimer = setTimeout(() => { |
| 205 | restartTimer = null; |
| 206 | restartQueue = restartQueue |
| 207 | .catch(() => undefined) |
| 208 | .then(async () => { |
| 209 | await stopApp(); |
| 210 | if (!shuttingDown) { |
| 211 | startApp(); |
| 212 | } |
| 213 | }); |
| 214 | }, restartDebounceMs); |
| 215 | } |
| 216 | |
| 217 | function startWatchers() { |
| 218 | for (const { directory, files } of watchedDirectories) { |
| 219 | const watcher = NodeFS.watch( |
| 220 | NodePath.join(desktopDir, directory), |
| 221 | { persistent: true }, |
| 222 | (_eventType, filename) => { |
| 223 | if (typeof filename !== "string" || !files.has(filename)) { |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | scheduleRestart(); |
| 228 | }, |
| 229 | ); |
| 230 | |
| 231 | watchers.push(watcher); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | function killChildTree(signal) { |
| 236 | if (hostPlatform === "win32") { |
| 237 | return; |
| 238 | } |
| 239 | |
| 240 | NodeChildProcess.spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { |
| 241 | stdio: "ignore", |
| 242 | }); |
| 243 | } |
| 244 | |
| 245 | async function shutdown(exitCode) { |
| 246 | if (shuttingDown) return; |
| 247 | shuttingDown = true; |
| 248 | |
| 249 | if (restartTimer) { |
| 250 | clearTimeout(restartTimer); |
| 251 | restartTimer = null; |
| 252 | } |
| 253 | |
| 254 | for (const watcher of watchers) { |
| 255 | watcher.close(); |
| 256 | } |
| 257 | |
| 258 | await stopApp(); |
| 259 | killChildTree("TERM"); |
| 260 | await new Promise((resolve) => { |
| 261 | setTimeout(resolve, childTreeGracePeriodMs); |
| 262 | }); |
| 263 | killChildTree("KILL"); |
| 264 | |
| 265 | process.exit(exitCode); |
| 266 | } |
| 267 | |
| 268 | startWatchers(); |
| 269 | cleanupStaleDevApps(); |
| 270 | startApp(); |
| 271 | |
| 272 | process.once("SIGINT", () => { |
| 273 | void shutdown(130); |
| 274 | }); |
| 275 | process.once("SIGTERM", () => { |
| 276 | void shutdown(143); |
| 277 | }); |
| 278 | process.once("SIGHUP", () => { |
| 279 | void shutdown(129); |
| 280 | }); |
| 281 | // A parent killed without forwarding a signal leaves us reparented (to a subreaper on Linux, not |
| 282 | // necessarily PID 1), and nothing else would ever stop the restart loop. This only notices the |
| 283 | // death of our direct parent, so vite.config.ts launches us without a shell in between. Windows |
| 284 | // never reparents, and reading process.ppid there snapshots the process table. |
| 285 | if (hostPlatform !== "win32") { |
| 286 | setInterval(() => { |
| 287 | if (process.ppid !== parentPid) { |
| 288 | void shutdown(129); |
| 289 | } |
| 290 | }, parentWatchIntervalMs).unref(); |
| 291 | } |