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

threadShell.test.ts

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