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

threadShell.test.ts

885 lines33.5 KB

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