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