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 type { EnvironmentConnectionPhase } from "../connection/presentation.ts";
17import { v2Now, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
18import { applyShellStreamEvent } from "./shellReducer.ts";
19import { isThreadWorking } from "./threadInbox.ts";
20import {
21 childThreadInputsTitle,
22 createEnvironmentThreadShellAtoms,
23 resolveListedAncestorThreadRef,
24} from "./threadShell.ts";
25
26const environmentId = EnvironmentId.make("environment-v2");
27const remoteEnvironmentId = EnvironmentId.make("remote-environment-v2");
28const otherProjectId = ProjectId.make("other-project");
29
30function makeHarness(environmentIds: ReadonlyArray<EnvironmentId> = [environmentId]) {
31 const connectionPhaseAtom = Atom.family((_environmentId: EnvironmentId) =>
32 Atom.make<EnvironmentConnectionPhase>("connected"),
33 );
34 const snapshotAtom = Atom.family((_environmentId: EnvironmentId) =>
35 Atom.make<OrchestrationV2ShellSnapshot | null>(v2ShellSnapshot),
36 );
37 const catalogValueAtom = Atom.make({
38 isReady: true,
39 entries: new Map(
40 environmentIds.map((id) => [
41 id,
42 {
43 target: new PrimaryConnectionTarget({
44 environmentId: id,
45 label: "Environment",
46 httpBaseUrl: "https://example.test",
47 wsBaseUrl: "wss://example.test",
48 }),
49 profile: Option.none(),
50 enabled: true,
51 },
52 ]),
53 ),
54 });
55 return {
56 registry: AtomRegistry.make(),
57 snapshotAtom,
58 catalogValueAtom,
59 connectionPhaseAtom,
60 threads: createEnvironmentThreadShellAtoms({
61 catalogValueAtom,
62 snapshotAtom,
63 connectionPhaseAtom,
64 hiddenThreadTagsAtom: () => Atom.make(null),
65 }),
66 };
67}
68
69describe("v2 thread shell lists", () => {
70 it("updates cached point and list reads on connection loss and recovery without changing runtime", () => {
71 const { registry, threads, snapshotAtom, connectionPhaseAtom } = makeHarness([
72 environmentId,
73 remoteEnvironmentId,
74 ]);
75 const raw = {
76 ...v2ThreadShell,
77 status: "running" as const,
78 activeRunId: RunId.make("run-disconnected"),
79 latestRunId: RunId.make("run-disconnected"),
80 pinnedAt: v2Now,
81 };
82 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [raw] });
83 const ref = { environmentId, threadId: raw.id };
84 const reads = Atom.make((get) =>
85 [
86 get(threads.threadShellAtom(ref)),
87 get(threads.quietThreadShellAtom(ref)),
88 ...get(threads.threadShellsAtom),
89 ...get(threads.quietThreadShellsAtom),
90 ...get(threads.navigationThreadShellsAtom),
91 ...get(
92 threads.threadShellsForProjectRefsAtom([{ environmentId, projectId: raw.projectId }]),
93 ),
94 ].filter((thread) => thread?.environmentId === environmentId),
95 );
96 const dispose = registry.mount(reads);
97 const before = registry.get(threads.threadShellAtom(ref));
98 const other = registry.get(
99 threads.threadShellAtom({ ...ref, environmentId: remoteEnvironmentId }),
100 );
101 for (const phase of ["reconnecting", "error", "offline", "connecting", "connected"] as const) {
102 registry.set(connectionPhaseAtom(environmentId), phase);
103 expect(registry.get(reads)).toHaveLength(6);
104 for (const thread of registry.get(reads)) {
105 expect(thread).toMatchObject({
106 connectionPhase: phase,
107 pinnedAt: DateTime.formatIso(v2Now),
108 });
109 expect(thread?.runtime).toEqual(before?.runtime);
110 expect(thread?.source).toBe(raw);
111 }
112 expect(
113 registry.get(threads.threadShellAtom({ ...ref, environmentId: remoteEnvironmentId })),
114 ).toBe(other);
115 }
116 dispose();
117 registry.dispose();
118 });
119
120 it("builds no child index while no child asks for input", () => {
121 const { registry, threads, snapshotAtom } = makeHarness();
122 let parentIdReads = 0;
123 const child = {
124 ...v2ThreadShell,
125 id: ThreadId.make("child"),
126 creationSource: "mcp" as const,
127 lineage: {
128 rootThreadId: v2ThreadShell.id,
129 relationshipToParent: "subagent" as const,
130 // Nothing is pending, so only the child index would read parent ids.
131 get parentThreadId() {
132 parentIdReads++;
133 return v2ThreadShell.id;
134 },
135 },
136 };
137 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: v2ThreadShell.id });
138 const dispose = registry.mount(inputs);
139 registry.set(snapshotAtom(environmentId), {
140 ...v2ShellSnapshot,
141 threads: [v2ThreadShell, child],
142 });
143 expect(registry.get(inputs)).toEqual([]);
144 expect(parentIdReads).toBe(0);
145 dispose();
146 registry.dispose();
147 });
148
149 it("preserves ordered reference arrays when a middle thread changes", () => {
150 const { registry, threads, snapshotAtom } = makeHarness();
151 const snapshot = {
152 ...v2ShellSnapshot,
153 threads: ["a", "b", "c"].map((id) => ({ ...v2ThreadShell, id: ThreadId.make(id) })),
154 };
155 registry.set(snapshotAtom(environmentId), snapshot);
156 const dispose = registry.mount(threads.threadRefsAtom);
157 const before = registry.get(threads.threadRefsAtom);
158 registry.set(
159 snapshotAtom(environmentId),
160 applyShellStreamEvent(snapshot, {
161 kind: "thread.updated",
162 location: "active",
163 sequence: 1,
164 thread: { ...snapshot.threads[1]!, title: "Updated" },
165 }),
166 );
167 expect(registry.get(threads.threadRefsAtom)).toBe(before);
168 dispose();
169 registry.dispose();
170 });
171
172 it("keeps navigation stable on hidden subagent updates and retains user forks", () => {
173 const { registry, threads, snapshotAtom } = makeHarness();
174 const root = v2ThreadShell;
175 const child = {
176 ...root,
177 id: ThreadId.make("child"),
178 lineage: {
179 ...root.lineage,
180 parentThreadId: root.id,
181 relationshipToParent: "subagent" as const,
182 },
183 };
184 const fork = {
185 ...child,
186 id: ThreadId.make("fork"),
187 lineage: { ...child.lineage, relationshipToParent: "fork" as const },
188 };
189 const snapshot = { ...v2ShellSnapshot, threads: [root, child, fork] };
190 registry.set(snapshotAtom(environmentId), snapshot);
191 const dispose = registry.mount(threads.navigationThreadShellsAtom);
192 const before = registry.get(threads.navigationThreadShellsAtom);
193 expect(before.map((thread) => thread.id)).toEqual([root.id, fork.id]);
194 registry.set(snapshotAtom(environmentId), {
195 ...snapshot,
196 threads: [root, { ...child, title: "Child streaming" }, fork],
197 });
198 expect(registry.get(threads.navigationThreadShellsAtom)).toBe(before);
199 expect(registry.get(threads.threadShellsAtom)).toHaveLength(3);
200 dispose();
201 registry.dispose();
202 });
203
204 it("keeps a live subagent question inside the parent without flagging its thread", () => {
205 const { registry, threads, snapshotAtom } = makeHarness();
206 const root = v2ThreadShell;
207 const child = {
208 ...root,
209 id: ThreadId.make("child"),
210 creationSource: "mcp" as const,
211 status: "running" as const,
212 activityRunStatus: "running" as const,
213 lineage: {
214 ...root.lineage,
215 parentThreadId: root.id,
216 relationshipToParent: "subagent" as const,
217 },
218 pendingRuntimeRequest: {
219 id: RuntimeRequestId.make("question"),
220 kind: "user_input" as const,
221 createdAt: v2Now,
222 },
223 };
224 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: root.id });
225 const dispose = registry.mount(inputs);
226 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] });
227 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
228 expect(
229 registry.get(threads.threadShellAtom({ environmentId, threadId: root.id }))
230 ?.pendingSubagentRequest,
231 ).toBeNull();
232 registry.set(snapshotAtom(environmentId), {
233 ...v2ShellSnapshot,
234 threads: [root, { ...child, status: "queued" as const }],
235 });
236 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
237 registry.set(snapshotAtom(environmentId), {
238 ...v2ShellSnapshot,
239 threads: [root, { ...child, status: "completed" as const, activityRunStatus: null }],
240 });
241 expect(registry.get(inputs)).toEqual([]);
242 const { activityRunStatus: _omitted, ...legacyChild } = child;
243 registry.set(snapshotAtom(environmentId), {
244 ...v2ShellSnapshot,
245 threads: [root, { ...legacyChild, status: "completed" as const }],
246 });
247 expect(registry.get(inputs)).toEqual([]);
248 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] });
249 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
250 dispose();
251 registry.dispose();
252 });
253
254 it("flags the parent while a live subagent waits on a secret card", () => {
255 const { registry, threads, snapshotAtom } = makeHarness();
256 const root = v2ThreadShell;
257 const child = {
258 ...root,
259 id: ThreadId.make("child"),
260 creationSource: "mcp" as const,
261 status: "running" as const,
262 activityRunStatus: "running" as const,
263 lineage: {
264 ...root.lineage,
265 parentThreadId: root.id,
266 relationshipToParent: "subagent" as const,
267 },
268 pendingRuntimeRequest: {
269 id: RuntimeRequestId.make("secret-card"),
270 kind: "user_input" as const,
271 createdAt: v2Now,
272 blocking: true,
273 userOnly: true,
274 },
275 };
276 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] });
277 expect(
278 registry.get(threads.threadShellAtom({ environmentId, threadId: root.id }))
279 ?.pendingSubagentRequest,
280 ).toBe("user_input");
281 registry.dispose();
282 });
283
284 it("rolls a side chat's questions and approvals up to its parent row", () => {
285 const { registry, threads, snapshotAtom } = makeHarness();
286 const root = v2ThreadShell;
287 const sideChat = {
288 ...root,
289 id: ThreadId.make("side-chat"),
290 status: "running" as const,
291 activityRunStatus: "running" as const,
292 latestRunId: RunId.make("side-chat-run"),
293 lineage: {
294 ...root.lineage,
295 parentThreadId: root.id,
296 relationshipToParent: "fork" as const,
297 sideChat: true,
298 },
299 };
300 const request = { id: RuntimeRequestId.make("ask"), createdAt: v2Now };
301 const parentRef = { environmentId, threadId: root.id };
302 const parent = threads.threadShellAtom(parentRef);
303 const inputs = threads.childThreadInputsAtom(parentRef);
304 const disposeParent = registry.mount(parent);
305 const disposeInputs = registry.mount(inputs);
306 const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);
307 const withRequest = (
308 kind: "user_input" | "command",
309 options: { readonly blocking?: boolean } = {},
310 ) =>
311 registry.set(snapshotAtom(environmentId), {
312 ...v2ShellSnapshot,
313 threads: [
314 root,
315 {
316 ...sideChat,
317 pendingRuntimeRequest: {
318 ...request,
319 kind,
320 ...(options.blocking === undefined ? {} : { blocking: options.blocking }),
321 },
322 },
323 ],
324 });
325
326 withRequest("user_input");
327 expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input");
328 expect(childThreadInputsTitle(registry.get(inputs))).toBe("Side chat needs input");
329 expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([
330 root.id,
331 ]);
332
333 withRequest("user_input", { blocking: false });
334 expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input");
335
336 withRequest("command");
337 expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
338 expect(childThreadInputsTitle(registry.get(inputs))).toBe("Side chat needs approval");
339
340 const helper = {
341 ...sideChat,
342 id: ThreadId.make("side-chat-helper"),
343 creationSource: "mcp" as const,
344 lineage: {
345 ...sideChat.lineage,
346 parentThreadId: sideChat.id,
347 relationshipToParent: "subagent" as const,
348 sideChat: false,
349 },
350 pendingRuntimeRequest: { ...request, kind: "command" as const },
351 };
352 const sideChats = threads.sideChatsAtom(parentRef);
353 const disposeSideChats = registry.mount(sideChats);
354 registry.set(snapshotAtom(environmentId), {
355 ...v2ShellSnapshot,
356 threads: [root, sideChat, helper],
357 });
358 expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
359 expect(
360 registry.get(sideChats).map((thread) => [thread.id, thread.pendingSubagentRequest]),
361 ).toEqual([[sideChat.id, "approval"]]);
362
363 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, sideChat] });
364 expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();
365 expect(registry.get(sideChats).map((thread) => thread.pendingSubagentRequest)).toEqual([null]);
366 expect(registry.get(inputs)).toEqual([]);
367 disposeSideChats();
368 disposeNavigation();
369 disposeInputs();
370 disposeParent();
371 registry.dispose();
372 });
373
374 it("brings a parent back from Working while a nested subagent waits for approval", () => {
375 const { registry, threads, snapshotAtom } = makeHarness();
376 const child = {
377 ...v2ThreadShell,
378 id: ThreadId.make("review"),
379 creationSource: "mcp" as const,
380 status: "running" as const,
381 activityRunStatus: "running" as const,
382 lineage: {
383 ...v2ThreadShell.lineage,
384 parentThreadId: v2ThreadShell.id,
385 relationshipToParent: "subagent" as const,
386 },
387 };
388 const grandchild = {
389 ...child,
390 id: ThreadId.make("review-helper"),
391 lineage: { ...child.lineage, parentThreadId: child.id },
392 };
393 const root = {
394 ...v2ThreadShell,
395 latestRunId: RunId.make("root-run"),
396 status: "completed" as const,
397 pendingBackgroundTasks: [
398 { taskId: "review", kind: "subagent" as const, childThreadId: child.id },
399 ],
400 };
401 const approval = {
402 id: RuntimeRequestId.make("cat-file"),
403 kind: "command" as const,
404 createdAt: v2Now,
405 };
406 const parent = threads.threadShellAtom({ environmentId, threadId: root.id });
407 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: root.id });
408 const disposeParent = registry.mount(parent);
409 const disposeInputs = registry.mount(inputs);
410 registry.set(snapshotAtom(environmentId), {
411 ...v2ShellSnapshot,
412 threads: [root, child, grandchild],
413 });
414 expect(isThreadWorking(registry.get(parent)!)).toBe(true);
415
416 registry.set(snapshotAtom(environmentId), {
417 ...v2ShellSnapshot,
418 threads: [root, child, { ...grandchild, pendingRuntimeRequest: approval }],
419 });
420 expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
421 expect(isThreadWorking(registry.get(parent)!)).toBe(false);
422 const asking = registry.get(inputs);
423 expect(asking.map((thread) => thread.id)).toEqual([grandchild.id]);
424 expect(childThreadInputsTitle(asking)).toBe("Subagent needs approval");
425
426 registry.set(snapshotAtom(environmentId), {
427 ...v2ShellSnapshot,
428 threads: [root, child, grandchild],
429 });
430 expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();
431 expect(isThreadWorking(registry.get(parent)!)).toBe(true);
432 disposeInputs();
433 disposeParent();
434 registry.dispose();
435 });
436
437 it("lists a task a linked environment runs for a listed thread under that thread", () => {
438 const { registry, threads, snapshotAtom, catalogValueAtom } = makeHarness([
439 environmentId,
440 remoteEnvironmentId,
441 ]);
442 const parent = v2ThreadShell;
443 const task = {
444 ...v2ThreadShell,
445 id: ThreadId.make("remote-task"),
446 creationSource: "mcp" as const,
447 status: "running" as const,
448 activityRunStatus: "running" as const,
449 delegatedFrom: { environmentId, threadId: parent.id, title: parent.title },
450 };
451 const helper = {
452 ...task,
453 id: ThreadId.make("remote-helper"),
454 delegatedFrom: undefined,
455 lineage: {
456 ...task.lineage,
457 parentThreadId: task.id,
458 relationshipToParent: "subagent" as const,
459 },
460 };
461 const approval = {
462 id: RuntimeRequestId.make("cat-file"),
463 kind: "command" as const,
464 createdAt: v2Now,
465 };
466 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });
467 registry.set(snapshotAtom(remoteEnvironmentId), {
468 ...v2ShellSnapshot,
469 threads: [task, helper],
470 });
471 const parentRef = { environmentId, threadId: parent.id };
472 const inputs = threads.childThreadInputsAtom(parentRef);
473 const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);
474 const disposeParent = registry.mount(threads.threadShellAtom(parentRef));
475 const disposeInputs = registry.mount(inputs);
476 const listed = () =>
477 registry
478 .get(threads.navigationThreadShellsAtom)
479 .map((thread) => `${thread.environmentId}/${thread.id}`);
480 expect(listed()).toEqual([`${environmentId}/${parent.id}`]);
481
482 // The helper the task started there asks for approval: the parent here hears of it.
483 registry.set(snapshotAtom(remoteEnvironmentId), {
484 ...v2ShellSnapshot,
485 threads: [task, { ...helper, pendingRuntimeRequest: approval }],
486 });
487 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBe(
488 "approval",
489 );
490 expect(registry.get(inputs).map((thread) => `${thread.environmentId}/${thread.id}`)).toEqual([
491 `${remoteEnvironmentId}/${helper.id}`,
492 ]);
493
494 registry.set(snapshotAtom(remoteEnvironmentId), {
495 ...v2ShellSnapshot,
496 threads: [
497 task,
498 { ...helper, pendingRuntimeRequest: { ...approval, kind: "user_input" as const } },
499 ],
500 });
501 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBeNull();
502 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([helper.id]);
503
504 // A secret card needs the user, so it still reaches the parent here.
505 registry.set(snapshotAtom(remoteEnvironmentId), {
506 ...v2ShellSnapshot,
507 threads: [
508 task,
509 {
510 ...helper,
511 pendingRuntimeRequest: { ...approval, kind: "user_input" as const, userOnly: true },
512 },
513 ],
514 });
515 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBe(
516 "user_input",
517 );
518
519 // A task whose parent is gone there is listed on its own, as is one whose
520 // parent's environment is switched off.
521 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [] });
522 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
523 // Archiving the parent here leaves the task there unarchived, so it is listed on its own.
524 registry.set(snapshotAtom(environmentId), {
525 ...v2ShellSnapshot,
526 threads: [{ ...parent, archivedAt: v2Now }],
527 });
528 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
529 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });
530 expect(listed()).toEqual([`${environmentId}/${parent.id}`]);
531 const catalog = registry.get(catalogValueAtom);
532 const entries = new Map(catalog.entries);
533 entries.set(environmentId, { ...entries.get(environmentId)!, enabled: false });
534 registry.set(catalogValueAtom, { ...catalog, entries });
535 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
536 disposeInputs();
537 disposeParent();
538 disposeNavigation();
539 registry.dispose();
540 });
541
542 it("brings an approval up a chain of tasks across three environments to its root", () => {
543 const thirdEnvironmentId = EnvironmentId.make("third-environment-v2");
544 const { registry, threads, snapshotAtom } = makeHarness([
545 environmentId,
546 remoteEnvironmentId,
547 thirdEnvironmentId,
548 ]);
549 const root = v2ThreadShell;
550 const running = {
551 creationSource: "mcp" as const,
552 status: "running" as const,
553 activityRunStatus: "running" as const,
554 };
555 const task = {
556 ...v2ThreadShell,
557 ...running,
558 id: ThreadId.make("remote-task"),
559 delegatedFrom: { environmentId, threadId: root.id, title: root.title },
560 };
561 const nestedTask = {
562 ...v2ThreadShell,
563 ...running,
564 id: ThreadId.make("third-task"),
565 delegatedFrom: { environmentId: remoteEnvironmentId, threadId: task.id, title: task.title },
566 };
567 // A task the middle one delegates back to the root's own environment.
568 const returningTask = {
569 ...nestedTask,
570 id: ThreadId.make("returning-task"),
571 };
572 const approval = {
573 id: RuntimeRequestId.make("cat-file"),
574 kind: "command" as const,
575 createdAt: v2Now,
576 };
577 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root] });
578 registry.set(snapshotAtom(remoteEnvironmentId), { ...v2ShellSnapshot, threads: [task] });
579 registry.set(snapshotAtom(thirdEnvironmentId), {
580 ...v2ShellSnapshot,
581 threads: [{ ...nestedTask, pendingRuntimeRequest: approval }],
582 });
583 const rootRef = { environmentId, threadId: root.id };
584 const taskRef = { environmentId: remoteEnvironmentId, threadId: task.id };
585 const disposeRoot = registry.mount(threads.threadShellAtom(rootRef));
586 const disposeTask = registry.mount(threads.threadShellAtom(taskRef));
587 expect(registry.get(threads.threadShellAtom(taskRef))?.pendingSubagentRequest).toBe("approval");
588 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");
589
590 // Once it is answered, neither stays flagged.
591 registry.set(snapshotAtom(thirdEnvironmentId), {
592 ...v2ShellSnapshot,
593 threads: [nestedTask],
594 });
595 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBeNull();
596
597 // Environments that delegate to each other still settle on the root's flag.
598 registry.set(snapshotAtom(environmentId), {
599 ...v2ShellSnapshot,
600 threads: [root, { ...returningTask, pendingRuntimeRequest: approval }],
601 });
602 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");
603 disposeTask();
604 disposeRoot();
605 registry.dispose();
606 });
607
608 it.each([
609 { reason: "switched-off", state: { enabled: false } },
610 {
611 reason: "unsupported",
612 state: { enabled: true, unsupportedReason: "Use a compatible client." },
613 },
614 ])("leaves $reason environments out of navigation until restored", ({ state }) => {
615 const { registry, threads, catalogValueAtom } = makeHarness([
616 environmentId,
617 remoteEnvironmentId,
618 ]);
619 const dispose = registry.mount(threads.navigationThreadShellsAtom);
620 const environmentsOf = () =>
621 new Set(registry.get(threads.navigationThreadShellsAtom).map((t) => t.environmentId));
622 expect(environmentsOf()).toEqual(new Set([environmentId, remoteEnvironmentId]));
623
624 const setRemotePaused = (paused: boolean) => {
625 const catalog = registry.get(catalogValueAtom);
626 const entries = new Map(catalog.entries);
627 entries.set(remoteEnvironmentId, {
628 ...entries.get(remoteEnvironmentId)!,
629 ...(paused ? state : { enabled: true, unsupportedReason: undefined }),
630 });
631 registry.set(catalogValueAtom, { ...catalog, entries });
632 };
633 setRemotePaused(true);
634 expect(environmentsOf()).toEqual(new Set([environmentId]));
635 setRemotePaused(false);
636 expect(environmentsOf()).toEqual(new Set([environmentId, remoteEnvironmentId]));
637 dispose();
638 registry.dispose();
639 });
640
641 it("preserves project memberships on updates and keeps the same thread separate per environment", () => {
642 const harness = makeHarness([environmentId, remoteEnvironmentId]);
643 const otherThread = {
644 ...v2ThreadShell,
645 id: ThreadId.make("other-thread"),
646 projectId: otherProjectId,
647 };
648 const snapshot = { ...v2ShellSnapshot, threads: [v2ThreadShell, otherThread] };
649 harness.registry.set(harness.snapshotAtom(environmentId), snapshot);
650 const membershipAtom = harness.threads.environmentThreadRefsByProjectAtom(environmentId);
651 const listAtom = harness.threads.threadShellsForProjectRefsAtom([
652 { environmentId: remoteEnvironmentId, projectId: v2ThreadShell.projectId },
653 { environmentId, projectId: v2ThreadShell.projectId },
654 ]);
655 const disposeList = harness.registry.mount(listAtom);
656 try {
657 const membership = harness.registry.get(membershipAtom);
658 const before = harness.registry.get(listAtom);
659 expect(before).toHaveLength(2);
660 expect(before[0]).not.toBe(before[1]);
661 expect(before.map((thread) => thread.environmentId)).toEqual([
662 remoteEnvironmentId,
663 environmentId,
664 ]);
665
666 harness.registry.set(harness.snapshotAtom(environmentId), {
667 ...snapshot,
668 threads: [v2ThreadShell, { ...otherThread, title: "Changed elsewhere" }],
669 });
670 expect(harness.registry.get(membershipAtom)).toBe(membership);
671 expect(harness.registry.get(listAtom)).toBe(before);
672
673 harness.registry.set(harness.snapshotAtom(environmentId), {
674 ...snapshot,
675 threads: [{ ...v2ThreadShell, projectId: otherProjectId }, otherThread],
676 });
677 expect(harness.registry.get(listAtom)).toEqual([before[0]]);
678 harness.registry.set(harness.snapshotAtom(remoteEnvironmentId), {
679 ...v2ShellSnapshot,
680 threads: [],
681 });
682 expect(harness.registry.get(listAtom)).toEqual([]);
683 } finally {
684 disposeList();
685 harness.registry.dispose();
686 }
687 });
688
689 it("keeps the quiet shell through streaming ticks and follows every change once the run stops", () => {
690 const harness = makeHarness();
691 const runId = RunId.make("streaming-run");
692 const running: OrchestrationV2ThreadShell = {
693 ...v2ThreadShell,
694 latestRunId: runId,
695 activeRunId: runId,
696 status: "running",
697 itemCount: 1,
698 visibleItemCount: 1,
699 };
700 const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
701 harness.registry.set(harness.snapshotAtom(environmentId), {
702 ...v2ShellSnapshot,
703 snapshotSequence: sequence,
704 threads: [thread],
705 });
706 const at = (seconds: number) => DateTime.add(v2Now, { seconds });
707 setThread(running, 1);
708 const ref = { environmentId, threadId: v2ThreadShell.id };
709 const quietAtom = harness.threads.quietThreadShellAtom(ref);
710 const dispose = harness.registry.mount(quietAtom);
711 try {
712 const first = harness.registry.get(quietAtom);
713 setThread({ ...running, updatedAt: at(1), itemCount: 4, visibleItemCount: 3 }, 2);
714 expect(harness.registry.get(quietAtom)).toBe(first);
715 expect(harness.registry.get(harness.threads.threadShellAtom(ref))?.itemCount).toBe(4);
716
717 setThread({ ...running, updatedAt: at(2), itemCount: 5, title: "Renamed" }, 3);
718 const renamed = harness.registry.get(quietAtom);
719 expect(renamed?.title).toBe("Renamed");
720
721 const stopped: OrchestrationV2ThreadShell = {
722 ...running,
723 activeRunId: null,
724 status: "completed",
725 };
726 setThread({ ...stopped, title: "Renamed", updatedAt: at(3) }, 4);
727 const completed = harness.registry.get(quietAtom);
728 expect(completed).not.toBe(renamed);
729 setThread({ ...stopped, title: "Renamed", updatedAt: at(4) }, 5);
730 expect(harness.registry.get(quietAtom)?.updatedAt).toBe(DateTime.formatIso(at(4)));
731 expect(harness.registry.get(quietAtom)).not.toBe(completed);
732 } finally {
733 dispose();
734 harness.registry.dispose();
735 }
736 });
737
738 it("keeps the quiet shell list through streaming ticks", () => {
739 const harness = makeHarness();
740 const runId = RunId.make("streaming-list-run");
741 const running: OrchestrationV2ThreadShell = {
742 ...v2ThreadShell,
743 latestRunId: runId,
744 activeRunId: runId,
745 status: "running",
746 itemCount: 1,
747 visibleItemCount: 1,
748 };
749 const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
750 harness.registry.set(harness.snapshotAtom(environmentId), {
751 ...v2ShellSnapshot,
752 snapshotSequence: sequence,
753 threads: [thread],
754 });
755 setThread(running, 1);
756 const listAtom = harness.threads.quietThreadShellsAtom;
757 const dispose = harness.registry.mount(listAtom);
758 try {
759 const first = harness.registry.get(listAtom);
760 expect(first).toHaveLength(1);
761 setThread({ ...running, updatedAt: DateTime.add(v2Now, { seconds: 1 }), itemCount: 4 }, 2);
762 expect(harness.registry.get(listAtom)).toBe(first);
763
764 setThread({ ...running, title: "Renamed" }, 3);
765 expect(harness.registry.get(listAtom)).not.toBe(first);
766 expect(harness.registry.get(listAtom)[0]?.title).toBe("Renamed");
767 } finally {
768 dispose();
769 harness.registry.dispose();
770 }
771 });
772});
773
774describe("resolveListedAncestorThreadRef", () => {
775 type Thread = Parameters<typeof resolveListedAncestorThreadRef>[1][number];
776 const otherEnvironmentId = EnvironmentId.make("environment-other");
777 const ref = (environment: EnvironmentId, threadId: ThreadId) => ({
778 environmentId: environment,
779 threadId,
780 });
781 const listed = (
782 id: string,
783 environment = environmentId,
784 overrides?: Partial<Thread>,
785 ): Thread => ({
786 id: ThreadId.make(id),
787 environmentId: environment,
788 lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
789 archivedAt: null,
790 delegatedFrom: null,
791 ...overrides,
792 });
793 const subagentOf = (id: string, parentId: ThreadId, environment = environmentId) =>
794 listed(id, environment, {
795 lineage: {
796 rootThreadId: parentId,
797 parentThreadId: parentId,
798 relationshipToParent: "subagent",
799 },
800 });
801 const rowOf = (threadId: ThreadId, environment: EnvironmentId, threads: readonly Thread[]) =>
802 resolveListedAncestorThreadRef(ref(environment, threadId), threads);
803
804 it("maps an open subagent to its nearest listed ancestor", () => {
805 const root = listed("thread-root");
806 const fork = listed("thread-fork", environmentId, {
807 lineage: { rootThreadId: root.id, parentThreadId: root.id, relationshipToParent: "fork" },
808 });
809 const child = subagentOf("thread-child", root.id);
810 const grandchild = subagentOf("thread-grandchild", child.id);
811 const forkChild = subagentOf("thread-fork-child", fork.id);
812 const orphan = subagentOf("thread-orphan", ThreadId.make("thread-missing"));
813 const elsewhere = subagentOf("thread-elsewhere", root.id, otherEnvironmentId);
814 const threads = [root, fork, child, grandchild, forkChild, orphan, elsewhere];
815
816 expect(rowOf(child.id, environmentId, threads)).toEqual(ref(environmentId, root.id));
817 expect(rowOf(grandchild.id, environmentId, threads)).toEqual(ref(environmentId, root.id));
818 expect(rowOf(forkChild.id, environmentId, threads)).toEqual(ref(environmentId, fork.id));
819 expect(rowOf(elsewhere.id, otherEnvironmentId, threads)).toEqual(
820 ref(otherEnvironmentId, elsewhere.id),
821 );
822 expect(rowOf(orphan.id, environmentId, threads)).toEqual(ref(environmentId, orphan.id));
823 const loopA = subagentOf("thread-loop-a", ThreadId.make("thread-loop-b"));
824 const loopB = subagentOf("thread-loop-b", loopA.id);
825 expect(rowOf(loopA.id, environmentId, [loopA, loopB])).toEqual(ref(environmentId, loopA.id));
826 });
827
828 it("maps an open task a linked environment delegated to its listed parent", () => {
829 const parent = listed("thread-parent", remoteEnvironmentId);
830 const task = listed("thread-task", environmentId, {
831 delegatedFrom: { environmentId: remoteEnvironmentId, threadId: parent.id, title: "Parent" },
832 });
833
834 expect(rowOf(task.id, environmentId, [parent, task])).toEqual(
835 ref(remoteEnvironmentId, parent.id),
836 );
837 });
838});