@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 400 lines 15.9 KB
Raw
1 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Mock native realpath to exercise macOS case correction on every platform.
2 import * as NodeFSP from "node:fs/promises";
3 // @effect-diagnostics-next-line nodeBuiltinImport:off -- The Muse SDK spawns with Node's child_process, so the launch test quotes arguments the same way.
4 import * as NodeChildProcess from "node:child_process";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { spawnMspConnection, type MspHandshake, type SpawnedMspConnection } from "@muse-code/sdk";
7 import { it } from "@effect/vitest";
8 import * as HostProcess from "@t3tools/shared/HostProcess";
9 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
10 import * as Effect from "effect/Effect";
11 import * as Fiber from "effect/Fiber";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Path from "effect/Path";
14 import { afterEach, describe, expect, onTestFinished, vi } from "vite-plus/test";
15 import {
16 createMuseSdkHost,
17 createMuseSdkHostEffect,
18 makeMuseEnvironment,
19 museApprovalMode,
20 museLaunch,
21 museVerbatimPath,
22 museWorkspaceRoot,
23 type MuseSdkHost,
24 } from "./sdk.ts";
25
26 vi.mock("node:fs/promises", { spy: true });
27
28 vi.mock("@muse-code/sdk", () => ({ spawnMspConnection: vi.fn() }));
29
30 function pending<A>() {
31 let resolve = (_value: A) => {};
32 let reject = (_error: unknown) => {};
33 const promise = new Promise<A>((yes, no) => {
34 resolve = yes;
35 reject = no;
36 });
37 return { promise, resolve, reject };
38 }
39
40 function mockSpawn() {
41 const startup = pending<SpawnedMspConnection>();
42 const shutdown = pending<{ code: number; signal: null }>();
43 const closing = pending<void>();
44 const initializing = pending<void>();
45 const initialize = vi.fn(() => {
46 initializing.resolve();
47 return startup.promise;
48 });
49 const close = vi.fn(() => {
50 closing.resolve();
51 return shutdown.promise;
52 });
53 const handshake = { initialize, close } as unknown as MspHandshake;
54 vi.mocked(spawnMspConnection).mockReturnValue(handshake);
55 const ready = {
56 connection: {},
57 initializeResult: { grantedCapabilities: [], schema: { version: 1 } },
58 exited: shutdown.promise,
59 fingerprintWarning: { warning: "additive optional" },
60 } as unknown as SpawnedMspConnection;
61 return { startup, shutdown, closing, initializing, initialize, close, ready };
62 }
63
64 afterEach(() => {
65 vi.useRealTimers();
66 vi.clearAllMocks();
67 });
68
69 describe("Muse SDK host", () => {
70 it.each(["META_API_KEY", "meta_api_key", "Meta_Api_Key"])(
71 "excludes %s without reading its value or mutating the supplied environment",
72 (key) => {
73 const source: NodeJS.ProcessEnv = { PATH: "/bin", MUSE_TEST: "yes" };
74 const read = vi.fn(() => {
75 throw new Error("The API override must not be read.");
76 });
77 Object.defineProperty(source, key, { enumerable: true, get: read });
78 expect(makeMuseEnvironment(source)).toEqual({
79 PATH: "/bin",
80 MUSE_TEST: "yes",
81 MUSE_NO_AUTO_UPDATE: "1",
82 });
83 expect(read).not.toHaveBeenCalled();
84 expect(Object.keys(source)).toContain(key);
85 },
86 );
87
88 it("selects full access explicitly and keeps other runtime modes sandboxed", async () => {
89 for (const mode of ["approval-required", "auto-accept-edits", "auto", "full-access"] as const) {
90 const fake = mockSpawn();
91 const running = createMuseSdkHost({
92 binaryPath: "/custom/muse",
93 cwd: "/workspace",
94 runtimeMode: mode,
95 environment: { PATH: "/bin" },
96 });
97 expect(vi.mocked(spawnMspConnection).mock.lastCall?.[0]).toMatchObject({
98 command: "/custom/muse",
99 cwd: "/workspace",
100 args:
101 mode === "full-access"
102 ? ["serve", "--trust-workspace", "--disable-sandbox"]
103 : ["serve", "--trust-workspace"],
104 });
105 expect(museApprovalMode(mode)).toBe(mode === "full-access" ? "allowAll" : "promptUnmatched");
106 fake.startup.resolve(fake.ready);
107 const host = await running;
108 fake.shutdown.resolve({ code: 0, signal: null });
109 await host.close();
110 await host.close();
111 expect(fake.close).toHaveBeenCalledOnce();
112 }
113 });
114
115 it.each([undefined, 2])(
116 "rejects unsupported envelope version %s and awaits shutdown",
117 async (version) => {
118 const fake = mockSpawn();
119 const started = createMuseSdkHost({ binaryPath: "muse" });
120 let settled = false;
121 const outcome = started.catch((error: unknown) => {
122 settled = true;
123 return error;
124 });
125 fake.startup.resolve({
126 ...fake.ready,
127 initializeResult: {
128 ...fake.ready.initializeResult,
129 schema: { fingerprint: "test", version },
130 },
131 } as unknown as SpawnedMspConnection);
132 await fake.closing.promise;
133 expect(fake.close).toHaveBeenCalledOnce();
134 expect(settled).toBe(false);
135 fake.shutdown.resolve({ code: 0, signal: null });
136 expect(await outcome).toMatchObject({
137 message: "Muse SDK returned an unsupported protocol envelope version.",
138 });
139 },
140 );
141
142 it.effect(
143 "observes native host exit while the SDK still waits for a detached stdout holder",
144 () =>
145 Effect.gen(function* () {
146 if ((yield* HostProcess.Platform) === "win32") return;
147 yield* Effect.promise(async () => {
148 const sdk = await vi.importActual<typeof import("@muse-code/sdk")>("@muse-code/sdk");
149 const processExited = pending<{ code: number | null; signal: NodeJS.Signals | null }>();
150 const holderSource = `process.send("ready", () => {
151 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
152 });`;
153 const fixture = `
154 const { spawn } = require("node:child_process");
155 require("node:readline").createInterface({ input: process.stdin }).on("line", async line => {
156 const frame = JSON.parse(line);
157 if (!("id" in frame)) return;
158 let result = { schema: { version: 1, fingerprint: "t3-native-fixture" }, grantedCapabilities: [] };
159 if (frame.method === "fixture/exit") {
160 const holder = spawn(process.execPath, ["-e", ${JSON.stringify(holderSource)}], {
161 detached: true, stdio: ["ignore", 1, 2, "ipc"]
162 });
163 await new Promise(resolve => holder.once("message", resolve));
164 result = { pid: holder.pid };
165 }
166 process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result }) + "\\n",
167 () => { if (frame.method === "fixture/exit") process.exit(7); });
168 });
169 `;
170 let holderPid: number | undefined;
171 let host: MuseSdkHost | undefined;
172 const reap = () => {
173 if (holderPid !== undefined) {
174 try {
175 process.kill(holderPid, "SIGKILL");
176 } catch {
177 /* Already reaped. */
178 }
179 holderPid = undefined;
180 }
181 };
182 onTestFinished(async () => {
183 reap();
184 await host?.close();
185 });
186 try {
187 host = await createMuseSdkHost(
188 {
189 binaryPath: process.execPath,
190 launch: { command: process.execPath, args: ["-e", fixture] },
191 onProcessExit: processExited.resolve,
192 },
193 sdk.spawnMspConnection,
194 );
195 let sdkExited = false;
196 let connectionClosed = false;
197 void host.exited.then(() => {
198 sdkExited = true;
199 });
200 void host.connection.closed.then(() => {
201 connectionClosed = true;
202 });
203 const response = await host.connection.request("fixture/exit", {});
204 expect(response).toMatchObject({ pid: expect.any(Number) });
205 holderPid = Number((response as { pid: number }).pid);
206 expect(await processExited.promise).toEqual({ code: 7, signal: null });
207 expect(sdkExited).toBe(false);
208 expect(connectionClosed).toBe(false);
209 reap();
210 expect(await host.exited).toEqual({ code: 7, signal: null });
211 await host.close();
212 expect(connectionClosed).toBe(true);
213 } finally {
214 reap();
215 await host?.close();
216 }
217 });
218 }),
219 );
220
221 it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
222 Effect.gen(function* () {
223 const started = pending<void>();
224 const startup = pending<MuseSdkHost>();
225 const closing = pending<void>();
226 const shutdown = pending<void>();
227 const host = {
228 close: vi.fn(() => {
229 closing.resolve();
230 return shutdown.promise;
231 }),
232 } as unknown as MuseSdkHost;
233 let released = false;
234 const fiber = yield* Effect.forkChild(
235 createMuseSdkHostEffect({ binaryPath: "muse" }, () => {
236 started.resolve();
237 return startup.promise;
238 }).pipe(
239 Effect.ensuring(
240 Effect.sync(() => {
241 released = true;
242 }),
243 ),
244 ),
245 );
246 yield* Effect.promise(() => started.promise);
247 startup.resolve(host);
248 const interrupted = yield* Fiber.interrupt(fiber).pipe(
249 Effect.forkChild({ startImmediately: true }),
250 );
251 yield* Effect.promise(() => closing.promise);
252 expect(released).toBe(false);
253 shutdown.resolve();
254 yield* Fiber.join(interrupted);
255 expect(released).toBe(true);
256 expect(host.close).toHaveBeenCalledOnce();
257 }),
258 );
259 });
260
261 describe("Muse launch", () => {
262 const CMD = "C:\\Windows\\system32\\cmd.exe";
263 const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) =>
264 museLaunch("muse", env).pipe(
265 Effect.provideService(HostProcess.Platform, "win32"),
266 Effect.provideService(SpawnExecutableResolution, () => resolved),
267 );
268
269 it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () =>
270 Effect.gen(function* () {
271 expect(yield* onWindows("C:\\Muse\\muse.exe")).toEqual({
272 command: "C:\\Muse\\muse.exe",
273 args: [],
274 });
275 const spaced = "C:\\Users\\Jane Doe\\AppData\\Local\\Programs\\muse\\muse.cmd";
276 expect(yield* onWindows(spaced)).toEqual({ command: CMD, args: ["/d", "/c", "@", spaced] });
277 const spacedAmpersand = "C:\\Users\\R&D Team\\AppData\\Local\\Programs\\muse\\muse.cmd";
278 expect(yield* onWindows(spacedAmpersand)).toEqual({
279 command: CMD,
280 args: ["/d", "/c", "@", spacedAmpersand],
281 });
282 expect(yield* onWindows("C:\\Users\\R&D(1)\\muse.cmd")).toEqual({
283 command: CMD,
284 args: ["/d", "/c", "C:\\Users\\R^&D^(1^)\\muse.cmd"],
285 });
286 expect((yield* onWindows("C:\\Muse\\muse.bat", { SYSTEMROOT: "C:\\Windows" })).command).toBe(
287 "C:\\Windows\\System32\\cmd.exe",
288 );
289 expect(yield* onWindows(undefined)).toEqual({ command: "muse", args: [] });
290 }),
291 );
292
293 // The SDK spawns natively: libuv would wait on a hung mount under the cwd or PATH.
294 it.effect("launches through env on Linux, which enters the cwd and searches PATH", () =>
295 Effect.gen(function* () {
296 if ((yield* HostProcess.Platform) !== "linux") return;
297 const launched = (options: Parameters<typeof createMuseSdkHostEffect>[0]) =>
298 Effect.gen(function* () {
299 const createHost = vi.fn(async (_options: unknown) => ({}) as MuseSdkHost);
300 yield* createMuseSdkHostEffect(options, createHost);
301 return createHost.mock.calls[0]?.[0];
302 });
303 const throughEnv = yield* launched({ binaryPath: "muse", cwd: "/work space" });
304 expect(throughEnv).toMatchObject({
305 launch: { command: "/usr/bin/env", args: ["-C", "/work space", "--", "muse"] },
306 });
307 expect(throughEnv).not.toHaveProperty("cwd");
308 // env would read this path as an assignment.
309 expect(yield* launched({ binaryPath: "/opt/a=b/muse", cwd: "/work" })).toMatchObject({
310 launch: { command: "/opt/a=b/muse", args: [] },
311 cwd: "/work",
312 });
313 }),
314 );
315
316 // cmd's quote rules only show with a real cmd.exe, spawning as the SDK does.
317 it.effect("starts a real launcher from a folder with spaces and cmd metacharacters", () =>
318 Effect.gen(function* () {
319 if ((yield* HostProcess.Platform) !== "win32") return;
320 const fs = yield* FileSystem.FileSystem;
321 const path = yield* Path.Path;
322 const folder = path.join(
323 yield* fs.makeTempDirectoryScoped({ prefix: "MuseLaunch-" }),
324 "R&D Team (x) @ ^y",
325 );
326 yield* fs.makeDirectory(folder);
327 const launcher = path.join(folder, "muse.cmd");
328 yield* fs.writeFileString(launcher, '@echo off\r\necho %*>"%~dp0args.txt"\r\n');
329 const launch = yield* museLaunch(launcher);
330 const run = NodeChildProcess.spawnSync(launch.command, [...launch.args, "serve", "--x"], {
331 cwd: folder,
332 encoding: "utf8",
333 });
334 expect(run.status, run.stderr).toBe(0);
335 expect((yield* fs.readFileString(path.join(folder, "args.txt"))).trim()).toBe("serve --x");
336 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
337 );
338 });
339
340 describe("Muse workspace root", () => {
341 it.effect("uses native canonical case off Windows", () =>
342 Effect.gen(function* () {
343 using _realpath = vi.spyOn(NodeFSP, "realpath").mockResolvedValue("/workspace/eevee");
344 expect(yield* museWorkspaceRoot("/workspace/EEVEE")).toBe("/workspace/eevee");
345 }).pipe(Effect.provideService(HostProcess.Platform, "darwin")),
346 );
347
348 it("writes Windows paths in their verbatim form", () => {
349 expect(museVerbatimPath("C:\\Users\\Person\\repo")).toBe("\\\\?\\C:\\Users\\Person\\repo");
350 expect(museVerbatimPath("\\\\server\\share\\repo")).toBe("\\\\?\\UNC\\server\\share\\repo");
351 expect(museVerbatimPath("\\\\?\\C:\\repo")).toBe("\\\\?\\C:\\repo");
352 });
353
354 it.effect("keeps a root it cannot resolve off Windows", () =>
355 Effect.gen(function* () {
356 expect(yield* museWorkspaceRoot("/workspace/repo")).toBe("/workspace/repo");
357 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
358 );
359
360 it.effect("keeps a Windows root it cannot resolve, in verbatim form", () =>
361 Effect.gen(function* () {
362 expect(yield* museWorkspaceRoot("C:\\definitely-missing\\repo")).toBe(
363 "\\\\?\\C:\\definitely-missing\\repo",
364 );
365 expect(yield* museWorkspaceRoot("C:/definitely-missing/repo")).toBe(
366 "\\\\?\\C:\\definitely-missing\\repo",
367 );
368 expect(yield* museWorkspaceRoot("//server/share/missing")).toBe(
369 "\\\\?\\UNC\\server\\share\\missing",
370 );
371 }).pipe(Effect.provideService(HostProcess.Platform, "win32")),
372 );
373
374 // FileSystem.realPath keeps the case it is given; Muse rejects a root whose case
375 // differs from the disk's, and APFS is case-insensitive just like NTFS.
376 it.effect("fixes the case of a macOS root natively", () =>
377 Effect.gen(function* () {
378 if ((yield* HostProcess.Platform) !== "darwin") return;
379 const fs = yield* FileSystem.FileSystem;
380 const path = yield* Path.Path;
381 const created = yield* fs.makeTempDirectoryScoped({ prefix: "MuseRoot-" });
382 // Only a case-insensitive volume resolves the miscased path; skip on a case-sensitive one.
383 if (!(yield* fs.exists(created.toUpperCase()))) return;
384 const root = yield* museWorkspaceRoot(created.toUpperCase());
385 expect(path.basename(root)).toBe(path.basename(created));
386 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
387 );
388
389 it.effect("fixes the case of a Windows root natively", () =>
390 Effect.gen(function* () {
391 if ((yield* HostProcess.Platform) !== "win32") return;
392 const fs = yield* FileSystem.FileSystem;
393 const path = yield* Path.Path;
394 const created = yield* fs.makeTempDirectoryScoped({ prefix: "MuseRoot-" });
395 const root = yield* museWorkspaceRoot(created.toLowerCase());
396 expect(root.startsWith("\\\\?\\")).toBe(true);
397 expect(root.endsWith(`\\${path.basename(created)}`)).toBe(true);
398 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
399 );
400 });