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

ThreadRelationshipsControl.browser.test.tsx

408 lines13.5 KB

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