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

Sidebar.browser.test.tsx

1,495 lines60.7 KB

1import appCss from "../index.css?inline";
2import {
3 createMemoryHistory,
4 createRootRoute,
5 createRoute,
6 createRouter,
7 RouterProvider,
8} from "@tanstack/react-router";
9import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
10import {
11 scopedThreadKey,
12 scopeProjectRef,
13 scopeThreadRef,
14} from "@t3tools/client-runtime/environment";
15import { threadKey } from "@t3tools/client-runtime/state/entities";
16import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
17import * as shelfHooks from "../state/olderSettledShelf";
18import { createWorkspaceFocusController, workspaceAreaProps } from "../lib/workspaceFocus";
19import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
20import {
21 DEFAULT_CLIENT_SETTINGS,
22 EnvironmentId,
23 IssueTrackerKind,
24 type LocalApi,
25 ProjectId,
26 ProviderInstanceId,
27 ThreadId,
28 type ScopedThreadRef,
29} from "@t3tools/contracts";
30import { resolveSidebarRowLayout } from "./sidebar/sidebarRowLayout";
31import { isMacPlatform } from "@t3tools/shared/keybindings";
32import { AsyncResult } from "effect/reactivity";
33import { useSyncExternalStore } from "react";
34import { describe, expect, it, vi } from "vite-plus/test";
35import { page, userEvent } from "vite-plus/test/browser";
36​
37import { act, fakeTimers, render, stubGlobal } from "../../test/render";
38import { openCommandPalette } from "../commandPaletteBus";
39import { DraftId, useComposerDraftStore } from "../composerDraftStore";
40import { makeThreadFixture } from "../test-fixtures";
41import { useHandleNewThread } from "../hooks/useHandleNewThread";
42import { useNowMinute } from "../hooks/useNowMinute";
43import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings";
44import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
45import { I18nProvider } from "../i18n/I18nProvider";
46import { settleAndAdvance } from "../settleAndAdvance";
47import {
48 readEnvironmentServerConfigLoaded,
49 readThreadShell,
50 useDelegatedUnderParent,
51 useProjects,
52 useQuietThreadShells,
53 useServerConfigs,
54} from "../state/entities";
55import {
56 useConnectedEnvironmentIds,
57 useEnvironmentIdentities,
58 usePrimaryEnvironmentId,
59} from "../state/environments";
60import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
61import { useOrchestrationCommand } from "../state/use-orchestration-command";
62import { useThreadRunningTerminalIds } from "../state/terminalSessions";
63import { useTerminalUiStateStore } from "../terminalUiStateStore";
64import { useThreadSelectionStore } from "../threadSelectionStore";
65import { readLocalApi } from "../localApi";
66import type { Project } from "../types";
67import Sidebar from "./Sidebar";
68import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic";
69import { SortableThreadRow } from "./sidebar/SidebarThreadRow";
70import { SidebarProvider, useSidebar } from "./ui/sidebar";
71​
72vi.mock(import("../state/olderSettledShelf"), async (original) => {
73 const actual = await original();
74 return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) };
75});
76vi.mock("../state/entities", { spy: true });
77vi.mock("../state/environments", { spy: true });
78vi.mock("../hooks/useHandleNewThread", { spy: true });
79vi.mock("../hooks/useNowMinute", { spy: true });
80vi.mock("../hooks/useThreadRouteTarget", { spy: true });
81vi.mock("./sidebar/SidebarThreadRow", { spy: true });
82vi.mock("../state/session", { spy: true });
83vi.mock("../state/use-orchestration-command", { spy: true });
84vi.mock("../localApi", { spy: true });
85vi.mock("../state/terminalSessions", { spy: true });
86vi.mock(import("../state/server"), async (original) => {
87 const { Atom } = await import("effect/reactivity");
88 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
89 // The desktop defaults: holding Mod alone already matches a thread jump.
90 const keybindings = compileResolvedKeybindingsConfig([
91 { key: "mod+1", command: "thread.jump.1" },
92 { key: "mod+2", command: "thread.jump.2" },
93 { key: "mod+shift+[", command: "thread.previous" },
94 ]);
95 return { ...(await original()), primaryServerKeybindingsAtom: Atom.make(keybindings) };
96});
97vi.mock("../commandPaletteBus", () => ({
98 openCommandPalette: vi.fn(),
99 isCommandPaletteOpen: () => false,
100}));
101vi.mock("./sidebar/SidebarChrome", () => ({
102 SidebarChromeHeader: () => null,
103 SidebarChromeFooter: () => null,
104}));
105​
106function project(id: string): Project {
107 return {
108 id: ProjectId.make(id),
109 environmentId: EnvironmentId.make("local"),
110 title: id,
111 workspaceRoot: `/projects/${id}`,
112 repositoryIdentity: null,
113 defaultModelSelection: null,
114 createdAt: "2026-01-01T00:00:00.000Z",
115 updatedAt: "2026-01-01T00:00:00.000Z",
116 scripts: [],
117 };
119​
120describe("sidebar header new thread", () => {
121 it.each([
122 { mode: "normal", count: 2, shift: false, picker: true },
123 { mode: "boring", count: 2, shift: false, picker: true },
124 { mode: "boring", count: 2, shift: true, picker: false },
125 { mode: "boring", count: 1, shift: false, picker: false },
126 ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => {
127 using stack = new DisposableStack();
128 const previousSettings = getClientSettings();
129 stack.defer(() => __setClientSettingsForTests(previousSettings));
130 __setClientSettingsForTests({
131 ...DEFAULT_CLIENT_SETTINGS,
132 boringSidebarEnabled: scenario.mode === "boring",
133 });
134 const projects = [project("active"), project("idle")].slice(0, scenario.count);
135 const currentProjectRef = {
136 environmentId: projects[0]!.environmentId,
137 projectId: projects[0]!.id,
138 };
139 const startThread = vi.fn().mockResolvedValue(null);
140 vi.mocked(useProjects).mockReturnValue(projects);
141 vi.mocked(useHandleNewThread).mockReturnValue({
142 activeDraftThread: null,
143 activeThread: null,
144 defaultProjectRef: currentProjectRef,
145 defaultProjectFallbackReady: true,
146 handleNewThread: startThread,
147 routeDraftId: null,
148 routeThreadRef: null,
149 });
150 vi.mocked(openCommandPalette).mockClear();
151 await using screen = await render(
152 <SidebarProvider>
153 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
154 </SidebarProvider>,
155 );
156​
157 await userEvent.click(screen.getByRole("button", { name: "New thread", exact: true }), {
158 modifiers: scenario.shift ? ["Shift"] : [],
159 });
160​
161 if (scenario.picker) {
162 expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "new-thread-in" });
163 expect(startThread).not.toHaveBeenCalled();
164 } else {
165 expect(openCommandPalette).not.toHaveBeenCalled();
166 expect(startThread).toHaveBeenCalledExactlyOnceWith(currentProjectRef);
167 }
168 });
169});
170​
171// regression: #41549 a grouped project's folder New thread went to the primary copy
172describe("sidebar project folder new thread", () => {
173 it("starts in the copy of the viewed thread, as the new-thread shortcut does", async () => {
174 using stack = new DisposableStack();
175 const previousSettings = getClientSettings();
176 stack.defer(() => __setClientSettingsForTests(previousSettings));
177 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, boringSidebarEnabled: true });
178 const primary = EnvironmentId.make("local");
179 const dev1 = EnvironmentId.make("dev1");
180 const repositoryIdentity = {
181 canonicalKey: "github.com/acme/demo-repo",
182 locator: {
183 source: "git-remote" as const,
184 remoteName: "origin",
185 remoteUrl: "https://github.com/acme/demo-repo.git",
186 },
187 displayName: "acme/demo-repo",
188 };
189 const primaryCopy = { ...project("demo-primary"), repositoryIdentity };
190 const dev1Copy = {
191 ...project("demo-dev1"),
192 environmentId: dev1,
193 repositoryIdentity,
194 };
195 vi.mocked(usePrimaryEnvironmentId).mockReturnValue(primary);
196 vi.mocked(useConnectedEnvironmentIds).mockReturnValue([primary, dev1]);
197 vi.mocked(useProjects).mockReturnValue([primaryCopy, dev1Copy]);
198 const dev1Thread = makeThreadFixture({
199 environmentId: dev1,
200 id: ThreadId.make("dev1-thread"),
201 projectId: dev1Copy.id,
202 title: "dev1 work",
203 });
204 vi.mocked(useQuietThreadShells).mockReturnValue([dev1Thread]);
205 const threadRef = scopeThreadRef(dev1, dev1Thread.id);
206 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
207 const dev1ProjectRef = scopeProjectRef(dev1, dev1Copy.id);
208 const startThread = vi.fn().mockResolvedValue(null);
209 vi.mocked(useHandleNewThread).mockReturnValue({
210 activeDraftThread: null,
211 activeThread: dev1Thread,
212 defaultProjectRef: dev1ProjectRef,
213 defaultProjectFallbackReady: true,
214 handleNewThread: startThread,
215 routeDraftId: null,
216 routeThreadRef: threadRef,
217 });
218​
219 await using screen = await render(
220 <SidebarProvider>
221 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
222 </SidebarProvider>,
223 );
224 await userEvent.click(screen.getByRole("button", { name: "New thread in acme/demo-repo" }));
225​
226 expect(startThread).toHaveBeenCalledExactlyOnceWith(dev1ProjectRef);
227 });
228});
229​
230// regression: #38623 unsent drafts are listed above threads but mod+1..9 skipped them
231describe("sidebar numbered jumps", () => {
232 it("numbers the unsent draft at the top before the threads below it", async () => {
233 const initial = useComposerDraftStore.getState();
234 using stack = new DisposableStack();
235 stack.defer(() => useComposerDraftStore.setState(initial, true));
236 const previousSettings = getClientSettings();
237 stack.defer(() => __setClientSettingsForTests(previousSettings));
238 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
239 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
240 const web = project("web");
241 vi.mocked(useProjects).mockReturnValue([web]);
242 const thread = threadShell(web.id, 0);
243 vi.mocked(useQuietThreadShells).mockReturnValue([thread]);
244 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
245 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
246 vi.mocked(useHandleNewThread).mockReturnValue({
247 activeDraftThread: null,
248 activeThread: null,
249 defaultProjectRef: null,
250 defaultProjectFallbackReady: true,
251 handleNewThread: vi.fn(),
252 routeDraftId: null,
253 routeThreadRef: threadRef,
254 });
255 const draftId = DraftId.make("unsent-draft");
256 initial.setProjectDraftThreadId(scopeProjectRef(web.environmentId, web.id), draftId, {
257 threadId: ThreadId.make("unsent-draft-thread"),
258 createdAt: "2026-01-02T00:00:00.000Z",
259 });
260 initial.setPrompt(draftId, "Unsent prompt");
261​
262 await using screen = await render(
263 <SidebarProvider>
264 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
265 </SidebarProvider>,
266 );
267 const draftRow = screen.getByTestId("sidebar-draft-row");
268 await expect.element(draftRow).toBeInTheDocument();
269 await expect.element(screen.getByText("Thread 0").first()).toBeInTheDocument();
270 await userEvent.keyboard("{Control>}");
271 await expect.element(screen.getByText("Ctrl+1")).toBeVisible();
272 await expect.element(draftRow.getByText("Ctrl+1")).toBeVisible();
273 await expect.element(screen.getByText("Ctrl+2")).toBeVisible();
274 await userEvent.keyboard("{/Control}");
275​
276 // Previous thread from the open thread steps up to the draft above it.
277 await userEvent.keyboard("{Control>}{Shift>}{BracketLeft}{/Shift}{/Control}");
278 await vi.waitFor(() =>
279 expect(screen.router!.state.location.pathname).toBe(`/draft/${draftId}`),
280 );
281 await userEvent.keyboard("{Control>}2{/Control}");
282 await vi.waitFor(() =>
283 expect(screen.router!.state.location.pathname).not.toBe(`/draft/${draftId}`),
284 );
285 await userEvent.keyboard("{Control>}1{/Control}");
286 await vi.waitFor(() =>
287 expect(screen.router!.state.location.pathname).toBe(`/draft/${draftId}`),
288 );
289 });
290});
291​
292function threadShell(projectId: ProjectId, index: number): EnvironmentThreadShell {
293 return makeThreadFixture({
294 environmentId: EnvironmentId.make("local"),
295 id: ThreadId.make(`thread-${index}`),
296 projectId,
297 title: `Thread ${index}`,
298 });
300​
301describe("sidebar project labels for older records", () => {
302 it.each(["repository", "repository_path", "separate"] as const)(
303 "keeps names on pinned and unpinned threads when grouping by %s",
304 async (mode) => {
305 using stack = new DisposableStack();
306 const previousSettings = getClientSettings();
307 stack.defer(() => __setClientSettingsForTests(previousSettings));
308 __setClientSettingsForTests({
309 ...DEFAULT_CLIENT_SETTINGS,
310 sidebarProjectGroupingMode: mode,
311 });
312 const older = { ...project("older"), title: "Desktop", workspaceRoot: "/projects/Desktop" };
313 const newer = {
314 ...older,
315 id: ProjectId.make("newer"),
316 updatedAt: "2026-01-02T00:00:00.000Z",
317 };
318 const pinned = {
319 ...threadShell(older.id, 0),
320 pinnedAt: "2026-01-03T00:00:00.000Z",
321 };
322 const unpinned = threadShell(older.id, 1);
323 const current = threadShell(newer.id, 2);
324 const threadRef = scopeThreadRef(older.environmentId, unpinned.id);
325 vi.mocked(useProjects).mockReturnValue([older, newer]);
326 vi.mocked(useQuietThreadShells).mockReturnValue([pinned, unpinned, current]);
327 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
328 vi.mocked(useHandleNewThread).mockReturnValue({
329 activeDraftThread: null,
330 activeThread: null,
331 defaultProjectRef: scopeProjectRef(newer.environmentId, newer.id),
332 defaultProjectFallbackReady: true,
333 handleNewThread: vi.fn(),
334 routeDraftId: null,
335 routeThreadRef: threadRef,
336 });
337​
338 await using screen = await render(
339 <SidebarProvider>
340 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
341 </SidebarProvider>,
342 );
343 for (const thread of [pinned, unpinned, current]) {
344 const row = screen.getByRole("button", { name: new RegExp(thread.title) });
345 await expect.element(row.getByText("Desktop", { exact: true })).toBeInTheDocument();
346 }
347 },
348 );
349});
350​
351describe("sidebar render isolation", () => {
352 // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads
353 it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => {
354 using stack = new DisposableStack();
355 const activeProject = project("active");
356 const threads = Array.from({ length: 5 }, (_, index) => threadShell(activeProject.id, index));
357 const routeThreadRef: ScopedThreadRef = {
358 environmentId: activeProject.environmentId,
359 threadId: threads[0]!.id,
360 };
361 threads.unshift(threadShell(activeProject.id, 100));
362 // A real wall-clock minute tick mid-test re-renders every row and reads as a leak.
363 vi.mocked(useNowMinute).mockReturnValue("2026-01-01T00:00");
364 vi.mocked(useProjects).mockReturnValue([activeProject]);
365 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
366 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef });
367 vi.mocked(useHandleNewThread).mockReturnValue({
368 activeDraftThread: null,
369 activeThread: null,
370 defaultProjectRef: {
371 environmentId: activeProject.environmentId,
372 projectId: activeProject.id,
373 },
374 defaultProjectFallbackReady: true,
375 handleNewThread: vi.fn().mockResolvedValue(null),
376 routeDraftId: null,
377 routeThreadRef,
378 });
379 const terminal = document.createElement("div");
380 terminal.dataset.terminalOwner = "drawer";
381 const terminalInput = document.createElement("textarea");
382 terminal.append(terminalInput);
383 document.body.append(terminal);
384 stack.defer(() => terminal.remove());
385 stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false));
386 await using screen = await render(
387 <SidebarProvider>
388 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
389 </SidebarProvider>,
390 );
391 await expect.element(screen.getByText("Thread 4").first()).toBeInTheDocument();
392 const rowRenders = () => vi.mocked(SortableThreadRow).mock.calls.length;
393​
394 using _timers = fakeTimers();
395 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
396 const beforeShortcut = rowRenders();
397 await userEvent.keyboard(`{${modifier}>}`);
398 await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true));
399 await act(() => terminalInput.focus());
400 await userEvent.keyboard(`{/${modifier}}`);
401 await act(() => terminalInput.blur());
402 expect(
403 rowRenders() - beforeShortcut,
404 "thread rows re-rendered while opening the terminal with a quick Mod shortcut",
405 ).toBe(0);
406​
407 const jumpLabelsSince = (start: number) =>
408 vi
409 .mocked(SortableThreadRow)
410 .mock.calls.slice(start)
411 .map(([props]) => props.jumpLabel)
412 .filter((label) => label !== null);
413 const beforeHold = rowRenders();
414 await userEvent.keyboard(`{${modifier}>}`);
415 await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS));
416 expect(jumpLabelsSince(beforeHold), "holding Mod showed no jump hints").toHaveLength(2);
417 const beforeRelease = rowRenders();
418 await userEvent.keyboard(`{/${modifier}}`);
419 expect(rowRenders()).toBeGreaterThan(beforeRelease);
420 expect(jumpLabelsSince(beforeRelease)).toEqual([]);
421 });
422​
423 it("only re-renders affected thread rows when switching threads", async () => {
424 // Keep visibility subscriptions fixed while counting route-driven renders.
425 using _observer = stubGlobal("IntersectionObserver", undefined);
426 using stack = new DisposableStack();
427 const previousSettings = getClientSettings();
428 stack.defer(() => __setClientSettingsForTests(previousSettings));
429 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, sidebarWorkingShelfEnabled: false });
430​
431 const activeProject = project("active");
432 const threads = ["aa", "ba", "ca", "da"].map((activeOrderKey, index) => ({
433 ...threadShell(activeProject.id, index),
434 activeOrderKey,
435 }));
436 const keys = threads.map((thread) =>
437 scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
438 );
439 const settledThread = threads[1]!;
440 const selection = useThreadSelectionStore.getState();
441 selection.clearSelection();
442 stack.defer(() => selection.clearSelection());
443 stack.defer(() => ThreadUndo.invalidate("settle", keys[1]!));
444​
445 const settle = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
446 vi.mocked(useNowMinute).mockReturnValue("2026-01-01T00:00");
447 vi.mocked(useProjects).mockReturnValue([activeProject]);
448 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
449 vi.mocked(useThreadRouteTarget).mockReset();
450 vi.mocked(useServerConfigs).mockReturnValue(
451 new Map([
452 [
453 activeProject.environmentId,
454 { environment: { capabilities: {} } } as unknown as EnvironmentServerConfig,
455 ],
456 ]),
457 );
458 vi.mocked(readEnvironmentServerConfigLoaded).mockReturnValue(true);
459 vi.mocked(useOrchestrationCommand).mockReturnValue(settle);
460 vi.mocked(readThreadShell).mockImplementation((ref) =>
461 ref.threadId === settledThread.id && settle.mock.calls.length > 0
462 ? { ...settledThread, settledOverride: "settled", settledAt: settledThread.createdAt }
463 : (threads.find((thread) => thread.id === ref.threadId) ?? null),
464 );
465 stack.defer(() => {
466 vi.mocked(useNowMinute).mockReset();
467 vi.mocked(useProjects).mockReset();
468 vi.mocked(useQuietThreadShells).mockReset();
469 vi.mocked(useServerConfigs).mockReset();
470 vi.mocked(readEnvironmentServerConfigLoaded).mockReset();
471 vi.mocked(useOrchestrationCommand).mockReset();
472 vi.mocked(readThreadShell).mockReset();
473 });
474​
475 const root = createRootRoute({
476 component: () => (
477 <SidebarProvider>
478 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
479 </SidebarProvider>
480 ),
481 });
482 const router = createRouter({
483 routeTree: root.addChildren([
484 createRoute({ getParentRoute: () => root, path: "/" }),
485 createRoute({ getParentRoute: () => root, path: "/$environmentId/$threadId" }),
486 ]),
487 history: createMemoryHistory({ initialEntries: ["/local/thread-0"] }),
488 disableGlobalCatchBoundary: true,
489 });
490 vi.mocked(useThreadRunningTerminalIds).mockClear();
491 await using screen = await render(
492 <I18nProvider>
493 <RouterProvider router={router} />
494 </I18nProvider>,
495 {
496 // The sidebar needs real route params for each navigation.
497 router: false,
498 },
499 );
500 const row = (index: number) =>
501 page.elementLocator(screen.container.querySelector(`[data-sidebar-row="${keys[index]}"]`)!);
502 const unaffectedRowRenders = () =>
503 vi.mocked(useThreadRunningTerminalIds).mock.calls.filter(([ref]) => {
504 return ref.threadId === threads[2]!.id || ref.threadId === threads[3]!.id;
505 }).length;
506 await expect.element(row(0)).toHaveAttribute("aria-current", "page");
507 const beforeSwitch = unaffectedRowRenders();
508 expect(beforeSwitch).toBeGreaterThan(0);
509​
510 await userEvent.click(screen.getByText("Thread 1", { exact: true }));
511 await expect.element(row(1)).toHaveAttribute("aria-current", "page");
512 expect(unaffectedRowRenders() - beforeSwitch, "unaffected row renders").toBe(0);
513​
514 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
515 await userEvent.click(screen.getByText("Thread 3", { exact: true }), { modifiers: [modifier] });
516 expect(useThreadSelectionStore.getState().selectedThreadKeys).toEqual(
517 new Set([keys[1], keys[3]]),
518 );
519 expect(router.state.location.pathname).toBe("/local/thread-1");
520​
521 await act(() => selection.clearSelection());
522 await userEvent.click(row(1).getByRole("button", { name: "Settle thread", exact: true }));
523 expect(settle).toHaveBeenCalledExactlyOnceWith({
524 environmentId: settledThread.environmentId,
525 input: { threadId: settledThread.id },
526 });
527 await expect.element(row(2)).toHaveAttribute("aria-current", "page");
528 });
529});
530​
531describe("sidebar thread rename", () => {
532 // regression: #35151 an untouched rename wrote back the title it opened with over a newer one
533 it.each(["{Enter}", "{Tab}"])(
534 "ending an untouched rename with %s keeps a title that arrived while it was open",
535 async (finish) => {
536 const activeProject = project("active");
537 const routeThreadRef: ScopedThreadRef = {
538 environmentId: activeProject.environmentId,
539 threadId: ThreadId.make("thread-0"),
540 };
541 const shellTitled = (title: string) => ({ ...threadShell(activeProject.id, 0), title });
542 const updateMetadata = vi.fn().mockResolvedValue({ _tag: "Success" });
543 vi.mocked(useOrchestrationCommand).mockReturnValue(updateMetadata);
544 vi.mocked(readEnvironmentScope).mockReturnValue(true);
545 vi.mocked(useEnvironmentScope).mockReturnValue(true);
546 vi.mocked(useProjects).mockReturnValue([activeProject]);
547 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Fix the login redirect")]);
548 vi.mocked(useThreadRouteTarget).mockReturnValue({
549 kind: "server",
550 threadRef: routeThreadRef,
551 });
552 vi.mocked(useHandleNewThread).mockReturnValue({
553 activeDraftThread: null,
554 activeThread: null,
555 defaultProjectRef: {
556 environmentId: activeProject.environmentId,
557 projectId: activeProject.id,
558 },
559 defaultProjectFallbackReady: true,
560 handleNewThread: vi.fn().mockResolvedValue(null),
561 routeDraftId: null,
562 routeThreadRef,
563 });
564 const tree = () => (
565 <SidebarProvider>
566 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
567 </SidebarProvider>
568 );
569 await using screen = await render(tree());
570 await userEvent.dblClick(screen.getByText("Fix the login redirect").first());
571 const input = screen.getByRole("textbox", { name: "Thread title" });
572 await expect.element(input).toHaveValue("Fix the login redirect");
573​
574 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Generated title")]);
575 await screen.rerender(tree());
576 await userEvent.keyboard(finish);
577​
578 await expect.element(input).not.toBeInTheDocument();
579 expect(updateMetadata).not.toHaveBeenCalled();
580 },
581 );
582});
583​
584describe("sidebar thread click", () => {
585 // regression: #40715 macOS counts quick clicks on different rows, so the next row got detail 2 and was ignored
586 it("opens another thread when the click arrives with a double-click count", async () => {
587 const activeProject = project("active");
588 const threads = [threadShell(activeProject.id, 0), threadShell(activeProject.id, 1)];
589 const routeThreadRef: ScopedThreadRef = {
590 environmentId: activeProject.environmentId,
591 threadId: threads[0]!.id,
592 };
593 vi.mocked(useProjects).mockReturnValue([activeProject]);
594 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
595 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef });
596 vi.mocked(useHandleNewThread).mockReturnValue({
597 activeDraftThread: null,
598 activeThread: null,
599 defaultProjectRef: {
600 environmentId: activeProject.environmentId,
601 projectId: activeProject.id,
602 },
603 defaultProjectFallbackReady: true,
604 handleNewThread: vi.fn().mockResolvedValue(null),
605 routeDraftId: null,
606 routeThreadRef,
607 });
608 await using screen = await render(
609 <SidebarProvider>
610 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
611 </SidebarProvider>,
612 { router: "/local/thread-0" },
613 );
614 const navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined);
615​
616 const openRow = screen.getByText("Thread 0").first().element();
617 await act(() => {
618 openRow.dispatchEvent(
619 new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 }),
620 );
621 });
622 expect(navigate).not.toHaveBeenCalled();
623​
624 const row = screen.getByText("Thread 1").first().element();
625 await act(() => {
626 row.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 }));
627 });
628​
629 expect(navigate).toHaveBeenCalledWith(
630 expect.objectContaining({ params: expect.objectContaining({ threadId: "thread-1" }) }),
631 );
632 });
633});
634​
635describe("sidebar settle and advance", () => {
636 it("advances from the parent row when settling an open linked delegated task", async () => {
637 using stack = new DisposableStack();
638 const previousSettings = getClientSettings();
639 stack.defer(() => __setClientSettingsForTests(previousSettings));
640 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, sidebarWorkingShelfEnabled: false });
641​
642 const local = project("local-work");
643 const linked = { ...project("linked-work"), environmentId: EnvironmentId.make("linked") };
644 const first = { ...threadShell(local.id, 0), activeOrderKey: "aa" };
645 const parent = { ...threadShell(local.id, 1), activeOrderKey: "ba" };
646 const next = { ...threadShell(local.id, 2), activeOrderKey: "ca" };
647 const parentRef = scopeThreadRef(parent.environmentId, parent.id);
648 const child = makeThreadFixture({
649 environmentId: linked.environmentId,
650 projectId: linked.id,
651 id: ThreadId.make("delegated-task"),
652 delegatedFrom: { ...parentRef, title: parent.title },
653 });
654 const childRef = scopeThreadRef(child.environmentId, child.id);
655 stack.defer(() => ThreadUndo.invalidate("settle", scopedThreadKey(childRef)));
656​
657 vi.mocked(useProjects).mockReturnValue([local, linked]);
658 vi.mocked(useQuietThreadShells).mockReturnValue([first, parent, next, child]);
659 vi.mocked(useDelegatedUnderParent).mockReturnValue(new Set([threadKey(childRef)]));
660 vi.mocked(useThreadRouteTarget).mockReset();
661 vi.mocked(readEnvironmentServerConfigLoaded).mockReturnValue(true);
662 let childShell = child;
663 vi.mocked(readThreadShell).mockImplementation((ref) =>
664 scopedThreadKey(ref) === scopedThreadKey(childRef)
665 ? childShell
666 : ([first, parent, next].find((thread) => thread.id === ref.threadId) ?? null),
667 );
668 const settle = vi.fn().mockImplementation(() => {
669 childShell = { ...child, settledOverride: "settled", settledAt: child.createdAt };
670 return Promise.resolve(AsyncResult.success(undefined));
671 });
672 vi.mocked(useOrchestrationCommand).mockReturnValue(settle);
673 stack.defer(() => {
674 vi.mocked(useProjects).mockReset();
675 vi.mocked(useQuietThreadShells).mockReset();
676 vi.mocked(useDelegatedUnderParent).mockReset();
677 vi.mocked(readEnvironmentServerConfigLoaded).mockReset();
678 vi.mocked(readThreadShell).mockReset();
679 vi.mocked(useOrchestrationCommand).mockReset();
680 });
681​
682 const root = createRootRoute({
683 component: () => (
684 <SidebarProvider>
685 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
686 </SidebarProvider>
687 ),
688 });
689 const router = createRouter({
690 routeTree: root.addChildren([
691 createRoute({ getParentRoute: () => root, path: "/" }),
692 createRoute({ getParentRoute: () => root, path: "/$environmentId/$threadId" }),
693 ]),
694 history: createMemoryHistory({ initialEntries: [`/${linked.environmentId}/${child.id}`] }),
695 disableGlobalCatchBoundary: true,
696 });
697 await using screen = await render(<RouterProvider router={router} />, {
698 // The sidebar reads the thread params from this router.
699 router: false,
700 });
701 const row = (ref: ScopedThreadRef) =>
702 screen.container.querySelector(`[data-sidebar-row="${scopedThreadKey(ref)}"]`);
703 expect(row(parentRef)).toHaveAttribute("aria-current", "page");
704 expect(row(childRef)).toBeNull();
705​
706 await act(() => expect(settleAndAdvance(childRef)).toBe(true));
707​
708 expect(settle).toHaveBeenCalledExactlyOnceWith({
709 environmentId: linked.environmentId,
710 input: { threadId: child.id },
711 });
712 await vi.waitFor(() =>
713 expect(router.state.location.pathname).toBe(`/${local.environmentId}/${next.id}`),
714 );
715 });
716 it.each([
717 { change: "deleted", apply: () => [] },
718 {
719 change: "settled",
720 apply: (thread: EnvironmentThreadShell) => [
721 { ...thread, settledOverride: "settled" as const, settledAt: thread.createdAt },
722 ],
723 },
724 ])("skips a next thread $change elsewhere while the settle was pending", async ({ apply }) => {
725 using stack = new DisposableStack();
726 const previousSettings = getClientSettings();
727 stack.defer(() => __setClientSettingsForTests(previousSettings));
728 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, sidebarWorkingShelfEnabled: false });
729​
730 const local = project("local-work");
731 const current = { ...threadShell(local.id, 0), activeOrderKey: "aa" };
732 const changed = { ...threadShell(local.id, 1), activeOrderKey: "ba" };
733 const remaining = { ...threadShell(local.id, 2), activeOrderKey: "ca" };
734 const currentRef = scopeThreadRef(current.environmentId, current.id);
735 stack.defer(() => ThreadUndo.invalidate("settle", scopedThreadKey(currentRef)));
736​
737 let shells: ReadonlyArray<EnvironmentThreadShell> = [current, changed, remaining];
738 const shellListeners = new Set<() => void>();
739 vi.mocked(useProjects).mockReturnValue([local]);
740 vi.mocked(useQuietThreadShells).mockImplementation(() =>
741 useSyncExternalStore(
742 (listener) => {
743 shellListeners.add(listener);
744 return () => shellListeners.delete(listener);
745 },
746 () => shells,
747 ),
748 );
749 vi.mocked(useThreadRouteTarget).mockReset();
750 vi.mocked(readEnvironmentServerConfigLoaded).mockReturnValue(true);
751 let currentShell = current;
752 vi.mocked(readThreadShell).mockImplementation((ref) =>
753 scopedThreadKey(ref) === scopedThreadKey(currentRef)
754 ? currentShell
755 : (shells.find((thread) => thread.id === ref.threadId) ?? null),
756 );
757 const settled = Promise.withResolvers<void>();
758 const settle = vi.fn().mockImplementation(async () => {
759 await settled.promise;
760 currentShell = { ...current, settledOverride: "settled", settledAt: current.createdAt };
761 return AsyncResult.success(undefined);
762 });
763 vi.mocked(useOrchestrationCommand).mockReturnValue(settle);
764 stack.defer(() => {
765 vi.mocked(useProjects).mockReset();
766 vi.mocked(useQuietThreadShells).mockReset();
767 vi.mocked(readEnvironmentServerConfigLoaded).mockReset();
768 vi.mocked(readThreadShell).mockReset();
769 vi.mocked(useOrchestrationCommand).mockReset();
770 });
771​
772 const root = createRootRoute({
773 component: () => (
774 <SidebarProvider>
775 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
776 </SidebarProvider>
777 ),
778 });
779 const router = createRouter({
780 routeTree: root.addChildren([
781 createRoute({ getParentRoute: () => root, path: "/" }),
782 createRoute({ getParentRoute: () => root, path: "/$environmentId/$threadId" }),
783 ]),
784 history: createMemoryHistory({ initialEntries: [`/${local.environmentId}/${current.id}`] }),
785 disableGlobalCatchBoundary: true,
786 });
787 await using screen = await render(<RouterProvider router={router} />, {
788 // The sidebar reads the thread params from this router.
789 router: false,
790 });
791 const row = (thread: EnvironmentThreadShell) =>
792 screen.container.querySelector(
793 `[data-sidebar-row="${scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))}"]`,
794 );
795 expect(row(current)).toHaveAttribute("aria-current", "page");
796​
797 await act(() => expect(settleAndAdvance(currentRef)).toBe(true));
798 expect(settle).toHaveBeenCalledOnce();
799 await act(() => {
800 shells = [current, ...apply(changed), remaining];
801 for (const listener of shellListeners) listener();
802 });
803 await act(() => settled.resolve());
804​
805 await vi.waitFor(() =>
806 expect(router.state.location.pathname).toBe(`/${local.environmentId}/${remaining.id}`),
807 );
808 });
809});
810​
811describe("sidebar thread menu", () => {
812 it("tells the menu whether the keyboard opened it", async () => {
813 const activeProject = project("active");
814 const thread = threadShell(activeProject.id, 0);
815 const threadRef = { environmentId: activeProject.environmentId, threadId: thread.id };
816 const show = vi.fn().mockResolvedValue(null);
817 vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi);
818 vi.mocked(useProjects).mockReturnValue([activeProject]);
819 vi.mocked(useQuietThreadShells).mockReturnValue([thread]);
820 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
821 vi.mocked(useHandleNewThread).mockReturnValue({
822 activeDraftThread: null,
823 activeThread: null,
824 defaultProjectRef: {
825 environmentId: activeProject.environmentId,
826 projectId: activeProject.id,
827 },
828 defaultProjectFallbackReady: true,
829 handleNewThread: vi.fn().mockResolvedValue(null),
830 routeDraftId: null,
831 routeThreadRef: threadRef,
832 });
833 await using screen = await render(
834 <SidebarProvider>
835 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
836 </SidebarProvider>,
837 );
838 const row = screen.getByText("Thread 0").first();
839 await expect.element(row).toBeInTheDocument();
840 row.element().closest<HTMLElement>("[data-sidebar-row]")!.focus();
841 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
842 await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(1));
843 expect(show.mock.lastCall?.[2]).toBe("keyboard");
844 await userEvent.click(row, { button: "right" });
845 await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(2));
846 expect(show.mock.lastCall?.[2]).toBe("mouse");
847 });
848});
849​
850function MobileSheetProbe() {
851 const { openMobile, setOpenMobile } = useSidebar();
852 return (
853 <button type="button" onClick={() => setOpenMobile(true)}>
854 {openMobile ? "Sheet open" : "Sheet closed"}
855 </button>
856 );
858​
859async function usePhoneViewport() {
860 const viewport = { width: window.innerWidth, height: window.innerHeight };
861 await page.viewport(390, 844);
862 return { [Symbol.asyncDispose]: () => page.viewport(viewport.width, viewport.height) };
864​
865describe("sidebar thread menu on a phone", () => {
866 it("closes the sheet when New thread on branch starts the thread", async () => {
867 await using _viewport = await usePhoneViewport();
868 const activeProject = project("active");
869 const thread = makeThreadFixture({
870 environmentId: EnvironmentId.make("local"),
871 id: ThreadId.make("thread-branch"),
872 projectId: activeProject.id,
873 title: "Branch thread",
874 branch: "feature/login",
875 });
876 const threadRef = { environmentId: activeProject.environmentId, threadId: thread.id };
877 const show = vi.fn().mockResolvedValue("new-thread-on-branch");
878 const startThread = vi.fn().mockResolvedValue(null);
879 vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi);
880 vi.mocked(useProjects).mockReturnValue([activeProject]);
881 vi.mocked(useQuietThreadShells).mockReturnValue([thread]);
882 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
883 vi.mocked(useHandleNewThread).mockReturnValue({
884 activeDraftThread: null,
885 activeThread: null,
886 defaultProjectRef: {
887 environmentId: activeProject.environmentId,
888 projectId: activeProject.id,
889 },
890 defaultProjectFallbackReady: true,
891 handleNewThread: startThread,
892 routeDraftId: null,
893 routeThreadRef: threadRef,
894 });
895 await using screen = await render(
896 <SidebarProvider>
897 <MobileSheetProbe />
898 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
899 </SidebarProvider>,
900 );
901 await userEvent.click(screen.getByRole("button", { name: "Sheet closed" }));
902 await expect.element(screen.getByRole("button", { name: "Sheet open" })).toBeInTheDocument();
903 await userEvent.click(screen.getByText("Branch thread").first(), { button: "right" });
904 await vi.waitFor(() => expect(startThread).toHaveBeenCalledTimes(1));
905 expect(startThread.mock.lastCall?.[1]).toMatchObject({ branch: "feature/login" });
906 await expect.element(screen.getByRole("button", { name: "Sheet closed" })).toBeInTheDocument();
907 });
908​
909 it("closes the sheet when Add project opens the picker, as New thread does", async () => {
910 await using _viewport = await usePhoneViewport();
911 vi.mocked(useProjects).mockReturnValue([]);
912 vi.mocked(useQuietThreadShells).mockReturnValue([]);
913 vi.mocked(useThreadRouteTarget).mockReturnValue(null);
914 vi.mocked(useHandleNewThread).mockReturnValue({
915 activeDraftThread: null,
916 activeThread: null,
917 defaultProjectRef: null,
918 defaultProjectFallbackReady: true,
919 handleNewThread: vi.fn().mockResolvedValue(null),
920 routeDraftId: null,
921 routeThreadRef: null,
922 });
923 vi.mocked(openCommandPalette).mockClear();
924 await using screen = await render(
925 <SidebarProvider>
926 <MobileSheetProbe />
927 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
928 </SidebarProvider>,
929 );
930 await userEvent.click(screen.getByRole("button", { name: "Sheet closed" }));
931 await userEvent.click(screen.getByRole("button", { name: "Add project" }));
932 expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "add-project" });
933 await expect.element(screen.getByRole("button", { name: "Sheet closed" })).toBeInTheDocument();
934 });
935});
936​
937describe("sidebar selection menu", () => {
938 it("counts only the selected threads Settle will settle", async () => {
939 const activeProject = project("active");
940 const activeThread = threadShell(activeProject.id, 0);
941 const settledThread = makeThreadFixture({
942 environmentId: activeProject.environmentId,
943 projectId: activeProject.id,
944 id: ThreadId.make("thread-1"),
945 title: "Thread 1",
946 settledOverride: "settled",
947 settledAt: "2026-01-01T00:00:00.000Z",
948 });
949 const settledRef = { environmentId: activeProject.environmentId, threadId: settledThread.id };
950 const show = vi.fn().mockResolvedValue(null);
951 vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi);
952 vi.mocked(useProjects).mockReturnValue([activeProject]);
953 vi.mocked(useQuietThreadShells).mockReturnValue([activeThread, settledThread]);
954 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: settledRef });
955 vi.mocked(useHandleNewThread).mockReturnValue({
956 activeDraftThread: null,
957 activeThread: null,
958 defaultProjectRef: {
959 environmentId: activeProject.environmentId,
960 projectId: activeProject.id,
961 },
962 defaultProjectFallbackReady: true,
963 handleNewThread: vi.fn().mockResolvedValue(null),
964 routeDraftId: null,
965 routeThreadRef: settledRef,
966 });
967 await using screen = await render(
968 <SidebarProvider>
969 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
970 </SidebarProvider>,
971 );
972 await expect.element(screen.getByText("Thread 1").first()).toBeInTheDocument();
973 const selection = useThreadSelectionStore.getState();
974 selection.clearSelection();
975 selection.toggleThread(
976 scopedThreadKey(scopeThreadRef(activeProject.environmentId, activeThread.id)),
977 );
978 selection.toggleThread(scopedThreadKey(settledRef));
979 await userEvent.click(screen.getByText("Thread 0").first(), { button: "right" });
980 await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(1));
981 const settleItem = show.mock.lastCall?.[0].find((item: { id: string }) => item.id === "settle");
982 expect(settleItem?.label).toBe("Settle (1)");
983 selection.clearSelection();
984 });
985});
986​
987describe("sidebar settled pagination", () => {
988 it("keeps the viewport in place when showing more settled threads", async () => {
989 using stack = new DisposableStack();
990 const style = document.createElement("style");
991 style.textContent = appCss;
992 document.head.append(style);
993 stack.defer(() => style.remove());
994 const focusController = createWorkspaceFocusController(document);
995 stack.defer(() => focusController.dispose());
996 let loading = false;
997 const originalShelf = vi.mocked(shelfHooks.useOlderSettledShelf).getMockImplementation()!;
998 using _shelf = vi.spyOn(shelfHooks, "useOlderSettledShelf").mockImplementation((input) => ({
999 ...originalShelf(input),
1000 loading,
1001 retry: () => {
1002 loading = true;
1003 },
1004 }));
1005 const activeProject = project("active");
1006 const threads = Array.from({ length: 70 }, (_, index) =>
1007 makeThreadFixture({
1008 environmentId: activeProject.environmentId,
1009 projectId: activeProject.id,
1010 id: ThreadId.make(`settled-${index}`),
1011 title: `Settled thread ${index}`,
1012 settledOverride: "settled",
1013 settledAt: "2026-01-01T00:00:00.000Z",
1014 }),
1015 );
1016 threads.unshift(threadShell(activeProject.id, 100));
1017 vi.mocked(useProjects).mockReturnValue([activeProject]);
1018 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
1019 vi.mocked(useThreadRouteTarget).mockReturnValue({
1020 kind: "server",
1021 threadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id },
1022 });
1023 vi.mocked(useHandleNewThread).mockReturnValue({
1024 activeDraftThread: null,
1025 activeThread: null,
1026 defaultProjectRef: {
1027 environmentId: activeProject.environmentId,
1028 projectId: activeProject.id,
1029 },
1030 defaultProjectFallbackReady: true,
1031 handleNewThread: vi.fn().mockResolvedValue(null),
1032 routeDraftId: null,
1033 routeThreadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id },
1034 });
1035 vi.mocked(useServerConfigs).mockReturnValue(
1036 new Map([
1038 activeProject.environmentId,
1040 scratchWorkspaceRoot: null,
1041 shellThreadFamilies: false,
1042 } as unknown as EnvironmentServerConfig,
1043 ],
1044 ]),
1045 );
1046 await using screen = await render(
1047 <SidebarProvider
1048 {...workspaceAreaProps("sidebar", 0, "Threads")}
1049 style={{ height: 400, minHeight: 400 }}
1051 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
1052 </SidebarProvider>,
1053 );
1054 const shelf = screen.container.querySelector<HTMLElement>(
1055 '[data-sidebar-row="shelf:settled"]',
1056 )!;
1057 if (shelf.getAttribute("aria-expanded") === "false") await act(() => shelf.click());
1058 const more = screen.getByRole("button", { name: "Show 25 more", exact: true });
1059 await expect.element(more).toBeInTheDocument();
1060 const moreButton = more.element() as HTMLButtonElement;
1061 const viewport = moreButton.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
1062 viewport.style.height = "300px";
1063 viewport.style.maxHeight = "300px";
1064 moreButton.scrollIntoView({ block: "nearest" });
1065 const before = viewport.scrollTop;
1066 expect(before).toBeGreaterThan(0);
1067 moreButton.focus({ preventScroll: true });
1068 await act(() => moreButton.click());
1069 await expect
1070 .element(screen.getByRole("button", { name: "Loading", exact: true }))
1071 .toBeInTheDocument();
1072 await expect
1073 .element(screen.getByRole("button", { name: "Loading", exact: true }))
1074 .toHaveFocus();
1075 expect(viewport.scrollTop).toBe(before);
1076 const loadedRows = screen.container.querySelectorAll("[data-thread-item]").length;
1077 await act(() => moreButton.click());
1078 expect(screen.container.querySelectorAll("[data-thread-item]")).toHaveLength(loadedRows);
1079 });
1080});
1081​
1082async function useDesktopViewport() {
1083 const viewport = { width: window.innerWidth, height: window.innerHeight };
1084 await page.viewport(1280, 800);
1085 return { [Symbol.asyncDispose]: () => page.viewport(viewport.width, viewport.height) };
1087​
1088/** Elements that poke out of the card, which would paint over the card next to it. */
1089function overflowingParts(card: HTMLElement) {
1090 const box = card.getBoundingClientRect();
1091 return [...card.querySelectorAll<HTMLElement>("*")].flatMap((node) => {
1092 const rect = node.getBoundingClientRect();
1093 const past = Math.max(
1094 rect.right - box.right,
1095 box.left - rect.left,
1096 rect.bottom - box.bottom,
1097 box.top - rect.top,
1098 );
1099 return rect.width > 0 && rect.height > 0 && past > 0.5
1100 ? [`${Math.round(past)}px ${node.outerHTML.slice(0, 60)}`]
1101 : [];
1102 });
1104​
1105describe("sidebar thread card layout", () => {
1106 const states = ["plain", "long", "linked", "working", "pinned"] as const;
1107 const RUNNING_TERMINALS = ["term-1"];
1108 // Heights per thread state, in the order above, including the li's py-0.5.
1109 it.each([
1110 { name: "default", layout: {}, heights: [82, 82, 82, 82, 82] },
1111 // Heights are measured back at the 16px default, so the card must scale with its contents.
1113 name: "default, 20px interface font",
1114 layout: {},
1115 fontSize: 20,
1116 heights: [82, 82, 82, 82, 82],
1117 },
1119 name: "title beside the project icon",
1120 layout: {
1121 top: ["projectIcon", "title", "spacer", "time"],
1122 middle: ["projectName"],
1123 bottom: ["branch", "spacer", "terminals", "pullRequest", "issues", "agents"],
1124 },
1125 heights: [82, 82, 82, 82, 82],
1126 },
1128 name: "everything on one line",
1129 layout: {
1130 top: [
1131 "projectIcon",
1132 "projectName",
1133 "title",
1134 "branch",
1135 "terminals",
1136 "pullRequest",
1137 "issues",
1138 "agents",
1139 "spacer",
1140 "time",
1141 ],
1142 middle: [],
1143 bottom: [],
1144 hidden: ["environment"],
1145 },
1146 heights: [40, 40, 40, 40, 40],
1147 },
1149 name: "fixed height",
1150 layout: {
1151 top: ["projectIcon", "projectName", "spacer"],
1152 middle: ["title"],
1153 bottom: ["branch", "spacer", "agents"],
1154 // An older layout that kept only one line still means a fixed height.
1155 keep: ["bottom"],
1156 },
1157 heights: [82, 82, 82, 82, 82],
1158 },
1160 // A kept line with nothing on it still folds.
1161 name: "fixed height, title on top, empty middle",
1162 layout: {
1163 top: ["projectIcon", "title", "time"],
1164 middle: [],
1165 bottom: ["branch", "spacer", "pullRequest", "agents"],
1166 hidden: ["projectName", "terminals", "issues"],
1167 keep: ["middle", "bottom"],
1168 },
1169 heights: [58, 58, 58, 58, 58],
1170 },
1172 name: "fixed height with only the title",
1173 layout: {
1174 top: [],
1175 middle: ["title"],
1176 bottom: [],
1177 hidden: [
1178 "projectIcon",
1179 "projectName",
1180 "branch",
1181 "agents",
1182 "environment",
1183 "terminals",
1184 "subagents",
1185 "pullRequest",
1186 "issues",
1187 ],
1188 keep: ["middle", "bottom"],
1189 },
1190 heights: [64, 64, 64, 64, 64],
1191 },
1193 name: "fixed height with only agents under the title",
1194 layout: {
1195 top: ["projectIcon", "projectName"],
1196 middle: ["title"],
1197 bottom: ["spacer", "agents"],
1198 hidden: ["branch", "terminals", "pullRequest", "issues", "time"],
1199 keep: ["middle", "bottom"],
1200 },
1201 heights: [82, 82, 82, 82, 82],
1202 },
1204 // The time keeps a sparse card's last line, so that line never folds.
1205 name: "time on the bottom line",
1206 layout: {
1207 top: ["projectIcon", "projectName"],
1208 middle: ["title"],
1209 bottom: ["branch", "spacer", "time"],
1210 },
1211 heights: [82, 82, 82, 82, 82],
1212 },
1214 // Under Fit, only the long title takes a second line; the hint stays at one line.
1215 name: "title wrapping onto two lines",
1216 layout: { middle: ["title:wrap"] },
1217 heights: [82, 102, 82, 82, 82],
1218 reserved: [82, 82, 82, 82, 82],
1219 },
1221 // Same height reserves the second line on every card.
1222 name: "title wrapping, same height",
1223 layout: { middle: ["title:wrap"], keep: ["middle", "bottom"] },
1224 heights: [102, 102, 102, 102, 102],
1225 },
1227 // On the top line hover controls narrow the title, so it reserves both lines to not jump.
1228 name: "title wrapping on the top line",
1229 layout: {
1230 top: ["projectIcon", "title:wrap", "time"],
1231 middle: [],
1232 bottom: ["environment:wide", "spacer", "pullRequest", "agents"],
1233 hidden: ["projectName"],
1234 },
1235 heights: [78, 78, 78, 78, 78],
1236 },
1238 // With the time hidden, a status still shows, at the end of the top line.
1239 name: "time hidden",
1240 layout: {
1241 top: ["projectIcon", "projectName", "spacer"],
1242 middle: ["title"],
1243 bottom: ["branch", "spacer", "terminals", "pullRequest", "issues", "agents"],
1244 hidden: ["time"],
1245 },
1246 heights: [82, 82, 82, 82, 82],
1247 },
1249 // A time that ends the top line sits in the status slot, even after agents fold into it.
1250 name: "title on top, agents folding into its line",
1251 layout: {
1252 top: ["projectIcon", "title", "time"],
1253 middle: [],
1254 bottom: ["branch", "agents"],
1255 hidden: ["projectName", "terminals", "pullRequest", "issues", "environment"],
1256 },
1257 heights: [40, 58, 58, 58, 58],
1258 },
1260 name: "compact forms",
1261 layout: {
1262 top: ["projectIcon", "projectName", "branch:compact", "spacer", "time"],
1263 middle: ["title", "environment:compact"],
1264 bottom: ["terminals", "pullRequest", "issues", "spacer", "agents"],
1265 },
1266 heights: [64, 64, 82, 64, 64],
1267 },
1269 name: "spacers in odd places",
1270 layout: {
1271 top: ["spacer", "spacer", "projectIcon", "time", "spacer"],
1272 middle: ["spacer", "title", "spacer", "agents"],
1273 bottom: ["spacer", "projectName", "spacer", "branch", "spacer"],
1274 },
1275 heights: [82, 82, 82, 82, 82],
1276 },
1278 name: "empty middle, title on the bottom line",
1279 layout: {
1280 top: ["projectIcon", "projectName", "spacer", "time"],
1281 middle: [],
1282 bottom: ["title", "branch", "pullRequest", "issues", "agents"],
1283 },
1284 heights: [62, 62, 62, 62, 62],
1285 },
1286 // Threads on two machines show the environment; the long thread lives on the second one.
1288 name: "two environments, default layout",
1289 layout: {},
1290 heights: [82, 82, 82, 82, 82],
1291 environments: 2,
1292 },
1294 name: "two environments, wide environment on the bottom line",
1295 layout: {
1296 top: ["projectIcon", "projectName", "spacer", "time"],
1297 middle: ["title"],
1298 bottom: ["environment:wide", "branch", "spacer", "pullRequest", "issues", "agents"],
1299 },
1300 heights: [82, 82, 82, 82, 82],
1301 environments: 2,
1302 },
1304 name: "two environments, wide environment crowding the title's line",
1305 layout: {
1306 top: ["projectIcon", "title", "environment:wide", "spacer", "time"],
1307 middle: [],
1308 bottom: ["branch", "spacer", "pullRequest", "agents"],
1309 },
1310 heights: [40, 58, 58, 58, 58],
1311 environments: 2,
1312 },
1313 ])("$name: every card fits the height it reserves", async (row) => {
1314 const { layout, heights } = row;
1315 const environments = "environments" in row ? row.environments : 1;
1316 const scale = ("fontSize" in row ? row.fontSize : 16) / 16;
1317 await using _viewport = await useDesktopViewport();
1318 using stack = new DisposableStack();
1319 const root = document.documentElement;
1320 const previousFontSize = root.style.fontSize;
1321 root.style.fontSize = `${16 * scale}px`;
1322 stack.defer(() => {
1323 root.style.fontSize = previousFontSize;
1324 });
1325 const style = document.createElement("style");
1326 style.textContent = appCss;
1327 document.head.append(style);
1328 stack.defer(() => style.remove());
1329 const previousSettings = getClientSettings();
1330 stack.defer(() => __setClientSettingsForTests(previousSettings));
1331 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, sidebarRowLayout: layout });
1332 const shortProject = project("web");
1333 const longName = "a-project-name-long-enough-to-crowd-any-line-it-is-placed-on";
1334 const remoteId = EnvironmentId.make("remote");
1335 const remoteLabel = "Studio Mac mini in the back office";
1336 const longProject = {
1337 ...project("long"),
1338 title: longName,
1339 ...(environments === 2 && { environmentId: remoteId }),
1340 };
1341 const environmentId = shortProject.environmentId;
1342 vi.mocked(useEnvironmentIdentities).mockReturnValue([
1343 { environmentId, label: "This Mac" },
1344 ...(environments === 2 ? [{ environmentId: remoteId, label: remoteLabel }] : []),
1345 ]);
1346 stack.defer(() => vi.mocked(useEnvironmentIdentities).mockRestore());
1347 const thread = (state: (typeof states)[number]) =>
1348 makeThreadFixture({
1349 environmentId: state === "long" ? longProject.environmentId : environmentId,
1350 id: ThreadId.make(`thread-${state}`),
1351 projectId: state === "long" ? longProject.id : shortProject.id,
1352 title:
1353 state === "long"
1354 ? "A thread title long enough that it can never fit on one sidebar line at all"
1355 : `Thread ${state}`,
1356 branch:
1357 state === "long"
1358 ? "feature/a-branch-name-long-enough-to-crowd-the-line-it-sits-on-too"
1359 : state === "plain"
1360 ? null
1361 : "fix/login",
1362 pinnedAt: state === "pinned" ? "2026-01-01T00:00:00.000Z" : null,
1363 ...(state === "working" && {
1364 runtime: {
1365 status: "running" as const,
1366 activeRunId: null,
1367 providerInstanceId: ProviderInstanceId.make("codex"),
1368 providerName: "Codex",
1369 lastError: null,
1370 updatedAt: "2026-01-01T00:00:00.000Z",
1371 },
1372 }),
1373 ...(state === "linked" && {
1374 pullRequests: [
1376 host: "github.com",
1377 repository: "pingdotgg/t3code",
1378 number: 4242,
1379 url: "https://github.com/pingdotgg/t3code/pull/4242",
1380 source: "manual" as const,
1381 linkedAt: "2026-01-01T00:00:00.000Z",
1382 snapshot: null,
1383 stack: null,
1384 },
1385 ],
1386 issues: [
1388 tracker: IssueTrackerKind.make("github"),
1389 host: "github.com",
1390 scope: "pingdotgg/t3code",
1391 key: "123",
1392 projectId: shortProject.id,
1393 url: "https://github.com/pingdotgg/t3code/issues/123",
1394 source: "manual" as const,
1395 linkedAt: "2026-01-01T00:00:00.000Z",
1396 displayKey: "#123",
1397 title: "Login redirect loops",
1398 },
1399 ],
1400 }),
1401 });
1402 vi.mocked(useThreadRunningTerminalIds).mockImplementation(({ threadId }) =>
1403 threadId === ThreadId.make("thread-linked") ? RUNNING_TERMINALS : [],
1404 );
1405 stack.defer(() => vi.mocked(useThreadRunningTerminalIds).mockRestore());
1406 // A server config is what lets rows show linked pull requests and issues.
1407 const serverConfig = {
1408 environment: { capabilities: {} },
1409 } as unknown as EnvironmentServerConfig;
1410 vi.mocked(useServerConfigs).mockReturnValue(
1411 new Map([
1412 [environmentId, serverConfig],
1413 [remoteId, serverConfig],
1414 ]),
1415 );
1416 vi.mocked(useProjects).mockReturnValue([shortProject, longProject]);
1417 vi.mocked(useQuietThreadShells).mockReturnValue(states.map(thread));
1418 vi.mocked(useThreadRouteTarget).mockReturnValue(null);
1419 vi.mocked(useHandleNewThread).mockReturnValue({
1420 activeDraftThread: null,
1421 activeThread: null,
1422 defaultProjectRef: { environmentId, projectId: shortProject.id },
1423 defaultProjectFallbackReady: true,
1424 handleNewThread: vi.fn().mockResolvedValue(null),
1425 routeDraftId: null,
1426 routeThreadRef: null,
1427 });
1428 await using screen = await render(
1429 <SidebarProvider>
1430 {/* The app sidebar's width, so crowded lines have to fit it. */}
1431 <div className="flex w-64 min-w-0 flex-col overflow-hidden">
1432 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
1433 </div>
1434 </SidebarProvider>,
1435 );
1436 const working = screen.getByRole("button", { name: "Working 1" });
1437 if (working.element().getAttribute("aria-expanded") !== "true") await userEvent.click(working);
1438 for (const state of states) {
1439 await expect.element(screen.getByText(thread(state).title).first()).toBeVisible();
1441 if (!("hidden" in layout && layout.hidden.includes("pullRequest"))) {
1442 await expect.element(screen.getByRole("link", { name: /PR #4242/ })).toBeInTheDocument();
1444 for (const [index, state] of states.entries()) {
1445 const item = screen.container.querySelector<HTMLElement>(
1446 `[data-thread-item$="thread-${state}"]`,
1447 )!;
1448 const card = item.querySelector<HTMLElement>("[data-testid=sidebar-row-card] > div")!;
1449 const reserved =
1450 Number.parseFloat(getComputedStyle(item).containIntrinsicSize.replace("auto ", "")) / scale;
1451 expect(Math.round(item.getBoundingClientRect().height / scale), state).toBe(heights[index]);
1452 expect(reserved + 4, `${state} reserved`).toBe(
1453 ("reserved" in row ? row.reserved : heights)[index],
1454 );
1455 expect(overflowingParts(card), state).toEqual([]);
1456 if ("top" in layout && layout.top.at(-1) === "time") {
1457 const inlineTime = card.querySelector(":scope > div:first-child > .tabular-nums");
1458 expect(inlineTime, `${state}: time outside the status slot`).toBeNull();
1460 if (state === "working") {
1461 // The status takes the time's place: on its line, or the top line when the time is hidden.
1462 const timeLine =
1463 (["middle", "bottom"] as const).find(
1464 (line) =>
1465 line in layout && (layout as Record<string, string[]>)[line]!.includes("time"),
1466 ) ?? "top";
1467 const walker = document.createTreeWalker(card, NodeFilter.SHOW_TEXT);
1468 let working: Node | null = null;
1469 while (working === null && walker.nextNode()) {
1470 if (walker.currentNode.textContent === "Working") working = walker.currentNode;
1472 const lines = [...card.children];
1473 const statusLine = lines.findIndex((line) => line.contains(working));
1474 expect(statusLine, "working: line holding the status").toBe(
1475 timeLine === "top" ? 0 : timeLine === "bottom" ? lines.length - 1 : 1,
1476 );
1478 // The environment shows wherever the layout places it, as on main, even with one machine.
1479 const resolved = resolveSidebarRowLayout(layout);
1480 const placesEnvironment = (["top", "middle", "bottom"] as const).some((line) =>
1481 resolved[line].some((token) => token.id === "environment"),
1482 );
1483 const environmentLabel = state === "long" && environments === 2 ? remoteLabel : "This Mac";
1484 const showsEnvironment =
1485 card.querySelector(`[aria-label="${environmentLabel}"]`) !== null ||
1486 card.textContent?.includes(environmentLabel) === true;
1487 expect(showsEnvironment, `${state}: environment shown`).toBe(placesEnvironment);
1488 const title = screen.getByText(thread(state).title, { exact: true }).first().element();
1489 expect(title.getBoundingClientRect().width, state).toBeGreaterThan(0);
1490 // Hover swaps the status label for the row's controls.
1491 await userEvent.hover(card);
1492 expect(overflowingParts(card), `${state} hovered`).toEqual([]);
1494 });
1495});