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

museSdk.test.ts

266 lines9.2 KB

1import { spawnMspConnection, type MspHandshake, type SpawnedMspConnection } from "@muse-code/sdk";
2import { it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import { afterEach, describe, expect, vi } from "vite-plus/test";
6import {
7 createMuseSdkHost,
8 createMuseSdkHostEffect,
9 makeMuseEnvironment,
10 museApprovalMode,
11 type MuseSdkHost,
12} from "./museSdk.ts";
13​
14vi.mock("@muse-code/sdk", () => ({ spawnMspConnection: vi.fn() }));
15​
16function pending<A>() {
17 let resolve = (_value: A) => {};
18 let reject = (_error: unknown) => {};
19 const promise = new Promise<A>((yes, no) => {
20 resolve = yes;
21 reject = no;
22 });
23 return { promise, resolve, reject };
25​
26function mockSpawn() {
27 const startup = pending<SpawnedMspConnection>();
28 const shutdown = pending<{ code: number; signal: null }>();
29 const closing = pending<void>();
30 const initializing = pending<void>();
31 const initialize = vi.fn(() => {
32 initializing.resolve();
33 return startup.promise;
34 });
35 const close = vi.fn(() => {
36 closing.resolve();
37 return shutdown.promise;
38 });
39 const handshake = { initialize, close } as unknown as MspHandshake;
40 vi.mocked(spawnMspConnection).mockReturnValue(handshake);
41 const ready = {
42 connection: {},
43 initializeResult: { grantedCapabilities: [], schema: { version: 1 } },
44 exited: shutdown.promise,
45 fingerprintWarning: { warning: "additive optional" },
46 } as unknown as SpawnedMspConnection;
47 return { startup, shutdown, closing, initializing, initialize, close, ready };
49​
50afterEach(() => {
51 vi.useRealTimers();
52 vi.clearAllMocks();
53});
54​
55describe("Muse SDK host", () => {
56 it.each(["META_API_KEY", "meta_api_key", "Meta_Api_Key"])(
57 "excludes %s without reading its value or mutating the supplied environment",
58 (key) => {
59 const source: NodeJS.ProcessEnv = { PATH: "/bin", MUSE_TEST: "yes" };
60 const read = vi.fn(() => {
61 throw new Error("The API override must not be read.");
62 });
63 Object.defineProperty(source, key, { enumerable: true, get: read });
64 expect(makeMuseEnvironment(source)).toEqual({
65 PATH: "/bin",
66 MUSE_TEST: "yes",
67 MUSE_NO_AUTO_UPDATE: "1",
68 });
69 expect(read).not.toHaveBeenCalled();
70 expect(Object.keys(source)).toContain(key);
71 },
72 );
73​
74 it("selects full access explicitly and keeps other runtime modes sandboxed", async () => {
75 for (const mode of ["approval-required", "auto-accept-edits", "auto", "full-access"] as const) {
76 const fake = mockSpawn();
77 const running = createMuseSdkHost({
78 binaryPath: "/custom/muse",
79 cwd: "/workspace",
80 runtimeMode: mode,
81 environment: { PATH: "/bin" },
82 });
83 expect(vi.mocked(spawnMspConnection).mock.lastCall?.[0]).toMatchObject({
84 command: "/custom/muse",
85 cwd: "/workspace",
86 args:
87 mode === "full-access"
88 ? ["serve", "--trust-workspace", "--disable-sandbox"]
89 : ["serve", "--trust-workspace"],
90 });
91 expect(museApprovalMode(mode)).toBe(mode === "full-access" ? "allowAll" : "promptUnmatched");
92 fake.startup.resolve(fake.ready);
93 const host = await running;
94 fake.shutdown.resolve({ code: 0, signal: null });
95 await host.close();
96 await host.close();
97 expect(fake.close).toHaveBeenCalledOnce();
98 }
99 });
100​
101 it("bounds startup and waits for native shutdown after timeout", async () => {
102 vi.useFakeTimers();
103 const fake = mockSpawn();
104 const startup = createMuseSdkHost({ binaryPath: "muse", startupTimeoutMs: 30 });
105 let settled = false;
106 const outcome = startup.then(
107 () => {
108 settled = true;
109 },
110 (error: unknown) => {
111 settled = true;
112 return error;
113 },
114 );
115 await vi.advanceTimersByTimeAsync(31);
116 expect(fake.close).toHaveBeenCalledOnce();
117 expect(settled).toBe(false);
118 fake.shutdown.resolve({ code: 0, signal: null });
119 expect(await outcome).toMatchObject({ message: "Muse SDK initialization timed out." });
120 });
121​
122 it("closes the pre-handshake host on abort and rejects only after shutdown", async () => {
123 const fake = mockSpawn();
124 const abort = new AbortController();
125 const started = createMuseSdkHost({ binaryPath: "muse", signal: abort.signal });
126 const reason = new Error("Cancelled by caller");
127 const outcome = started.catch((error: unknown) => error);
128 abort.abort(reason);
129 expect(fake.close).toHaveBeenCalledOnce();
130 fake.shutdown.resolve({ code: 0, signal: null });
131 expect(await outcome).toBe(reason);
132 });
133​
134 it("closes rejected initialization and keeps successful schema advisories usable", async () => {
135 const failed = mockSpawn();
136 const started = createMuseSdkHost({ binaryPath: "muse" });
137 const outcome = started.catch((error: unknown) => error);
138 failed.startup.reject(new Error("Handshake failed"));
139 failed.shutdown.resolve({ code: 0, signal: null });
140 expect(await outcome).toMatchObject({ message: "Handshake failed" });
141 expect(failed.close).toHaveBeenCalledOnce();
142 const success = mockSpawn();
143 const ready = createMuseSdkHost({ binaryPath: "muse", readOnly: true });
144 success.startup.resolve(success.ready);
145 const host = await ready;
146 expect(host.initializeResult.grantedCapabilities).toEqual([]);
147 expect(vi.mocked(spawnMspConnection).mock.lastCall?.[0].args).toEqual([
148 "serve",
149 "--disable-shell",
150 "--disable-write",
151 "--no-session-log",
152 ]);
153 success.shutdown.resolve({ code: 0, signal: null });
154 await host.close();
155 });
156​
157 it.each([undefined, 2])(
158 "rejects unsupported envelope version %s and awaits shutdown",
159 async (version) => {
160 const fake = mockSpawn();
161 const started = createMuseSdkHost({ binaryPath: "muse" });
162 let settled = false;
163 const outcome = started.catch((error: unknown) => {
164 settled = true;
165 return error;
166 });
167 fake.startup.resolve({
168 ...fake.ready,
169 initializeResult: {
170 ...fake.ready.initializeResult,
171 schema: { fingerprint: "test", version },
172 },
173 } as unknown as SpawnedMspConnection);
174 await fake.closing.promise;
175 expect(fake.close).toHaveBeenCalledOnce();
176 expect(settled).toBe(false);
177 fake.shutdown.resolve({ code: 0, signal: null });
178 expect(await outcome).toMatchObject({
179 message: "Muse SDK returned an unsupported protocol envelope version.",
180 });
181 },
182 );
183​
184 it("does not spawn when already aborted and closes a ready host on later abort", async () => {
185 const aborted = new AbortController();
186 aborted.abort();
187 await expect(
188 createMuseSdkHost({ binaryPath: "muse", signal: aborted.signal }),
189 ).rejects.toBeDefined();
190 expect(spawnMspConnection).not.toHaveBeenCalled();
191 const fake = mockSpawn();
192 const abort = new AbortController();
193 const running = createMuseSdkHost({ binaryPath: "muse", signal: abort.signal });
194 fake.startup.resolve(fake.ready);
195 const host = await running;
196 abort.abort();
197 fake.shutdown.resolve({ code: 0, signal: null });
198 await host.close();
199 expect(fake.close).toHaveBeenCalledOnce();
200 });
201​
202 it.effect(
203 "keeps Effect startup resources alive until interrupted initialization shuts down",
204 () =>
205 Effect.gen(function* () {
206 const fake = mockSpawn();
207 let released = false;
208 const fiber = yield* Effect.forkChild(
209 createMuseSdkHostEffect({ binaryPath: "muse" }).pipe(
210 Effect.ensuring(
211 Effect.sync(() => {
212 released = true;
213 }),
214 ),
215 ),
216 );
217 yield* Effect.promise(() => fake.initializing.promise);
218 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild);
219 yield* Effect.promise(() => fake.closing.promise);
220 expect(released).toBe(false);
221 fake.shutdown.resolve({ code: 0, signal: null });
222 yield* Fiber.join(interrupted);
223 expect(released).toBe(true);
224 expect(fake.close).toHaveBeenCalledOnce();
225 }),
226 );
227​
228 it.effect("closes a fulfilled host when interruption wins before acquisition is delivered", () =>
229 Effect.gen(function* () {
230 const started = pending<void>();
231 const startup = pending<MuseSdkHost>();
232 const closing = pending<void>();
233 const shutdown = pending<void>();
234 const host = {
235 close: vi.fn(() => {
236 closing.resolve();
237 return shutdown.promise;
238 }),
239 } as unknown as MuseSdkHost;
240 let released = false;
241 const fiber = yield* Effect.forkChild(
242 createMuseSdkHostEffect({ binaryPath: "muse" }, () => {
243 started.resolve();
244 return startup.promise;
245 }).pipe(
246 Effect.ensuring(
247 Effect.sync(() => {
248 released = true;
249 }),
250 ),
251 ),
252 );
253 yield* Effect.promise(() => started.promise);
254 startup.resolve(host);
255 const interrupted = yield* Fiber.interrupt(fiber).pipe(
256 Effect.forkChild({ startImmediately: true }),
257 );
258 yield* Effect.promise(() => closing.promise);
259 expect(released).toBe(false);
260 shutdown.resolve();
261 yield* Fiber.join(interrupted);
262 expect(released).toBe(true);
263 expect(host.close).toHaveBeenCalledOnce();
264 }),
265 );
266});