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

threadShell.test.ts

572 lines21.7 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 { 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 };
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("leaves side chats out of navigation until their parent is deleted", () => {
112 const { registry, threads, snapshotAtom } = makeHarness();
113 const parent = v2ThreadShell;
114 const sideChat = {
115 ...parent,
116 id: ThreadId.make("side"),
117 sideChat: true,
118 lineage: {
119 ...parent.lineage,
120 parentThreadId: parent.id,
121 relationshipToParent: "fork" as const,
122 },
123 };
124 registry.set(snapshotAtom(environmentId), {
125 ...v2ShellSnapshot,
126 threads: [parent, sideChat],
127 });
128 const dispose = registry.mount(threads.navigationThreadShellsAtom);
129 const navigationIds = () =>
130 registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id);
131 expect(navigationIds()).toEqual([parent.id]);
132 registry.set(snapshotAtom(environmentId), {
133 ...v2ShellSnapshot,
134 threads: [{ ...parent, deletedAt: v2Now }, sideChat],
135 });
136 expect(navigationIds()).toContain(sideChat.id);
137 dispose();
138 registry.dispose();
139 });
140​
141 it("keeps a live subagent question inside the parent without flagging its thread", () => {
142 const { registry, threads, snapshotAtom } = makeHarness();
143 const root = v2ThreadShell;
144 const child = {
145 ...root,
146 id: ThreadId.make("child"),
147 creationSource: "mcp" as const,
148 status: "running" as const,
149 activityRunStatus: "running" as const,
150 lineage: {
151 ...root.lineage,
152 parentThreadId: root.id,
153 relationshipToParent: "subagent" as const,
154 },
155 pendingRuntimeRequest: {
156 id: RuntimeRequestId.make("question"),
157 kind: "user_input" as const,
158 createdAt: v2Now,
159 },
160 };
161 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: root.id });
162 const dispose = registry.mount(inputs);
163 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] });
164 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
165 expect(
166 registry.get(threads.threadShellAtom({ environmentId, threadId: root.id }))
167 ?.pendingSubagentRequest,
168 ).toBeNull();
169 registry.set(snapshotAtom(environmentId), {
170 ...v2ShellSnapshot,
171 threads: [root, { ...child, status: "queued" as const }],
172 });
173 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]);
174 registry.set(snapshotAtom(environmentId), {
175 ...v2ShellSnapshot,
176 threads: [root, { ...child, status: "completed" as const, activityRunStatus: null }],
177 });
178 expect(registry.get(inputs)).toEqual([]);
179 const { activityRunStatus: _omitted, ...legacyChild } = child;
180 registry.set(snapshotAtom(environmentId), {
181 ...v2ShellSnapshot,
182 threads: [root, { ...legacyChild, status: "completed" as const }],
183 });
184 expect(registry.get(inputs)).toEqual([]);
185 dispose();
186 registry.dispose();
187 });
188​
189 it("brings a parent back from Working while a nested subagent waits for approval", () => {
190 const { registry, threads, snapshotAtom } = makeHarness();
191 const child = {
192 ...v2ThreadShell,
193 id: ThreadId.make("review"),
194 creationSource: "mcp" as const,
195 status: "running" as const,
196 activityRunStatus: "running" as const,
197 lineage: {
198 ...v2ThreadShell.lineage,
199 parentThreadId: v2ThreadShell.id,
200 relationshipToParent: "subagent" as const,
201 },
202 };
203 const grandchild = {
204 ...child,
205 id: ThreadId.make("review-helper"),
206 lineage: { ...child.lineage, parentThreadId: child.id },
207 };
208 const root = {
209 ...v2ThreadShell,
210 latestRunId: RunId.make("root-run"),
211 status: "completed" as const,
212 pendingBackgroundTasks: [
213 { taskId: "review", kind: "subagent" as const, childThreadId: child.id },
214 ],
215 };
216 const approval = {
217 id: RuntimeRequestId.make("cat-file"),
218 kind: "command" as const,
219 createdAt: v2Now,
220 };
221 const parent = threads.threadShellAtom({ environmentId, threadId: root.id });
222 const inputs = threads.childThreadInputsAtom({ environmentId, threadId: root.id });
223 const disposeParent = registry.mount(parent);
224 const disposeInputs = registry.mount(inputs);
225 registry.set(snapshotAtom(environmentId), {
226 ...v2ShellSnapshot,
227 threads: [root, child, grandchild],
228 });
229 expect(isThreadWorking(registry.get(parent)!)).toBe(true);
230​
231 registry.set(snapshotAtom(environmentId), {
232 ...v2ShellSnapshot,
233 threads: [root, child, { ...grandchild, pendingRuntimeRequest: approval }],
234 });
235 expect(registry.get(parent)?.pendingSubagentRequest).toBe("approval");
236 expect(isThreadWorking(registry.get(parent)!)).toBe(false);
237 const asking = registry.get(inputs);
238 expect(asking.map((thread) => thread.id)).toEqual([grandchild.id]);
239 expect(childThreadInputsTitle(asking)).toBe("Subagent needs approval");
240​
241 registry.set(snapshotAtom(environmentId), {
242 ...v2ShellSnapshot,
243 threads: [root, child, grandchild],
244 });
245 expect(registry.get(parent)?.pendingSubagentRequest).toBeNull();
246 expect(isThreadWorking(registry.get(parent)!)).toBe(true);
247 disposeInputs();
248 disposeParent();
249 registry.dispose();
250 });
251​
252 it("lists a task a linked environment runs for a listed thread under that thread", () => {
253 const { registry, threads, snapshotAtom, catalogValueAtom } = makeHarness([
254 environmentId,
255 remoteEnvironmentId,
256 ]);
257 const parent = v2ThreadShell;
258 const task = {
259 ...v2ThreadShell,
260 id: ThreadId.make("remote-task"),
261 creationSource: "mcp" as const,
262 status: "running" as const,
263 activityRunStatus: "running" as const,
264 delegatedFrom: { environmentId, threadId: parent.id, title: parent.title },
265 };
266 const helper = {
267 ...task,
268 id: ThreadId.make("remote-helper"),
269 delegatedFrom: undefined,
270 lineage: {
271 ...task.lineage,
272 parentThreadId: task.id,
273 relationshipToParent: "subagent" as const,
274 },
275 };
276 const approval = {
277 id: RuntimeRequestId.make("cat-file"),
278 kind: "command" as const,
279 createdAt: v2Now,
280 };
281 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });
282 registry.set(snapshotAtom(remoteEnvironmentId), {
283 ...v2ShellSnapshot,
284 threads: [task, helper],
285 });
286 const parentRef = { environmentId, threadId: parent.id };
287 const inputs = threads.childThreadInputsAtom(parentRef);
288 const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom);
289 const disposeParent = registry.mount(threads.threadShellAtom(parentRef));
290 const disposeInputs = registry.mount(inputs);
291 const listed = () =>
292 registry
293 .get(threads.navigationThreadShellsAtom)
294 .map((thread) => `${thread.environmentId}/${thread.id}`);
295 expect(listed()).toEqual([`${environmentId}/${parent.id}`]);
296​
297 // The helper the task started there asks for approval: the parent here hears of it.
298 registry.set(snapshotAtom(remoteEnvironmentId), {
299 ...v2ShellSnapshot,
300 threads: [task, { ...helper, pendingRuntimeRequest: approval }],
301 });
302 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBe(
303 "approval",
304 );
305 expect(registry.get(inputs).map((thread) => `${thread.environmentId}/${thread.id}`)).toEqual([
306 `${remoteEnvironmentId}/${helper.id}`,
307 ]);
308​
309 registry.set(snapshotAtom(remoteEnvironmentId), {
310 ...v2ShellSnapshot,
311 threads: [
312 task,
313 { ...helper, pendingRuntimeRequest: { ...approval, kind: "user_input" as const } },
314 ],
315 });
316 expect(registry.get(threads.threadShellAtom(parentRef))?.pendingSubagentRequest).toBeNull();
317 expect(registry.get(inputs).map((thread) => thread.id)).toEqual([helper.id]);
318​
319 // A task whose parent is gone there is listed on its own, as is one whose
320 // parent's environment is switched off.
321 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [] });
322 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
323 // Archiving the parent here leaves the task there unarchived, so it is listed on its own.
324 registry.set(snapshotAtom(environmentId), {
325 ...v2ShellSnapshot,
326 threads: [{ ...parent, archivedAt: v2Now }],
327 });
328 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
329 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [parent] });
330 expect(listed()).toEqual([`${environmentId}/${parent.id}`]);
331 const catalog = registry.get(catalogValueAtom);
332 const entries = new Map(catalog.entries);
333 entries.set(environmentId, { ...entries.get(environmentId)!, enabled: false });
334 registry.set(catalogValueAtom, { ...catalog, entries });
335 expect(listed()).toEqual([`${remoteEnvironmentId}/${task.id}`]);
336 disposeInputs();
337 disposeParent();
338 disposeNavigation();
339 registry.dispose();
340 });
341​
342 it("brings an approval up a chain of tasks across three environments to its root", () => {
343 const thirdEnvironmentId = EnvironmentId.make("third-environment-v2");
344 const { registry, threads, snapshotAtom } = makeHarness([
345 environmentId,
346 remoteEnvironmentId,
347 thirdEnvironmentId,
348 ]);
349 const root = v2ThreadShell;
350 const running = {
351 creationSource: "mcp" as const,
352 status: "running" as const,
353 activityRunStatus: "running" as const,
354 };
355 const task = {
356 ...v2ThreadShell,
357 ...running,
358 id: ThreadId.make("remote-task"),
359 delegatedFrom: { environmentId, threadId: root.id, title: root.title },
360 };
361 const nestedTask = {
362 ...v2ThreadShell,
363 ...running,
364 id: ThreadId.make("third-task"),
365 delegatedFrom: { environmentId: remoteEnvironmentId, threadId: task.id, title: task.title },
366 };
367 // A task the middle one delegates back to the root's own environment.
368 const returningTask = {
369 ...nestedTask,
370 id: ThreadId.make("returning-task"),
371 };
372 const approval = {
373 id: RuntimeRequestId.make("cat-file"),
374 kind: "command" as const,
375 createdAt: v2Now,
376 };
377 registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root] });
378 registry.set(snapshotAtom(remoteEnvironmentId), { ...v2ShellSnapshot, threads: [task] });
379 registry.set(snapshotAtom(thirdEnvironmentId), {
380 ...v2ShellSnapshot,
381 threads: [{ ...nestedTask, pendingRuntimeRequest: approval }],
382 });
383 const rootRef = { environmentId, threadId: root.id };
384 const taskRef = { environmentId: remoteEnvironmentId, threadId: task.id };
385 const disposeRoot = registry.mount(threads.threadShellAtom(rootRef));
386 const disposeTask = registry.mount(threads.threadShellAtom(taskRef));
387 expect(registry.get(threads.threadShellAtom(taskRef))?.pendingSubagentRequest).toBe("approval");
388 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");
389​
390 // Once it is answered, neither stays flagged.
391 registry.set(snapshotAtom(thirdEnvironmentId), {
392 ...v2ShellSnapshot,
393 threads: [nestedTask],
394 });
395 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBeNull();
396​
397 // Environments that delegate to each other still settle on the root's flag.
398 registry.set(snapshotAtom(environmentId), {
399 ...v2ShellSnapshot,
400 threads: [root, { ...returningTask, pendingRuntimeRequest: approval }],
401 });
402 expect(registry.get(threads.threadShellAtom(rootRef))?.pendingSubagentRequest).toBe("approval");
403 disposeTask();
404 disposeRoot();
405 registry.dispose();
406 });
407​
408 it.each([
409 { reason: "switched-off", state: { enabled: false } },
410 {
411 reason: "unsupported",
412 state: { enabled: true, unsupportedReason: "Use a compatible client." },
413 },
414 ])("leaves $reason environments out of navigation until restored", ({ state }) => {
415 const { registry, threads, catalogValueAtom } = makeHarness([
416 environmentId,
417 remoteEnvironmentId,
418 ]);
419 const dispose = registry.mount(threads.navigationThreadShellsAtom);
420 const environmentsOf = () =>
421 new Set(registry.get(threads.navigationThreadShellsAtom).map((t) => t.environmentId));
422 expect(environmentsOf()).toEqual(new Set([environmentId, remoteEnvironmentId]));
423​
424 const setRemotePaused = (paused: boolean) => {
425 const catalog = registry.get(catalogValueAtom);
426 const entries = new Map(catalog.entries);
427 entries.set(remoteEnvironmentId, {
428 ...entries.get(remoteEnvironmentId)!,
429 ...(paused ? state : { enabled: true, unsupportedReason: undefined }),
430 });
431 registry.set(catalogValueAtom, { ...catalog, entries });
432 };
433 setRemotePaused(true);
434 expect(environmentsOf()).toEqual(new Set([environmentId]));
435 setRemotePaused(false);
436 expect(environmentsOf()).toEqual(new Set([environmentId, remoteEnvironmentId]));
437 dispose();
438 registry.dispose();
439 });
440​
441 it("preserves project memberships on updates and keeps the same thread separate per environment", () => {
442 const harness = makeHarness([environmentId, remoteEnvironmentId]);
443 const otherThread = {
444 ...v2ThreadShell,
445 id: ThreadId.make("other-thread"),
446 projectId: otherProjectId,
447 };
448 const snapshot = { ...v2ShellSnapshot, threads: [v2ThreadShell, otherThread] };
449 harness.registry.set(harness.snapshotAtom(environmentId), snapshot);
450 const membershipAtom = harness.threads.environmentThreadRefsByProjectAtom(environmentId);
451 const listAtom = harness.threads.threadShellsForProjectRefsAtom([
452 { environmentId: remoteEnvironmentId, projectId: v2ThreadShell.projectId },
453 { environmentId, projectId: v2ThreadShell.projectId },
454 ]);
455 const disposeList = harness.registry.mount(listAtom);
456 try {
457 const membership = harness.registry.get(membershipAtom);
458 const before = harness.registry.get(listAtom);
459 expect(before).toHaveLength(2);
460 expect(before[0]).not.toBe(before[1]);
461 expect(before.map((thread) => thread.environmentId)).toEqual([
462 remoteEnvironmentId,
463 environmentId,
464 ]);
465​
466 harness.registry.set(harness.snapshotAtom(environmentId), {
467 ...snapshot,
468 threads: [v2ThreadShell, { ...otherThread, title: "Changed elsewhere" }],
469 });
470 expect(harness.registry.get(membershipAtom)).toBe(membership);
471 expect(harness.registry.get(listAtom)).toBe(before);
472​
473 harness.registry.set(harness.snapshotAtom(environmentId), {
474 ...snapshot,
475 threads: [{ ...v2ThreadShell, projectId: otherProjectId }, otherThread],
476 });
477 expect(harness.registry.get(listAtom)).toEqual([before[0]]);
478 harness.registry.set(harness.snapshotAtom(remoteEnvironmentId), {
479 ...v2ShellSnapshot,
480 threads: [],
481 });
482 expect(harness.registry.get(listAtom)).toEqual([]);
483 } finally {
484 disposeList();
485 harness.registry.dispose();
486 }
487 });
488​
489 it("keeps the quiet shell through streaming ticks and follows every change once the run stops", () => {
490 const harness = makeHarness();
491 const runId = RunId.make("streaming-run");
492 const running: OrchestrationV2ThreadShell = {
493 ...v2ThreadShell,
494 latestRunId: runId,
495 activeRunId: runId,
496 status: "running",
497 itemCount: 1,
498 visibleItemCount: 1,
499 };
500 const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
501 harness.registry.set(harness.snapshotAtom(environmentId), {
502 ...v2ShellSnapshot,
503 snapshotSequence: sequence,
504 threads: [thread],
505 });
506 const at = (seconds: number) => DateTime.add(v2Now, { seconds });
507 setThread(running, 1);
508 const ref = { environmentId, threadId: v2ThreadShell.id };
509 const quietAtom = harness.threads.quietThreadShellAtom(ref);
510 const dispose = harness.registry.mount(quietAtom);
511 try {
512 const first = harness.registry.get(quietAtom);
513 setThread({ ...running, updatedAt: at(1), itemCount: 4, visibleItemCount: 3 }, 2);
514 expect(harness.registry.get(quietAtom)).toBe(first);
515 expect(harness.registry.get(harness.threads.threadShellAtom(ref))?.itemCount).toBe(4);
516​
517 setThread({ ...running, updatedAt: at(2), itemCount: 5, title: "Renamed" }, 3);
518 const renamed = harness.registry.get(quietAtom);
519 expect(renamed?.title).toBe("Renamed");
520​
521 const stopped: OrchestrationV2ThreadShell = {
522 ...running,
523 activeRunId: null,
524 status: "completed",
525 };
526 setThread({ ...stopped, title: "Renamed", updatedAt: at(3) }, 4);
527 const completed = harness.registry.get(quietAtom);
528 expect(completed).not.toBe(renamed);
529 setThread({ ...stopped, title: "Renamed", updatedAt: at(4) }, 5);
530 expect(harness.registry.get(quietAtom)?.updatedAt).toBe(DateTime.formatIso(at(4)));
531 expect(harness.registry.get(quietAtom)).not.toBe(completed);
532 } finally {
533 dispose();
534 harness.registry.dispose();
535 }
536 });
537​
538 it("keeps the quiet shell list through streaming ticks", () => {
539 const harness = makeHarness();
540 const runId = RunId.make("streaming-list-run");
541 const running: OrchestrationV2ThreadShell = {
542 ...v2ThreadShell,
543 latestRunId: runId,
544 activeRunId: runId,
545 status: "running",
546 itemCount: 1,
547 visibleItemCount: 1,
548 };
549 const setThread = (thread: OrchestrationV2ThreadShell, sequence: number) =>
550 harness.registry.set(harness.snapshotAtom(environmentId), {
551 ...v2ShellSnapshot,
552 snapshotSequence: sequence,
553 threads: [thread],
554 });
555 setThread(running, 1);
556 const listAtom = harness.threads.quietThreadShellsAtom;
557 const dispose = harness.registry.mount(listAtom);
558 try {
559 const first = harness.registry.get(listAtom);
560 expect(first).toHaveLength(1);
561 setThread({ ...running, updatedAt: DateTime.add(v2Now, { seconds: 1 }), itemCount: 4 }, 2);
562 expect(harness.registry.get(listAtom)).toBe(first);
563​
564 setThread({ ...running, title: "Renamed" }, 3);
565 expect(harness.registry.get(listAtom)).not.toBe(first);
566 expect(harness.registry.get(listAtom)[0]?.title).toBe("Renamed");
567 } finally {
568 dispose();
569 harness.registry.dispose();
570 }
571 });
572});