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

ThreadRelationshipsControl.browser.test.tsx

451 lines15.0 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 useEnvironment: (() => null) as never,
46 useEnvironmentProviders: (() => new Map()) as never,
47}));
48vi.mock(import("../../lib/archivedThreadsState"), () => ({
49 useArchivedThreadSnapshots: (() => ({
50 snapshots: [{ environmentId: "environment", snapshot: { threads: state.archivedThreads } }],
51 })) as never,
52}));
53vi.mock(import("../../state/use-atom-command"), () => ({
54 useAtomCommand: (() => async () =>
55 state.commandSucceeds
56 ? AsyncResult.success(undefined)
57 : AsyncResult.failure(Cause.fail(new Error("Connection lost")))) as never,
58}));
59​
60import { render } from "../../../test/render";
61import { makeThreadProjectionFixture } from "../../test-fixtures";
62import { ScrollArea } from "../ui/scroll-area";
63import { ToastProvider } from "../ui/toast";
64import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
65​
66const environmentId = EnvironmentId.make("environment");
67const threadId = ThreadId.make("fork");
68​
69function setup() {
70 state.commandSucceeds = false;
71 state.relatedShells = [];
72 state.threadTitles = { source: "Source" };
73 state.archivedThreads = [];
74 state.projection = {
75 thread: {
76 id: threadId,
77 title: "Fork",
78 activeProviderThreadId: null,
79 lineage: { parentThreadId: ThreadId.make("source"), relationshipToParent: "fork" },
80 forkedFrom: null,
81 },
82 runs: [{ id: "run", ordinal: 1, status: "completed" }],
83 subagents: [],
84 contextTransfers: [],
85 providerThreads: [],
86 providerSessions: [{ id: "session", status: "ready" }],
87 };
89​
90it.each([
91 ["merge", "Could not merge back"],
92 ["disconnect", "Could not disconnect agent session"],
93])("reports a rejected %s command and clears the busy state", async (action, title) => {
94 setup();
95 await using screen = await render(
96 <ToastProvider timeout={0}>
97 <ThreadRelationshipsPanel
98 environmentId={environmentId}
99 threadId={threadId}
100 showLineage
101 showSideChats
102 />
103 </ToastProvider>,
104 );
105​
106 if (action === "merge") {
107 await screen.getByRole("button", { name: "Merge back to source conversation" }).click();
108 } else {
109 await screen.getByRole("button", { name: "More thread actions" }).click();
110 await page.getByRole("menuitem", { name: "Disconnect agent session" }).click();
111 }
112​
113 await expect.element(page.getByText(title, { exact: true })).toBeVisible();
114 await expect
115 .element(
116 screen.getByRole("button", {
117 name: action === "merge" ? "Merge back to source conversation" : "More thread actions",
118 }),
119 )
120 .toBeEnabled();
121});
122​
123it.each([
124 ["merge", "Could not merge back"],
125 ["disconnect", "Could not disconnect agent session"],
126])("clears the previous %s error after a successful retry", async (action, title) => {
127 setup();
128 await using screen = await render(
129 <ToastProvider timeout={0}>
130 <ThreadRelationshipsPanel
131 environmentId={environmentId}
132 threadId={threadId}
133 showLineage
134 showSideChats
135 />
136 </ToastProvider>,
137 { router: "/environment/fork" },
138 );
139​
140 const runAction = async () => {
141 if (action === "merge") {
142 await screen.getByRole("button", { name: "Merge back to source conversation" }).click();
143 } else {
144 await screen.getByRole("button", { name: "More thread actions" }).click();
145 await page.getByRole("menuitem", { name: "Disconnect agent session" }).click();
146 }
147 };
148​
149 await runAction();
150 await expect.element(page.getByText(title, { exact: true })).toBeVisible();
151 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
152​
153 state.commandSucceeds = true;
154 await runAction();
155​
156 await expect.element(page.getByText(title, { exact: true })).not.toBeInTheDocument();
157 await vi.waitFor(() => {
158 expect(screen.router?.state.location.pathname).toBe(
159 action === "merge" ? "/environment/source" : "/environment/fork",
160 );
161 });
162 if (action === "disconnect") {
163 await expect.element(screen.getByRole("button", { name: "More thread actions" })).toBeEnabled();
164 }
165});
166​
167it("opens an idle child from Lineage when its shell has not been loaded", async () => {
168 setup();
169 const projection = makeThreadProjectionFixture();
170 const childId = ThreadId.make("omitted-child");
171 const environmentId = EnvironmentId.make("local");
172 state.projection = {
173 ...projection,
174 subagents: [
175 {
176 id: NodeId.make("agent"),
177 threadId: projection.thread.id,
178 runId: null,
179 parentNodeId: NodeId.make("parent"),
180 origin: "app_owned",
181 createdBy: "agent",
182 driver: "codex",
183 providerInstanceId: projection.thread.providerInstanceId,
184 providerThreadId: null,
185 childThreadId: childId,
186 nativeTaskRef: null,
187 prompt: "Inspect the change",
188 title: "Idle child",
189 model: null,
190 status: "completed",
191 result: null,
192 startedAt: null,
193 completedAt: projection.thread.updatedAt,
194 updatedAt: projection.thread.updatedAt,
195 },
196 ],
197 };
198 await using screen = await render(
199 <ThreadRelationshipsPanel
200 environmentId={environmentId}
201 threadId={projection.thread.id}
202 showLineage
203 showSideChats
204 />,
205 );
206 await screen.getByRole("button", { name: /Previous agents/ }).click();
207 const child = screen.getByRole("button", { name: /Idle child/ });
208 await expect.element(child).toBeEnabled();
209 await child.click();
210 await vi.waitFor(() =>
211 expect(screen.router?.state.location.pathname).toBe("/local/omitted-child"),
212 );
213});
214​
215it("shows a lineage thread's full title in its tooltip", async () => {
216 setup();
217 const longTitle = "Compare the lineage tooltip against a title that the row truncates";
218 const sourceThread = {
219 ...(state.projection as { thread: Record<string, unknown> }).thread,
220 id: "source",
221 title: longTitle,
222 lineage: { parentThreadId: null, relationshipToParent: null },
223 };
224 state.relatedShells = [sourceThread];
225 await using _screen = await render(
226 <ThreadRelationshipsPanel
227 environmentId={environmentId}
228 threadId={threadId}
229 showLineage
230 showSideChats={false}
231 />,
232 );
233​
234 await userEvent.hover(page.getByText(longTitle, { exact: true }));
235 await vi.waitFor(() =>
236 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
237 );
238});
239​
240it("shows a side chat's full title in its tooltip", async () => {
241 setup();
242 const longTitle = "Side chat question with a title that the side chat row truncates";
243 state.relatedShells = [
244 {
245 id: "side",
246 title: longTitle,
247 lineage: {
248 parentThreadId: threadId,
249 relationshipToParent: "fork",
250 rootThreadId: threadId,
251 sideChat: true,
252 },
253 },
254 ];
255 await using _screen = await render(
256 <ThreadRelationshipsPanel
257 environmentId={environmentId}
258 threadId={threadId}
259 showLineage={false}
260 showSideChats
261 />,
262 );
263​
264 await userEvent.hover(page.getByText(longTitle, { exact: true }));
265 await vi.waitFor(() =>
266 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
267 );
268});
269​
270it("shows a remote subagent's full title in its tooltip even when its environment is unavailable", async () => {
271 setup();
272 const longTitle = "Investigate a remote subagent issue across linked environments";
273 const remoteEnvId = EnvironmentId.make("remote-env");
274 const remoteThreadId = ThreadId.make("remote-thread");
275 const now = DateTime.makeUnsafe("2026-10-31T20:00:00.000Z");
276 state.projection = {
277 ...(state.projection as Record<string, unknown>),
278 subagents: [
279 {
280 id: NodeId.make("remote-agent"),
281 threadId,
282 runId: null,
283 parentNodeId: NodeId.make("parent"),
284 origin: "app_owned",
285 createdBy: "agent",
286 driver: "codex",
287 providerInstanceId: "provider",
288 providerThreadId: null,
289 childThreadId: null,
290 nativeTaskRef: null,
291 prompt: "Run remote task",
292 title: longTitle,
293 model: null,
294 status: "completed",
295 result: null,
296 startedAt: null,
297 completedAt: null,
298 updatedAt: now,
299 remoteChild: {
300 environmentId: remoteEnvId,
301 threadId: remoteThreadId,
302 label: "Remote VM with a long machine name in the office",
303 },
304 },
305 ],
306 };
307 await using screen = await render(
308 <div style={{ width: 320 }}>
309 <ThreadRelationshipsPanel
310 environmentId={environmentId}
311 threadId={threadId}
312 showLineage
313 showSideChats={false}
314 />
315 </div>,
316 { router: "/environment/fork" },
317 );
318​
319 // A finished remote task sits with the other finished agents, not in its own list.
320 await expect
321 .element(screen.getByRole("button", { name: new RegExp(longTitle) }))
322 .not.toBeInTheDocument();
323 await screen.getByRole("button", { name: /Previous agents/ }).click();
324 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
325 // A long environment label must not squeeze the title out of the row.
326 expect(
327 page.getByText(longTitle, { exact: true }).element().getBoundingClientRect().width,
328 ).toBeGreaterThan(0);
329 await userEvent.hover(row);
330 await vi.waitFor(() =>
331 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
332 );
333 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
334 "Runs on Remote VM with a long machine name in the office. Connect to it to open the thread there.",
335 );
336​
337 await row.click({ force: true });
338 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
339});
340​
341it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => {
342 setup();
343 const longTitle = "Parent task delegated from another machine that has a long description";
344 state.projection = {
345 ...(state.projection as Record<string, unknown>),
346 thread: {
347 ...(state.projection as { thread: Record<string, unknown> }).thread,
348 delegatedFrom: {
349 environmentId: EnvironmentId.make("parent-env"),
350 threadId: ThreadId.make("parent-thread"),
351 title: longTitle,
352 },
353 },
354 };
355 await using screen = await render(
356 <ThreadRelationshipsPanel
357 environmentId={environmentId}
358 threadId={threadId}
359 showLineage
360 showSideChats={false}
361 />,
362 { router: "/environment/fork" },
363 );
364​
365 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
366 await userEvent.hover(row);
367 await vi.waitFor(() =>
368 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
369 );
370 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
371 "Delegated from a linked environment. Connect to it to open the parent thread.",
372 );
373​
374 await row.click({ force: true });
375 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
376});
377​
378it("hides a deleted fork and keeps unloaded and archived forks with their current titles", async () => {
379 setup();
380 const projection = makeThreadProjectionFixture();
381 state.threadTitles = { "unloaded-fork": "Unloaded fork", "archived-fork": "Archived fork" };
382 state.archivedThreads = [
383 {
384 ...projection.thread,
385 id: ThreadId.make("archived-fork"),
386 title: "Old archived title",
387 archivedAt: projection.thread.updatedAt,
388 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "fork" },
389 },
390 ];
391 state.projection = {
392 ...projection,
393 contextTransfers: ["deleted-fork", "unloaded-fork", "archived-fork"].map((id) => ({
394 sourceThreadId: projection.thread.id,
395 targetThreadId: ThreadId.make(id),
396 status: "pending",
397 })),
398 };
399 await using screen = await render(
400 <ThreadRelationshipsPanel
401 environmentId={environmentId}
402 threadId={projection.thread.id}
403 showLineage
404 showSideChats
405 />,
406 );
407 await expect.element(screen.getByText("Unloaded fork", { exact: true })).toBeVisible();
408 await expect.element(screen.getByText("Archived fork", { exact: true })).toBeVisible();
409 await expect.element(screen.getByText("deleted-fork", { exact: true })).not.toBeInTheDocument();
410});
411​
412it.each([1, 18])("continues scrolling the panel past a list of %i subagents", async (count) => {
413 setup();
414 const projection = makeThreadProjectionFixture();
415 state.projection = projection;
416 state.relatedShells = Array.from({ length: count }, (_, index) => ({
417 id: ThreadId.make(`subagent-${index}`),
418 title: `Subagent ${index}`,
419 forkedFrom: null,
420 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "subagent" },
421 activityRunStatus: "running",
422 status: "running",
423 }));
424 await using screen = await render(
425 <div data-testid="panel" style={{ height: 320, width: 280 }}>
426 <ScrollArea>
427 <ThreadRelationshipsPanel
428 environmentId={environmentId}
429 threadId={projection.thread.id}
430 showLineage
431 showSideChats
432 />
433 <div style={{ height: 600 }} />
434 </ScrollArea>
435 </div>,
436 );
437 if (count > 6) {
438 await screen.getByRole("button", { name: "Show 12 more" }).click();
439 await expect.element(screen.getByText("Subagent 17", { exact: true })).toBeInTheDocument();
440 }
441 const list = screen.getByRole("list", { name: "Related threads" }).element();
442 const viewport = screen
443 .getByTestId("panel")
444 .element()
445 .querySelector<HTMLElement>("[data-slot=scroll-area-viewport]")!;
446 list.scrollTop = list.scrollHeight;
447 if (count > 6) expect(list.scrollTop).toBeGreaterThan(0);
448 viewport.scrollTop = 0;
449 await userEvent.wheel(list, { delta: { y: 300 } });
450 await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0));
451});