Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 RunId,
5 RuntimeRequestId,
6 ThreadId,
7 type OrchestrationV2ShellSnapshot,
8 type OrchestrationV2ThreadShell,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Option from "effect/Option";
12import { Atom, AtomRegistry } from "effect/reactivity";
13import { describe, expect, it } from "vite-plus/test";
14
15import { PrimaryConnectionTarget } from "../connection/model.ts";
16import { v2Now, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
17import { applyShellStreamEvent } from "./shellReducer.ts";
18import { isThreadWorking } from "./threadInbox.ts";
19import { childThreadInputsTitle, createEnvironmentThreadShellAtoms } from "./threadShell.ts";
20
21const environmentId = EnvironmentId.make("environment-v2");
22const remoteEnvironmentId = EnvironmentId.make("remote-environment-v2");
23const otherProjectId = ProjectId.make("other-project");
24
25function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [environmentId]) {
26 const snapshotAtom = Atom.family((_environmentId: EnvironmentId) =>
27 Atom.make<OrchestrationV2ShellSnapshot | null>(v2ShellSnapshot),
28 );
29 const catalogValueAtom = Atom.make({
30 isReady: true,
31 entries: new Map(
32 environmentIds.map((id) => [
33 id,
34 {
35 target: new PrimaryConnectionTarget({
36 environmentId: id,
37 label: "Environment",
38 httpBaseUrl: "https://example.test",
39 wsBaseUrl: "wss://example.test",
40 }),
41 profile: Option.none(),
42 enabled: true,
43 },
44 ]),
45 ),
46 });
47 return {
48 registry: AtomRegistry.make(),
49 snapshotAtom,
50 catalogValueAtom,
51 threads: createEnvironmentThreadShellAtoms({ catalogValueAtom, snapshotAtom }),
52 };
53}
54
55describe("v2 thread shell lists", () => {
56 it("preserves ordered reference arrays when a middle thread changes", () => {
57 const { registry, threads, snapshotAtom } = makeHarness();
58 const snapshot = {
59 ...v2ShellSnapshot,
60 threads: ["a", "b", "c"].map((id) => ({ ...v2ThreadShell, id: ThreadId.make(id) })),
61 };
62 registry.set(snapshotAtom(environmentId), snapshot);
63 const dispose = registry.mount(threads.threadRefsAtom);
64 const before = registry.get(threads.threadRefsAtom);
65 registry.set(
66 snapshotAtom(environmentId),
67 applyShellStreamEvent(snapshot, {
68 kind: "thread.updated",
69 location: "active",
70 sequence: 1,
71 thread: { ...snapshot.threads[1]!, title: "Updated" },
72 }),
73 );
74 expect(registry.get(threads.threadRefsAtom)).toBe(before);
75 dispose();
76 registry.dispose();
77 });
78
79 it("keeps navigation stable on hidden subagent updates and retains user forks", () => {
80 const { registry, threads, snapshotAtom } = makeHarness();
81 const root = v2ThreadShell;
82 const child = {
83 ...root,
84 id: ThreadId.make("child"),
85 lineage: {
86 ...root.lineage,
87 parentThreadId: root.id,
88 relationshipToParent: "subagent" as const,
89 },
90 };
91 const fork = {
92 ...child,
93 id: ThreadId.make("fork"),
94 lineage: { ...child.lineage, relationshipToParent: "fork" as const },
95 };
96 const snapshot = { ...v2ShellSnapshot, threads: [root, child, fork] };
97 registry.set(snapshotAtom(environmentId), snapshot);
98 const dispose = registry.mount(threads.navigationThreadShellsAtom);
99 const before = registry.get(threads.navigationThreadShellsAtom);
100 expect(before.map((thread) => thread.id)).toEqual([root.id, fork.id]);
101 registry.set(snapshotAtom(environmentId), {
102 ...snapshot,
103 threads: [root, { ...child, title: "Child streaming" }, fork],
104 });
105 expect(registry.get(threads.navigationThreadShellsAtom)).toBe(before);
106 expect(registry.get(threads.threadShellsAtom)).toHaveLength(3);
107 dispose();
108 registry.dispose();
109 });
110
111 it("keeps a live subagent question inside the parent without flagging its thread", () => {
112 const { registry, threads, snapshotAtom } = makeHarness();
113 const root = v2ThreadShell;
114 const child = {
115 ...root,
116 id: ThreadId.make("child"),
117 creationSource: "mcp" as const,
118 status: "running" as const,
119 activityRunStatus: "running" as const,
120 lineage: {
121 ...root.lineage,
122 parentThreadId: root.id,
123 relationshipToParent: "subagent" as const,
124 },
125 pendingRuntimeRequest: {
126 id: RuntimeRequestId.make("question"),
127 kind: "user_input" as const,
128 createdAt: v2Now,
129 },
130 };
131 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: root.id });
132 const dispose = registry.mount(inputs);
133 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] });
134 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
135 expect(
136 registry.get(threads.threadShellAtom({ environmentId, threadId: root.id }))
137 ?.pendingSubagentRequest,
138 ).toBeNull();
139 registry.set(snapshotAtom(environmentId), {
140 ...v2ShellSnapshot,
141 threads: [root, { ...child, status: "queued" as const }],
142 });
143 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
144 registry.set(snapshotAtom(environmentId), {
145 ...v2ShellSnapshot,
146 threads: [root, { ...child, status: "completed" as const, activityRunStatus: null }],
147 });
148 expect(registry.get(inputs)).toEqual([]);
149 const { activityRunStatus: _omitted, ...legacyChild } = child;
150 registry.set(snapshotAtom(environmentId), {
151 ...v2ShellSnapshot,
152 threads: [root, { ...legacyChild, status: "completed" as const }],
153 });
154 expect(registry.get(inputs)).toEqual([]);
155 dispose();
156 registry.dispose();
157 });
158
159 it("brings a parent back from Working while a nested subagent waits for approval", () => {
160 const { registry, threads, snapshotAtom } = makeHarness();
161 const child = {
162 ...v2ThreadShell,
163 id: ThreadId.make("review"),
164 creationSource: "mcp" as const,
165 status: "running" as const,
166 activityRunStatus: "running" as const,
167 lineage: {
168 ...v2ThreadShell.lineage,
169 parentThreadId: v2ThreadShell.id,
170 relationshipToParent: "subagent" as const,
171 },
172 };
173 const grandchild = {
174 ...child,
175 id: ThreadId.make("review-helper"),
176 lineage: { ...child.lineage, parentThreadId: child.id },
177 };
178 const root = {
179 ...v2ThreadShell,
180 latestRunId: RunId.make("root-run"),
181 status: "completed" as const,
182 pendingBackgroundTasks: [
183 { taskId: "review", kind: "subagent" as const, childThreadId: child.id },
184 ],
185 };
186 const approval = {
187 id: RuntimeRequestId.make("cat-file"),
188 kind: "command" as const,
189 createdAt: v2Now,
190 };
191 const parent = threads.threadShellAtom({ environmentId, threadId: root.id });
192 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: root.id });
193 const disposeParent = registry.mount(parent);
194 const disposeInputs = registry.mount(inputs);
195 registry.set(snapshotAtom(environmentId), {
196 ...v2ShellSnapshot,
197 threads: [root, child, grandchild],
198 });
199 expect(isThreadWorking(registry.get(parent)!)).toBe(true);
200
201 registry.set(snapshotAtom(environmentId), {
202 ...v2ShellSnapshot,
203 threads: [root, child, { ...grandchild, pendingRuntimeRequest: approval }],
204 });
205 expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
206 expect(isThreadWorking(registry.get(parent)!)).toBe(false);
207 const asking = registry.get(inputs);
208 expect(asking.map((thread) => thread.id)).toEqual([grandchild.id]);
209 expect(childThreadInputsTitle(asking)).toBe("Subagent needs approval");
210
211 registry.set(snapshotAtom(environmentId), {
212 ...v2ShellSnapshot,
213 threads: [root, child, grandchild],
214 });
215 expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();
216 expect(isThreadWorking(registry.get(parent)!)).toBe(true);
217 disposeInputs();
218 disposeParent();
219 registry.dispose();
220 });
221
222 it("lists a task a linked environment runs for a listed thread under that thread", () => {
223 const { registry, threads, snapshotAtom, catalogValueAtom } = makeHarness([
224 environmentId,
225 remoteEnvironmentId,
226 ]);
227 const parent = v2ThreadShell;
228 const task = {
229 ...v2ThreadShell,
230 id: ThreadId.make("remote-task"),
231 creationSource: "mcp" as const,
232 status: "running" as const,
233 activityRunStatus: "running" as const,
234 delegatedFrom: { environmentId, threadId: parent.id, title: parent.title },
235 };
236 const helper = {
237 ...task,
238 id: ThreadId.make("remote-helper"),
239 delegatedFrom: undefined,
240 lineage: {
241 ...task.lineage,
242 parentThreadId: task.id,
243 relationshipToParent: "subagent" as const,
244 },
245 };
246 const approval = {
247 id: RuntimeRequestId.make("cat-file"),
248 kind: "command" as const,
249 createdAt: v2Now,
250 };
251 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });
252 registry.set(snapshotAtom(remoteEnvironmentId), {
253 ...v2ShellSnapshot,
254 threads: [task, helper],
255 });
256 const parentRef = { environmentId, threadId: parent.id };
257 const inputs = threads.childThreadInputsAtom(parentRef);
258 const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);
259 const disposeParent = registry.mount(threads.threadShellAtom(parentRef));
260 const disposeInputs = registry.mount(inputs);
261 const listed = () =>
262 registry
263 .get(threads.navigationThreadShellsAtom)
264 .map((thread) => `${thread.environmentId}/${thread.id}`);
265 expect(listed()).toEqual([`${environmentId}/${parent.id}`]);
266
267 // The helper the task started there asks for approval: the parent here hears of it.
268 registry.set(snapshotAtom(remoteEnvironmentId), {
269 ...v2ShellSnapshot,
270 threads: [task, { ...helper, pendingRuntimeRequest: approval }],
271 });
272 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBe(
273 "approval",
274 );
275 expect(registry.get(inputs).map((thread) => `${thread.environmentId}/${thread.id}`)).toEqual([
276 `${remoteEnvironmentId}/${helper.id}`,
277 ]);
278
279 registry.set(snapshotAtom(remoteEnvironmentId), {
280 ...v2ShellSnapshot,
281 threads: [
282 task,
283 { ...helper, pendingRuntimeRequest: { ...approval, kind: "user_input" as const } },
284 ],
285 });
286 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBeNull();
287 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([helper.id]);
288
289 // A task whose parent is gone there is listed on its own, as is one whose
290 // parent's environment is switched off.
291 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [] });
292 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
293 // Archiving the parent here leaves the task there unarchived, so it is listed on its own.
294 registry.set(snapshotAtom(environmentId), {
295 ...v2ShellSnapshot,
296 threads: [{ ...parent, archivedAt: v2Now }],
297 });
298 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
299 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });
300 expect(listed()).toEqual([`${environmentId}/${parent.id}`]);
301 const catalog = registry.get(catalogValueAtom);
302 const entries = new Map(catalog.entries);
303 entries.set(environmentId, { ...entries.get(environmentId)!, enabled: false });
304 registry.set(catalogValueAtom, { ...catalog, entries });
305 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
306 disposeInputs();
307 disposeParent();
308 disposeNavigation();
309 registry.dispose();
310 });
311
312 it("brings an approval up a chain of tasks across three environments to its root", () => {
313 const thirdEnvironmentId = EnvironmentId.make("third-environment-v2");
314 const { registry, threads, snapshotAtom } = makeHarness([
315 environmentId,
316 remoteEnvironmentId,
317 thirdEnvironmentId,
318 ]);
319 const root = v2ThreadShell;
320 const running = {
321 creationSource: "mcp" as const,
322 status: "running" as const,
323 activityRunStatus: "running" as const,
324 };
325 const task = {
326 ...v2ThreadShell,
327 ...running,
328 id: ThreadId.make("remote-task"),
329 delegatedFrom: { environmentId, threadId: root.id, title: root.title },
330 };
331 const nestedTask = {
332 ...v2ThreadShell,
333 ...running,
334 id: ThreadId.make("third-task"),
335 delegatedFrom: { environmentId: remoteEnvironmentId, threadId: task.id, title: task.title },
336 };
337 // A task the middle one delegates back to the root's own environment.
338 const returningTask = {
339 ...nestedTask,
340 id: ThreadId.make("returning-task"),
341 };
342 const approval = {
343 id: RuntimeRequestId.make("cat-file"),
344 kind: "command" as const,
345 createdAt: v2Now,
346 };
347 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root] });
348 registry.set(snapshotAtom(remoteEnvironmentId), { ...v2ShellSnapshot, threads: [task] });
349 registry.set(snapshotAtom(thirdEnvironmentId), {
350 ...v2ShellSnapshot,
351 threads: [{ ...nestedTask, pendingRuntimeRequest: approval }],
352 });
353 const rootRef = { environmentId, threadId: root.id };
354 const taskRef = { environmentId: remoteEnvironmentId, threadId: task.id };
355 const disposeRoot = registry.mount(threads.threadShellAtom(rootRef));
356 const disposeTask = registry.mount(threads.threadShellAtom(taskRef));
357 expect(registry.get(threads.threadShellAtom(taskRef))?.pendingSubagentRequest).toBe("approval");
358 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");
359
360 // Once it is answered, neither stays flagged.
361 registry.set(snapshotAtom(thirdEnvironmentId), {
362 ...v2ShellSnapshot,
363 threads: [nestedTask],
364 });
365 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBeNull();
366
367 // Environments that delegate to each other still settle on the root's flag.
368 registry.set(snapshotAtom(environmentId), {
369 ...v2ShellSnapshot,
370 threads: [root, { ...returningTask, pendingRuntimeRequest: approval }],
371 });
372 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");
373 disposeTask();
374 disposeRoot();
375 registry.dispose();
376 });
377
378 it.each([
379 { reason: "switched-off", state: { enabled: false } },
380 {
381 reason: "unsupported",
382 state: { enabled: true, unsupportedReason: "Use a compatible client." },
383 },
384 ])("leaves $reason environments out of navigation until restored", ({ state }) => {
385 const { registry, threads, catalogValueAtom } = makeHarness([
386 environmentId,
387 remoteEnvironmentId,
388 ]);
389 const dispose = registry.mount(threads.navigationThreadShellsAtom);
390 const environmentsOf = () =>
391 new Set(registry.get(threads.navigationThreadShellsAtom).map((t) => t.environmentId));
392 expect(environmentsOf()).toEqual(new Set([environmentId, remoteEnvironmentId]));
393
394 const setRemotePaused = (paused: boolean) => {
395 const catalog = registry.get(catalogValueAtom);
396 const entries = new Map(catalog.entries);
397 entries.set(remoteEnvironmentId, {
398 ...entries.get(remoteEnvironmentId)!,
399 ...(paused ? state : { enabled: true, unsupportedReason: undefined }),
400 });
401 registry.set(catalogValueAtom, { ...catalog, entries });
402 };
403 setRemotePaused(true);
404 expect(environmentsOf()).toEqual(new Set([environmentId]));
405 setRemotePaused(false);
406 expect(environmentsOf()).toEqual(new Set([environmentId, remoteEnvironmentId]));
407 dispose();
408 registry.dispose();
409 });
410
411 it("preserves project memberships on updates and keeps the same thread separate per environment", () => {
412 const harness = makeHarness([environmentId, remoteEnvironmentId]);
413 const otherThread = {
414 ...v2ThreadShell,
415 id: ThreadId.make("other-thread"),
416 projectId: otherProjectId,
417 };
418 const snapshot = { ...v2ShellSnapshot, threads: [v2ThreadShell, otherThread] };
419 harness.registry.set(harness.snapshotAtom(environmentId), snapshot);
420 const membershipAtom = harness.threads.environmentThreadRefsByProjectAtom(environmentId);
421 const listAtom = harness.threads.threadShellsForProjectRefsAtom([
422 { environmentId: remoteEnvironmentId, projectId: v2ThreadShell.projectId },
423 { environmentId, projectId: v2ThreadShell.projectId },
424 ]);
425 const disposeList = harness.registry.mount(listAtom);
426 try {
427 const membership = harness.registry.get(membershipAtom);
428 const before = harness.registry.get(listAtom);
429 expect(before).toHaveLength(2);
430 expect(before[0]).not.toBe(before[1]);
431 expect(before.map((thread) => thread.environmentId)).toEqual([
432 remoteEnvironmentId,
433 environmentId,
434 ]);
435
436 harness.registry.set(harness.snapshotAtom(environmentId), {
437 ...snapshot,
438 threads: [v2ThreadShell, { ...otherThread, title: "Changed elsewhere" }],
439 });
440 expect(harness.registry.get(membershipAtom)).toBe(membership);
441 expect(harness.registry.get(listAtom)).toBe(before);
442
443 harness.registry.set(harness.snapshotAtom(environmentId), {
444 ...snapshot,
445 threads: [{ ...v2ThreadShell, projectId: otherProjectId }, otherThread],
446 });
447 expect(harness.registry.get(listAtom)).toEqual([before[0]]);
448 harness.registry.set(harness.snapshotAtom(remoteEnvironmentId), {
449 ...v2ShellSnapshot,
450 threads: [],
451 });
452 expect(harness.registry.get(listAtom)).toEqual([]);
453 } finally {
454 disposeList();
455 harness.registry.dispose();
456 }
457 });
458
459 it("keeps the quiet shell through streaming ticks and follows every change once the run stops", () => {
460 const harness = makeHarness();
461 const runId = RunId.make("streaming-run");
462 const running: OrchestrationV2ThreadShell = {
463 ...v2ThreadShell,
464 latestRunId: runId,
465 activeRunId: runId,
466 status: "running",
467 itemCount: 1,
468 visibleItemCount: 1,
469 };
470 const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
471 harness.registry.set(harness.snapshotAtom(environmentId), {
472 ...v2ShellSnapshot,
473 snapshotSequence: sequence,
474 threads: [thread],
475 });
476 const at = (seconds: number) => DateTime.add(v2Now, { seconds });
477 setThread(running, 1);
478 const ref = { environmentId, threadId: v2ThreadShell.id };
479 const quietAtom = harness.threads.quietThreadShellAtom(ref);
480 const dispose = harness.registry.mount(quietAtom);
481 try {
482 const first = harness.registry.get(quietAtom);
483 setThread({ ...running, updatedAt: at(1), itemCount: 4, visibleItemCount: 3 }, 2);
484 expect(harness.registry.get(quietAtom)).toBe(first);
485 expect(harness.registry.get(harness.threads.threadShellAtom(ref))?.itemCount).toBe(4);
486
487 setThread({ ...running, updatedAt: at(2), itemCount: 5, title: "Renamed" }, 3);
488 const renamed = harness.registry.get(quietAtom);
489 expect(renamed?.title).toBe("Renamed");
490
491 const stopped: OrchestrationV2ThreadShell = {
492 ...running,
493 activeRunId: null,
494 status: "completed",
495 };
496 setThread({ ...stopped, title: "Renamed", updatedAt: at(3) }, 4);
497 const completed = harness.registry.get(quietAtom);
498 expect(completed).not.toBe(renamed);
499 setThread({ ...stopped, title: "Renamed", updatedAt: at(4) }, 5);
500 expect(harness.registry.get(quietAtom)?.updatedAt).toBe(DateTime.formatIso(at(4)));
501 expect(harness.registry.get(quietAtom)).not.toBe(completed);
502 } finally {
503 dispose();
504 harness.registry.dispose();
505 }
506 });
507
508 it("keeps the quiet shell list through streaming ticks", () => {
509 const harness = makeHarness();
510 const runId = RunId.make("streaming-list-run");
511 const running: OrchestrationV2ThreadShell = {
512 ...v2ThreadShell,
513 latestRunId: runId,
514 activeRunId: runId,
515 status: "running",
516 itemCount: 1,
517 visibleItemCount: 1,
518 };
519 const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
520 harness.registry.set(harness.snapshotAtom(environmentId), {
521 ...v2ShellSnapshot,
522 snapshotSequence: sequence,
523 threads: [thread],
524 });
525 setThread(running, 1);
526 const listAtom = harness.threads.quietThreadShellsAtom;
527 const dispose = harness.registry.mount(listAtom);
528 try {
529 const first = harness.registry.get(listAtom);
530 expect(first).toHaveLength(1);
531 setThread({ ...running, updatedAt: DateTime.add(v2Now, { seconds: 1 }), itemCount: 4 }, 2);
532 expect(harness.registry.get(listAtom)).toBe(first);
533
534 setThread({ ...running, title: "Renamed" }, 3);
535 expect(harness.registry.get(listAtom)).not.toBe(first);
536 expect(harness.registry.get(listAtom)[0]?.title).toBe("Renamed");
537 } finally {
538 dispose();
539 harness.registry.dispose();
540 }
541 });
542});