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

sdk.test.ts

332 lines12.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, onTestFinished, 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.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(
139 "observes native host exit while the SDK still waits for a detached stdout holder",
140 () =>
141 Effect.gen(function* () {
142 if ((yield* HostProcess.Platform) === "win32") return;
143 yield* Effect.promise(async () => {
144 const sdk = await vi.importActual<typeof import("@muse-code/sdk")>("@muse-code/sdk");
145 const processExited = pending<{ code: number | null; signal: NodeJS.Signals | null }>();
146 const holderSource = `process.send("ready", () => {
147 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
148 });`;
149 const fixture = `
150 const { spawn } = require("node:child_process");
151 require("node:readline").createInterface({ input: process.stdin }).on("line", async line => {
152 const frame = JSON.parse(line);
153 if (!("id" in frame)) return;
154 let result = { schema: { version: 1, fingerprint: "t3-native-fixture" }, grantedCapabilities: [] };
155 if (frame.method === "fixture/exit") {
156 const holder = spawn(process.execPath, ["-e", ${JSON.stringify(holderSource)}], {
157 detached: true, stdio: ["ignore", 1, 2, "ipc"]
158 });
159 await new Promise(resolve => holder.once("message", resolve));
160 result = { pid: holder.pid };
161 }
162 process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result }) + "\\n",
163 () => { if (frame.method === "fixture/exit") process.exit(7); });
164 });
165 `;
166 let holderPid: number | undefined;
167 let host: MuseSdkHost | undefined;
168 const reap = () => {
169 if (holderPid !== undefined) {
170 try {
171 process.kill(holderPid, "SIGKILL");
172 } catch {
173 /* Already reaped. */
174 }
175 holderPid = undefined;
176 }
177 };
178 onTestFinished(async () => {
179 reap();
180 await host?.close();
181 });
182 try {
183 host = await createMuseSdkHost(
184 {
185 binaryPath: process.execPath,
186 launch: { command: process.execPath, args: ["-e", fixture] },
187 onProcessExit: processExited.resolve,
188 },
189 sdk.spawnMspConnection,
190 );
191 let sdkExited = false;
192 let connectionClosed = false;
193 void host.exited.then(() => {
194 sdkExited = true;
195 });
196 void host.connection.closed.then(() => {
197 connectionClosed = true;
198 });
199 const response = await host.connection.request("fixture/exit", {});
200 expect(response).toMatchObject({ pid: expect.any(Number) });
201 holderPid = Number((response as { pid: number }).pid);
202 expect(await processExited.promise).toEqual({ code: 7, signal: null });
203 expect(sdkExited).toBe(false);
204 expect(connectionClosed).toBe(false);
205 reap();
206 expect(await host.exited).toEqual({ code: 7, signal: null });
207 await host.close();
208 expect(connectionClosed).toBe(true);
209 } finally {
210 reap();
211 await host?.close();
212 }
213 });
214 }),
215 );
216​
217 it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
218 Effect.gen(function* () {
219 const started = pending<void>();
220 const startup = pending<MuseSdkHost>();
221 const closing = pending<void>();
222 const shutdown = pending<void>();
223 const host = {
224 close: vi.fn(() => {
225 closing.resolve();
226 return shutdown.promise;
227 }),
228 } as unknown as MuseSdkHost;
229 let released = false;
230 const fiber = yield* Effect.forkChild(
231 createMuseSdkHostEffect({ binaryPath: "muse" }, () => {
232 started.resolve();
233 return startup.promise;
234 }).pipe(
235 Effect.ensuring(
236 Effect.sync(() => {
237 released = true;
238 }),
239 ),
240 ),
241 );
242 yield* Effect.promise(() => started.promise);
243 startup.resolve(host);
244 const interrupted = yield* Fiber.interrupt(fiber).pipe(
245 Effect.forkChild({ startImmediately: true }),
246 );
247 yield* Effect.promise(() => closing.promise);
248 expect(released).toBe(false);
249 shutdown.resolve();
250 yield* Fiber.join(interrupted);
251 expect(released).toBe(true);
252 expect(host.close).toHaveBeenCalledOnce();
253 }),
254 );
255});
256​
257describe("Muse launch", () => {
258 const CMD = "C:\\Windows\\system32\\cmd.exe";
259 const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) =>
260 museLaunch("muse", env).pipe(
261 Effect.provideService(HostProcess.Platform, "win32"),
262 Effect.provideService(SpawnExecutableResolution, () => resolved),
263 );
264​
265 it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () =>
266 Effect.gen(function* () {
267 expect(yield* onWindows("C:\\Muse\\muse.exe")).toEqual({
268 command: "C:\\Muse\\muse.exe",
269 args: [],
270 });
271 const spaced = "C:\\Users\\Jane Doe\\AppData\\Local\\Programs\\muse\\muse.cmd";
272 expect(yield* onWindows(spaced)).toEqual({ command: CMD, args: ["/d", "/c", "@", spaced] });
273 const spacedAmpersand = "C:\\Users\\R&D Team\\AppData\\Local\\Programs\\muse\\muse.cmd";
274 expect(yield* onWindows(spacedAmpersand)).toEqual({
275 command: CMD,
276 args: ["/d", "/c", "@", spacedAmpersand],
277 });
278 expect(yield* onWindows("C:\\Users\\R&D(1)\\muse.cmd")).toEqual({
279 command: CMD,
280 args: ["/d", "/c", "C:\\Users\\R^&D^(1^)\\muse.cmd"],
281 });
282 expect((yield* onWindows("C:\\Muse\\muse.bat", { SYSTEMROOT: "C:\\Windows" })).command).toBe(
283 "C:\\Windows\\System32\\cmd.exe",
284 );
285 expect(yield* onWindows(undefined)).toEqual({ command: "muse", args: [] });
286 }),
287 );
288​
289 // cmd's quote rules only show with a real cmd.exe, spawning as the SDK does.
290 it.effect("starts a real launcher from a folder with spaces and cmd metacharacters", () =>
291 Effect.gen(function* () {
292 if ((yield* HostProcess.Platform) !== "win32") return;
293 const fs = yield* FileSystem.FileSystem;
294 const path = yield* Path.Path;
295 const folder = path.join(
296 yield* fs.makeTempDirectoryScoped({ prefix: "MuseLaunch-" }),
297 "R&D Team (x) @ ^y",
298 );
299 yield* fs.makeDirectory(folder);
300 const launcher = path.join(folder, "muse.cmd");
301 yield* fs.writeFileString(launcher, '@echo off\r\necho %*>"%~dp0args.txt"\r\n');
302 const launch = yield* museLaunch(launcher);
303 const run = NodeChildProcess.spawnSync(launch.command, [...launch.args, "serve", "--x"], {
304 cwd: folder,
305 encoding: "utf8",
306 });
307 expect(run.status, run.stderr).toBe(0);
308 expect((yield* fs.readFileString(path.join(folder, "args.txt"))).trim()).toBe("serve --x");
309 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
310 );
311});
312​
313describe("Muse workspace root", () => {
314 it("writes Windows paths in their verbatim form", () => {
315 expect(museVerbatimPath("C:\\Users\\Person\\repo")).toBe("\\\\?\\C:\\Users\\Person\\repo");
316 expect(museVerbatimPath("\\\\server\\share\\repo")).toBe("\\\\?\\UNC\\server\\share\\repo");
317 expect(museVerbatimPath("\\\\?\\C:\\repo")).toBe("\\\\?\\C:\\repo");
318 });
319​
320 // FileSystem.realPath keeps the case it is given; Muse rejects a root whose case differs from the disk's.
321 it.effect("fixes the case of a Windows root natively", () =>
322 Effect.gen(function* () {
323 if ((yield* HostProcess.Platform) !== "win32") return;
324 const fs = yield* FileSystem.FileSystem;
325 const path = yield* Path.Path;
326 const created = yield* fs.makeTempDirectoryScoped({ prefix: "MuseRoot-" });
327 const root = yield* museWorkspaceRoot(created.toLowerCase());
328 expect(root.startsWith("\\\\?\\")).toBe(true);
329 expect(root.endsWith(`\\${path.basename(created)}`)).toBe(true);
330 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
331 );
332});