Open History to see the last commit
1import "~/index.css";
2import * as DateTime from "effect/DateTime";
3import { EnvironmentId, NodeId, ThreadId } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import { AsyncResult } from "effect/reactivity";
6import { expect, it, vi } from "vite-plus/test";
7import { page, userEvent } from "vite-plus/test/browser";
8
9import "~/index.css";
10
11const state = vi.hoisted(() => ({
12 projection: null as unknown,
13 commandSucceeds: false,
14 relatedShells: [] as unknown[],
15 threadTitles: {} as Record<string, string>,
16 archivedThreads: [] as unknown[],
17}));
18
19vi.mock(import("../../state/query"), async (original) => ({
20 ...(await original()),
21 useEnvironmentQuery: ((atom: unknown) =>
22 atom === null
23 ? { data: null, isSuccess: false, isPending: false }
24 : { data: state.threadTitles, isSuccess: true, isPending: false }) as never,
25}));
26
27vi.mock(import("@effect/atom-react"), async (original) => ({
28 ...(await original()),
29 useAtomValue: (() => false) as never,
30}));
31
32vi.mock(import("../../state/entities"), () => ({
33 useQuietThreadShell: (() => null) as never,
34 useQuietThreadProjection: ((ref: unknown) =>
35 ref === null ? null : { projection: state.projection }) as never,
36 useThreadRelationshipShells: (() =>
37 state.projection === null
38 ? []
39 : [(state.projection as { thread: unknown }).thread, ...state.relatedShells]) as never,
40 useProjects: (() => []) as never,
41 useHiddenThreadKeys: (() => new Set()) as never,
42 useAnyEnvironmentHiding: (() => false) as never,
43}));
44vi.mock(import("../../state/environments"), () => ({
45 // The click rule reads the client setting, whose module asks for these.
46 useEnvironments: (() => []) as never,
47 usePrimaryEnvironment: (() => null) as never,
48 useEnvironment: (() => null) as never,
49 useEnvironmentProviders: (() => new Map()) as never,
50}));
51vi.mock(import("../../state/peerLinks"), () => ({
52 peerLinkEnvironment: { readThread: {} } as never,
53 useLinkedEnvironments: (() => new Map()) as never,
54}));
55vi.mock(import("../../lib/archivedThreadsState"), () => ({
56 useArchivedThreadSnapshots: (() => ({
57 snapshots: [{ environmentId: "environment", snapshot: { threads: state.archivedThreads } }],
58 })) as never,
59}));
60vi.mock(import("../../state/use-atom-command"), () => ({
61 useAtomCommand: (() => async () =>
62 state.commandSucceeds
63 ? AsyncResult.success(undefined)
64 : AsyncResult.failure(Cause.fail(new Error("Connection lost")))) as never,
65}));
66
67import { scopeThreadRef } from "@t3tools/client-runtime/environment";
68
69import { render } from "../../../test/render";
70import { isMacPlatform } from "../../lib/utils";
71import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
72import { makeThreadProjectionFixture } from "../../test-fixtures";
73import { ScrollArea } from "../ui/scroll-area";
74import { ToastProvider } from "../ui/toast";
75import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
76
77const environmentId = EnvironmentId.make("environment");
78const threadId = ThreadId.make("fork");
79
80function setup() {
81 useRightPanelStore.setState(useRightPanelStore.getInitialState());
82 state.commandSucceeds = false;
83 state.relatedShells = [];
84 state.threadTitles = { source: "Source" };
85 state.archivedThreads = [];
86 state.projection = {
87 thread: {
88 id: threadId,
89 title: "Fork",
90 activeProviderThreadId: null,
91 lineage: { parentThreadId: ThreadId.make("source"), relationshipToParent: "fork" },
92 forkedFrom: null,
93 },
94 runs: [{ id: "run", ordinal: 1, status: "completed" }],
95 subagents: [],
96 contextTransfers: [],
97 providerThreads: [],
98 providerSessions: [{ id: "session", status: "ready" }],
99 };
100}
101
102it.each([
103 ["merge", "Could not merge back"],
104 ["disconnect", "Could not disconnect agent session"],
105])("reports a rejected %s command and clears the busy state", async (action, title) => {
106 setup();
107 await using screen = await render(
108 <ToastProvider timeout={0}>
109 <ThreadRelationshipsPanel
110 environmentId={environmentId}
111 threadId={threadId}
112 showLineage
113 showSideChats
114 />
115 </ToastProvider>,
116 );
117
118 if (action === "merge") {
119 await screen.getByRole("button", { name: "Merge back to source conversation" }).click();
120 } else {
121 await screen.getByRole("button", { name: "More thread actions" }).click();
122 await page.getByRole("menuitem", { name: "Disconnect agent session" }).click();
123 }
124
125 await expect.element(page.getByText(title, { exact: true })).toBeVisible();
126 await expect
127 .element(
128 screen.getByRole("button", {
129 name: action === "merge" ? "Merge back to source conversation" : "More thread actions",
130 }),
131 )
132 .toBeEnabled();
133});
134
135it.each([
136 ["merge", "Could not merge back"],
137 ["disconnect", "Could not disconnect agent session"],
138])("clears the previous %s error after a successful retry", async (action, title) => {
139 setup();
140 await using screen = await render(
141 <ToastProvider timeout={0}>
142 <ThreadRelationshipsPanel
143 environmentId={environmentId}
144 threadId={threadId}
145 showLineage
146 showSideChats
147 />
148 </ToastProvider>,
149 { router: "/environment/fork" },
150 );
151
152 const runAction = async () => {
153 if (action === "merge") {
154 await screen.getByRole("button", { name: "Merge back to source conversation" }).click();
155 } else {
156 await screen.getByRole("button", { name: "More thread actions" }).click();
157 await page.getByRole("menuitem", { name: "Disconnect agent session" }).click();
158 }
159 };
160
161 await runAction();
162 await expect.element(page.getByText(title, { exact: true })).toBeVisible();
163 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
164
165 state.commandSucceeds = true;
166 await runAction();
167
168 await expect.element(page.getByText(title, { exact: true })).not.toBeInTheDocument();
169 await vi.waitFor(() => {
170 expect(screen.router?.state.location.pathname).toBe(
171 action === "merge" ? "/environment/source" : "/environment/fork",
172 );
173 });
174 if (action === "disconnect") {
175 await expect.element(screen.getByRole("button", { name: "More thread actions" })).toBeEnabled();
176 }
177});
178
179it("opens an idle child beside the thread, and in its place with the modifier", async () => {
180 setup();
181 const projection = makeThreadProjectionFixture();
182 const childId = ThreadId.make("omitted-child");
183 const environmentId = EnvironmentId.make("local");
184 state.projection = {
185 ...projection,
186 subagents: [
187 {
188 id: NodeId.make("agent"),
189 threadId: projection.thread.id,
190 runId: null,
191 parentNodeId: NodeId.make("parent"),
192 origin: "app_owned",
193 createdBy: "agent",
194 driver: "codex",
195 providerInstanceId: projection.thread.providerInstanceId,
196 providerThreadId: null,
197 childThreadId: childId,
198 nativeTaskRef: null,
199 prompt: "Inspect the change",
200 title: "Idle child",
201 model: null,
202 status: "completed",
203 result: null,
204 startedAt: null,
205 completedAt: projection.thread.updatedAt,
206 updatedAt: projection.thread.updatedAt,
207 },
208 ],
209 };
210 await using screen = await render(
211 <ThreadRelationshipsPanel
212 environmentId={environmentId}
213 threadId={projection.thread.id}
214 showLineage
215 showSideChats
216 />,
217 );
218 await screen.getByRole("button", { name: /Previous agents/ }).click();
219 const child = screen.getByRole("button", { name: /Idle child/ });
220 await expect.element(child).toBeEnabled();
221 const panelRef = scopeThreadRef(environmentId, projection.thread.id);
222 const panel = () =>
223 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, panelRef);
224 await child.click();
225 expect(panel()).toMatchObject({
226 isOpen: true,
227 activeSurfaceId: "thread:omitted-child",
228 surfaces: [{ kind: "thread", threadId: childId }],
229 });
230 expect(screen.router?.state.location.pathname).toBe("/");
231 // Idle children can be omitted from the shell; the route loads the child's own detail.
232 await child.click({ modifiers: [isMacPlatform(navigator.platform) ? "Meta" : "Control"] });
233 await vi.waitFor(() =>
234 expect(screen.router?.state.location.pathname).toBe("/local/omitted-child"),
235 );
236 expect(panel().surfaces).toHaveLength(1);
237});
238
239it("keeps focus on the list when Show more pages reveal the last rows", async () => {
240 setup();
241 const projection = makeThreadProjectionFixture();
242 const environmentId = EnvironmentId.make("local");
243 const { updatedAt } = projection.thread;
244 state.projection = {
245 ...projection,
246 subagents: Array.from({ length: 7 }, (_, index) => ({
247 id: NodeId.make(`agent-${index}`),
248 threadId: projection.thread.id,
249 runId: null,
250 parentNodeId: NodeId.make("parent"),
251 origin: "app_owned",
252 createdBy: "agent",
253 driver: "codex",
254 providerInstanceId: projection.thread.providerInstanceId,
255 providerThreadId: null,
256 childThreadId: ThreadId.make(`omitted-child-${index}`),
257 nativeTaskRef: null,
258 prompt: `Inspect the change part ${index}`,
259 title: `Agent ${index}`,
260 model: null,
261 status: "completed",
262 result: null,
263 startedAt: null,
264 completedAt: updatedAt,
265 updatedAt,
266 })),
267 };
268 await using screen = await render(
269 <ThreadRelationshipsPanel
270 environmentId={environmentId}
271 threadId={projection.thread.id}
272 showLineage
273 showSideChats
274 />,
275 );
276 await screen.getByRole("button", { name: /Previous agents/ }).click();
277 await screen.getByRole("button", { name: "Show 1 more" }).click();
278 await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus();
279});
280
281it("shows a lineage thread's full title in its tooltip", async () => {
282 setup();
283 const longTitle = "Compare the lineage tooltip against a title that the row truncates";
284 const sourceThread = {
285 ...(state.projection as { thread: Record<string, unknown> }).thread,
286 id: "source",
287 title: longTitle,
288 lineage: { parentThreadId: null, relationshipToParent: null },
289 };
290 state.relatedShells = [sourceThread];
291 await using _screen = await render(
292 <ThreadRelationshipsPanel
293 environmentId={environmentId}
294 threadId={threadId}
295 showLineage
296 showSideChats={false}
297 />,
298 );
299
300 await userEvent.hover(page.getByText(longTitle, { exact: true }));
301 await vi.waitFor(() =>
302 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
303 );
304});
305
306it("shows a side chat's full title in its tooltip", async () => {
307 setup();
308 const longTitle = "Side chat question with a title that the side chat row truncates";
309 state.relatedShells = [
310 {
311 id: "side",
312 title: longTitle,
313 lineage: {
314 parentThreadId: threadId,
315 relationshipToParent: "fork",
316 rootThreadId: threadId,
317 sideChat: true,
318 },
319 },
320 ];
321 await using _screen = await render(
322 <ThreadRelationshipsPanel
323 environmentId={environmentId}
324 threadId={threadId}
325 showLineage={false}
326 showSideChats
327 />,
328 );
329
330 await userEvent.hover(page.getByText(longTitle, { exact: true }));
331 await vi.waitFor(() =>
332 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
333 );
334});
335
336it("shows a remote subagent's full title in its tooltip even when its environment is unavailable", async () => {
337 setup();
338 const longTitle = "Investigate a remote subagent issue across linked environments";
339 const remoteEnvId = EnvironmentId.make("remote-env");
340 const remoteThreadId = ThreadId.make("remote-thread");
341 const now = DateTime.makeUnsafe("2026-10-31T20:00:00.000Z");
342 state.projection = {
343 ...(state.projection as Record<string, unknown>),
344 subagents: [
345 {
346 id: NodeId.make("remote-agent"),
347 threadId,
348 runId: null,
349 parentNodeId: NodeId.make("parent"),
350 origin: "app_owned",
351 createdBy: "agent",
352 driver: "codex",
353 providerInstanceId: "provider",
354 providerThreadId: null,
355 childThreadId: null,
356 nativeTaskRef: null,
357 prompt: "Run remote task",
358 title: longTitle,
359 model: null,
360 status: "completed",
361 result: null,
362 startedAt: null,
363 completedAt: null,
364 updatedAt: now,
365 remoteChild: {
366 environmentId: remoteEnvId,
367 threadId: remoteThreadId,
368 label: "Remote VM with a long machine name in the office",
369 },
370 },
371 ],
372 };
373 await using screen = await render(
374 <div style={{ width: 320 }}>
375 <ThreadRelationshipsPanel
376 environmentId={environmentId}
377 threadId={threadId}
378 showLineage
379 showSideChats={false}
380 />
381 </div>,
382 { router: "/environment/fork" },
383 );
384
385 // A finished remote task sits with the other finished agents, not in its own list.
386 await expect
387 .element(screen.getByRole("button", { name: new RegExp(longTitle) }))
388 .not.toBeInTheDocument();
389 await screen.getByRole("button", { name: /Previous agents/ }).click();
390 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
391 // A long environment label must not squeeze the title out of the row.
392 expect(
393 page.getByText(longTitle, { exact: true }).element().getBoundingClientRect().width,
394 ).toBeGreaterThan(0);
395 await userEvent.hover(row);
396 await vi.waitFor(() =>
397 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
398 );
399 // This client is not connected there, so the row reads the thread through this environment.
400 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
401 "Read the thread on Remote VM with a long machine name in the office",
402 );
403
404 await row.click({ force: true });
405 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
406});
407
408it("explains why Merge back is unavailable before the fork completes a run", async () => {
409 setup();
410 state.projection = { ...(state.projection as Record<string, unknown>), runs: [] };
411 await using screen = await render(
412 <ThreadRelationshipsPanel
413 environmentId={environmentId}
414 threadId={threadId}
415 showLineage
416 showSideChats={false}
417 />,
418 { router: "/environment/fork" },
419 );
420
421 const mergeBack = screen.getByRole("button", { name: "Merge back to source conversation" });
422 await userEvent.hover(mergeBack);
423 await vi.waitFor(() =>
424 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(
425 "Complete a run in this fork before merging it back",
426 ),
427 );
428
429 state.commandSucceeds = true;
430 await mergeBack.click({ force: true });
431 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
432});
433
434it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => {
435 setup();
436 const longTitle = "Parent task delegated from another machine that has a long description";
437 state.projection = {
438 ...(state.projection as Record<string, unknown>),
439 thread: {
440 ...(state.projection as { thread: Record<string, unknown> }).thread,
441 delegatedFrom: {
442 environmentId: EnvironmentId.make("parent-env"),
443 threadId: ThreadId.make("parent-thread"),
444 title: longTitle,
445 },
446 },
447 };
448 await using screen = await render(
449 <ThreadRelationshipsPanel
450 environmentId={environmentId}
451 threadId={threadId}
452 showLineage
453 showSideChats={false}
454 />,
455 { router: "/environment/fork" },
456 );
457
458 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
459 await userEvent.hover(row);
460 await vi.waitFor(() =>
461 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
462 );
463 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
464 "Delegated from a linked environment. Connect to it to open the parent thread.",
465 );
466
467 await row.click({ force: true });
468 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
469});
470
471it("hides a deleted fork and keeps unloaded and archived forks with their current titles", async () => {
472 setup();
473 const projection = makeThreadProjectionFixture();
474 state.threadTitles = { "unloaded-fork": "Unloaded fork", "archived-fork": "Archived fork" };
475 state.archivedThreads = [
476 {
477 ...projection.thread,
478 id: ThreadId.make("archived-fork"),
479 title: "Old archived title",
480 archivedAt: projection.thread.updatedAt,
481 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "fork" },
482 },
483 ];
484 state.projection = {
485 ...projection,
486 contextTransfers: ["deleted-fork", "unloaded-fork", "archived-fork"].map((id) => ({
487 sourceThreadId: projection.thread.id,
488 targetThreadId: ThreadId.make(id),
489 status: "pending",
490 })),
491 };
492 await using screen = await render(
493 <ThreadRelationshipsPanel
494 environmentId={environmentId}
495 threadId={projection.thread.id}
496 showLineage
497 showSideChats
498 />,
499 );
500 await expect.element(screen.getByText("Unloaded fork", { exact: true })).toBeVisible();
501 await expect.element(screen.getByText("Archived fork", { exact: true })).toBeVisible();
502 await expect.element(screen.getByText("deleted-fork", { exact: true })).not.toBeInTheDocument();
503});
504
505it.each([1, 18])("continues scrolling the panel past a list of %i subagents", async (count) => {
506 setup();
507 const projection = makeThreadProjectionFixture();
508 state.projection = projection;
509 state.relatedShells = Array.from({ length: count }, (_, index) => ({
510 id: ThreadId.make(`subagent-${index}`),
511 title: `Subagent ${index}`,
512 forkedFrom: null,
513 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "subagent" },
514 activityRunStatus: "running",
515 status: "running",
516 }));
517 await using screen = await render(
518 <div data-testid="panel" style={{ height: 320, width: 280 }}>
519 <ScrollArea>
520 <ThreadRelationshipsPanel
521 environmentId={environmentId}
522 threadId={projection.thread.id}
523 showLineage
524 showSideChats
525 />
526 <div style={{ height: 600 }} />
527 </ScrollArea>
528 </div>,
529 );
530 if (count > 6) {
531 await screen.getByRole("button", { name: "Show 12 more" }).click();
532 await expect.element(screen.getByText("Subagent 17", { exact: true })).toBeInTheDocument();
533 }
534 const list = screen.getByRole("list", { name: "Related threads" }).element();
535 const viewport = screen
536 .getByTestId("panel")
537 .element()
538 .querySelector<HTMLElement>("[data-slot=scroll-area-viewport]")!;
539 list.scrollTop = list.scrollHeight;
540 if (count > 6) expect(list.scrollTop).toBeGreaterThan(0);
541 viewport.scrollTop = 0;
542 await userEvent.wheel(list, { delta: { y: 300 } });
543 await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0));
544});