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

ThreadRelationshipsControl.browser.test.tsx

596 lines20.1 KB

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 { fakeTimers, 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 };
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("shows how long a running remote subagent has been running, as a local one does", async () => {
409 setup();
410 const remoteTitle = "Remote subagent running on a linked machine";
411 using _timers = fakeTimers();
412 vi.setSystemTime(new Date("2026-11-23T12:12:00.000Z"));
413 const startedAt = DateTime.makeUnsafe("2026-11-23T12:00:00.000Z");
414 state.projection = {
415 ...(state.projection as Record<string, unknown>),
416 subagents: [
417 {
418 id: NodeId.make("remote-agent"),
419 threadId,
420 runId: null,
421 parentNodeId: NodeId.make("parent"),
422 origin: "app_owned",
423 createdBy: "agent",
424 driver: "remote",
425 providerInstanceId: "provider",
426 providerThreadId: null,
427 childThreadId: null,
428 nativeTaskRef: null,
429 prompt: "Run remote task",
430 title: remoteTitle,
431 model: null,
432 status: "running",
433 result: null,
434 startedAt,
435 completedAt: null,
436 updatedAt: startedAt,
437 remoteChild: {
438 environmentId: EnvironmentId.make("remote-env"),
439 threadId: ThreadId.make("remote-thread"),
440 label: "127x05",
441 },
442 },
443 ],
444 };
445 await using screen = await render(
446 <ThreadRelationshipsPanel
447 environmentId={environmentId}
448 threadId={threadId}
449 showLineage
450 showSideChats={false}
451 />,
452 { router: "/environment/fork" },
453 );
454​
455 // Assert synchronously: expect.element polls on timers this test fakes.
456 const row = screen.getByRole("button", { name: new RegExp(remoteTitle) });
457 expect(row.element().textContent).toContain("12m");
458});
459​
460it("explains why Merge back is unavailable before the fork completes a run", async () => {
461 setup();
462 state.projection = { ...(state.projection as Record<string, unknown>), runs: [] };
463 await using screen = await render(
464 <ThreadRelationshipsPanel
465 environmentId={environmentId}
466 threadId={threadId}
467 showLineage
468 showSideChats={false}
469 />,
470 { router: "/environment/fork" },
471 );
472​
473 const mergeBack = screen.getByRole("button", { name: "Merge back to source conversation" });
474 await userEvent.hover(mergeBack);
475 await vi.waitFor(() =>
476 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(
477 "Complete a run in this fork before merging it back",
478 ),
479 );
480​
481 state.commandSucceeds = true;
482 await mergeBack.click({ force: true });
483 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
484});
485​
486it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => {
487 setup();
488 const longTitle = "Parent task delegated from another machine that has a long description";
489 state.projection = {
490 ...(state.projection as Record<string, unknown>),
491 thread: {
492 ...(state.projection as { thread: Record<string, unknown> }).thread,
493 delegatedFrom: {
494 environmentId: EnvironmentId.make("parent-env"),
495 threadId: ThreadId.make("parent-thread"),
496 title: longTitle,
497 },
498 },
499 };
500 await using screen = await render(
501 <ThreadRelationshipsPanel
502 environmentId={environmentId}
503 threadId={threadId}
504 showLineage
505 showSideChats={false}
506 />,
507 { router: "/environment/fork" },
508 );
509​
510 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
511 await userEvent.hover(row);
512 await vi.waitFor(() =>
513 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
514 );
515 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
516 "Delegated from a linked environment. Connect to it to open the parent thread.",
517 );
518​
519 await row.click({ force: true });
520 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
521});
522​
523it("hides a deleted fork and keeps unloaded and archived forks with their current titles", async () => {
524 setup();
525 const projection = makeThreadProjectionFixture();
526 state.threadTitles = { "unloaded-fork": "Unloaded fork", "archived-fork": "Archived fork" };
527 state.archivedThreads = [
528 {
529 ...projection.thread,
530 id: ThreadId.make("archived-fork"),
531 title: "Old archived title",
532 archivedAt: projection.thread.updatedAt,
533 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "fork" },
534 },
535 ];
536 state.projection = {
537 ...projection,
538 contextTransfers: ["deleted-fork", "unloaded-fork", "archived-fork"].map((id) => ({
539 sourceThreadId: projection.thread.id,
540 targetThreadId: ThreadId.make(id),
541 status: "pending",
542 })),
543 };
544 await using screen = await render(
545 <ThreadRelationshipsPanel
546 environmentId={environmentId}
547 threadId={projection.thread.id}
548 showLineage
549 showSideChats
550 />,
551 );
552 await expect.element(screen.getByText("Unloaded fork", { exact: true })).toBeVisible();
553 await expect.element(screen.getByText("Archived fork", { exact: true })).toBeVisible();
554 await expect.element(screen.getByText("deleted-fork", { exact: true })).not.toBeInTheDocument();
555});
556​
557it.each([1, 18])("continues scrolling the panel past a list of %i subagents", async (count) => {
558 setup();
559 const projection = makeThreadProjectionFixture();
560 state.projection = projection;
561 state.relatedShells = Array.from({ length: count }, (_, index) => ({
562 id: ThreadId.make(`subagent-${index}`),
563 title: `Subagent ${index}`,
564 forkedFrom: null,
565 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "subagent" },
566 activityRunStatus: "running",
567 status: "running",
568 }));
569 await using screen = await render(
570 <div data-testid="panel" style={{ height: 320, width: 280 }}>
571 <ScrollArea>
572 <ThreadRelationshipsPanel
573 environmentId={environmentId}
574 threadId={projection.thread.id}
575 showLineage
576 showSideChats
577 />
578 <div style={{ height: 600 }} />
579 </ScrollArea>
580 </div>,
581 );
582 if (count > 6) {
583 await screen.getByRole("button", { name: "Show 12 more" }).click();
584 await expect.element(screen.getByText("Subagent 17", { exact: true })).toBeInTheDocument();
585 }
586 const list = screen.getByRole("list", { name: "Related threads" }).element();
587 const viewport = screen
588 .getByTestId("panel")
589 .element()
590 .querySelector<HTMLElement>("[data-slot=scroll-area-viewport]")!;
591 list.scrollTop = list.scrollHeight;
592 if (count > 6) expect(list.scrollTop).toBeGreaterThan(0);
593 viewport.scrollTop = 0;
594 await userEvent.wheel(list, { delta: { y: 300 } });
595 await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0));
596});