-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathdev-desktop-sandbox.ts
More file actions
382 lines (328 loc) · 12.3 KB
/
Copy pathdev-desktop-sandbox.ts
File metadata and controls
382 lines (328 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env bun
/**
* Start an isolated Electron dev instance (Vite + Electron main process).
*
* Why:
* - Electron uses the xum home directory (XUM_ROOT / ~/.xum-dev) for config,
* sessions, worktrees, etc.
* - Running multiple Electron instances against the same mux root is noisy and
* risky during development.
*
* This script creates a fresh temporary mux root dir, optionally copies over the
* user's providers/config, picks free ports, then launches:
* - `make dev` (Vite + watchers)
* - `bunx electron ... .` (desktop app)
*
* Usage:
* make dev-desktop-sandbox
*
* Optional CLI flags:
* - --clean-providers
* - --clean-projects
* - --help
*
* Optional env vars:
* - SEED_XUM_ROOT=/path/to/xum/home # where to copy providers.jsonc/config.json from
* - SEED_MUX_ROOT=/path/to/mux/home # legacy alias for SEED_XUM_ROOT
* - KEEP_SANDBOX=1 # don't delete temp XUM_ROOT on exit
* - XUM_VITE_PORT / VITE_PORT # override picked Vite port
* - VITE_READY_TIMEOUT_MS=60000 # override Vite readiness timeout
* - ELECTRON_DEBUG_PORT=9223 # override picked Electron remote debugging port
* - ELECTRON_DEBUG_PORT=0 # disable Electron remote debugging port entirely
* - XUM_ENABLE_TUTORIALS_IN_SANDBOX=1 # re-enable tutorials inside the sandbox
* - MAKE=gmake # override make binary
*/
import { spawn, spawnSync } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import {
assignXumEnvironmentValue,
resolveXumEnvironmentValue,
} from "../src/common/compat/xumEnv";
import {
chooseSeedSources,
copyConfigClearingProjectsIfExists,
copyFileIfExists,
forwardSignalsToChildProcesses,
getFreePort,
parseOptionalPort,
sanitizeSandboxProviderEnv,
waitForHttpReady,
} from "./sandboxUtils";
type SandboxCliFlags = {
cleanProviders: boolean;
cleanProjects: boolean;
help: boolean;
};
function parseSandboxCliFlags(argv: string[]): SandboxCliFlags {
const args = new Set(argv);
const knownArgs = new Set(["--clean-providers", "--clean-projects", "--help"]);
for (const arg of args) {
if (!knownArgs.has(arg)) {
throw new Error(`Unknown arg: ${arg}`);
}
}
return {
cleanProviders: args.has("--clean-providers"),
cleanProjects: args.has("--clean-projects"),
help: args.has("--help"),
};
}
function printHelp(): void {
console.log(`Usage:
make dev-desktop-sandbox
Optional CLI flags:
--clean-providers Do not copy providers.jsonc into the sandbox
--clean-projects Do not import projects from config.json (projects will be empty)
Optional env vars:
XUM_ENABLE_TUTORIALS_IN_SANDBOX=1 Re-enable tutorials inside the sandbox
Examples:
make dev-desktop-sandbox DEV_DESKTOP_SANDBOX_ARGS="--clean-providers --clean-projects"
XUM_ENABLE_TUTORIALS_IN_SANDBOX=1 XUM_VITE_PORT=5175 ELECTRON_DEBUG_PORT=9223 make dev-desktop-sandbox`);
}
function parseElectronDebugPort(
raw: string | undefined
): { mode: "disabled" } | { mode: "enabled"; portOverride: number | null } {
if (raw === "0") {
return { mode: "disabled" };
}
return { mode: "enabled", portOverride: parseOptionalPort(raw) };
}
function formatHostForUrl(host: string): string {
const trimmed = host.trim();
const unbracketed =
trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
// IPv6 URLs must be bracketed: http://[::1]:1234
if (unbracketed.includes(":")) {
// If the host contains a zone index (e.g. fe80::1%en0), percent must be encoded.
// Encode zone indices (including numeric ones like %12) while avoiding double-encoding
// if the user already provided a URL-safe %25.
const escaped = unbracketed.replace(/%(?!25)/gi, "%25");
return `[${escaped}]`;
}
return unbracketed;
}
async function waitForChildExit(child: ReturnType<typeof spawn>, name: string): Promise<number> {
if (!name) {
throw new Error("Expected process name");
}
return await new Promise<number>((resolve) => {
let resolved = false;
const finish = (code: number): void => {
if (resolved) return;
resolved = true;
resolve(code);
};
child.on("error", (err) => {
console.error(`Failed to start ${name}:`, err);
finish(1);
});
child.on("exit", (code, signal) => {
if (typeof code === "number") {
finish(code);
} else {
// When killed by signal, prefer a non-zero exit code.
finish(signal ? 1 : 0);
}
});
});
}
async function main(): Promise<number> {
const cliFlags = parseSandboxCliFlags(process.argv.slice(2));
if (cliFlags.help) {
printHelp();
return 0;
}
const cleanProviders = cliFlags.cleanProviders;
const cleanProjects = cliFlags.cleanProjects;
const keepSandbox = process.env.KEEP_SANDBOX === "1";
const makeCmd = process.env.MAKE ?? "make";
// Do any validation that might throw *before* creating the temp root so we
// don't leave behind stale `mux-desktop-*` directories for simple mistakes.
const shouldSeed = !(cleanProviders && cleanProjects);
const seedSources = shouldSeed ? chooseSeedSources() : { providersPath: null, configPath: null };
const vitePortOverride = parseOptionalPort(
resolveXumEnvironmentValue("VITE_PORT", process.env) ?? process.env.VITE_PORT
);
const debugPortConfig = parseElectronDebugPort(process.env.ELECTRON_DEBUG_PORT);
let vitePort: number;
if (vitePortOverride !== null) {
vitePort = vitePortOverride;
} else {
vitePort = await getFreePort();
}
let electronDebugPort: number | null;
if (debugPortConfig.mode === "disabled") {
electronDebugPort = null;
} else if (debugPortConfig.portOverride !== null) {
electronDebugPort = debugPortConfig.portOverride;
} else {
electronDebugPort = await getFreePort();
}
if (electronDebugPort !== null) {
while (electronDebugPort === vitePort) {
electronDebugPort = await getFreePort();
}
}
const muxRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mux-desktop-"));
let devProc: ReturnType<typeof spawn> | null = null;
let electronProc: ReturnType<typeof spawn> | null = null;
try {
const seedProvidersPath = !cleanProviders ? seedSources.providersPath : null;
const seedConfigPath = seedSources.configPath;
const sandboxProvidersPath = path.join(muxRoot, "providers.jsonc");
const sandboxConfigPath = path.join(muxRoot, "config.json");
const copiedProviders = seedProvidersPath
? copyFileIfExists(seedProvidersPath, sandboxProvidersPath, { mode: 0o600 })
: false;
const copiedConfig = seedConfigPath
? cleanProjects
? copyConfigClearingProjectsIfExists(seedConfigPath, sandboxConfigPath)
: copyFileIfExists(seedConfigPath, sandboxConfigPath)
: false;
console.log("\nStarting mux desktop sandbox...");
console.log(` XUM_ROOT: ${muxRoot}`);
console.log(` Seed config: ${copiedConfig && seedConfigPath ? seedConfigPath : "(none)"}`);
console.log(
` Seed providers: ${copiedProviders && seedProvidersPath ? seedProvidersPath : "(none)"}`
);
if (cleanProviders || cleanProjects) {
console.log(` Clean providers: ${cleanProviders ? "yes" : "no"}`);
console.log(` Clean projects: ${cleanProjects ? "yes" : "no"}`);
}
console.log(` Vite: http://127.0.0.1:${vitePort}`);
if (electronDebugPort !== null) {
console.log(` Electron debug: http://127.0.0.1:${electronDebugPort}`);
} else {
console.log(" Electron debug: (disabled)");
}
if (keepSandbox) {
console.log(" KEEP_SANDBOX=1 (temp root will not be deleted)");
}
// Guard against provider env-var fallback: strip all provider env vars on
// --clean-providers, strip the seeded providers' env vars when a
// providers.jsonc was copied, and warn when env fallback would apply.
const childEnv = sanitizeSandboxProviderEnv({
cleanProviders,
seededProvidersPath: copiedProviders ? sandboxProvidersPath : null,
});
childEnv.NODE_ENV = "development";
assignXumEnvironmentValue(childEnv, "ROOT", muxRoot);
assignXumEnvironmentValue(childEnv, "VITE_PORT", String(vitePort));
assignXumEnvironmentValue(
childEnv,
"ENABLE_TUTORIALS_IN_SANDBOX",
resolveXumEnvironmentValue("ENABLE_TUTORIALS_IN_SANDBOX", process.env) ?? "0"
);
devProc = spawn(makeCmd, ["dev"], {
stdio: "inherit",
env: childEnv,
});
const devExitPromise = waitForChildExit(devProc, `${makeCmd} dev`);
// Forward signals so Ctrl+C stops all subprocesses.
forwardSignalsToChildProcesses(() => [devProc, electronProc]);
// Wait for Vite to be ready before starting Electron.
const viteReadyTimeoutMs = (() => {
const raw = process.env.VITE_READY_TIMEOUT_MS;
if (!raw) return 60_000;
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed <= 0) return 60_000;
return parsed;
})();
const viteReadyUrls = [
`http://${formatHostForUrl("127.0.0.1")}:${vitePort}`,
`http://${formatHostForUrl("localhost")}:${vitePort}`,
];
const readyOrExit = await Promise.race([
waitForHttpReady(viteReadyUrls, viteReadyTimeoutMs).then(() => ({ type: "ready" as const })),
devExitPromise.then((code) => ({ type: "exit" as const, code })),
]);
if (readyOrExit.type === "exit") {
console.error(`Vite dev server exited early (code ${readyOrExit.code})`);
return readyOrExit.code;
}
// Electron expects dist/splash.html to exist (make start depends on build-static).
const staticResult = spawnSync(makeCmd, ["build-static"], {
stdio: "inherit",
env: {
...process.env,
},
});
if (staticResult.status !== 0) {
console.error(
`Failed to run ${makeCmd} build-static (exit ${staticResult.status ?? "unknown"})`
);
return staticResult.status ?? 1;
}
const electronArgs = ["electron"];
if (electronDebugPort !== null) {
electronArgs.push(`--remote-debugging-port=${electronDebugPort}`);
}
electronArgs.push(".");
// Keep sandboxed desktop launches profile-ready; callers can set XUM_PROFILE_REACT=0
// to compare against an uninstrumented renderer.
assignXumEnvironmentValue(
childEnv,
"PROFILE_REACT",
resolveXumEnvironmentValue("PROFILE_REACT", process.env) ?? "1"
);
assignXumEnvironmentValue(childEnv, "DEVSERVER_HOST", "127.0.0.1");
assignXumEnvironmentValue(childEnv, "DEVSERVER_PORT", String(vitePort));
// If config.json pins apiServerPort, multiple sandboxes can collide; default to 0.
assignXumEnvironmentValue(
childEnv,
"SERVER_PORT",
resolveXumEnvironmentValue("SERVER_PORT", process.env) ?? "0"
);
assignXumEnvironmentValue(childEnv, "ALLOW_MULTIPLE_INSTANCES", "1");
childEnv.CMUX_ALLOW_MULTIPLE_INSTANCES = "1";
electronProc = spawn("bunx", electronArgs, {
stdio: "inherit",
env: childEnv,
});
const electronExitPromise = waitForChildExit(electronProc, "bunx electron");
const firstExit = await Promise.race([
devExitPromise.then((code) => ({ which: "dev" as const, code })),
electronExitPromise.then((code) => ({ which: "electron" as const, code })),
]);
if (firstExit.which === "dev") {
// Vite/watchers exited - stop Electron too.
if (electronProc.exitCode === null && !electronProc.killed) {
electronProc.kill("SIGTERM");
}
// Ensure the Electron process is torn down before returning.
await electronExitPromise;
return firstExit.code;
}
// Electron exited - stop Vite/watchers.
if (devProc.exitCode === null && !devProc.killed) {
devProc.kill("SIGTERM");
}
await devExitPromise;
return firstExit.code;
} finally {
// Best-effort cleanup.
if (electronProc && electronProc.exitCode === null && !electronProc.killed) {
electronProc.kill("SIGTERM");
}
if (devProc && devProc.exitCode === null && !devProc.killed) {
devProc.kill("SIGTERM");
}
if (!keepSandbox) {
try {
fs.rmSync(muxRoot, { recursive: true, force: true });
} catch (err) {
console.error(`Failed to remove sandbox MUX_ROOT at ${muxRoot}:`, err);
}
}
}
}
main()
.then((exitCode) => {
process.exit(exitCode);
})
.catch((err) => {
console.error(err);
process.exit(1);
});