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

ThreadRelationshipsControl.agents.browser.test.tsx

1,236 lines41.1 KB

1import { act, cloneElement, type ReactElement, type ReactNode } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import {
4 EnvironmentId,
5 ThreadId,
6 type ModelSelection,
7 type ProviderOptionDescriptor,
8 type OrchestrationV2ContextTransfer,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12​
13import "~/index.css";
14​
15const state = vi.hoisted(() => ({
16 stopWorkflowLabel: "environment-data:orchestration:stop-workflow",
17 projection: null as unknown,
18 navigate: vi.fn(),
19 shells: [] as unknown[],
20 projects: [] as unknown[],
21 configs: new Map<string, unknown>(),
22 showTooltips: false,
23 command: vi.fn().mockResolvedValue({ _tag: "Success" }),
24 workflowCommand: vi.fn().mockResolvedValue({ _tag: "Success" }),
25 toast: vi.fn(),
26}));
27​
28vi.mock(import("@tanstack/react-router"), async (original) => ({
29 ...(await original()),
30 useNavigate: (() => state.navigate) as never,
31}));
32vi.mock(import("../../state/entities"), async (original) => ({
33 ...(await original()),
34 useThreadProjection: (() => ({ projection: state.projection })) as never,
35 useThreadRelationshipShells: ((ref: { readonly environmentId: string }) =>
36 (state.shells as ReadonlyArray<{ readonly environmentId: string; readonly source: unknown }>)
37 .filter((shell) => shell.environmentId === ref.environmentId)
38 .map((shell) => shell.source)) as never,
39 useProjects: (() => state.projects) as never,
40}));
41vi.mock(import("../../state/environments"), async (original) => ({
42 ...(await original()),
43 useEnvironmentProviders: (() =>
44 new Map(
45 [...state.configs].map(([id, config]) => [id, (config as { providers: unknown }).providers]),
46 )) as never,
47}));
48vi.mock(import("../../lib/archivedThreadsState"), async (original) => ({
49 ...(await original()),
50 useArchivedThreadSnapshots: (() => ({ snapshots: [] })) as never,
51}));
52vi.mock(import("../../state/use-atom-command"), async (original) => ({
53 ...(await original()),
54 useAtomCommand: ((command: { label?: string }) =>
55 command.label === state.stopWorkflowLabel ? state.workflowCommand : state.command) as never,
56}));
57vi.mock(import("../ui/toast"), async (original) => {
58 const actual = await original();
59 return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } as never };
60});
61vi.mock(import("../../state/orchestration"), async (original) => {
62 const actual = await original();
63 const { Atom } = await import("effect/reactivity");
64 const granted = Atom.make(true);
65 const stopWorkflow = actual.orchestrationEnvironment.stopWorkflow;
66 return {
67 ...actual,
68 orchestrationEnvironment: Object.assign(Object.create(actual.orchestrationEnvironment), {
69 stopWorkflow: Object.assign(Object.create(stopWorkflow), {
70 label: state.stopWorkflowLabel,
71 permissionAtom: () => granted,
72 }),
73 }),
74 };
75});
76// Tooltip and hover card content renders inline so the suite can read every row's agent
77// details across many states without hovering each row.
78vi.mock(import("../ui/tooltip"), async () => {
79 const { cloneElement } = await import("react");
80 return {
81 Tooltip: (({ children }: { children: ReactNode }) => children) as never,
82 TooltipTrigger: (({ render, children }: { render: ReactElement; children: ReactNode }) =>
83 cloneElement(render, {}, children)) as never,
84 TooltipPopup: (({ children }: { children: ReactNode }) =>
85 state.showTooltips ? children : null) as never,
86 };
87});
88​
89import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
90​
91let root: Root;
92let container: HTMLDivElement;
93let current: ReactElement;
94​
95async function render(element: ReactElement) {
96 current = element;
97 await act(async () => root.render(element));
99// The mocked hooks read `state` while rendering, so a new element picks up changes.
100const update = () => act(async () => root.render(cloneElement(current)));
101const click = (element: HTMLElement) => act(async () => element.click());
102const buttons = () => [...container.querySelectorAll("button")];
103const allByLabel = (label: string) =>
104 buttons().filter((button) => button.getAttribute("aria-label") === label);
105function byLabel(label: string) {
106 const matches = allByLabel(label);
107 if (matches.length !== 1)
108 throw new Error(`Expected one "${label}" button, got ${matches.length}`);
109 return matches[0]!;
111const sectionToggles = (expanded: boolean) =>
112 buttons().filter(
113 (button) =>
114 button.getAttribute("aria-expanded") === String(expanded) &&
115 !button.hasAttribute("aria-label"),
116 );
117function sectionToggle(expanded: boolean) {
118 const [toggle] = sectionToggles(expanded);
119 if (!toggle) throw new Error(`No ${expanded ? "expanded" : "collapsed"} section toggle`);
120 return toggle;
122const heading = () => container.querySelector("h3")?.textContent;
123const buttonsWithLabel = (matches: (label: string) => boolean) =>
124 buttons().filter((button) => matches(button.getAttribute("aria-label") ?? ""));
125// Joins rendered text nodes; `visibleOnly` drops screen-reader-only text.
126function textNodes(separator: string, visibleOnly = false) {
127 const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
128 const parts: string[] = [];
129 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
130 if (visibleOnly && node.parentElement?.closest(".sr-only")) continue;
131 parts.push(node.textContent ?? "");
132 }
133 return parts.join(separator);
135​
136beforeEach(() => {
137 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
138 container = document.createElement("div");
139 document.body.append(container);
140 root = createRoot(container);
141});
142​
143afterEach(async () => {
144 await act(async () => root.unmount());
145 container.remove();
146 vi.unstubAllGlobals();
147 state.shells = [];
148 state.projects = [];
149 state.configs.clear();
150 state.showTooltips = false;
151 state.navigate.mockClear();
152 state.command.mockClear();
153 state.workflowCommand.mockReset().mockResolvedValue({ _tag: "Success" });
154 state.toast.mockClear();
155 state.projection = null;
156});
157​
158it("stops the entire native workflow through its parent without changing state before acknowledgement", async () => {
159 const coordinator = {
160 id: "workflow",
161 origin: "provider_native",
162 driver: "claudeAgent",
163 providerInstanceId: "claude-work",
164 childThreadId: "workflow-chat",
165 title: "Checkout review",
166 status: "running",
167 startedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
168 completedAt: null,
169 updatedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
170 workflow: {
171 name: "Checkout review",
172 phases: [{ index: 0, title: "Inspect" }],
173 agents: [{ index: 0, label: "Checker", state: "running", phaseIndex: 0 }],
174 },
175 };
176 state.projection = {
177 thread: { id: "parent", lineage: { relationshipToParent: null } },
178 runs: [],
179 providerThreads: [],
180 providerSessions: [],
181 contextTransfers: [],
182 subagents: [
183 coordinator,
184 {
185 ...coordinator,
186 id: "worker",
187 childThreadId: "worker-chat",
188 origin: "app_owned",
189 title: "Worker",
190 workflow: undefined,
191 },
192 ],
193 };
194 state.shells = [
195 {
196 environmentId: "remote",
197 source: {
198 id: "workflow-chat",
199 title: "Coordinator chat",
200 lineage: { parentThreadId: "parent", relationshipToParent: "subagent" },
201 activityRunStatus: "waiting",
202 },
203 },
204 ];
205 await render(
206 <ThreadRelationshipsPanel
207 environmentId={EnvironmentId.make("remote")}
208 threadId={ThreadId.make("parent")}
209 />,
210 );
211 await click(byLabel("Expand Checkout review"));
212 const stopButton = () => byLabel("Stop workflow Checkout review");
213 expect(buttonsWithLabel((label) => label.startsWith("Stop "))).toHaveLength(2);
214 let acknowledge!: (result: { _tag: string }) => void;
215 state.workflowCommand.mockImplementationOnce(
216 () =>
217 new Promise((resolve) => {
218 acknowledge = resolve;
219 }),
220 );
221 await click(stopButton());
222 expect(state.workflowCommand).toHaveBeenCalledExactlyOnceWith({
223 environmentId: "remote",
224 input: { threadId: "parent", subagentId: "workflow" },
225 });
226 expect(state.command).not.toHaveBeenCalled();
227 expect(state.navigate).not.toHaveBeenCalled();
228 expect(stopButton().disabled).toBe(true);
229 expect(byLabel("Stop subagent Worker").disabled).toBe(true);
230 expect(byLabel("Open Checker chat")).toBeDefined();
231 expect(heading()).toBe("Lineage · 2 running");
232 await act(async () => {
233 acknowledge({ _tag: "Success" });
234 });
235 expect(stopButton().disabled).toBe(false);
236 expect(heading()).toBe("Lineage · 2 running");
237 state.workflowCommand.mockResolvedValueOnce({ _tag: "Failure" });
238 await click(stopButton());
239 expect(state.toast).toHaveBeenCalledExactlyOnceWith({
240 type: "error",
241 title: "Could not stop workflow",
242 });
243 expect(stopButton().disabled).toBe(false);
244 expect(state.command).not.toHaveBeenCalled();
245 expect(state.navigate).not.toHaveBeenCalled();
246});
247​
248it.each([
249 ["claudeAgent", "provider_native", "completed"],
250 ["claudeAgent", "provider_native", "failed"],
251 ["claudeAgent", "provider_native", "interrupted"],
252 ["claudeAgent", "provider_native", "waiting"],
253 ["codex", "provider_native", "running"],
254 ["claudeAgent", "app_owned", "running"],
255])("does not offer workflow stop for %s %s %s", async (driver, origin, status) => {
256 state.projection = {
257 thread: { id: "parent", lineage: { relationshipToParent: null } },
258 runs: [],
259 providerThreads: [],
260 providerSessions: [],
261 contextTransfers: [],
262 subagents: [
263 {
264 id: "workflow",
265 driver,
266 origin,
267 status,
268 providerInstanceId: "claude-work",
269 childThreadId: "workflow-chat",
270 title: "Checkout review",
271 startedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
272 completedAt: null,
273 updatedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
274 workflow: { name: "Checkout review", phases: [], agents: [] },
275 },
276 ],
277 };
278 await render(
279 <ThreadRelationshipsPanel
280 environmentId={EnvironmentId.make("remote")}
281 threadId={ThreadId.make("parent")}
282 />,
283 );
284 const previousAgents = sectionToggles(false);
285 if (previousAgents.length > 0) await click(previousAgents[0]!);
286 expect(byLabel("Expand Checkout review")).toBeDefined();
287 expect(allByLabel("Stop workflow Checkout review")).toHaveLength(0);
288 expect(state.workflowCommand).not.toHaveBeenCalled();
289});
290​
291it("opens the correct chat for every workflow phase and unphased member", async () => {
292 state.showTooltips = true;
293 state.configs.set("remote", {
294 providers: [
295 {
296 instanceId: "claude-personal",
297 driver: "claudeAgent",
298 displayName: "Personal account",
299 models: [],
300 },
301 {
302 instanceId: "claude-work",
303 driver: "claudeAgent",
304 displayName: "Work account",
305 models: [{ slug: "claude-sonnet-4-6", name: "Sonnet" }],
306 },
307 ],
308 });
309 const phases = ["Inspect", "Improve", "Verify"].map((title, index) => ({ index, title }));
310 const agents = Array.from({ length: 7 }, (_, index) => ({
311 index,
312 label: `Member ${index}`,
313 state:
314 index === 2 ? "cancelled" : index === 4 ? "failed" : index === 5 ? "running" : "completed",
315 ...(index < 6 ? { phaseIndex: Math.floor(index / 2) } : {}),
316 childThreadId: `member-chat-${index}`,
317 model: "claude-sonnet-4-6",
318 result: `Result ${index}`,
319 totalTokens: 1200,
320 startedAt: 1_700_000_000_000 + index * 1000,
321 durationMs: 5000,
322 }));
323 const project = (members: typeof agents) => ({
324 thread: { id: "parent", lineage: { relationshipToParent: null } },
325 runs: [],
326 providerThreads: [],
327 providerSessions: [],
328 contextTransfers: [],
329 subagents: [
330 {
331 id: "workflow",
332 driver: "claudeAgent",
333 providerInstanceId: "claude-work",
334 childThreadId: "workflow-chat",
335 title: "Checkout review",
336 status: "running",
337 startedAt: null,
338 completedAt: null,
339 updatedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
340 workflow: { name: "Checkout review", phases, agents: members },
341 },
342 ],
343 });
344 state.projection = project(agents);
345 const memberShells = agents.map((agent) => ({
346 id: agent.childThreadId,
347 title: agent.label,
348 lineage: { parentThreadId: "workflow-chat", relationshipToParent: "subagent" },
349 status: "completed",
350 activityRunStatus: null,
351 }));
352 state.shells = memberShells.map((source) => ({ environmentId: "other", source }));
353 const panel = (
354 <ThreadRelationshipsPanel
355 environmentId={EnvironmentId.make("remote")}
356 threadId={ThreadId.make("parent")}
357 />
358 );
359 await render(panel);
360 await click(byLabel("Expand Checkout review"));
361 const memberButtons = () => buttonsWithLabel((label) => label.startsWith("Open Member"));
362 const phaseButtons = () =>
363 buttonsWithLabel((label) => label.includes(" phase, ")).filter((button) =>
364 button.hasAttribute("aria-expanded"),
365 );
366 expect(memberButtons()).toHaveLength(3);
367 expect(phaseButtons()).toHaveLength(3);
368 expect(byLabel("Expand Inspect phase, done")).toBeDefined();
369 expect(byLabel("Expand Improve phase, stopped")).toBeDefined();
370 expect(byLabel("Collapse Verify phase, running")).toBeDefined();
371 for (const phase of phaseButtons().slice(0, 2)) await click(phase);
372 expect(memberButtons()).toHaveLength(7);
373 for (const button of memberButtons()) {
374 expect(button.disabled).toBe(true);
375 await click(button);
376 }
377 expect(state.navigate).not.toHaveBeenCalled();
378 state.shells = memberShells.map((source) => ({ environmentId: "remote", source }));
379 await update();
380 for (const button of memberButtons()) expect(button.disabled).toBe(false);
381 for (const agent of agents) {
382 await click(byLabel(`Open ${agent.label} chat`));
383 expect(state.navigate).toHaveBeenLastCalledWith({
384 to: "/$environmentId/$threadId",
385 params: { environmentId: "remote", threadId: agent.childThreadId },
386 });
387 }
388 const rendered = textNodes("|");
389 expect(rendered.match(/Sonnet · Work account/g)).toHaveLength(7);
390 expect(rendered).not.toContain("Personal account");
391 for (const phase of phases) expect(rendered).toContain(phase.title);
392 expect(rendered).not.toContain(" phases");
393 expect(rendered).toContain("1|/|2| |agents");
394 expect(rendered).toContain("Running");
395 expect(rendered).toContain("running");
396 expect(buttonsWithLabel((label) => label.endsWith("phase, done"))).toHaveLength(1);
397 expect(buttonsWithLabel((label) => label.endsWith("phase, stopped"))).toHaveLength(1);
398 expect(rendered).toContain("|6s|");
399 for (const phase of phaseButtons()) {
400 const label = String(phase.getAttribute("aria-label")).slice("Collapse ".length);
401 await click(phase);
402 expect(memberButtons()).toHaveLength(5);
403 await click(byLabel(`Expand ${label}`));
404 expect(memberButtons()).toHaveLength(7);
405 }
406 await click(phaseButtons()[0]!);
407 expect(memberButtons()).toHaveLength(5);
408 const restarted = agents.map((agent) =>
409 agent.index === 0 ? { ...agent, state: "running" } : agent,
410 );
411 state.projection = project(restarted);
412 await update();
413 expect(memberButtons()).toHaveLength(5);
414 state.projection = project(agents);
415 await update();
416 expect(memberButtons()).toHaveLength(5);
417 await click(byLabel("Collapse Checkout review"));
418 expect(memberButtons()).toHaveLength(0);
419 expect(state.navigate).toHaveBeenCalledTimes(7);
420});
421​
422it("groups and counts a workflow by its run status instead of its coordinator chat", async () => {
423 state.showTooltips = true;
424 const coordinator = {
425 id: "workflow",
426 driver: "claudeAgent",
427 providerInstanceId: "claudeAgent",
428 childThreadId: "workflow-chat",
429 title: "Checkout review",
430 status: "running",
431 startedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
432 progress: "Inspecting the checkout workflow",
433 result: "Workflow checks complete",
434 completedAt: null,
435 updatedAt: DateTime.makeUnsafe("2026-09-21T12:00:00Z"),
436 workflow: {
437 name: "Checkout review",
438 phases: [{ index: 0, title: "Inspect" }],
439 agents: [{ index: 0, label: "Checker", state: "running", phaseIndex: 0 }],
440 },
441 };
442 const projection = {
443 thread: { id: "parent", lineage: { relationshipToParent: null } },
444 runs: [],
445 providerThreads: [],
446 providerSessions: [],
447 contextTransfers: [],
448 subagents: [coordinator],
449 };
450 const child = {
451 id: "workflow-chat",
452 title: "Coordinator chat",
453 lineage: { parentThreadId: "parent", relationshipToParent: "subagent" },
454 status: "completed",
455 activityRunStatus: null,
456 };
457 state.projection = projection;
458 state.shells = [{ environmentId: "test", source: child }];
459 const panel = (
460 <ThreadRelationshipsPanel
461 environmentId={EnvironmentId.make("test")}
462 threadId={ThreadId.make("parent")}
463 />
464 );
465 await render(panel);
466 const text = () => textNodes("");
467 expect(heading()).toBe("Lineage · 1 running");
468 await click(byLabel("Expand Checkout review"));
469 expect(byLabel("Open Checker chat")).toBeDefined();
470 state.shells = [{ environmentId: "test", source: { ...child, activityRunStatus: "waiting" } }];
471 await update();
472 expect(heading()).toBe("Lineage · 1 running");
473 expect(text()).toContain("Inspecting the checkout workflow");
474 state.projection = {
475 ...projection,
476 subagents: [
477 {
478 ...coordinator,
479 status: "completed",
480 completedAt: DateTime.makeUnsafe("2026-09-21T12:10:00Z"),
481 },
482 ],
483 };
484 await update();
485 expect(heading()).toBe("Lineage");
486 expect(text()).toContain("Previous agents");
487 expect(allByLabel("Open Checker chat")).toHaveLength(0);
488 await click(sectionToggle(false));
489 expect(byLabel("Expand Checkout review")).toBeDefined();
490 expect(text()).toContain("Workflow checks complete");
491 expect(text()).toContain("10m");
492});
493​
494it.each([
495 { driver: "codex", origin: "app_owned", runId: null, canStop: true },
496 { driver: "claudeAgent", origin: "app_owned", runId: null, canStop: true },
497 { driver: "claudeAgent", origin: "provider_native", runId: "run-1", canStop: true },
498 { driver: "claudeAgent", origin: "provider_native", runId: null, canStop: false },
499])(
500 "offers individual Stop for supported $origin $driver subagents with run $runId",
501 async ({ driver, origin, runId, canStop }) => {
502 const parent = {
503 id: "parent",
504 lineage: { relationshipToParent: null },
505 activeProviderThreadId: null,
506 };
507 const child = {
508 id: "child",
509 title: "Worker",
510 lineage: { parentThreadId: "parent", relationshipToParent: "subagent" },
511 };
512 const agent = {
513 id: "agent",
514 childThreadId: "child",
515 origin,
516 threadId: "parent",
517 runId,
518 nativeTaskRef: { driver, nativeId: "claude-task", strength: "strong" },
519 driver,
520 providerInstanceId: "codex",
521 title: "Worker",
522 prompt: "Check the change",
523 model: "gpt-5.4",
524 status: "running",
525 progress: null,
526 result: null,
527 startedAt: DateTime.makeUnsafe("2026-09-16T12:00:00Z"),
528 completedAt: null,
529 updatedAt: DateTime.makeUnsafe("2026-09-16T12:00:00Z"),
530 };
531 state.shells = [{ environmentId: "test", source: child }];
532 const projection = {
533 thread: parent,
534 runs: [],
535 providerThreads: [],
536 providerSessions: [],
537 contextTransfers: [],
538 subagents: [agent],
539 };
540 state.projection = projection;
541 const panel = (
542 <ThreadRelationshipsPanel
543 environmentId={EnvironmentId.make("test")}
544 threadId={ThreadId.make("parent")}
545 />
546 );
547 await render(panel);
548 if (!canStop) {
549 expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
550 return;
551 }
552 const stopButton = () => byLabel("Stop subagent Worker");
553 await click(stopButton());
554 expect(state.command).toHaveBeenCalledWith({
555 environmentId: "test",
556 input:
557 origin === "provider_native"
558 ? { threadId: "parent", subagentId: "agent" }
559 : { threadId: "child" },
560 });
561 expect(state.navigate).not.toHaveBeenCalled();
562​
563 for (const status of ["starting", "running", "waiting"] as const) {
564 state.command.mockClear();
565 state.shells = [
566 {
567 environmentId: "test",
568 source: {
569 ...child,
570 activityRunStatus: status,
571 activityRunStartedAt: DateTime.makeUnsafe("2026-09-16T12:05:00Z"),
572 },
573 },
574 ];
575 state.projection = {
576 ...projection,
577 subagents: [{ ...agent, origin: "provider_native", status: "completed" }],
578 };
579 await update();
580 expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
581 state.projection = { ...projection, subagents: [{ ...agent, status: "completed" }] };
582 await update();
583 if (origin === "provider_native") {
584 expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
585 continue;
586 }
587 await click(stopButton());
588 expect(state.command).toHaveBeenCalledTimes(1);
589 expect(state.command).toHaveBeenLastCalledWith({
590 environmentId: "test",
591 input: { threadId: "child" },
592 });
593 }
594 state.shells = [{ environmentId: "test", source: child }];
595 for (const status of ["completed", "failed", "interrupted"]) {
596 state.projection = { ...projection, subagents: [{ ...agent, status }] };
597 await update();
598 expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
599 }
600 state.projection = { ...projection, subagents: [{ ...agent, startedAt: null }] };
601 await update();
602 expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
603 state.projection = {
604 ...projection,
605 subagents: [{ ...agent, origin: "provider_native", driver: "codex" }],
606 };
607 await update();
608 expect(allByLabel("Stop subagent Worker")).toHaveLength(0);
609 },
610);
611​
612it("shows the matching child agent details and refreshes them when the agent settles", async () => {
613 const agent = {
614 id: "agent-1",
615 driver: "codex",
616 providerInstanceId: "codex",
617 childThreadId: "child-1",
618 title: "Checker",
619 prompt: "Check the change",
620 model: "gpt-5.4",
621 status: "running",
622 progress: "Running checks",
623 result: null,
624 startedAt: DateTime.makeUnsafe("2026-09-16T12:00:00Z"),
625 completedAt: null,
626 updatedAt: DateTime.makeUnsafe("2026-09-16T12:00:00Z"),
627 };
628 const projection = {
629 thread: {
630 id: "parent",
631 lineage: { relationshipToParent: null },
632 activeProviderThreadId: null,
633 },
634 runs: [],
635 providerThreads: [],
636 providerSessions: [],
637 contextTransfers: [],
638 subagents: [
639 { ...agent, id: "unlinked", childThreadId: null, title: "Unlinked agent" },
640 agent,
641 { ...agent, id: "agent-2", childThreadId: "child-2", title: "Worker", model: "gpt-5.3" },
642 ],
643 };
644 state.projection = projection;
645 const panel = (
646 <ThreadRelationshipsPanel
647 environmentId={EnvironmentId.make("test")}
648 threadId={ThreadId.make("parent")}
649 />
650 );
651 await render(panel);
652 const text = () => textNodes(" ").replace(/\s+/g, " ");
653 expect(text()).toContain("Checker");
654 expect(text()).toContain("Lineage · 3 running");
655 expect(text()).toContain("running");
656 expect(text()).not.toContain("gpt-5.4");
657 expect(text()).not.toContain("gpt-5.3");
658 expect(text()).not.toContain("tok");
659 expect(text()).not.toContain("Unlinked agent");
660 expect(text()).not.toContain("Active agents");
661 expect(sectionToggles(true)).toHaveLength(0);
662​
663 state.projection = {
664 ...projection,
665 subagents: [
666 {
667 ...agent,
668 status: "completed",
669 progress: undefined,
670 result: "All checks passed",
671 completedAt: DateTime.makeUnsafe("2026-09-16T12:02:15Z"),
672 },
673 ],
674 };
675 await update();
676 expect(heading()).toBe("Lineage");
677 expect(text()).toContain("Previous agents (1)");
678 expect(text()).not.toContain("Checker");
679 await click(sectionToggle(false));
680 expect(text()).toContain("Checker");
681 expect(text()).toContain("Checker 2m");
682 expect(text()).not.toContain("(1)");
683 expect(text()).not.toContain("Done");
684 expect(text()).not.toContain("running");
685 expect(text()).not.toContain("Worker");
686 await click(sectionToggle(true));
687 expect(text()).not.toContain("Checker");
688 expect(text()).toContain("Previous agents (1)");
689 await click(sectionToggle(false));
690 expect(text()).toContain("Checker");
691​
692 state.projection = {
693 ...projection,
694 subagents: Array.from({ length: 8 }, (_, index) => ({
695 ...agent,
696 id: `running-agent-${index}`,
697 childThreadId: `running-child-${index}`,
698 })),
699 };
700 await update();
701 expect(text()).toContain("Lineage · 8 running");
702​
703 state.projection = {
704 ...projection,
705 subagents: Array.from({ length: 8 }, (_, index) => ({
706 ...agent,
707 id: `old-agent-${index}`,
708 childThreadId: `old-child-${index}`,
709 status: index === 7 ? "failed" : "completed",
710 title: `Old agent ${index}`,
711 result: index === 7 ? "Earlier build failed" : "Done",
712 completedAt: DateTime.makeUnsafe("2026-09-16T12:02:15Z"),
713 })),
714 };
715 await update();
716 expect(text()).toContain("1 failed");
717 expect(text()).not.toContain("Old agent 7");
718 await click(buttons().find((button) => button.textContent?.startsWith("Show "))!);
719 expect(text()).toContain("Old agent 7");
720​
721 state.projection = {
722 ...projection,
723 subagents: [{ ...agent, childThreadId: null }],
724 };
725 await update();
726 expect(text()).toContain("Lineage · 1 running");
727});
728​
729it("shows readable models and only differing workspace details in agent tooltips", async () => {
730 state.showTooltips = true;
731 const parent = {
732 id: "parent",
733 projectId: "main",
734 worktreePath: null,
735 lineage: {},
736 activeProviderThreadId: null,
737 };
738 const child = {
739 id: "child",
740 projectId: "main",
741 worktreePath: null as string | null,
742 branch: null as string | null,
743 title: "Worker",
744 modelSelection: {
745 instanceId: "codex",
746 model: "gpt-5.4",
747 options: [{ id: "reasoningEffort", value: "high" }] as ModelSelection["options"],
748 },
749 lineage: { parentThreadId: "parent", relationshipToParent: "subagent" },
750 };
751 state.projects = [
752 { id: "main", environmentId: "test", title: "Main", workspaceRoot: "/main" },
753 {
754 id: "other",
755 environmentId: "elsewhere",
756 title: "Wrong environment",
757 workspaceRoot: "/wrong",
758 },
759 { id: "other", environmentId: "test", title: "Other project", workspaceRoot: "/other" },
760 ];
761 state.shells = [{ environmentId: "test", source: child }];
762 state.configs.set("test", {
763 providers: [
764 {
765 instanceId: "codex",
766 driver: "codex",
767 models: [
768 { slug: "gpt-5.4", name: "My GPT model", shortName: "My GPT", aliases: ["model-alias"] },
769 ],
770 },
771 ],
772 });
773 const projection = {
774 thread: parent,
775 runs: [],
776 providerThreads: [],
777 providerSessions: [],
778 contextTransfers: [],
779 subagents: [
780 {
781 id: "agent",
782 childThreadId: "child",
783 origin: "app_owned",
784 driver: "codex",
785 providerInstanceId: "codex",
786 title: "Worker",
787 prompt: "Check",
788 model: "gpt-5.4",
789 status: "pending",
790 startedAt: null,
791 completedAt: null,
792 updatedAt: DateTime.makeUnsafe("2026-09-16T12:00:00Z"),
793 },
794 ],
795 };
796 state.projection = projection;
797 const panel = (
798 <ThreadRelationshipsPanel
799 environmentId={EnvironmentId.make("test")}
800 threadId={ThreadId.make("parent")}
801 />
802 );
803 await render(panel);
804 const text = (visibleOnly = false) => textNodes("", visibleOnly);
805 const rerender = async (source = child) => {
806 // Fresh objects, as real shells are: the compiled component memoizes on identity.
807 state.shells = [
808 {
809 environmentId: "test",
810 source: {
811 ...source,
812 modelSelection: { ...source.modelSelection, options: source.modelSelection.options },
813 },
814 },
815 ];
816 await update();
817 };
818 const nativeProjection = {
819 ...projection,
820 subagents: [{ ...projection.subagents[0], origin: "provider_native" }],
821 };
822 expect(text()).toContain("My GPT · high");
823 state.projection = nativeProjection;
824 await update();
825 expect(text()).toContain("My GPT");
826 expect(text()).not.toContain("My GPT · high");
827 state.projection = projection;
828 await update();
829 expect(text()).not.toContain("Tokens");
830 expect(text()).not.toContain("Open subagent");
831 expect(text()).not.toContain("Project");
832 expect(text()).not.toContain("Worktree");
833 expect(text()).not.toContain("Workspace");
834​
835 for (const [model, expected] of [
836 [null, "Not reported"],
837 ["", "Not reported"],
838 [" ", "Not reported"],
839 ["model-alias", "My GPT"],
840 ["gpt-5.5", "GPT-5.5"],
841 ["custom/model-v1", "custom/model-v1"],
842 ] as const) {
843 state.projection = {
844 ...projection,
845 subagents: [{ ...projection.subagents[0], model }],
846 };
847 await update();
848 expect(text()).toContain(expected);
849 if (!model?.trim() || model === "gpt-5.5" || model === "custom/model-v1") {
850 expect(text()).not.toContain(" · high");
851 } else {
852 expect(text()).toContain(`${expected} · high`);
853 }
854 expect(text()).not.toContain("Unknown");
855 if (!model?.trim()) expect(text()).not.toContain("My GPT");
856 }
857​
858 for (const driver of [
859 "codex",
860 "claudeAgent",
861 "cursor",
862 "opencode",
863 "grok",
864 "antigravity",
865 "pi",
866 "acpRegistry",
867 ]) {
868 state.projection = {
869 ...projection,
870 subagents: [{ ...projection.subagents[0], driver, model: null }],
871 };
872 await update();
873 expect(text()).toContain("Not reported");
874 expect(text()).not.toContain("My GPT");
875 }
876​
877 state.projection = projection;
878 for (const [options, expected] of [
879 [[{ id: "effort", value: "max" }], " · max"],
880 [[{ id: "reasoning", value: "low" }], " · low"],
881 [[{ id: "variant", value: "high" }], " · high"],
882 [[{ id: "reasoningEffort", value: "none" }], " · none"],
883 [[{ id: "reasoningEffort", value: true }], ""],
884 [[{ id: "serviceTier", value: "fast" }], ""],
885 [[], ""],
886 [undefined, ""],
887 ] as const) {
888 child.modelSelection.options = options;
889 await rerender();
890 expect(text()).toContain(`My GPT${expected}`);
891 if (!expected) expect(text()).not.toContain("My GPT ·");
892 }
893 const speedConfig = state.configs.get("test");
894 const serviceTier: ProviderOptionDescriptor = {
895 id: "serviceTier",
896 label: "Service Tier",
897 type: "select",
898 currentValue: "priority",
899 options: [
900 { id: "default", label: "Standard", isDefault: true },
901 { id: "priority", label: "Fast" },
902 { id: "ultrafast", label: "Ultrafast" },
903 { id: "flex", label: "Flex" },
904 ],
905 };
906 const fastMode: ProviderOptionDescriptor = {
907 id: "fastMode",
908 label: "Fast Mode",
909 type: "boolean",
910 currentValue: true,
911 };
912 for (const [driver, descriptor, value, iconLabel] of [
913 ["codex", serviceTier, "default", ""],
914 ["codex", serviceTier, "priority", "Fast mode on"],
915 ["codex", serviceTier, "ultrafast", "Ultrafast mode on"],
916 ["codex", serviceTier, "flex", ""],
917 ["codex", serviceTier, "unknown", ""],
918 [
919 "codex",
920 { ...serviceTier, options: serviceTier.options.filter(({ id }) => id !== "ultrafast") },
921 "ultrafast",
922 "",
923 ],
924 ["codex", serviceTier, true, ""],
925 ["codex", serviceTier, undefined, ""],
926 ["claudeAgent", fastMode, true, "Fast mode on"],
927 ["claudeAgent", fastMode, false, ""],
928 ["cursor", fastMode, true, "Fast mode on"],
929 ["cursor", fastMode, false, ""],
930 ["opencode", fastMode, true, "Fast mode on"],
931 ["cursor", fastMode, "true", ""],
932 ["cursor", serviceTier, "priority", ""],
933 ] as const) {
934 state.configs.set("test", {
935 providers: [
936 {
937 instanceId: "codex",
938 driver,
939 models: [
940 {
941 slug: "gpt-5.4",
942 name: "My GPT",
943 capabilities: { optionDescriptors: [descriptor] },
944 },
945 ],
946 },
947 ],
948 });
949 child.modelSelection.options = [
950 { id: "reasoningEffort", value: "high" },
951 ...(value === undefined ? [] : [{ id: descriptor.id, value }]),
952 ];
953 await rerender();
954 expect(text(true)).toContain("My GPT · high");
955 expect(text(true)).not.toMatch(/Fast|Ultrafast|Normal|Standard|Flex/);
956 expect(text()).toContain(`My GPT · ${iconLabel}high`);
957 if (!iconLabel) expect(text()).not.toContain("mode on");
958 child.modelSelection.options = child.modelSelection.options.filter(
959 ({ id }) => id !== "reasoningEffort",
960 );
961 await rerender();
962 expect(text()).not.toContain(" · high");
963 expect(text(true)).not.toMatch(/Fast|Ultrafast|Normal|Standard|Flex/);
964 if (iconLabel) expect(text()).toContain(iconLabel);
965 else expect(text()).not.toContain("mode on");
966 }
967 state.configs.set("test", {
968 providers: [
969 {
970 instanceId: "codex",
971 driver: "codex",
972 displayName: "Work account",
973 models: [
974 {
975 slug: "gpt-5.4",
976 name: "My GPT",
977 capabilities: { optionDescriptors: [serviceTier] },
978 },
979 ],
980 },
981 {
982 instanceId: "codex_personal",
983 driver: "codex",
984 displayName: "Personal account",
985 models: [],
986 },
987 ],
988 });
989 child.modelSelection.options = [
990 { id: "reasoningEffort", value: "high" },
991 { id: "serviceTier", value: "priority" },
992 ];
993 await rerender();
994 expect(text(true)).toContain("My GPT · Work account · high");
995 expect(text()).toContain("My GPT · Work account · Fast mode onhigh");
996 expect(text()).not.toContain("Personal account");
997 state.projection = nativeProjection;
998 await update();
999 expect(text()).not.toMatch(/Fast|Ultrafast|Normal|Standard|Flex| · high/);
1000 state.projection = projection;
1001 for (const modelSelection of [
1002 { ...child.modelSelection, instanceId: "other" },
1003 { ...child.modelSelection, model: "gpt-5.5" },
1004 ]) {
1005 await rerender({ ...child, modelSelection });
1006 expect(text()).not.toMatch(/Fast|Ultrafast|Normal|Standard|Flex| · high/);
1008 state.shells = [];
1009 for (const status of ["running", "completed", "failed"] as const) {
1010 state.projection = {
1011 ...projection,
1012 subagents: [
1014 ...projection.subagents[0],
1015 origin: "provider_native",
1016 status,
1017 modelSelection: {
1018 instanceId: "codex",
1019 model: "gpt-5.4",
1020 options: [
1021 { id: "reasoningEffort", value: "low" },
1022 { id: "serviceTier", value: "ultrafast" },
1023 ],
1024 },
1025 },
1026 ],
1027 };
1028 await update();
1029 if (status === "completed") {
1030 await click(sectionToggle(false));
1032 expect(text()).toContain("My GPT · Work account · Ultrafast mode onlow");
1033 expect(text()).not.toContain(" · high");
1035 await click(sectionToggle(true));
1036 state.projection = projection;
1037 state.configs.set("test", speedConfig);
1038 child.modelSelection.options = [{ id: "reasoningEffort", value: "high" }];
1039 await rerender({ ...child, modelSelection: { ...child.modelSelection, instanceId: "other" } });
1040 expect(text()).not.toContain("My GPT ·");
1041 const config = state.configs.get("test");
1042 state.configs.clear();
1043 await update();
1044 expect(text()).toContain("GPT-5.4");
1045 expect(text()).not.toContain("GPT-5.4 ·");
1046 await rerender();
1047 expect(text()).toContain("GPT-5.4 · high");
1048 state.configs.set("test", config);
1049 for (const model of ["custom/model-v1", "custom/model-v2"]) {
1050 state.projection = {
1051 ...projection,
1052 subagents: [{ ...projection.subagents[0], model }],
1053 };
1054 await rerender({
1055 ...child,
1056 modelSelection: { ...child.modelSelection, model: "custom/model-v1" },
1057 });
1058 expect(text().includes(`${model} · high`)).toBe(model === "custom/model-v1");
1060​
1061 state.projection = {
1062 ...projection,
1063 subagents: [
1065 ...projection.subagents[0],
1066 progress: "Checking the latest changes",
1067 result: "Old intermediate result",
1068 },
1069 ],
1070 };
1071 await update();
1072 expect(text()).toContain("Checking the latest changes");
1073 expect(text()).not.toContain("Old intermediate result");
1074 const result = "Final checks passed. " + "More detail. ".repeat(50) + "Hidden tail";
1075 state.projection = {
1076 ...projection,
1077 subagents: [
1078 { ...projection.subagents[0], status: "failed", progress: "Stale progress", result },
1079 ],
1080 };
1081 await update();
1082 await click(sectionToggle(false));
1083 expect(text()).toContain("Final checks passed.");
1084 expect(text()).not.toContain("Stale progress");
1085 expect(text()).not.toContain("Hidden tail");
1086 expect(text()).not.toContain(result);
1087 state.projection = projection;
1088​
1089 child.worktreePath = "/main/worktrees/checker";
1090 await rerender();
1091 expect(text()).toContain("Worktree");
1092 expect(text()).toContain("checker");
1093 expect(text()).not.toContain("/main/worktrees");
1094 expect(text()).not.toContain("Project");
1095​
1096 child.branch = "fix/checker";
1097 await rerender();
1098 expect(text()).toContain("Branch");
1099 expect(text()).toContain("fix/checker");
1100 expect(text()).not.toContain("Worktree");
1101 expect(text()).not.toContain("/main/worktrees");
1102​
1103 child.projectId = "other";
1104 child.worktreePath = null;
1105 child.branch = null;
1106 await rerender();
1107 expect(text()).toContain("Other project");
1108 expect(text()).toContain("Workspace");
1109 expect(text()).toContain("other");
1110 expect(text()).not.toContain("/other");
1111 expect(text()).not.toContain("Wrong environment");
1112 expect(text()).not.toContain("Worktree");
1113​
1114 state.shells = [];
1115 state.configs.clear();
1116 await update();
1117 expect(text()).toContain("GPT-5.4");
1118 expect(text()).not.toContain("GPT-5.4 ·");
1119 expect(text()).not.toContain("gpt-5.4");
1120 expect(text()).not.toContain("Project");
1121 expect(text()).not.toContain("Workspace");
1122​
1123 for (const [driver, model, expected] of [
1124 ["codex", "gpt-5.3-codex-spark", "GPT-5.3-Codex-Spark"],
1125 ["codex", "custom/model-v2", "custom/model-v2"],
1126 ["claudeAgent", "gpt-5.4", "GPT-5.4"],
1127 ["claudeAgent", "claude-opus-4-6", "Claude Opus 4.6"],
1128 ["cursor", "composer-2", "Composer 2"],
1129 ["grok", "grok-4-fast", "Grok 4 Fast"],
1130 ["antigravity", "gemini-3.8-flash-high", "Gemini 3.8 Flash High"],
1131 ["opencode", "anthropic/claude-sonnet-4-6", "anthropic/Claude Sonnet 4.6"],
1132 ["codex", null, "Not reported"],
1133 ] as const) {
1134 state.projection = {
1135 ...projection,
1136 subagents: [{ ...projection.subagents[0], driver, model }],
1137 };
1138 await update();
1139 expect(text()).toContain(expected);
1141});
1142​
1143it("shows the parent's own visible status as parent and child activity change", async () => {
1144 const environmentId = EnvironmentId.make("test");
1145 const parent = {
1146 id: "parent",
1147 title: "Parent conversation",
1148 status: "completed",
1149 activityRunStatus: "running",
1150 lineage: { parentThreadId: null, relationshipToParent: null },
1151 };
1152 const child = {
1153 id: "child",
1154 title: "Current fork",
1155 status: "completed",
1156 lineage: { parentThreadId: "parent", relationshipToParent: "fork" },
1157 };
1158 state.projection = {
1159 thread: { ...child, activeProviderThreadId: null },
1160 runs: [],
1161 providerThreads: [],
1162 providerSessions: [],
1163 contextTransfers: [],
1164 subagents: [],
1165 };
1166 const shells = (parentSource: typeof parent, childSource: typeof child) => [
1167 { environmentId, source: parentSource },
1168 { environmentId, source: childSource },
1169 ];
1170 state.shells = shells(parent, child);
1171 const panel = (
1172 <ThreadRelationshipsPanel environmentId={environmentId} threadId={ThreadId.make("child")} />
1173 );
1174 await render(panel);
1175 const visibleText = () => textNodes(" ", true);
1176 expect(visibleText()).toContain("Parent conversation");
1177 expect(visibleText()).toContain("Running");
1178 state.shells = shells(
1179 { ...parent, activityRunStatus: "completed" },
1180 { ...child, status: "running" },
1181 );
1182 await update();
1183 expect(visibleText()).toContain("Done");
1184 expect(visibleText()).not.toContain("Running");
1185});
1186​
1187it.each(["source", "target"])(
1188 "shows transfer lifecycle states when viewing the %s thread",
1189 async (currentThreadId) => {
1190 const environmentId = EnvironmentId.make("test");
1191 const threads = ["source", "target"].map((id) => ({
1192 id,
1193 title: `${id} conversation`,
1194 status: "running",
1195 activityRunStatus: "running",
1196 lineage: { parentThreadId: null, relationshipToParent: null },
1197 }));
1198 state.shells = threads.map((source) => ({ environmentId, source }));
1199 const labels: Record<OrchestrationV2ContextTransfer["status"], string> = {
1200 pending: "Queued",
1201 resolved_native: "Resolved (native)",
1202 resolved_portable: "Resolved (portable)",
1203 failed: "Failed",
1204 consumed: "Consumed",
1205 superseded: "Superseded",
1206 };
1207 const panel = (
1208 <ThreadRelationshipsPanel
1209 environmentId={environmentId}
1210 threadId={ThreadId.make(currentThreadId)}
1211 />
1212 );
1213 for (const [status, label] of Object.entries(labels)) {
1214 state.projection = {
1215 thread: {
1216 ...threads.find((thread) => thread.id === currentThreadId),
1217 activeProviderThreadId: null,
1218 },
1219 runs: [],
1220 providerThreads: [],
1221 providerSessions: [],
1222 subagents: [],
1223 contextTransfers: [{ sourceThreadId: "source", targetThreadId: "target", status }],
1224 };
1225 if (status === "pending") await render(panel);
1226 else await update();
1227 const visibleText = textNodes(" ");
1228 expect(visibleText).toContain(
1229 currentThreadId === "source" ? "target conversation" : "source conversation",
1230 );
1231 expect(visibleText).toContain(label);
1232 expect(visibleText).not.toContain("Unknown");
1233 expect(visibleText).not.toContain("Running");
1235 },