Open History to see the last commit
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 };
34}
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 };
58}
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.each([undefined, 2])(
112 "rejects unsupported envelope version %s and awaits shutdown",
113 async (version) => {
114 const fake = mockSpawn();
115 const started = createMuseSdkHost({ binaryPath: "muse" });
116 let settled = false;
117 const outcome = started.catch((error: unknown) => {
118 settled = true;
119 return error;
120 });
121 fake.startup.resolve({
122 ...fake.ready,
123 initializeResult: {
124 ...fake.ready.initializeResult,
125 schema: { fingerprint: "test", version },
126 },
127 } as unknown as SpawnedMspConnection);
128 await fake.closing.promise;
129 expect(fake.close).toHaveBeenCalledOnce();
130 expect(settled).toBe(false);
131 fake.shutdown.resolve({ code: 0, signal: null });
132 expect(await outcome).toMatchObject({
133 message: "Muse SDK returned an unsupported protocol envelope version.",
134 });
135 },
136 );
137
138 it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
139 Effect.gen(function* () {
140 const started = pending<void>();
141 const startup = pending<MuseSdkHost>();
142 const closing = pending<void>();
143 const shutdown = pending<void>();
144 const host = {
145 close: vi.fn(() => {
146 closing.resolve();
147 return shutdown.promise;
148 }),
149 } as unknown as MuseSdkHost;
150 let released = false;
151 const fiber = yield* Effect.forkChild(
152 createMuseSdkHostEffect({ binaryPath: "muse" }, () => {
153 started.resolve();
154 return startup.promise;
155 }).pipe(
156 Effect.ensuring(
157 Effect.sync(() => {
158 released = true;
159 }),
160 ),
161 ),
162 );
163 yield* Effect.promise(() => started.promise);
164 startup.resolve(host);
165 const interrupted = yield* Fiber.interrupt(fiber).pipe(
166 Effect.forkChild({ startImmediately: true }),
167 );
168 yield* Effect.promise(() => closing.promise);
169 expect(released).toBe(false);
170 shutdown.resolve();
171 yield* Fiber.join(interrupted);
172 expect(released).toBe(true);
173 expect(host.close).toHaveBeenCalledOnce();
174 }),
175 );
176});
177
178describe("Muse launch", () => {
179 const CMD = "C:\\Windows\\system32\\cmd.exe";
180 const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) =>
181 museLaunch("muse", env).pipe(
182 Effect.provideService(HostProcess.Platform, "win32"),
183 Effect.provideService(SpawnExecutableResolution, () => resolved),
184 );
185
186 it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () =>
187 Effect.gen(function* () {
188 expect(yield* onWindows("C:\\Muse\\muse.exe")).toEqual({
189 command: "C:\\Muse\\muse.exe",
190 args: [],
191 });
192 const spaced = "C:\\Users\\Jane Doe\\AppData\\Local\\Programs\\muse\\muse.cmd";
193 expect(yield* onWindows(spaced)).toEqual({ command: CMD, args: ["/d", "/c", "@", spaced] });
194 const spacedAmpersand = "C:\\Users\\R&D Team\\AppData\\Local\\Programs\\muse\\muse.cmd";
195 expect(yield* onWindows(spacedAmpersand)).toEqual({
196 command: CMD,
197 args: ["/d", "/c", "@", spacedAmpersand],
198 });
199 expect(yield* onWindows("C:\\Users\\R&D(1)\\muse.cmd")).toEqual({
200 command: CMD,
201 args: ["/d", "/c", "C:\\Users\\R^&D^(1^)\\muse.cmd"],
202 });
203 expect((yield* onWindows("C:\\Muse\\muse.bat", { SYSTEMROOT: "C:\\Windows" })).command).toBe(
204 "C:\\Windows\\System32\\cmd.exe",
205 );
206 expect(yield* onWindows(undefined)).toEqual({ command: "muse", args: [] });
207 }),
208 );
209
210 // cmd's quote rules only show with a real cmd.exe, spawning as the SDK does.
211 it.effect("starts a real launcher from a folder with spaces and cmd metacharacters", () =>
212 Effect.gen(function* () {
213 if ((yield* HostProcess.Platform) !== "win32") return;
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const folder = path.join(
217 yield* fs.makeTempDirectoryScoped({ prefix: "MuseLaunch-" }),
218 "R&D Team (x) @ ^y",
219 );
220 yield* fs.makeDirectory(folder);
221 const launcher = path.join(folder, "muse.cmd");
222 // Records its arguments next to itself; reaching the file at all proves cmd found it.
223 yield* fs.writeFileString(launcher, '@echo off\r\necho %*>"%~dp0args.txt"\r\n');
224 const launch = yield* museLaunch(launcher);
225 const run = NodeChildProcess.spawnSync(launch.command, [...launch.args, "serve", "--x"], {
226 cwd: folder,
227 encoding: "utf8",
228 });
229 expect(run.status, run.stderr).toBe(0);
230 expect((yield* fs.readFileString(path.join(folder, "args.txt"))).trim()).toBe("serve --x");
231 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
232 );
233});
234
235describe("Muse workspace root", () => {
236 it("writes Windows paths in their verbatim form", () => {
237 expect(museVerbatimPath("C:\\Users\\Person\\repo")).toBe("\\\\?\\C:\\Users\\Person\\repo");
238 expect(museVerbatimPath("\\\\server\\share\\repo")).toBe("\\\\?\\UNC\\server\\share\\repo");
239 expect(museVerbatimPath("\\\\?\\C:\\repo")).toBe("\\\\?\\C:\\repo");
240 });
241
242 // FileSystem.realPath keeps the case it is given; Muse rejects a root whose case differs from the disk's.
243 it.effect("fixes the case of a Windows root natively", () =>
244 Effect.gen(function* () {
245 if ((yield* HostProcess.Platform) !== "win32") return;
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const created = yield* fs.makeTempDirectoryScoped({ prefix: "MuseRoot-" });
249 const root = yield* museWorkspaceRoot(created.toLowerCase());
250 expect(root.startsWith("\\\\?\\")).toBe(true);
251 expect(root.endsWith(`\\${path.basename(created)}`)).toBe(true);
252 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
253 );
254});