Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sdk.test.ts

455 lines16.7 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- The Muse SDK spawns with Node's child_process, so the launch test quotes arguments the same way.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { spawnMspConnection, type MspHandshake, type SpawnedMspConnection } from "@muse-code/sdk";
5import { it } from "@effect/vitest";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { SpawnExecutableResolution } from "@t3tools/shared/shell";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Path from "effect/Path";
12import { afterEach, describe, expect, vi } from "vite-plus/test";
13import {
14 createMuseSdkHost,
15 createMuseSdkHostEffect,
16 makeMuseEnvironment,
17 museApprovalMode,
18 museLaunch,
19 museVerbatimPath,
20 museWorkspaceRoot,
21 type MuseSdkHost,
22} from "./sdk.ts";
23​
24vi.mock("@muse-code/sdk", () => ({ spawnMspConnection: vi.fn() }));
25​
26function pending<A>() {
27 let resolve = (_value: A) => {};
28 let reject = (_error: unknown) => {};
29 const promise = new Promise<A>((yes, no) => {
30 resolve = yes;
31 reject = no;
32 });
33 return { promise, resolve, reject };
35​
36function mockSpawn() {
37 const startup = pending<SpawnedMspConnection>();
38 const shutdown = pending<{ code: number; signal: null }>();
39 const closing = pending<void>();
40 const initializing = pending<void>();
41 const initialize = vi.fn(() => {
42 initializing.resolve();
43 return startup.promise;
44 });
45 const close = vi.fn(() => {
46 closing.resolve();
47 return shutdown.promise;
48 });
49 const handshake = { initialize, close } as unknown as MspHandshake;
50 vi.mocked(spawnMspConnection).mockReturnValue(handshake);
51 const ready = {
52 connection: {},
53 initializeResult: { grantedCapabilities: [], schema: { version: 1 } },
54 exited: shutdown.promise,
55 fingerprintWarning: { warning: "additive optional" },
56 } as unknown as SpawnedMspConnection;
57 return { startup, shutdown, closing, initializing, initialize, close, ready };
59​
60afterEach(() => {
61 vi.useRealTimers();
62 vi.clearAllMocks();
63});
64​
65describe("Muse SDK host", () => {
66 it.each(["META_API_KEY", "meta_api_key", "Meta_Api_Key"])(
67 "excludes %s without reading its value or mutating the supplied environment",
68 (key) => {
69 const source: NodeJS.ProcessEnv = { PATH: "/bin", MUSE_TEST: "yes" };
70 const read = vi.fn(() => {
71 throw new Error("The API override must not be read.");
72 });
73 Object.defineProperty(source, key, { enumerable: true, get: read });
74 expect(makeMuseEnvironment(source)).toEqual({
75 PATH: "/bin",
76 MUSE_TEST: "yes",
77 MUSE_NO_AUTO_UPDATE: "1",
78 });
79 expect(read).not.toHaveBeenCalled();
80 expect(Object.keys(source)).toContain(key);
81 },
82 );
83​
84 it("selects full access explicitly and keeps other runtime modes sandboxed", async () => {
85 for (const mode of ["approval-required", "auto-accept-edits", "auto", "full-access"] as const) {
86 const fake = mockSpawn();
87 const running = createMuseSdkHost({
88 binaryPath: "/custom/muse",
89 cwd: "/workspace",
90 runtimeMode: mode,
91 environment: { PATH: "/bin" },
92 });
93 expect(vi.mocked(spawnMspConnection).mock.lastCall?.[0]).toMatchObject({
94 command: "/custom/muse",
95 cwd: "/workspace",
96 args:
97 mode === "full-access"
98 ? ["serve", "--trust-workspace", "--disable-sandbox"]
99 : ["serve", "--trust-workspace"],
100 });
101 expect(museApprovalMode(mode)).toBe(mode === "full-access" ? "allowAll" : "promptUnmatched");
102 fake.startup.resolve(fake.ready);
103 const host = await running;
104 fake.shutdown.resolve({ code: 0, signal: null });
105 await host.close();
106 await host.close();
107 expect(fake.close).toHaveBeenCalledOnce();
108 }
109 });
110​
111 it("bounds startup and waits for native shutdown after timeout", async () => {
112 vi.useFakeTimers();
113 const fake = mockSpawn();
114 const startup = createMuseSdkHost({ binaryPath: "muse", startupTimeoutMs: 30 });
115 let settled = false;
116 const outcome = startup.then(
117 () => {
118 settled = true;
119 },
120 (error: unknown) => {
121 settled = true;
122 return error;
123 },
124 );
125 await vi.advanceTimersByTimeAsync(31);
126 expect(fake.close).toHaveBeenCalledOnce();
127 expect(settled).toBe(false);
128 fake.shutdown.resolve({ code: 0, signal: null });
129 expect(await outcome).toMatchObject({ message: "Muse SDK initialization timed out." });
130 });
131​
132 it("closes the pre-handshake host on abort and rejects only after shutdown", async () => {
133 const fake = mockSpawn();
134 const abort = new AbortController();
135 const started = createMuseSdkHost({ binaryPath: "muse", signal: abort.signal });
136 const reason = new Error("Cancelled by caller");
137 const outcome = started.catch((error: unknown) => error);
138 abort.abort(reason);
139 expect(fake.close).toHaveBeenCalledOnce();
140 fake.shutdown.resolve({ code: 0, signal: null });
141 expect(await outcome).toBe(reason);
142 });
143​
144 it("closes rejected initialization and keeps successful schema advisories usable", async () => {
145 const failed = mockSpawn();
146 const started = createMuseSdkHost({ binaryPath: "muse" });
147 const outcome = started.catch((error: unknown) => error);
148 failed.startup.reject(new Error("Handshake failed"));
149 failed.shutdown.resolve({ code: 0, signal: null });
150 expect(await outcome).toMatchObject({ message: "Handshake failed" });
151 expect(failed.close).toHaveBeenCalledOnce();
152 const success = mockSpawn();
153 const ready = createMuseSdkHost({ binaryPath: "muse", readOnly: true });
154 success.startup.resolve(success.ready);
155 const host = await ready;
156 expect(host.initializeResult.grantedCapabilities).toEqual([]);
157 expect(vi.mocked(spawnMspConnection).mock.lastCall?.[0].args).toEqual([
158 "serve",
159 "--disable-shell",
160 "--disable-write",
161 "--no-session-log",
162 ]);
163 success.shutdown.resolve({ code: 0, signal: null });
164 await host.close();
165 });
166​
167 it.each([undefined, 2])(
168 "rejects unsupported envelope version %s and awaits shutdown",
169 async (version) => {
170 const fake = mockSpawn();
171 const started = createMuseSdkHost({ binaryPath: "muse" });
172 let settled = false;
173 const outcome = started.catch((error: unknown) => {
174 settled = true;
175 return error;
176 });
177 fake.startup.resolve({
178 ...fake.ready,
179 initializeResult: {
180 ...fake.ready.initializeResult,
181 schema: { fingerprint: "test", version },
182 },
183 } as unknown as SpawnedMspConnection);
184 await fake.closing.promise;
185 expect(fake.close).toHaveBeenCalledOnce();
186 expect(settled).toBe(false);
187 fake.shutdown.resolve({ code: 0, signal: null });
188 expect(await outcome).toMatchObject({
189 message: "Muse SDK returned an unsupported protocol envelope version.",
190 });
191 },
192 );
193​
194 it("does not spawn when already aborted and closes a ready host on later abort", async () => {
195 const aborted = new AbortController();
196 aborted.abort();
197 await expect(
198 createMuseSdkHost({ binaryPath: "muse", signal: aborted.signal }),
199 ).rejects.toBeDefined();
200 expect(spawnMspConnection).not.toHaveBeenCalled();
201 const fake = mockSpawn();
202 const abort = new AbortController();
203 const running = createMuseSdkHost({ binaryPath: "muse", signal: abort.signal });
204 fake.startup.resolve(fake.ready);
205 const host = await running;
206 abort.abort();
207 fake.shutdown.resolve({ code: 0, signal: null });
208 await host.close();
209 expect(fake.close).toHaveBeenCalledOnce();
210 });
211​
212 it.effect(
213 "keeps Effect startup resources alive until interrupted initialization shuts down",
214 () =>
215 Effect.gen(function* () {
216 const fake = mockSpawn();
217 let released = false;
218 const fiber = yield* Effect.forkChild(
219 createMuseSdkHostEffect({ binaryPath: "muse" }).pipe(
220 Effect.ensuring(
221 Effect.sync(() => {
222 released = true;
223 }),
224 ),
225 ),
226 );
227 yield* Effect.promise(() => fake.initializing.promise);
228 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild);
229 yield* Effect.promise(() => fake.closing.promise);
230 expect(released).toBe(false);
231 fake.shutdown.resolve({ code: 0, signal: null });
232 yield* Fiber.join(interrupted);
233 expect(released).toBe(true);
234 expect(fake.close).toHaveBeenCalledOnce();
235 }),
236 );
237​
238 it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
239 Effect.gen(function* () {
240 const started = pending<void>();
241 const startup = pending<MuseSdkHost>();
242 const closing = pending<void>();
243 const shutdown = pending<void>();
244 const host = {
245 close: vi.fn(() => {
246 closing.resolve();
247 return shutdown.promise;
248 }),
249 } as unknown as MuseSdkHost;
250 let released = false;
251 const fiber = yield* Effect.forkChild(
252 createMuseSdkHostEffect({ binaryPath: "muse" }, () => {
253 started.resolve();
254 return startup.promise;
255 }).pipe(
256 Effect.ensuring(
257 Effect.sync(() => {
258 released = true;
259 }),
260 ),
261 ),
262 );
263 yield* Effect.promise(() => started.promise);
264 startup.resolve(host);
265 const interrupted = yield* Fiber.interrupt(fiber).pipe(
266 Effect.forkChild({ startImmediately: true }),
267 );
268 yield* Effect.promise(() => closing.promise);
269 expect(released).toBe(false);
270 shutdown.resolve();
271 yield* Fiber.join(interrupted);
272 expect(released).toBe(true);
273 expect(host.close).toHaveBeenCalledOnce();
274 }),
275 );
276});
277​
278describe("Muse launch", () => {
279 const CMD = "C:\\Windows\\system32\\cmd.exe";
280 const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) =>
281 museLaunch("muse", env).pipe(
282 Effect.provideService(HostProcess.Platform, "win32"),
283 Effect.provideService(SpawnExecutableResolution, () => resolved),
284 );
285​
286 it.effect("starts the binary itself off Windows", () =>
287 Effect.gen(function* () {
288 expect(yield* museLaunch("muse")).toEqual({ command: "muse", args: [] });
289 }).pipe(
290 Effect.provideService(HostProcess.Platform, "linux"),
291 Effect.provideService(SpawnExecutableResolution, () => {
292 throw new Error("Nothing is resolved off Windows.");
293 }),
294 ),
295 );
296​
297 it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () =>
298 Effect.gen(function* () {
299 expect(yield* onWindows("C:\\Muse\\muse.exe")).toEqual({
300 command: "C:\\Muse\\muse.exe",
301 args: [],
302 });
303 const spaced = "C:\\Users\\Jane Doe\\AppData\\Local\\Programs\\muse\\muse.cmd";
304 expect(yield* onWindows(spaced)).toEqual({ command: CMD, args: ["/d", "/c", "@", spaced] });
305 const spacedAmpersand = "C:\\Users\\R&D Team\\AppData\\Local\\Programs\\muse\\muse.cmd";
306 expect(yield* onWindows(spacedAmpersand)).toEqual({
307 command: CMD,
308 args: ["/d", "/c", "@", spacedAmpersand],
309 });
310 expect(yield* onWindows("C:\\Users\\R&D(1)\\muse.cmd")).toEqual({
311 command: CMD,
312 args: ["/d", "/c", "C:\\Users\\R^&D^(1^)\\muse.cmd"],
313 });
314 expect((yield* onWindows("C:\\Muse\\muse.bat", { SYSTEMROOT: "C:\\Windows" })).command).toBe(
315 "C:\\Windows\\System32\\cmd.exe",
316 );
317 expect(yield* onWindows(undefined)).toEqual({ command: "muse", args: [] });
318 }),
319 );
320​
321 // cmd's quote rules only show with a real cmd.exe, spawning as the SDK does.
322 it.effect("starts a real launcher from a folder with spaces and cmd metacharacters", () =>
323 Effect.gen(function* () {
324 if ((yield* HostProcess.Platform) !== "win32") return;
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const folder = path.join(
328 yield* fs.makeTempDirectoryScoped({ prefix: "MuseLaunch-" }),
329 "R&D Team (x) @ ^y",
330 );
331 yield* fs.makeDirectory(folder);
332 const launcher = path.join(folder, "muse.cmd");
333 // Records its arguments next to itself; reaching the file at all proves cmd found it.
334 yield* fs.writeFileString(launcher, '@echo off\r\necho %*>"%~dp0args.txt"\r\n');
335 const launch = yield* museLaunch(launcher);
336 const run = NodeChildProcess.spawnSync(launch.command, [...launch.args, "serve", "--x"], {
337 cwd: folder,
338 encoding: "utf8",
339 });
340 expect(run.status, run.stderr).toBe(0);
341 expect((yield* fs.readFileString(path.join(folder, "args.txt"))).trim()).toBe("serve --x");
342 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
343 );
344​
345 it.effect("starts Muse's Windows launcher through cmd.exe", () =>
346 Effect.gen(function* () {
347 const fake = mockSpawn();
348 const starting = yield* Effect.forkChild(
349 createMuseSdkHostEffect({
350 binaryPath: "muse",
351 environment: { ComSpec: CMD },
352 readOnly: true,
353 }),
354 );
355 yield* Effect.promise(() => fake.initializing.promise);
356 const spawned = vi.mocked(spawnMspConnection).mock.lastCall?.[0];
357 fake.startup.resolve(fake.ready);
358 const host = yield* Fiber.join(starting);
359 fake.shutdown.resolve({ code: 0, signal: null });
360 yield* Effect.promise(() => host.close());
361 expect(spawned).toMatchObject({
362 command: CMD,
363 args: [
364 "/d",
365 "/c",
366 "C:\\Muse\\muse.cmd",
367 "serve",
368 "--disable-shell",
369 "--disable-write",
370 "--no-session-log",
371 ],
372 });
373 }).pipe(
374 Effect.provideService(HostProcess.Platform, "win32"),
375 Effect.provideService(SpawnExecutableResolution, () => "C:\\Muse\\muse.cmd"),
376 ),
377 );
378​
379 it.effect("passes launcher arguments to the binary that cmd.exe starts", () =>
380 Effect.gen(function* () {
381 const fake = mockSpawn();
382 const starting = yield* Effect.forkChild(
383 createMuseSdkHostEffect({
384 binaryPath: "muse",
385 launchArgs: ["--launcher-arg"],
386 environment: { ComSpec: CMD },
387 readOnly: true,
388 }),
389 );
390 yield* Effect.promise(() => fake.initializing.promise);
391 const spawned = vi.mocked(spawnMspConnection).mock.lastCall?.[0];
392 fake.startup.resolve(fake.ready);
393 const host = yield* Fiber.join(starting);
394 fake.shutdown.resolve({ code: 0, signal: null });
395 yield* Effect.promise(() => host.close());
396 expect(spawned).toMatchObject({
397 command: CMD,
398 args: [
399 "/d",
400 "/c",
401 "C:\\Muse\\muse.cmd",
402 "--launcher-arg",
403 "serve",
404 "--disable-shell",
405 "--disable-write",
406 "--no-session-log",
407 ],
408 });
409 }).pipe(
410 Effect.provideService(HostProcess.Platform, "win32"),
411 Effect.provideService(SpawnExecutableResolution, () => "C:\\Muse\\muse.cmd"),
412 ),
413 );
414});
415​
416describe("Muse workspace root", () => {
417 it("writes Windows paths in their verbatim form", () => {
418 expect(museVerbatimPath("C:\\Users\\Person\\repo")).toBe("\\\\?\\C:\\Users\\Person\\repo");
419 expect(museVerbatimPath("\\\\server\\share\\repo")).toBe("\\\\?\\UNC\\server\\share\\repo");
420 expect(museVerbatimPath("\\\\?\\C:\\repo")).toBe("\\\\?\\C:\\repo");
421 });
422​
423 it.effect("leaves the root alone off Windows", () =>
424 Effect.gen(function* () {
425 expect(yield* museWorkspaceRoot("/workspace/repo")).toBe("/workspace/repo");
426 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
427 );
428​
429 it.effect("keeps a Windows root it cannot resolve, in verbatim form", () =>
430 Effect.gen(function* () {
431 expect(yield* museWorkspaceRoot("C:\\definitely-missing\\repo")).toBe(
432 "\\\\?\\C:\\definitely-missing\\repo",
433 );
434 expect(yield* museWorkspaceRoot("C:/definitely-missing/repo")).toBe(
435 "\\\\?\\C:\\definitely-missing\\repo",
436 );
437 expect(yield* museWorkspaceRoot("//server/share/missing")).toBe(
438 "\\\\?\\UNC\\server\\share\\missing",
439 );
440 }).pipe(Effect.provideService(HostProcess.Platform, "win32")),
441 );
442​
443 // FileSystem.realPath keeps the case it is given; Muse rejects a root whose case differs from the disk's.
444 it.effect("fixes the case of a Windows root natively", () =>
445 Effect.gen(function* () {
446 if ((yield* HostProcess.Platform) !== "win32") return;
447 const fs = yield* FileSystem.FileSystem;
448 const path = yield* Path.Path;
449 const created = yield* fs.makeTempDirectoryScoped({ prefix: "MuseRoot-" });
450 const root = yield* museWorkspaceRoot(created.toLowerCase());
451 expect(root.startsWith("\\\\?\\")).toBe(true);
452 expect(root.endsWith(`\\${path.basename(created)}`)).toBe(true);
453 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
454 );
455});