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 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 };
88}
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("explains why Merge back is unavailable before the fork completes a run", async () => {
342 setup();
343 state.projection = { ...(state.projection as Record<string, unknown>), runs: [] };
344 await using screen = await render(
345 <ThreadRelationshipsPanel
346 environmentId={environmentId}
347 threadId={threadId}
348 showLineage
349 showSideChats={false}
350 />,
351 { router: "/environment/fork" },
352 );
353
354 const mergeBack = screen.getByRole("button", { name: "Merge back to source conversation" });
355 await userEvent.hover(mergeBack);
356 await vi.waitFor(() =>
357 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(
358 "Complete a run in this fork before merging it back",
359 ),
360 );
361
362 state.commandSucceeds = true;
363 await mergeBack.click({ force: true });
364 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
365});
366
367it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => {
368 setup();
369 const longTitle = "Parent task delegated from another machine that has a long description";
370 state.projection = {
371 ...(state.projection as Record<string, unknown>),
372 thread: {
373 ...(state.projection as { thread: Record<string, unknown> }).thread,
374 delegatedFrom: {
375 environmentId: EnvironmentId.make("parent-env"),
376 threadId: ThreadId.make("parent-thread"),
377 title: longTitle,
378 },
379 },
380 };
381 await using screen = await render(
382 <ThreadRelationshipsPanel
383 environmentId={environmentId}
384 threadId={threadId}
385 showLineage
386 showSideChats={false}
387 />,
388 { router: "/environment/fork" },
389 );
390
391 const row = screen.getByRole("button", { name: new RegExp(longTitle) });
392 await userEvent.hover(row);
393 await vi.waitFor(() =>
394 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(longTitle),
395 );
396 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toContain(
397 "Delegated from a linked environment. Connect to it to open the parent thread.",
398 );
399
400 await row.click({ force: true });
401 expect(screen.router?.state.location.pathname).toBe("/environment/fork");
402});
403
404it("hides a deleted fork and keeps unloaded and archived forks with their current titles", async () => {
405 setup();
406 const projection = makeThreadProjectionFixture();
407 state.threadTitles = { "unloaded-fork": "Unloaded fork", "archived-fork": "Archived fork" };
408 state.archivedThreads = [
409 {
410 ...projection.thread,
411 id: ThreadId.make("archived-fork"),
412 title: "Old archived title",
413 archivedAt: projection.thread.updatedAt,
414 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "fork" },
415 },
416 ];
417 state.projection = {
418 ...projection,
419 contextTransfers: ["deleted-fork", "unloaded-fork", "archived-fork"].map((id) => ({
420 sourceThreadId: projection.thread.id,
421 targetThreadId: ThreadId.make(id),
422 status: "pending",
423 })),
424 };
425 await using screen = await render(
426 <ThreadRelationshipsPanel
427 environmentId={environmentId}
428 threadId={projection.thread.id}
429 showLineage
430 showSideChats
431 />,
432 );
433 await expect.element(screen.getByText("Unloaded fork", { exact: true })).toBeVisible();
434 await expect.element(screen.getByText("Archived fork", { exact: true })).toBeVisible();
435 await expect.element(screen.getByText("deleted-fork", { exact: true })).not.toBeInTheDocument();
436});
437
438it.each([1, 18])("continues scrolling the panel past a list of %i subagents", async (count) => {
439 setup();
440 const projection = makeThreadProjectionFixture();
441 state.projection = projection;
442 state.relatedShells = Array.from({ length: count }, (_, index) => ({
443 id: ThreadId.make(`subagent-${index}`),
444 title: `Subagent ${index}`,
445 forkedFrom: null,
446 lineage: { parentThreadId: projection.thread.id, relationshipToParent: "subagent" },
447 activityRunStatus: "running",
448 status: "running",
449 }));
450 await using screen = await render(
451 <div data-testid="panel" style={{ height: 320, width: 280 }}>
452 <ScrollArea>
453 <ThreadRelationshipsPanel
454 environmentId={environmentId}
455 threadId={projection.thread.id}
456 showLineage
457 showSideChats
458 />
459 <div style={{ height: 600 }} />
460 </ScrollArea>
461 </div>,
462 );
463 if (count > 6) {
464 await screen.getByRole("button", { name: "Show 12 more" }).click();
465 await expect.element(screen.getByText("Subagent 17", { exact: true })).toBeInTheDocument();
466 }
467 const list = screen.getByRole("list", { name: "Related threads" }).element();
468 const viewport = screen
469 .getByTestId("panel")
470 .element()
471 .querySelector<HTMLElement>("[data-slot=scroll-area-viewport]")!;
472 list.scrollTop = list.scrollHeight;
473 if (count > 6) expect(list.scrollTop).toBeGreaterThan(0);
474 viewport.scrollTop = 0;
475 await userEvent.wheel(list, { delta: { y: 300 } });
476 await vi.waitFor(() => expect(viewport.scrollTop).toBeGreaterThan(0));
477});