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

MuseTextGeneration.test.ts

623 lines21.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import type { NotificationHandler } from "@muse-code/sdk";
4import { MuseSettings, ProviderInstanceId } from "@t3tools/contracts";
5import { createModelSelection } from "@t3tools/shared/model";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Schema from "effect/Schema";
10import { vi } from "vite-plus/test";
11​
12import type { MuseSdkHost } from "../provider/museSdk.ts";
13import { museModelCapabilities } from "../provider/museModelCatalog.ts";
14import { makeMuseTextGeneration } from "./MuseTextGeneration.ts";
15​
16const settings = Schema.decodeSync(MuseSettings)({ enabled: true });
17const modelSelection = createModelSelection(
18 ProviderInstanceId.make("muse"),
19 "muse-spark-1.3-contributor",
20 [{ id: "reasoningEffort", value: "high" }],
21);
22const titleInput = {
23 cwd: "/project/should-not-be-used",
24 message: "Fix the login form",
25 modelSelection,
26};
27​
28function fixture(
29 onTurn?: (emit: (method: string, params: Record<string, unknown>) => void) => void,
30 acknowledgeTurn = true,
31 modelCatalog?: Parameters<typeof makeMuseTextGeneration>[3],
32) {
33 let handler: NotificationHandler = () => {};
34 let commandSequence = 0;
35 let activeTurnId: string | undefined;
36 const mintCommandId = () => `turn-${++commandSequence}`;
37 const started = Promise.withResolvers<void>();
38 const closed = Promise.withResolvers<void>();
39 const emit = (method: string, params: Record<string, unknown>) =>
40 handler({
41 jsonrpc: "2.0",
42 method,
43 params: {
44 sessionId: "session-1",
45 turnId: activeTurnId,
46 ...params,
47 ...(params.item
48 ? {
49 item: {
50 revision: 1,
51 turnId: activeTurnId,
52 ...(params.item as Record<string, unknown>),
53 },
54 }
55 : {}),
56 },
57 });
58 const host: MuseSdkHost = {
59 initializeResult: {
60 experimentalApi: false,
61 grantedCapabilities: [],
62 museHome: "/fake/muse",
63 platformFamily: "unix",
64 platformOs: "linux",
65 schema: { fingerprint: "test", version: 1 },
66 serverInfo: { name: "muse", version: "1.1.1" },
67 userAgent: "test",
68 },
69 connection: {
70 command: vi.fn(async (method, _params, options) => {
71 // Connection.command overwrites params.commandId unless supplied in options.
72 const commandId = options?.commandId ?? mintCommandId();
73 if (method === "session/start") return { session: { sessionId: "session-1" } };
74 if (method === "turn/start") {
75 activeTurnId = commandId;
76 started.resolve();
77 onTurn?.(emit);
78 if (!acknowledgeTurn) return await new Promise<Record<string, unknown>>(() => {});
79 return { turnId: commandId };
80 }
81 return {};
82 }),
83 request: vi.fn(async () => ({})),
84 mintCommandId,
85 onNotification: (nextHandler) => {
86 handler = nextHandler;
87 },
88 onProtocolError: () => {},
89 onServerRequest: () => {},
90 closed: closed.promise,
91 },
92 close: vi.fn(async () => {
93 closed.resolve();
94 }),
95 exited: new Promise(() => {}),
96 };
97 const createHost = vi.fn(async () => host);
98 const make = makeMuseTextGeneration(settings, undefined, createHost, modelCatalog);
99 return {
100 host,
101 createHost,
102 started: started.promise,
103 closeConnection: closed.resolve,
104 emit,
105 make,
106 };
108​
109const finish =
110 (text: string) => (emit: (method: string, params: Record<string, unknown>) => void) => {
111 emit("item/updated", { item: { itemId: "answer", kind: "agentMessage", text: "partial" } });
112 emit("item/completed", {
113 item: { itemId: "answer", kind: "agentMessage", revision: 2, text },
114 });
115 emit("turn/completed", { terminal: "completed" });
116 };
117​
118it.layer(NodeServices.layer)("Muse text generation", (it) => {
119 it.effect("rejects unsupported effort before starting a host", () =>
120 Effect.gen(function* () {
121 const test = fixture();
122 const service = yield* test.make;
123 const error = yield* service
124 .generateThreadTitle({
125 ...titleInput,
126 modelSelection: createModelSelection(
127 ProviderInstanceId.make("muse"),
128 modelSelection.model,
129 [{ id: "reasoningEffort", value: "invalid-effort" }],
130 ),
131 })
132 .pipe(Effect.flip);
133 expect(error.detail).toContain("does not support reasoning effort 'invalid-effort'");
134 expect(test.createHost).not.toHaveBeenCalled();
135 }),
136 );
137​
138 it.effect("validates the final item once and closes an isolated restrictive host", () =>
139 Effect.gen(function* () {
140 const test = fixture(finish('{"title":"Fix login form"}'));
141 const service = yield* test.make;
142 expect(yield* service.generateThreadTitle(titleInput)).toEqual({
143 title: "Fix login form",
144 });
145 expect(test.createHost).toHaveBeenCalledWith(
146 expect.objectContaining({ readOnly: true, sessionLogging: true }),
147 );
148 expect(test.createHost).not.toHaveBeenCalledWith(
149 expect.objectContaining({ cwd: titleInput.cwd }),
150 );
151 expect(test.host.connection.command).toHaveBeenCalledWith(
152 "session/start",
153 expect.objectContaining({
154 providerId: "meta",
155 modelId: modelSelection.model,
156 approvalMode: "denyUnmatched",
157 }),
158 );
159 expect(test.host.connection.command).toHaveBeenCalledWith(
160 "turn/start",
161 expect.objectContaining({
162 reasoningEffort: "high",
163 }),
164 { commandId: "turn-1" },
165 );
166 expect(test.host.close).toHaveBeenCalledOnce();
167 }),
168 );
169​
170 it.effect("forwards max effort unchanged when the native model catalog advertises it", () =>
171 Effect.gen(function* () {
172 const test = fixture(
173 finish('{"title":"Fix login form"}'),
174 true,
175 Effect.succeed([
176 {
177 slug: "muse-spark-1.3",
178 name: "Muse Spark 1.3",
179 isCustom: false,
180 capabilities: museModelCapabilities("muse-spark-1.3", [{ tier: "max" }]),
181 },
182 ]),
183 );
184 const service = yield* test.make;
185 expect(
186 yield* service.generateThreadTitle({
187 ...titleInput,
188 modelSelection: createModelSelection(ProviderInstanceId.make("muse"), "muse-spark-1.3", [
189 { id: "reasoningEffort", value: "max" },
190 ]),
191 }),
192 ).toEqual({ title: "Fix login form" });
193 expect(test.host.connection.command).toHaveBeenCalledWith(
194 "session/start",
195 expect.objectContaining({ modelId: "muse-spark-1.3" }),
196 );
197 expect(test.host.connection.command).toHaveBeenCalledWith(
198 "turn/start",
199 expect.objectContaining({ reasoningEffort: "max" }),
200 { commandId: "turn-1" },
201 );
202 expect(test.host.close).toHaveBeenCalledOnce();
203 }),
204 );
205​
206 it.effect("preserves Contributor Max while the model catalog is unavailable", () =>
207 Effect.gen(function* () {
208 const test = fixture(finish('{"title":"Fix login form"}'));
209 const service = yield* test.make;
210 yield* service.generateThreadTitle({
211 ...titleInput,
212 modelSelection: createModelSelection(
213 ProviderInstanceId.make("muse"),
214 modelSelection.model,
215 [{ id: "reasoningEffort", value: "max" }],
216 ),
217 });
218 expect(test.host.connection.command).toHaveBeenCalledWith(
219 "turn/start",
220 expect.objectContaining({ reasoningEffort: "max" }),
221 { commandId: "turn-1" },
222 );
223 }),
224 );
225​
226 it.effect("normalizes stale settings and the metadata default against model capabilities", () =>
227 Effect.gen(function* () {
228 for (const { saved, tiers, expected } of [
229 { saved: "ultra", tiers: ["medium", "xhigh"], expected: "medium" },
230 { saved: "max", tiers: ["medium", "xhigh"], expected: "medium" },
231 { saved: undefined, tiers: ["xhigh", "max"], expected: "max" },
232 { saved: "high", tiers: [], expected: undefined },
233 ]) {
234 const test = fixture(
235 finish('{"title":"Fix login form"}'),
236 true,
237 Effect.succeed([
238 {
239 slug: modelSelection.model,
240 name: modelSelection.model,
241 isCustom: false,
242 capabilities: museModelCapabilities(
243 modelSelection.model,
244 tiers.map((tier) => ({ tier })),
245 ),
246 },
247 ]),
248 );
249 const service = yield* test.make;
250 expect(
251 yield* service.generateThreadTitle({
252 ...titleInput,
253 modelSelection: createModelSelection(
254 ProviderInstanceId.make("muse"),
255 modelSelection.model,
256 saved !== undefined ? [{ id: "reasoningEffort", value: saved }] : undefined,
257 ),
258 }),
259 ).toEqual({ title: "Fix login form" });
260 const turn = vi
261 .mocked(test.host.connection.command)
262 .mock.calls.find(([method]) => method === "turn/start");
263 expect(turn?.[1].reasoningEffort).toBe(expected);
264 expect(Object.hasOwn(turn?.[1] ?? {}, "reasoningEffort")).toBe(expected !== undefined);
265 expect(test.host.close).toHaveBeenCalledOnce();
266 }
267 }),
268 );
269​
270 it.effect("accepts none, minimal, and ultra when advertised by the native model catalog", () =>
271 Effect.gen(function* () {
272 for (const reasoningEffort of ["none", "minimal", "ultra"]) {
273 const test = fixture(
274 finish('{"title":"Fix login form"}'),
275 true,
276 Effect.succeed([
277 {
278 slug: modelSelection.model,
279 name: modelSelection.model,
280 isCustom: false,
281 capabilities: museModelCapabilities(modelSelection.model, [
282 { tier: reasoningEffort },
283 ]),
284 },
285 ]),
286 );
287 const service = yield* test.make;
288 expect(
289 yield* service.generateThreadTitle({
290 ...titleInput,
291 modelSelection: createModelSelection(
292 ProviderInstanceId.make("muse"),
293 modelSelection.model,
294 [{ id: "reasoningEffort", value: reasoningEffort }],
295 ),
296 }),
297 ).toEqual({ title: "Fix login form" });
298 expect(test.host.connection.command).toHaveBeenCalledWith(
299 "turn/start",
300 expect.objectContaining({ reasoningEffort }),
301 { commandId: "turn-1" },
302 );
303 }
304 }),
305 );
306​
307 it.effect("rejects invalid structured output and releases the host", () =>
308 Effect.gen(function* () {
309 const test = fixture(finish('{"title":42}'));
310 const service = yield* test.make;
311 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
312 _tag: "TextGenerationError",
313 detail: "Muse returned invalid structured output.",
314 });
315 expect(test.host.close).toHaveBeenCalledOnce();
316 }),
317 );
318​
319 it.effect("uses the shared metadata effort when the selection has no override", () =>
320 Effect.gen(function* () {
321 const test = fixture(finish('{"title":"Fix login form"}'));
322 const service = yield* test.make;
323 yield* service.generateThreadTitle({
324 ...titleInput,
325 modelSelection: createModelSelection(ProviderInstanceId.make("muse"), modelSelection.model),
326 });
327 expect(test.host.connection.command).toHaveBeenCalledWith(
328 "turn/start",
329 expect.objectContaining({ reasoningEffort: "max" }),
330 { commandId: "turn-1" },
331 );
332 }),
333 );
334​
335 it.effect("uses the final assistant answer and accepts fenced JSON like other providers", () =>
336 Effect.gen(function* () {
337 const test = fixture((emit) => {
338 emit("item/completed", {
339 item: { itemId: "commentary", kind: "agentMessage", text: "I will write a title." },
340 });
341 finish('```json\n{"title":"Fix login form"}\n```')(emit);
342 });
343 const service = yield* test.make;
344 expect(yield* service.generateThreadTitle(titleInput)).toEqual({ title: "Fix login form" });
345 }),
346 );
347​
348 it.effect("ignores stale snapshots and retracted answers", () =>
349 Effect.gen(function* () {
350 const test = fixture((emit) => {
351 emit("item/completed", {
352 item: {
353 itemId: "answer",
354 kind: "agentMessage",
355 revision: 2,
356 text: '{"title":"Fix login form"}',
357 },
358 });
359 emit("item/updated", {
360 item: { itemId: "answer", kind: "agentMessage", text: "stale partial text" },
361 });
362 emit("item/completed", {
363 item: { itemId: "withdrawn", kind: "agentMessage", text: "Withdrawn answer" },
364 });
365 emit("item/updated", {
366 item: { itemId: "withdrawn", kind: "agentMessage", revision: 2, retracted: true },
367 });
368 emit("turn/completed", { terminal: "completed" });
369 });
370 const service = yield* test.make;
371 expect(yield* service.generateThreadTitle(titleInput)).toEqual({ title: "Fix login form" });
372 }),
373 );
374​
375 it.effect("ignores output and terminal notifications for another turn", () =>
376 Effect.gen(function* () {
377 const test = fixture((emit) => {
378 emit("item/completed", {
379 item: {
380 itemId: "other-answer",
381 kind: "agentMessage",
382 turnId: "another-turn",
383 text: '{"title":"Wrong title"}',
384 },
385 });
386 emit("turn/completed", { turnId: "another-turn", terminal: "completed" });
387 finish('{"title":"Fix login form"}')(emit);
388 });
389 const service = yield* test.make;
390 expect(yield* service.generateThreadTitle(titleInput)).toEqual({ title: "Fix login form" });
391 expect(test.host.connection.command).toHaveBeenCalledWith(
392 "turn/start",
393 expect.objectContaining({ sessionId: "session-1" }),
394 { commandId: "turn-1" },
395 );
396 }),
397 );
398​
399 it.effect("rejects a truncated response even when its prefix contains valid JSON", () =>
400 Effect.gen(function* () {
401 const test = fixture((emit) => {
402 emit("item/completed", {
403 item: {
404 itemId: "answer",
405 kind: "agentMessage",
406 text: '{"title":"Incomplete answer"}',
407 truncated: true,
408 },
409 });
410 emit("turn/completed", { terminal: "completed" });
411 });
412 const service = yield* test.make;
413 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
414 _tag: "TextGenerationError",
415 });
416 expect(test.host.close).toHaveBeenCalledOnce();
417 }),
418 );
419​
420 it.effect("settles a completed turn even when its start acknowledgement never arrives", () =>
421 Effect.gen(function* () {
422 const test = fixture(finish('{"title":"Fix login form"}'), false);
423 const service = yield* test.make;
424 expect(yield* service.generateThreadTitle(titleInput)).toEqual({ title: "Fix login form" });
425 expect(test.host.close).toHaveBeenCalledOnce();
426 }),
427 );
428​
429 it.effect("reports a failed turn without trying another provider", () =>
430 Effect.gen(function* () {
431 const test = fixture((emit) =>
432 emit("turn/completed", {
433 terminal: "failed",
434 error: { message: "Authentication required. Run muse login." },
435 }),
436 );
437 const service = yield* test.make;
438 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
439 _tag: "TextGenerationError",
440 });
441 expect(test.createHost).toHaveBeenCalledOnce();
442 expect(test.host.close).toHaveBeenCalledOnce();
443 }),
444 );
445​
446 it.effect("does not accept assistant output before a later failed terminal event", () =>
447 Effect.gen(function* () {
448 const test = fixture((emit) => {
449 emit("item/completed", {
450 item: { itemId: "answer", kind: "agentMessage", text: '{"title":"Fix login"}' },
451 });
452 emit("turn/completed", {
453 terminal: "failed",
454 error: { message: "Turn failed after producing an answer." },
455 });
456 });
457 const service = yield* test.make;
458 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
459 _tag: "TextGenerationError",
460 });
461 expect(test.host.close).toHaveBeenCalledOnce();
462 }),
463 );
464​
465 it.effect("settles when the transport closes before completion", () =>
466 Effect.gen(function* () {
467 const test = fixture();
468 const service = yield* test.make;
469 const pending = yield* service
470 .generateThreadTitle(titleInput)
471 .pipe(Effect.flip, Effect.forkChild);
472 yield* Effect.promise(() => test.started);
473 test.closeConnection();
474 expect(yield* Fiber.join(pending)).toMatchObject({ _tag: "TextGenerationError" });
475 expect(test.host.close).toHaveBeenCalledOnce();
476 }),
477 );
478​
479 it.effect("releases the host when interrupted after the turn starts", () =>
480 Effect.gen(function* () {
481 const test = fixture();
482 const service = yield* test.make;
483 const fiber = yield* service.generateThreadTitle(titleInput).pipe(Effect.forkChild);
484 yield* Effect.promise(() => test.started);
485 yield* Fiber.interrupt(fiber);
486 expect(test.host.close).toHaveBeenCalledOnce();
487 }),
488 );
489​
490 it.effect("retains its temporary workspace until interrupted SDK startup has shut down", () =>
491 Effect.gen(function* () {
492 const fs = yield* FileSystem.FileSystem;
493 const starting = Promise.withResolvers<{ signal: AbortSignal; cwd: string }>();
494 const closing = Promise.withResolvers<void>();
495 const shutdown = Promise.withResolvers<void>();
496 const service = yield* makeMuseTextGeneration(settings, undefined, (options) => {
497 const signal = options.signal!;
498 starting.resolve({ signal, cwd: options.cwd! });
499 return new Promise<MuseSdkHost>((_resolve, reject) => {
500 signal.addEventListener(
501 "abort",
502 () => {
503 closing.resolve();
504 void shutdown.promise.then(() => reject(signal.reason));
505 },
506 { once: true },
507 );
508 });
509 });
510 const fiber = yield* service.generateThreadTitle(titleInput).pipe(Effect.forkChild);
511 const { signal, cwd } = yield* Effect.promise(() => starting.promise);
512 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild);
513 yield* Effect.promise(() => closing.promise);
514 expect(signal.aborted).toBe(true);
515 expect(yield* fs.exists(cwd)).toBe(true);
516 shutdown.resolve();
517 yield* Fiber.join(interrupted);
518 expect(yield* fs.exists(cwd)).toBe(false);
519 }),
520 );
521​
522 it.effect("denies approval requests and fails the noninteractive request", () =>
523 Effect.gen(function* () {
524 const test = fixture((emit) =>
525 emit("approval/requested", {
526 approvalId: "approval-1",
527 currentRequirementId: "requirement-1",
528 availableChoices: [{ choiceId: "deny-1", decision: "denied" }],
529 }),
530 );
531 const service = yield* test.make;
532 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
533 _tag: "TextGenerationError",
534 });
535 expect(test.host.connection.command).toHaveBeenCalledWith("approval/decide", {
536 sessionId: "session-1",
537 approvalId: "approval-1",
538 requirementId: "requirement-1",
539 choiceId: "deny-1",
540 });
541 expect(test.host.close).toHaveBeenCalledOnce();
542 }),
543 );
544​
545 it.effect("cancels user input requests", () =>
546 Effect.gen(function* () {
547 const test = fixture((emit) => emit("userInput/requested", { userInputId: "input-1" }));
548 const service = yield* test.make;
549 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
550 _tag: "TextGenerationError",
551 });
552 expect(test.host.connection.command).toHaveBeenCalledWith(
553 "userInput/cancel",
554 expect.objectContaining({
555 userInputId: "input-1",
556 }),
557 );
558 expect(test.host.close).toHaveBeenCalledOnce();
559 }),
560 );
561​
562 it.effect("rejects interactive requests before a successful terminal event can win", () =>
563 Effect.gen(function* () {
564 const test = fixture((emit) => {
565 emit("userInput/requested", { userInputId: "input-1" });
566 finish('{"title":"Unexpected success"}')(emit);
567 });
568 const service = yield* test.make;
569 expect(yield* service.generateThreadTitle(titleInput).pipe(Effect.flip)).toMatchObject({
570 _tag: "TextGenerationError",
571 });
572 expect(test.host.close).toHaveBeenCalledOnce();
573 }),
574 );
575​
576 it.effect("generates and sanitizes commit content through Muse", () =>
577 Effect.gen(function* () {
578 const test = fixture(
579 finish('{"subject":"Fix login.","body":" Details ","branch":"fix-login"}'),
580 );
581 const service = yield* test.make;
582 const generated = yield* service.generateCommitMessage({
583 cwd: titleInput.cwd,
584 branch: "main",
585 stagedSummary: "login.ts",
586 stagedPatch: "login change",
587 includeBranch: true,
588 modelSelection,
589 });
590 expect(generated.subject).toBe("Fix login");
591 expect(generated.body).toBe("Details");
592 expect(generated.branch).toContain("fix-login");
593 }),
594 );
595​
596 it.effect("generates PR content through Muse", () =>
597 Effect.gen(function* () {
598 const test = fixture(finish('{"title":"Fix login","body":" Changes "}'));
599 const service = yield* test.make;
600 expect(
601 yield* service.generatePrContent({
602 cwd: titleInput.cwd,
603 baseBranch: "main",
604 headBranch: "fix-login",
605 commitSummary: "Fix login",
606 diffSummary: "login.ts",
607 diffPatch: "patch",
608 modelSelection,
609 }),
610 ).toEqual({ title: "Fix login", body: "Changes" });
611 }),
612 );
613​
614 it.effect("generates branch names through Muse", () =>
615 Effect.gen(function* () {
616 const test = fixture(finish('{"branch":"Fix Login Form"}'));
617 const service = yield* test.make;
618 expect(yield* service.generateBranchName(titleInput)).toEqual({
619 branch: "fix-login-form",
620 });
621 }),
622 );
623});