Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it, vi } from "@effect/vitest";
3import { ProviderInstanceId } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5
6import type { MuseSdkHost } from "../provider/museSdk.ts";
7import { makeMuseSessionImport, type MuseImportSession } from "./MuseSessionImport.ts";
8
9const SESSION_ID = "123e4567-e89b-42d3-a456-426614174000";
10const instance = {
11 instanceId: ProviderInstanceId.make("muse_work"),
12 binaryPath: "/fake/muse",
13 environment: { HOME: "/fake/account" },
14};
15const session: MuseImportSession = {
16 sessionId: SESSION_ID,
17 path: `/fake/muse-home/sessions/2026/09/11/${SESSION_ID}/session.jsonl`,
18 workspaceRoot: "/work/project",
19 modelId: "muse-spark-1.3-contributor",
20 providerId: "meta",
21 createdAt: "2026-09-11T10:00:00.000Z",
22 updatedAt: "2026-09-11T10:01:00.000Z",
23};
24const limits = { records: 100, historyBytes: 1024, messages: 3 };
25const event = (
26 itemId: string,
27 kind: "userMessage" | "agentMessage",
28 text: string,
29 extra: Record<string, unknown> = {},
30) => ({
31 method: "item/completed",
32 params: {
33 sessionId: SESSION_ID,
34 item: {
35 itemId,
36 kind,
37 text,
38 status: "completed",
39 revision: 1,
40 ...extra,
41 },
42 },
43});
44const modelEvent = (
45 method: "session/tokenUsage" | "session/modelChanged",
46 modelId: string,
47 extra: Record<string, unknown> = {},
48) => ({ method, params: { sessionId: SESSION_ID, modelId, ...extra } });
49
50function makeMuseImportHost(
51 request: MuseSdkHost["connection"]["request"],
52 museHome = "/fake/muse-home",
53): MuseSdkHost {
54 return {
55 initializeResult: {
56 experimentalApi: false,
57 grantedCapabilities: [],
58 museHome,
59 platformFamily: "unix",
60 platformOs: "linux",
61 schema: { fingerprint: "test", version: 1 },
62 serverInfo: { name: "muse", version: "1.1.1" },
63 userAgent: "test",
64 },
65 connection: {
66 request,
67 command: vi.fn(async () => ({})),
68 mintCommandId: () => "unused",
69 onNotification: () => {},
70 onServerRequest: () => {},
71 onProtocolError: () => {},
72 closed: new Promise(() => {}),
73 },
74 exited: new Promise(() => {}),
75 close: vi.fn(async () => {}),
76 };
77}
78const historyHost = (
79 pages: ReadonlyArray<Record<string, unknown>>,
80 metadata: Record<string, unknown> = {},
81) => {
82 let pageIndex = 0;
83 return makeMuseImportHost(
84 vi.fn(async (method) => {
85 if (method === "session/read")
86 return {
87 session: { ...session, ...metadata },
88 history: { mode: "none", noneReason: "excluded", snapshot: null },
89 };
90 if (method === "view/page") return pages[pageIndex++]!;
91 throw new Error(`Unexpected request ${method}`);
92 }),
93 );
94};
95
96it.layer(NodeServices.layer)("Muse session import", (it) => {
97 it.effect("lists root Meta sessions with bounded pagination and closes its read-only host", () =>
98 Effect.gen(function* () {
99 const request = vi.fn(async (_method: string, params?: Record<string, unknown>) =>
100 params?.cursor
101 ? { sessions: [session], nextCursor: null }
102 : {
103 sessions: [
104 { ...session, providerId: null },
105 { ...session, providerId: "other" },
106 { ...session, path: "" },
107 {
108 ...session,
109 path: `/fake/muse-home/sessions/2026/09/11/parent/subagent/${SESSION_ID}/session.jsonl`,
110 },
111 ],
112 nextCursor: "page-2",
113 },
114 );
115 const host = makeMuseImportHost(request);
116 const createHost = vi.fn(async () => host);
117 const result = yield* Effect.scoped(
118 Effect.gen(function* () {
119 const reader = yield* makeMuseSessionImport(createHost);
120 return yield* reader.list(instance, 10);
121 }),
122 );
123 expect(result).toEqual({ sessions: [session], truncated: false });
124 expect(request).toHaveBeenNthCalledWith(2, "session/list", { cursor: "page-2", limit: 6 });
125 expect(createHost).toHaveBeenCalledExactlyOnceWith(
126 expect.objectContaining({
127 binaryPath: instance.binaryPath,
128 environment: instance.environment,
129 readOnly: true,
130 sessionLogging: true,
131 }),
132 );
133 expect(host.close).toHaveBeenCalledOnce();
134 expect(host.connection.command).not.toHaveBeenCalled();
135 }),
136 );
137
138 it.effect("retains only the first prompt when the message budget is one", () =>
139 Effect.gen(function* () {
140 const host = historyHost([
141 {
142 events: [
143 event("u1", "userMessage", "first"),
144 event("a1", "agentMessage", "first answer"),
145 event("u2", "userMessage", "second"),
146 event("a2", "agentMessage", "second answer"),
147 modelEvent("session/tokenUsage", "muse-spark-1.3-contributor"),
148 ],
149 nextCursor: null,
150 },
151 ]);
152 const result = yield* Effect.scoped(
153 Effect.gen(function* () {
154 const reader = yield* makeMuseSessionImport(async () => host);
155 return yield* reader.read(instance, SESSION_ID, { ...limits, messages: 1 });
156 }),
157 );
158 expect(result.messages.map((message) => message.text)).toEqual(["first"]);
159 expect(result.title).toBe("first");
160 expect(host.close).toHaveBeenCalledOnce();
161 }),
162 );
163
164 it.effect(
165 "folds message revisions and retractions across pages and retains a first prompt plus recent history",
166 () =>
167 Effect.gen(function* () {
168 const host = historyHost([
169 {
170 events: [
171 event("u1", "userMessage", "first"),
172 event("a1", "agentMessage", "draft"),
173 event("gone", "userMessage", "retracted"),
174 ],
175 nextCursor: "page-2",
176 },
177 {
178 events: [
179 event("a1", "agentMessage", "final", { revision: 2, recordedAt: session.updatedAt }),
180 event("a1", "agentMessage", "stale"),
181 event("gone", "userMessage", "retracted", { revision: 2, retracted: true }),
182 event("u2", "userMessage", "second"),
183 event("a2", "agentMessage", "second answer"),
184 modelEvent("session/tokenUsage", "muse-spark-1.3-contributor"),
185 ],
186 nextCursor: null,
187 },
188 ]);
189 const result = yield* Effect.scoped(
190 Effect.gen(function* () {
191 const reader = yield* makeMuseSessionImport(async () => host);
192 return yield* reader.read(instance, SESSION_ID, limits);
193 }),
194 );
195 expect(result.messages.map((message) => message.text)).toEqual([
196 "first",
197 "second",
198 "second answer",
199 ]);
200 expect(result.title).toBe("first");
201 expect(result.recordCount).toBe(9);
202 expect(result.messages[0]?.createdAt).toBe(session.createdAt);
203 expect(host.close).toHaveBeenCalledOnce();
204 }),
205 );
206
207 it.effect("uses effective Contributor usage instead of normalized base-model metadata", () =>
208 Effect.gen(function* () {
209 const host = historyHost(
210 [
211 {
212 events: [
213 event("u", "userMessage", "first"),
214 event("a", "agentMessage", "answer"),
215 modelEvent("session/tokenUsage", "muse-spark-1.2", { providerId: "meta" }),
216 modelEvent("session/tokenUsage", "muse-spark-1.3-contributor", {
217 providerId: "meta",
218 }),
219 ],
220 nextCursor: null,
221 },
222 ],
223 { modelId: "muse-spark-1.3" },
224 );
225 const result = yield* Effect.scoped(
226 Effect.gen(function* () {
227 const reader = yield* makeMuseSessionImport(async () => host);
228 return yield* reader.read(instance, SESSION_ID, limits);
229 }),
230 );
231 expect(result.session.modelId).toBe("muse-spark-1.3-contributor");
232 expect(result.messages.map((message) => message.text)).toEqual(["first", "answer"]);
233 expect(host.connection.command).not.toHaveBeenCalled();
234 expect(host.close).toHaveBeenCalledOnce();
235 }),
236 );
237
238 it.effect("preserves the latest explicit model selection over late previous-turn usage", () =>
239 Effect.gen(function* () {
240 const host = historyHost([
241 {
242 events: [
243 event("u", "userMessage", "first"),
244 modelEvent("session/modelChanged", "muse-spark-1.3-contributor", {
245 providerId: "meta",
246 }),
247 ],
248 nextCursor: "more",
249 },
250 {
251 events: [
252 modelEvent("session/modelChanged", "muse-spark-1.3", { providerId: "meta" }),
253 modelEvent("session/tokenUsage", "muse-spark-1.3-contributor"),
254 ],
255 nextCursor: null,
256 },
257 ]);
258 const result = yield* Effect.scoped(
259 Effect.gen(function* () {
260 const reader = yield* makeMuseSessionImport(async () => host);
261 return yield* reader.read(instance, SESSION_ID, limits);
262 }),
263 );
264 expect(result.session.modelId).toBe("muse-spark-1.3");
265 expect(host.close).toHaveBeenCalledOnce();
266 }),
267 );
268
269 for (const [label, pages, budget] of [
270 [
271 "unverifiable effective model",
272 [{ events: [event("u", "userMessage", "first")], nextCursor: null }],
273 limits,
274 ],
275 [
276 "invalid effective model",
277 [
278 {
279 events: [event("u", "userMessage", "first"), modelEvent("session/tokenUsage", " ")],
280 nextCursor: null,
281 },
282 ],
283 limits,
284 ],
285 [
286 "foreign model usage",
287 [
288 {
289 events: [
290 event("u", "userMessage", "first"),
291 modelEvent("session/tokenUsage", "muse-spark-1.3-contributor", {
292 sessionId: "child-session",
293 }),
294 ],
295 nextCursor: null,
296 },
297 ],
298 limits,
299 ],
300 ...["other", null].map(
301 (providerId) =>
302 [
303 `model usage from provider ${providerId}`,
304 [
305 {
306 events: [
307 event("u", "userMessage", "first"),
308 modelEvent("session/tokenUsage", "muse-spark-1.3-contributor", { providerId }),
309 ],
310 nextCursor: null,
311 },
312 ],
313 limits,
314 ] as const,
315 ),
316 [
317 "foreign model provider",
318 [
319 {
320 events: [
321 event("u", "userMessage", "first"),
322 modelEvent("session/modelChanged", "another-model", { providerId: "other" }),
323 ],
324 nextCursor: null,
325 },
326 ],
327 limits,
328 ],
329 [
330 "record limit",
331 [{ events: [event("u", "userMessage", "first")], nextCursor: "more" }],
332 { ...limits, records: 1 },
333 ],
334 [
335 "text limit",
336 [{ events: [event("u", "userMessage", "larger than budget")], nextCursor: null }],
337 { ...limits, historyBytes: 4 },
338 ],
339 [
340 "truncated message",
341 [
342 {
343 events: [
344 event("u", "userMessage", "first"),
345 event("a", "agentMessage", "partial", { truncated: true }),
346 ],
347 nextCursor: null,
348 },
349 ],
350 limits,
351 ],
352 [
353 "stalled cursor",
354 [
355 { events: [event("u", "userMessage", "first")], nextCursor: "same" },
356 { events: [], nextCursor: "same" },
357 ],
358 limits,
359 ],
360 [
361 "foreign session",
362 [
363 {
364 events: [{ ...event("u", "userMessage", "first"), params: { sessionId: "another" } }],
365 nextCursor: null,
366 },
367 ],
368 limits,
369 ],
370 ] as const) {
371 it.effect(`rejects ${label} and releases the host`, () =>
372 Effect.gen(function* () {
373 const host = historyHost(pages);
374 const result = yield* Effect.scoped(
375 Effect.gen(function* () {
376 const reader = yield* makeMuseSessionImport(async () => host);
377 return yield* reader.read(instance, SESSION_ID, budget);
378 }),
379 ).pipe(Effect.result);
380 expect(result._tag).toBe("Failure");
381 expect(host.close).toHaveBeenCalledOnce();
382 }),
383 );
384 }
385
386 it.effect("reuses a host within one import and rejects unknown schemas before reading", () =>
387 Effect.gen(function* () {
388 const host = makeMuseImportHost(
389 vi.fn(async () => ({ sessions: [session], nextCursor: null })),
390 );
391 const createHost = vi.fn(async () => host);
392 yield* Effect.scoped(
393 Effect.gen(function* () {
394 const reader = yield* makeMuseSessionImport(createHost);
395 yield* reader.list(instance, 10);
396 yield* reader.list(instance, 10);
397 }),
398 );
399 expect(createHost).toHaveBeenCalledOnce();
400 expect(host.close).toHaveBeenCalledOnce();
401 const unsupported = {
402 ...host,
403 initializeResult: { ...host.initializeResult, schema: { fingerprint: "new", version: 2 } },
404 };
405 const result = yield* Effect.scoped(
406 Effect.gen(function* () {
407 const reader = yield* makeMuseSessionImport(async () => unsupported);
408 return yield* reader.list(instance, 10);
409 }),
410 ).pipe(Effect.result);
411 expect(result._tag).toBe("Failure");
412 }),
413 );
414});