Open History to see the last commit
1import "~/index.css";
2import * as DateTime from "effect/DateTime";
3import {
4 EnvironmentId,
5 NodeId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 ThreadId,
9 type OrchestrationV2ThreadFamily,
10 type OrchestrationV2ThreadProjection,
11 type ServerProvider,
12} from "@t3tools/contracts";
13import * as Cause from "effect/Cause";
14import { AsyncResult } from "effect/reactivity";
15import { expect, it, vi } from "vite-plus/test";
16import { page, userEvent } from "vite-plus/test/browser";
17
18import "~/index.css";
19
20const state = vi.hoisted(() => ({
21 projection: null as unknown,
22 commandSucceeds: false,
23 relatedShells: [] as unknown[],
24 remoteShells: new Map<string, { title: string }>(),
25 connectedEnvironment: null as EnvironmentId | null,
26 family: null as OrchestrationV2ThreadFamily | null,
27 familyQuery: {},
28 providers: new Map<EnvironmentId, ReadonlyArray<ServerProvider>>(),
29 threadTitles: {} as Record<string, string>,
30 archivedThreads: [] as unknown[],
31}));
32
33vi.mock(import("../../state/query"), async (original) => ({
34 ...(await original()),
35 useEnvironmentQuery: ((atom: unknown) =>
36 atom === null
37 ? { data: null, isSuccess: false, isPending: false }
38 : {
39 data: atom === state.familyQuery ? state.family : state.threadTitles,
40 isSuccess: true,
41 isPending: false,
42 }) as never,
43}));
44
45vi.mock(import("../../state/orchestration"), async (original) => {
46 const actual = await original();
47 return {
48 ...actual,
49 orchestrationEnvironment: {
50 ...actual.orchestrationEnvironment,
51 threadFamily: () => state.familyQuery as never,
52 },
53 };
54});
55
56vi.mock(import("@effect/atom-react"), async (original) => ({
57 ...(await original()),
58 useAtomValue: (() => false) as never,
59}));
60
61vi.mock(import("../../state/entities"), () => ({
62 useReopenedRemoteTasks: () => new Set(),
63 useQuietThreadShell: ((ref: { environmentId: EnvironmentId; threadId: ThreadId } | null) =>
64 ref ? (state.remoteShells.get(`${ref.environmentId}/${ref.threadId}`) ?? null) : null) as never,
65 useQuietThreadProjection: ((ref: unknown) =>
66 ref === null ? null : { projection: state.projection }) as never,
67 useThreadRelationshipShells: (() =>
68 state.projection === null
69 ? []
70 : [(state.projection as { thread: unknown }).thread, ...state.relatedShells]) as never,
71 useProjects: (() => []) as never,
72 useHiddenThreadKeys: (() => new Set()) as never,
73 useAnyEnvironmentHiding: (() => false) as never,
74}));
75vi.mock(import("../../state/environments"), () => ({
76 // The click rule reads the client setting, whose module asks for these.
77 useEnvironments: (() => []) as never,
78 usePrimaryEnvironment: (() => null) as never,
79 useEnvironment: ((id: EnvironmentId | null) =>
80 id !== null && id === state.connectedEnvironment
81 ? { label: "Linked machine", connection: { phase: "connected" } }
82 : null) as never,
83 useEnvironmentProviders: () => state.providers,
84}));
85vi.mock(import("../../state/peerLinks"), () => ({
86 peerLinkEnvironment: { readThread: {} } as never,
87 useLinkedEnvironments: (() => new Map()) as never,
88}));
89vi.mock(import("../../lib/archivedThreadsState"), () => ({
90 useArchivedThreadSnapshots: (() => ({
91 snapshots: [{ environmentId: "environment", snapshot: { threads: state.archivedThreads } }],
92 })) as never,
93}));
94vi.mock(import("../../state/use-atom-command"), () => ({
95 useAtomCommand: (() => async () =>
96 state.commandSucceeds
97 ? AsyncResult.success(undefined)
98 : AsyncResult.failure(Cause.fail(new Error("Connection lost")))) as never,
99}));
100
101import { scopeThreadRef } from "@t3tools/client-runtime/environment";
102
103import { act, fakeTimers, render } from "../../../test/render";
104import { isMacPlatform } from "../../lib/utils";
105import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
106import { makeThreadFixture, makeThreadProjectionFixture } from "../../test-fixtures";
107import { ScrollArea } from "../ui/scroll-area";
108import { ToastProvider } from "../ui/toast";
109import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
110
111const environmentId = EnvironmentId.make("environment");
112const threadId = ThreadId.make("fork");
113
114function setup() {
115 useRightPanelStore.setState(useRightPanelStore.getInitialState());
116 state.commandSucceeds = false;
117 state.relatedShells = [];
118 state.remoteShells.clear();
119 state.connectedEnvironment = null;
120 state.family = null;
121 state.providers = new Map();
122 state.threadTitles = { source: "Source" };
123 state.archivedThreads = [];
124 state.projection = {
125 thread: {
126 id: threadId,
127 title: "Fork",
128 activeProviderThreadId: null,
129 lineage: { parentThreadId: ThreadId.make("source"), relationshipToParent: "fork" },
130 forkedFrom: null,
131 },
132 runs: [{ id: "run", ordinal: 1, status: "completed" }],
133 subagents: [],
134 contextTransfers: [],
135 providerThreads: [],
136 providerSessions: [{ id: "session", status: "ready" }],
137 };
138}
139
140it.each([
141 ["merge", "Could not merge back"],
142 ["disconnect", "Could not disconnect agent session"],
143])("reports a rejected %s command and clears the busy state", async (action, title) => {
144 setup();
145 await using screen = await render(
146 <ToastProvider timeout={0}>
147 <ThreadRelationshipsPanel
148 environmentId={environmentId}
149 threadId={threadId}
150 showLineage
151 showSideChats
152 />
153 </ToastProvider>,
154 );
155
156 if (action === "merge") {
157 await screen.getByRole("button", { name: "Merge back to source conversation" }).click();
158 } else {
159 await screen.getByRole("button", { name: "More thread actions" }).click();
160 await page.getByRole("menuitem", { name: "Disconnect agent session" }).click();
161 }
162
163 await expect.element(page.getByText(title, { exact: true })).toBeVisible();
164 await expect
165 .element(
166 screen.getByRole("button", {
167 name: action === "merge" ? "Merge back to source conversation" : "More thread actions",
168 }),
169 )
170 .toBeEnabled();
171});
172
173it.each([
174 ["merge", "Could not merge back"],
175 ["disconnect", "Could not disconnect agent session"],
176])("clears the previous %s error after a successful retry", async (action, title) => {
177 setup();
178 await using screen = await render(
179 <ToastProvider timeout={0}>
180 <ThreadRelationshipsPanel
181 environmentId={environmentId}
182 threadId={threadId}
183 showLineage
184 showSideChats
185 />
186 </ToastProvider>,
187 { router: "/environment/fork" },
188 );
189
190 const runAction = async () => {
191 if (action === "merge") {
192 await screen.getByRole("button", { name: "Merge back to source conversation" }).click();
193 } else {
194 await screen.getByRole("button", { name: "More thread actions" }).click();
195 await page.getByRole("menuitem", { name: "Disconnect agent session" }).click();
196 }
197 };
198
199 await runAction();
200 await expect.element(page.getByText(title, { exact: true })).toBeVisible();
201 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
202
203 state.commandSucceeds = true;
204 await runAction();
205
206 await expect.element(page.getByText(title, { exact: true })).not.toBeInTheDocument();
207 await vi.waitFor(() => {
208 expect(screen.router?.state.location.pathname).toBe(
209 action === "merge" ? "/environment/source" : "/environment/fork",
210 );
211 });
212 if (action === "disconnect") {
213 await expect.element(screen.getByRole("button", { name: "More thread actions" })).toBeEnabled();
214 }
215});
216
217it("opens an idle child beside the thread, and in its place with the modifier", async () => {
218 setup();
219 const projection = makeThreadProjectionFixture();
220 const childId = ThreadId.make("omitted-child");
221 const environmentId = EnvironmentId.make("local");
222 state.projection = {
223 ...projection,
224 subagents: [
225 {
226 id: NodeId.make("agent"),
227 threadId: projection.thread.id,
228 runId: null,
229 parentNodeId: NodeId.make("parent"),
230 origin: "app_owned",
231 createdBy: "agent",
232 driver: "codex",
233 providerInstanceId: projection.thread.providerInstanceId,
234 providerThreadId: null,
235 childThreadId: childId,
236 nativeTaskRef: null,
237 prompt: "Inspect the change",
238 title: "Idle child",
239 model: null,
240 status: "completed",
241 result: null,
242 startedAt: null,
243 completedAt: projection.thread.updatedAt,
244 updatedAt: projection.thread.updatedAt,
245 },
246 ],
247 };
248 await using screen = await render(
249 <ThreadRelationshipsPanel
250 environmentId={environmentId}
251 threadId={projection.thread.id}
252 showLineage
253 showSideChats
254 />,
255 );
256 await screen.getByRole("button", { name: /Previous agents/ }).click();
257 const child = screen.getByRole("button", { name: /Idle child/ });
258 await expect.element(child).toBeEnabled();
259 const panelRef = scopeThreadRef(environmentId, projection.thread.id);
260 const panel = () =>
261 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, panelRef);
262 await child.click();
263 expect(panel()).toMatchObject({
264 isOpen: true,
265 activeSurfaceId: "thread:omitted-child",
266 surfaces: [{ kind: "thread", threadId: childId }],
267 });
268 expect(screen.router?.state.location.pathname).toBe("/");
269 // Idle children can be omitted from the shell; the route loads the child's own detail.
270 await child.click({ modifiers: [isMacPlatform(navigator.platform) ? "Meta" : "Control"] });
271 await vi.waitFor(() =>
272 expect(screen.router?.state.location.pathname).toBe("/local/omitted-child"),
273 );
274 expect(panel().surfaces).toHaveLength(1);
275});
276
277it("keeps focus on the list when Show more pages reveal the last rows", async () => {
278 setup();
279 const projection = makeThreadProjectionFixture();
280 const environmentId = EnvironmentId.make("local");
281 const { updatedAt } = projection.thread;
282 state.projection = {
283 ...projection,
284 subagents: Array.from({ length: 7 }, (_, index) => ({
285 id: NodeId.make(`agent-${index}`),
286 threadId: projection.thread.id,
287 runId: null,
288 parentNodeId: NodeId.make("parent"),
289 origin: "app_owned",
290 createdBy: "agent",
291 driver: "codex",
292 providerInstanceId: projection.thread.providerInstanceId,
293 providerThreadId: null,
294 childThreadId: ThreadId.make(`omitted-child-${index}`),
295 nativeTaskRef: null,
296 prompt: `Inspect the change part ${index}`,
297 title: `Agent ${index}`,
298 model: null,
299 status: "completed",
300 result: null,
301 startedAt: null,
302 completedAt: updatedAt,
303 updatedAt,
304 })),
305 };
306 await using screen = await render(
307 <ThreadRelationshipsPanel
308 environmentId={environmentId}
309 threadId={projection.thread.id}
310 showLineage
311 showSideChats
312 />,
313 );
314 await screen.getByRole("button", { name: /Previous agents/ }).click();
315 await screen.getByRole("button", { name: "Show 1 more" }).click();
316 await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus();
317});
318
319it("shows a lineage thread's full title in its tooltip", async () => {
320 setup();
321 const longTitle = "Compare the lineage tooltip against a title that the row truncates";
322 const sourceThread = {
323 ...(state.projection as { thread: Record<string, unknown> }).thread,
324 id: "source",
325 title: longTitle,
326 lineage: { parentThreadId: null, relationshipToParent: null },
327 };
328 state.relatedShells = [sourceThread];
329 await using _screen = await render(
330 <ThreadRelationshipsPanel
331 environmentId={environmentId}
332 threadId={threadId}
333 showLineage
334 showSideChats={false}
335 />,
336 );
337
338 await userEvent.hover(page.getByText(longTitle, { exact: true }));
339 await vi.waitFor(() =>
340 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
341 );
342});
343
344it("shows the current Fast mode while a child runs and after its shell is omitted", async () => {
345 setup();
346 const projection = makeThreadProjectionFixture();
347 const childId = ThreadId.make("opus-child");
348 const instanceId = ProviderInstanceId.make("claudeAgent");
349 const model = "claude-opus-5-5";
350 const title = "Opus child";
351 const selection = (fastMode: boolean) => ({
352 instanceId,
353 model,
354 options: [{ id: "fastMode", value: fastMode }],
355 });
356 const provider: ServerProvider = {
357 instanceId,
358 driver: ProviderDriverKind.make("claudeAgent"),
359 enabled: true,
360 installed: true,
361 version: null,
362 status: "ready",
363 auth: { status: "authenticated" },
364 checkedAt: DateTime.formatIso(projection.thread.updatedAt),
365 models: [
366 {
367 slug: model,
368 name: "Opus 5.5",
369 isCustom: false,
370 capabilities: {
371 optionDescriptors: [{ id: "fastMode", label: "Fast", type: "boolean" }],
372 },
373 },
374 ],
375 slashCommands: [],
376 skills: [],
377 };
378 state.providers.set(environmentId, [provider]);
379 const running = {
380 ...projection,
381 subagents: [
382 {
383 id: NodeId.make("agent"),
384 threadId: projection.thread.id,
385 runId: null,
386 parentNodeId: NodeId.make("parent"),
387 childThreadId: childId,
388 providerThreadId: null,
389 nativeTaskRef: null,
390 prompt: "Inspect the change",
391 title,
392 origin: "app_owned",
393 createdBy: "agent",
394 status: "running",
395 driver: provider.driver,
396 providerInstanceId: instanceId,
397 model,
398 modelSelection: selection(false),
399 result: null,
400 startedAt: projection.thread.updatedAt,
401 completedAt: null,
402 updatedAt: projection.thread.updatedAt,
403 },
404 ],
405 } satisfies OrchestrationV2ThreadProjection;
406 state.projection = running;
407 const childShell = (fastMode: boolean) =>
408 makeThreadFixture({
409 id: childId,
410 title,
411 providerInstanceId: instanceId,
412 modelSelection: selection(fastMode),
413 lineage: {
414 parentThreadId: projection.thread.id,
415 rootThreadId: projection.thread.id,
416 relationshipToParent: "subagent",
417 },
418 }).source;
419 const panel = () => (
420 <ThreadRelationshipsPanel
421 environmentId={environmentId}
422 threadId={projection.thread.id}
423 showLineage
424 showSideChats={false}
425 />
426 );
427
428 state.relatedShells = [childShell(true)];
429 await using screen = await render(panel());
430 await userEvent.hover(screen.getByText(title, { exact: true }));
431 const popup = page.getByText("Opus 5.5", { exact: true });
432 const fast = page.getByText("Fast mode on", { exact: true });
433 await expect.element(fast).toBeInTheDocument();
434
435 state.relatedShells = [childShell(false)];
436 await screen.rerender(panel());
437 await expect.element(popup).toBeVisible();
438 await expect.element(fast).not.toBeInTheDocument();
439
440 state.relatedShells = [childShell(true)];
441 await screen.rerender(panel());
442 await expect.element(fast).toBeInTheDocument();
443
444 state.projection = {
445 ...running,
446 subagents: running.subagents.map((agent) => ({
447 ...agent,
448 status: "completed",
449 completedAt: projection.thread.updatedAt,
450 })),
451 } satisfies OrchestrationV2ThreadProjection;
452 state.relatedShells = [];
453 state.family = { snapshotSequence: 1, threads: [childShell(true)] };
454 await screen.rerender(panel());
455 await screen.getByRole("button", { name: /Previous agents/ }).click();
456 await userEvent.hover(screen.getByText(title, { exact: true }));
457 await expect.element(fast).toBeInTheDocument();
458});
459
460it("shows a side chat's full title in its tooltip", async () => {
461 setup();
462 const longTitle = "Side chat question with a title that the side chat row truncates";
463 state.relatedShells = [
464 {
465 id: "side",
466 title: longTitle,
467 lineage: {
468 parentThreadId: threadId,
469 relationshipToParent: "fork",
470 rootThreadId: threadId,
471 sideChat: true,
472 },
473 },
474 ];
475 await using _screen = await render(
476 <ThreadRelationshipsPanel
477 environmentId={environmentId}
478 threadId={threadId}
479 showLineage={false}
480 showSideChats
481 />,
482 );
483
484 await userEvent.hover(page.getByText(longTitle, { exact: true }));
485 await vi.waitFor(() =>
486 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
487 );
488});
489
490it("shows a remote subagent's current title and falls back when disconnected", async () => {
491 setup();
492 const longTitle = "Investigate a remote subagent issue across linked environments";
493 const remoteEnvId = EnvironmentId.make("remote-env");
494 const remoteThreadId = ThreadId.make("remote-thread");
495 const now = DateTime.makeUnsafe("2026-10-31T20:00:00.000Z");
496 state.projection = {
497 ...(state.projection as Record<string, unknown>),
498 subagents: [
499 {
500 id: NodeId.make("remote-agent"),
501 threadId,
502 runId: null,
503 parentNodeId: NodeId.make("parent"),
504 origin: "app_owned",
505 createdBy: "agent",
506 driver: "codex",
507 providerInstanceId: "provider",
508 providerThreadId: null,
509 childThreadId: null,
510 nativeTaskRef: null,
511 prompt: "Run remote task",
512 title: longTitle,
513 model: null,
514 status: "completed",
515 result: null,
516 startedAt: null,
517 completedAt: null,
518 updatedAt: now,
519 remoteChild: {
520 environmentId: remoteEnvId,
521 threadId: remoteThreadId,
522 label: "Remote VM with a long machine name in the office",
523 },
524 },
525 ],
526 };
527 const panel = () => (
528 <div style={{ width: 320 }}>
529 <ThreadRelationshipsPanel
530 environmentId={environmentId}
531 threadId={threadId}
532 showLineage
533 showSideChats={false}
534 />
535 </div>
536 );
537 await using screen = await render(panel(), { router: "/environment/fork" });
538
539 // A finished remote task sits with the other finished agents, not in its own list.
540 await expect
541 .element(screen.getByRole("button", { name: new RegExp(longTitle) }))
542 .not.toBeInTheDocument();
543 await screen.getByRole("button", { name: /Previous agents/ }).click();
544 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
545 // A long environment label must not squeeze the title out of the row.
546 expect(
547 page.getByText(longTitle, { exact: true }).element().getBoundingClientRect().width,
548 ).toBeGreaterThan(0);
549 await userEvent.hover(row);
550 await vi.waitFor(() =>
551 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
552 );
553 // This client is not connected there, so the row reads the thread through this environment.
554 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
555 "Read the thread on Remote VM with a long machine name in the office",
556 );
557
558 await row.click({ force: true });
559 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
560
561 const renamed = "Renamed remote child";
562 state.connectedEnvironment = remoteEnvId;
563 state.remoteShells.set(`${remoteEnvId}/${remoteThreadId}`, { title: renamed });
564 await screen.rerender(panel());
565 const renamedRow = screen.getByRole("button", { name: new RegExp(renamed) });
566 await expect.element(renamedRow).toBeVisible();
567 await userEvent.hover(screen.getByRole("button", { name: /Previous agents/ }));
568 await userEvent.hover(renamedRow);
569 await vi.waitFor(() =>
570 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(renamed),
571 );
572
573 state.remoteShells.clear();
574 state.threadTitles[remoteThreadId] = "Renamed idle remote child";
575 await screen.rerender(panel());
576 await expect
577 .element(screen.getByRole("button", { name: /Renamed idle remote child/ }))
578 .toBeVisible();
579});
580
581it("shows how long a running remote subagent has been running, as a local one does", async () => {
582 setup();
583 const remoteTitle = "Remote subagent running on a linked machine";
584 using _timers = fakeTimers();
585 vi.setSystemTime(new Date("2026-11-23T12:12:00.000Z"));
586 const startedAt = DateTime.makeUnsafe("2026-11-23T12:00:00.000Z");
587 state.projection = {
588 ...(state.projection as Record<string, unknown>),
589 subagents: [
590 {
591 id: NodeId.make("remote-agent"),
592 threadId,
593 runId: null,
594 parentNodeId: NodeId.make("parent"),
595 origin: "app_owned",
596 createdBy: "agent",
597 driver: "remote",
598 providerInstanceId: "provider",
599 providerThreadId: null,
600 childThreadId: null,
601 nativeTaskRef: null,
602 prompt: "Run remote task",
603 title: remoteTitle,
604 model: null,
605 status: "running",
606 result: null,
607 startedAt,
608 completedAt: null,
609 updatedAt: startedAt,
610 remoteChild: {
611 environmentId: EnvironmentId.make("remote-env"),
612 threadId: ThreadId.make("remote-thread"),
613 label: "127x05",
614 },
615 },
616 ],
617 };
618 await using screen = await render(
619 <ThreadRelationshipsPanel
620 environmentId={environmentId}
621 threadId={threadId}
622 showLineage
623 showSideChats={false}
624 />,
625 { router: "/environment/fork" },
626 );
627
628 // Assert synchronously: expect.element polls on timers this test fakes.
629 const row = screen.getByRole("button", { name: new RegExp(remoteTitle) });
630 expect(row.element().textContent).toContain("12m");
631});
632
633it("explains why Merge back is unavailable before the fork completes a run", async () => {
634 setup();
635 state.projection = { ...(state.projection as Record<string, unknown>), runs: [] };
636 await using screen = await render(
637 <ThreadRelationshipsPanel
638 environmentId={environmentId}
639 threadId={threadId}
640 showLineage
641 showSideChats={false}
642 />,
643 { router: "/environment/fork" },
644 );
645
646 const mergeBack = screen.getByRole("button", { name: "Merge back to source conversation" });
647 await userEvent.hover(mergeBack);
648 await vi.waitFor(() =>
649 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(
650 "Complete a run in this fork before merging it back",
651 ),
652 );
653
654 state.commandSucceeds = true;
655 await mergeBack.click({ force: true });
656 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
657});
658
659it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => {
660 setup();
661 const longTitle = "Parent task delegated from another machine that has a long description";
662 state.projection = {
663 ...(state.projection as Record<string, unknown>),
664 thread: {
665 ...(state.projection as { thread: Record<string, unknown> }).thread,
666 delegatedFrom: {
667 environmentId: EnvironmentId.make("parent-env"),
668 threadId: ThreadId.make("parent-thread"),
669 title: longTitle,
670 },
671 },
672 };
673 await using screen = await render(
674 <ThreadRelationshipsPanel
675 environmentId={environmentId}
676 threadId={threadId}
677 showLineage
678 showSideChats={false}
679 />,
680 { router: "/environment/fork" },
681 );
682
683 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
684 await userEvent.hover(row);
685 await vi.waitFor(() =>
686 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
687 );
688 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
689 "Delegated from a linked environment. Connect to it to open the parent thread.",
690 );
691
692 await row.click({ force: true });
693 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
694});
695
696it("hides a deleted fork and keeps unloaded and archived forks with their current titles", async () => {
697 setup();
698 const projection = makeThreadProjectionFixture();
699 state.threadTitles = { "unloaded-fork": "Unloaded fork", "archived-fork": "Archived fork" };
700 state.archivedThreads = [
701 {
702 ...projection.thread,
703 id: ThreadId.make("archived-fork"),
704 title: "Old archived title",
705 archivedAt: projection.thread.updatedAt,
706 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "fork" },
707 },
708 ];
709 state.projection = {
710 ...projection,
711 contextTransfers: ["deleted-fork", "unloaded-fork", "archived-fork"].map((id) => ({
712 sourceThreadId: projection.thread.id,
713 targetThreadId: ThreadId.make(id),
714 status: "pending",
715 })),
716 };
717 await using screen = await render(
718 <ThreadRelationshipsPanel
719 environmentId={environmentId}
720 threadId={projection.thread.id}
721 showLineage
722 showSideChats
723 />,
724 );
725 await expect.element(screen.getByText("Unloaded fork", { exact: true })).toBeVisible();
726 await expect.element(screen.getByText("Archived fork", { exact: true })).toBeVisible();
727 await expect.element(screen.getByText("deleted-fork", { exact: true })).not.toBeInTheDocument();
728});
729
730it("shares the hover delay between adjacent lineage rows", async () => {
731 setup();
732 state.relatedShells = [
733 { id: "source", title: "First agent", lineage: { parentThreadId: null } },
734 {
735 id: "child",
736 title: "Second agent",
737 lineage: { parentThreadId: threadId, relationshipToParent: "fork", sideChat: false },
738 },
739 ];
740 await using screen = await render(
741 <ThreadRelationshipsPanel
742 environmentId={environmentId}
743 threadId={threadId}
744 showLineage
745 showSideChats={false}
746 />,
747 );
748 using _timers = fakeTimers();
749 const first = screen.getByRole("button", { name: /^First agent/ });
750 const second = screen.getByRole("button", { name: /^Second agent/ });
751 await userEvent.hover(first);
752 await act(() => vi.advanceTimersByTime(200));
753 expect(first.element()).toHaveAttribute("data-popup-open");
754 await userEvent.hover(second);
755 await act(() => vi.advanceTimersByTime(1));
756 expect(second.element()).toHaveAttribute("data-popup-open");
757});
758
759it.each([1, 18])("continues scrolling the panel past a list of %i subagents", async (count) => {
760 setup();
761 const projection = makeThreadProjectionFixture();
762 state.projection = projection;
763 state.relatedShells = Array.from({ length: count }, (_, index) => ({
764 id: ThreadId.make(`subagent-${index}`),
765 title: `Subagent ${index}`,
766 forkedFrom: null,
767 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "subagent" },
768 activityRunStatus: "running",
769 status: "running",
770 }));
771 await using screen = await render(
772 <div data-testid="panel" style={{ height: 320, width: 280 }}>
773 <ScrollArea>
774 <ThreadRelationshipsPanel
775 environmentId={environmentId}
776 threadId={projection.thread.id}
777 showLineage
778 showSideChats
779 />
780 <div style={{ height: 600 }} />
781 </ScrollArea>
782 </div>,
783 );
784 if (count > 6) {
785 await screen.getByRole("button", { name: "Show 12 more" }).click();
786 await expect.element(screen.getByText("Subagent 17", { exact: true })).toBeInTheDocument();
787 }
788 const list = screen.getByRole("list", { name: "Related threads" }).element();
789 const viewport = screen
790 .getByTestId("panel")
791 .element()
792 .querySelector<HTMLElement>("[data-slot=scroll-area-viewport]")!;
793 list.scrollTop = list.scrollHeight;
794 if (count > 6) expect(list.scrollTop).toBeGreaterThan(0);
795 viewport.scrollTop = 0;
796 await userEvent.wheel(list, { delta: { y: 300 } });
797 await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0));
798});
799
800function makeSwitchedProviders() {
801 const claudeId = ProviderInstanceId.make("claude_pool");
802 const gemini1Id = ProviderInstanceId.make("antigravity");
803 const gemini2Id = ProviderInstanceId.make("antigravity_2");
804 const providers: ReadonlyArray<ServerProvider> = [
805 {
806 instanceId: claudeId,
807 driver: ProviderDriverKind.make("claudeAgent"),
808 displayName: "Claude",
809 enabled: true,
810 installed: true,
811 version: "1.0.0",
812 status: "ready",
813 auth: { status: "authenticated" },
814 checkedAt: "2026-01-01T00:00:00.000Z",
815 models: [
816 { slug: "claude-opus-5-5", name: "Claude Opus 5.5", isCustom: false, capabilities: null },
817 ],
818 slashCommands: [],
819 skills: [],
820 },
821 {
822 instanceId: gemini1Id,
823 driver: ProviderDriverKind.make("antigravity"),
824 displayName: "Gemini 1",
825 enabled: true,
826 installed: true,
827 version: "1.0.0",
828 status: "ready",
829 auth: { status: "authenticated" },
830 checkedAt: "2026-01-01T00:00:00.000Z",
831 models: [
832 { slug: "gemini-4-neon", name: "Gemini 4 Neon", isCustom: false, capabilities: null },
833 ],
834 slashCommands: [],
835 skills: [],
836 },
837 {
838 instanceId: gemini2Id,
839 driver: ProviderDriverKind.make("antigravity"),
840 displayName: "Gemini 2",
841 enabled: true,
842 installed: true,
843 version: "1.0.0",
844 status: "ready",
845 auth: { status: "authenticated" },
846 checkedAt: "2026-01-01T00:00:00.000Z",
847 models: [
848 { slug: "gemini-4-neon", name: "Gemini 4 Neon", isCustom: false, capabilities: null },
849 ],
850 slashCommands: [],
851 skills: [],
852 },
853 ];
854 return { claudeId, gemini2Id, providers };
855}
856
857it("updates the lineage row icon, badge, and hover card when a delegated child switches providers, including when omitted from the shell", async () => {
858 setup();
859 const projection = makeThreadProjectionFixture();
860 const childId = ThreadId.make("switched-child");
861 const title = "Switched child";
862 const { claudeId, gemini2Id, providers } = makeSwitchedProviders();
863 state.providers.set(environmentId, providers);
864 const completedOnClaude = {
865 ...projection,
866 subagents: [
867 {
868 id: NodeId.make("task:switched"),
869 threadId: projection.thread.id,
870 runId: null,
871 parentNodeId: NodeId.make("node:parent"),
872 createdBy: "agent",
873 prompt: "Work",
874 origin: "app_owned",
875 driver: ProviderDriverKind.make("claudeAgent"),
876 providerInstanceId: claudeId,
877 providerThreadId: null,
878 childThreadId: childId,
879 nativeTaskRef: null,
880 title,
881 model: "claude-opus-5-5",
882 modelSelection: { instanceId: claudeId, model: "claude-opus-5-5" },
883 status: "completed",
884 result: "done",
885 startedAt: projection.thread.createdAt,
886 completedAt: projection.thread.updatedAt,
887 updatedAt: projection.thread.updatedAt,
888 },
889 ],
890 } satisfies OrchestrationV2ThreadProjection;
891 const switchedChildShell = (status: "running" | "completed") => ({
892 ...makeThreadFixture({
893 id: childId,
894 title,
895 providerInstanceId: gemini2Id,
896 modelSelection: { instanceId: gemini2Id, model: "gemini-4-neon" },
897 lineage: {
898 parentThreadId: projection.thread.id,
899 rootThreadId: projection.thread.id,
900 relationshipToParent: "subagent",
901 },
902 }).source,
903 status,
904 activityRunStatus: status === "running" ? ("running" as const) : null,
905 });
906
907 state.projection = completedOnClaude;
908 state.relatedShells = [switchedChildShell("running")];
909 const panel = () => (
910 <ThreadRelationshipsPanel
911 environmentId={environmentId}
912 threadId={projection.thread.id}
913 showLineage
914 showSideChats={false}
915 />
916 );
917 await using screen = await render(panel());
918
919 const activeRow = screen.getByRole("button", { name: new RegExp(title) });
920 await expect.element(activeRow).toBeVisible();
921 expect(activeRow.element().textContent).toContain("G2");
922 expect(activeRow.element().querySelector('svg[viewBox="0 0 128 128"] image')).not.toBeNull();
923
924 // Once idle and omitted from the shell, expanding Previous agents loads the family
925 // so the row icon, badge, and hover card reflect Antigravity (G2) instead of Claude.
926 state.relatedShells = [];
927 state.family = { snapshotSequence: 2, threads: [switchedChildShell("completed")] };
928 await screen.rerender(panel());
929 await screen.getByRole("button", { name: /Previous agents/ }).click();
930 const previousRow = screen.getByRole("button", { name: new RegExp(title) });
931 await expect.element(previousRow).toBeVisible();
932 expect(previousRow.element().textContent).toContain("G2");
933 expect(previousRow.element().querySelector('svg[viewBox="0 0 128 128"] image')).not.toBeNull();
934
935 await userEvent.hover(previousRow);
936 await vi.waitFor(() => {
937 const popup = document.querySelector('[data-slot="tooltip-popup"]');
938 expect(popup?.textContent).toContain("4 Neon · Gemini 2");
939 expect(popup?.querySelector('svg[viewBox="0 0 128 128"] image')).not.toBeNull();
940 });
941});