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

Sidebar.browser.test.tsx

464 lines19.6 KB

1import appCss from "../index.css?inline";
2import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
3import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
4import * as shelfHooks from "../state/olderSettledShelf";
5import { createWorkspaceFocusController, workspaceAreaProps } from "../lib/workspaceFocus";
6import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
7import {
8 DEFAULT_CLIENT_SETTINGS,
9 EnvironmentId,
10 type LocalApi,
11 ProjectId,
12 ThreadId,
13 type ScopedThreadRef,
14} from "@t3tools/contracts";
15import { isMacPlatform } from "@t3tools/shared/keybindings";
16import { describe, expect, it, vi } from "vite-plus/test";
17import { userEvent } from "vite-plus/test/browser";
18​
19import { act, fakeTimers, render } from "../../test/render";
20import { openCommandPalette } from "../commandPaletteBus";
21import { DraftId, useComposerDraftStore } from "../composerDraftStore";
22import { makeThreadFixture } from "../test-fixtures";
23import { useHandleNewThread } from "../hooks/useHandleNewThread";
24import { useNowMinute } from "../hooks/useNowMinute";
25import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings";
26import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
27import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities";
28import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
29import { useOrchestrationCommand } from "../state/use-orchestration-command";
30import { useTerminalUiStateStore } from "../terminalUiStateStore";
31import { readLocalApi } from "../localApi";
32import type { Project } from "../types";
33import Sidebar from "./Sidebar";
34import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic";
35import { SortableThreadRow } from "./sidebar/SidebarThreadRow";
36import { SidebarProvider } from "./ui/sidebar";
37​
38vi.mock(import("../state/olderSettledShelf"), async (original) => {
39 const actual = await original();
40 return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) };
41});
42vi.mock("../state/entities", { spy: true });
43vi.mock("../hooks/useHandleNewThread", { spy: true });
44vi.mock("../hooks/useNowMinute", { spy: true });
45vi.mock("../hooks/useThreadRouteTarget", { spy: true });
46vi.mock("./sidebar/SidebarThreadRow", { spy: true });
47vi.mock("../state/session", { spy: true });
48vi.mock("../state/use-orchestration-command", { spy: true });
49vi.mock("../localApi", { spy: true });
50vi.mock(import("../state/server"), async (original) => {
51 const { Atom } = await import("effect/reactivity");
52 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
53 // The desktop defaults: holding Mod alone already matches a thread jump.
54 const keybindings = compileResolvedKeybindingsConfig([
55 { key: "mod+1", command: "thread.jump.1" },
56 { key: "mod+2", command: "thread.jump.2" },
57 { key: "mod+shift+[", command: "thread.previous" },
58 ]);
59 return { ...(await original()), primaryServerKeybindingsAtom: Atom.make(keybindings) };
60});
61vi.mock("../commandPaletteBus", () => ({
62 openCommandPalette: vi.fn(),
63 isCommandPaletteOpen: () => false,
64}));
65vi.mock("./sidebar/SidebarChrome", () => ({
66 SidebarChromeHeader: () => null,
67 SidebarChromeFooter: () => null,
68}));
69​
70function project(id: string): Project {
71 return {
72 id: ProjectId.make(id),
73 environmentId: EnvironmentId.make("local"),
74 title: id,
75 workspaceRoot: `/projects/${id}`,
76 repositoryIdentity: null,
77 defaultModelSelection: null,
78 createdAt: "2026-01-01T00:00:00.000Z",
79 updatedAt: "2026-01-01T00:00:00.000Z",
80 scripts: [],
81 };
83​
84describe("sidebar header new thread", () => {
85 it.each([
86 { mode: "normal", count: 2, shift: false, picker: true },
87 { mode: "boring", count: 2, shift: false, picker: true },
88 { mode: "boring", count: 2, shift: true, picker: false },
89 { mode: "boring", count: 1, shift: false, picker: false },
90 ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => {
91 using stack = new DisposableStack();
92 const previousSettings = getClientSettings();
93 stack.defer(() => __setClientSettingsForTests(previousSettings));
94 __setClientSettingsForTests({
95 ...DEFAULT_CLIENT_SETTINGS,
96 boringSidebarEnabled: scenario.mode === "boring",
97 });
98 const projects = [project("active"), project("idle")].slice(0, scenario.count);
99 const currentProjectRef = {
100 environmentId: projects[0]!.environmentId,
101 projectId: projects[0]!.id,
102 };
103 const startThread = vi.fn().mockResolvedValue(null);
104 vi.mocked(useProjects).mockReturnValue(projects);
105 vi.mocked(useHandleNewThread).mockReturnValue({
106 activeDraftThread: null,
107 activeThread: null,
108 defaultProjectRef: currentProjectRef,
109 defaultProjectFallbackReady: true,
110 handleNewThread: startThread,
111 routeDraftId: null,
112 routeThreadRef: null,
113 });
114 vi.mocked(openCommandPalette).mockClear();
115 await using screen = await render(
116 <SidebarProvider>
117 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
118 </SidebarProvider>,
119 );
120​
121 await userEvent.click(screen.getByRole("button", { name: "New thread", exact: true }), {
122 modifiers: scenario.shift ? ["Shift"] : [],
123 });
124​
125 if (scenario.picker) {
126 expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "new-thread-in" });
127 expect(startThread).not.toHaveBeenCalled();
128 } else {
129 expect(openCommandPalette).not.toHaveBeenCalled();
130 expect(startThread).toHaveBeenCalledExactlyOnceWith(currentProjectRef);
131 }
132 });
133});
134​
135// regression: #38623 unsent drafts are listed above threads but mod+1..9 skipped them
136describe("sidebar numbered jumps", () => {
137 it("numbers the unsent draft at the top before the threads below it", async () => {
138 const initial = useComposerDraftStore.getState();
139 using stack = new DisposableStack();
140 stack.defer(() => useComposerDraftStore.setState(initial, true));
141 const previousSettings = getClientSettings();
142 stack.defer(() => __setClientSettingsForTests(previousSettings));
143 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
144 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
145 const web = project("web");
146 vi.mocked(useProjects).mockReturnValue([web]);
147 const thread = threadShell(web.id, 0);
148 vi.mocked(useQuietThreadShells).mockReturnValue([thread]);
149 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
150 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
151 vi.mocked(useHandleNewThread).mockReturnValue({
152 activeDraftThread: null,
153 activeThread: null,
154 defaultProjectRef: null,
155 defaultProjectFallbackReady: true,
156 handleNewThread: vi.fn(),
157 routeDraftId: null,
158 routeThreadRef: threadRef,
159 });
160 const draftId = DraftId.make("unsent-draft");
161 initial.setProjectDraftThreadId(scopeProjectRef(web.environmentId, web.id), draftId, {
162 threadId: ThreadId.make("unsent-draft-thread"),
163 createdAt: "2026-01-02T00:00:00.000Z",
164 });
165 initial.setPrompt(draftId, "Unsent prompt");
166​
167 await using screen = await render(
168 <SidebarProvider>
169 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
170 </SidebarProvider>,
171 );
172 const draftRow = screen.getByTestId("sidebar-draft-row");
173 await expect.element(draftRow).toBeInTheDocument();
174 await expect.element(screen.getByText("Thread 0").first()).toBeInTheDocument();
175 await userEvent.keyboard("{Control>}");
176 await expect.element(screen.getByText("Ctrl+1")).toBeVisible();
177 await expect.element(draftRow.getByText("Ctrl+1")).toBeVisible();
178 await expect.element(screen.getByText("Ctrl+2")).toBeVisible();
179 await userEvent.keyboard("{/Control}");
180​
181 // Previous thread from the open thread steps up to the draft above it.
182 await userEvent.keyboard("{Control>}{Shift>}{BracketLeft}{/Shift}{/Control}");
183 await vi.waitFor(() =>
184 expect(screen.router!.state.location.pathname).toBe(`/draft/${draftId}`),
185 );
186 await userEvent.keyboard("{Control>}2{/Control}");
187 await vi.waitFor(() =>
188 expect(screen.router!.state.location.pathname).not.toBe(`/draft/${draftId}`),
189 );
190 await userEvent.keyboard("{Control>}1{/Control}");
191 await vi.waitFor(() =>
192 expect(screen.router!.state.location.pathname).toBe(`/draft/${draftId}`),
193 );
194 });
195});
196​
197function threadShell(projectId: ProjectId, index: number): EnvironmentThreadShell {
198 return makeThreadFixture({
199 environmentId: EnvironmentId.make("local"),
200 id: ThreadId.make(`thread-${index}`),
201 projectId,
202 title: `Thread ${index}`,
203 });
205​
206describe("sidebar render isolation", () => {
207 // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads
208 it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => {
209 using stack = new DisposableStack();
210 const activeProject = project("active");
211 const threads = Array.from({ length: 5 }, (_, index) => threadShell(activeProject.id, index));
212 const routeThreadRef: ScopedThreadRef = {
213 environmentId: activeProject.environmentId,
214 threadId: threads[0]!.id,
215 };
216 threads.unshift(threadShell(activeProject.id, 100));
217 // A real wall-clock minute tick mid-test re-renders every row and reads as a leak.
218 vi.mocked(useNowMinute).mockReturnValue("2026-01-01T00:00");
219 vi.mocked(useProjects).mockReturnValue([activeProject]);
220 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
221 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef });
222 vi.mocked(useHandleNewThread).mockReturnValue({
223 activeDraftThread: null,
224 activeThread: null,
225 defaultProjectRef: {
226 environmentId: activeProject.environmentId,
227 projectId: activeProject.id,
228 },
229 defaultProjectFallbackReady: true,
230 handleNewThread: vi.fn().mockResolvedValue(null),
231 routeDraftId: null,
232 routeThreadRef,
233 });
234 const terminal = document.createElement("div");
235 terminal.dataset.terminalOwner = "drawer";
236 const terminalInput = document.createElement("textarea");
237 terminal.append(terminalInput);
238 document.body.append(terminal);
239 stack.defer(() => terminal.remove());
240 stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false));
241 await using screen = await render(
242 <SidebarProvider>
243 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
244 </SidebarProvider>,
245 );
246 await expect.element(screen.getByText("Thread 4").first()).toBeInTheDocument();
247 const rowRenders = () => vi.mocked(SortableThreadRow).mock.calls.length;
248​
249 using _timers = fakeTimers();
250 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
251 const beforeShortcut = rowRenders();
252 await userEvent.keyboard(`{${modifier}>}`);
253 await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true));
254 await act(() => terminalInput.focus());
255 await userEvent.keyboard(`{/${modifier}}`);
256 await act(() => terminalInput.blur());
257 expect(
258 rowRenders() - beforeShortcut,
259 "thread rows re-rendered while opening the terminal with a quick Mod shortcut",
260 ).toBe(0);
261​
262 const jumpLabelsSince = (start: number) =>
263 vi
264 .mocked(SortableThreadRow)
265 .mock.calls.slice(start)
266 .map(([props]) => props.jumpLabel)
267 .filter((label) => label !== null);
268 const beforeHold = rowRenders();
269 await userEvent.keyboard(`{${modifier}>}`);
270 await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS));
271 expect(jumpLabelsSince(beforeHold), "holding Mod showed no jump hints").toHaveLength(2);
272 const beforeRelease = rowRenders();
273 await userEvent.keyboard(`{/${modifier}}`);
274 expect(rowRenders()).toBeGreaterThan(beforeRelease);
275 expect(jumpLabelsSince(beforeRelease)).toEqual([]);
276 });
277});
278​
279describe("sidebar thread rename", () => {
280 // regression: #35151 an untouched rename wrote back the title it opened with over a newer one
281 it.each(["{Enter}", "{Tab}"])(
282 "ending an untouched rename with %s keeps a title that arrived while it was open",
283 async (finish) => {
284 const activeProject = project("active");
285 const routeThreadRef: ScopedThreadRef = {
286 environmentId: activeProject.environmentId,
287 threadId: ThreadId.make("thread-0"),
288 };
289 const shellTitled = (title: string) => ({ ...threadShell(activeProject.id, 0), title });
290 const updateMetadata = vi.fn().mockResolvedValue({ _tag: "Success" });
291 vi.mocked(useOrchestrationCommand).mockReturnValue(updateMetadata);
292 vi.mocked(readEnvironmentScope).mockReturnValue(true);
293 vi.mocked(useEnvironmentScope).mockReturnValue(true);
294 vi.mocked(useProjects).mockReturnValue([activeProject]);
295 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Fix the login redirect")]);
296 vi.mocked(useThreadRouteTarget).mockReturnValue({
297 kind: "server",
298 threadRef: routeThreadRef,
299 });
300 vi.mocked(useHandleNewThread).mockReturnValue({
301 activeDraftThread: null,
302 activeThread: null,
303 defaultProjectRef: {
304 environmentId: activeProject.environmentId,
305 projectId: activeProject.id,
306 },
307 defaultProjectFallbackReady: true,
308 handleNewThread: vi.fn().mockResolvedValue(null),
309 routeDraftId: null,
310 routeThreadRef,
311 });
312 const tree = () => (
313 <SidebarProvider>
314 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
315 </SidebarProvider>
316 );
317 await using screen = await render(tree());
318 await userEvent.dblClick(screen.getByText("Fix the login redirect").first());
319 const input = screen.getByRole("textbox", { name: "Thread title" });
320 await expect.element(input).toHaveValue("Fix the login redirect");
321​
322 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Generated title")]);
323 await screen.rerender(tree());
324 await userEvent.keyboard(finish);
325​
326 await expect.element(input).not.toBeInTheDocument();
327 expect(updateMetadata).not.toHaveBeenCalled();
328 },
329 );
330});
331​
332describe("sidebar thread menu", () => {
333 it("tells the menu whether the keyboard opened it", async () => {
334 const activeProject = project("active");
335 const thread = threadShell(activeProject.id, 0);
336 const threadRef = { environmentId: activeProject.environmentId, threadId: thread.id };
337 const show = vi.fn().mockResolvedValue(null);
338 vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi);
339 vi.mocked(useProjects).mockReturnValue([activeProject]);
340 vi.mocked(useQuietThreadShells).mockReturnValue([thread]);
341 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef });
342 vi.mocked(useHandleNewThread).mockReturnValue({
343 activeDraftThread: null,
344 activeThread: null,
345 defaultProjectRef: {
346 environmentId: activeProject.environmentId,
347 projectId: activeProject.id,
348 },
349 defaultProjectFallbackReady: true,
350 handleNewThread: vi.fn().mockResolvedValue(null),
351 routeDraftId: null,
352 routeThreadRef: threadRef,
353 });
354 await using screen = await render(
355 <SidebarProvider>
356 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
357 </SidebarProvider>,
358 );
359 const row = screen.getByText("Thread 0").first();
360 await expect.element(row).toBeInTheDocument();
361 row.element().closest<HTMLElement>("[data-sidebar-row]")!.focus();
362 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
363 await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(1));
364 expect(show.mock.lastCall?.[2]).toBe("keyboard");
365 await userEvent.click(row, { button: "right" });
366 await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(2));
367 expect(show.mock.lastCall?.[2]).toBe("mouse");
368 });
369});
370​
371describe("sidebar settled pagination", () => {
372 it("keeps the viewport in place when showing more settled threads", async () => {
373 using stack = new DisposableStack();
374 const style = document.createElement("style");
375 style.textContent = appCss;
376 document.head.append(style);
377 stack.defer(() => style.remove());
378 const focusController = createWorkspaceFocusController(document);
379 stack.defer(() => focusController.dispose());
380 let loading = false;
381 const originalShelf = vi.mocked(shelfHooks.useOlderSettledShelf).getMockImplementation()!;
382 using _shelf = vi.spyOn(shelfHooks, "useOlderSettledShelf").mockImplementation((input) => ({
383 ...originalShelf(input),
384 loading,
385 retry: () => {
386 loading = true;
387 },
388 }));
389 const activeProject = project("active");
390 const threads = Array.from({ length: 70 }, (_, index) =>
391 makeThreadFixture({
392 environmentId: activeProject.environmentId,
393 projectId: activeProject.id,
394 id: ThreadId.make(`settled-${index}`),
395 title: `Settled thread ${index}`,
396 settledOverride: "settled",
397 settledAt: "2026-01-01T00:00:00.000Z",
398 }),
399 );
400 threads.unshift(threadShell(activeProject.id, 100));
401 vi.mocked(useProjects).mockReturnValue([activeProject]);
402 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
403 vi.mocked(useThreadRouteTarget).mockReturnValue({
404 kind: "server",
405 threadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id },
406 });
407 vi.mocked(useHandleNewThread).mockReturnValue({
408 activeDraftThread: null,
409 activeThread: null,
410 defaultProjectRef: {
411 environmentId: activeProject.environmentId,
412 projectId: activeProject.id,
413 },
414 defaultProjectFallbackReady: true,
415 handleNewThread: vi.fn().mockResolvedValue(null),
416 routeDraftId: null,
417 routeThreadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id },
418 });
419 vi.mocked(useServerConfigs).mockReturnValue(
420 new Map([
421 [
422 activeProject.environmentId,
423 {
424 scratchWorkspaceRoot: null,
425 shellThreadFamilies: false,
426 } as unknown as EnvironmentServerConfig,
427 ],
428 ]),
429 );
430 await using screen = await render(
431 <SidebarProvider
432 {...workspaceAreaProps("sidebar", 0, "Threads")}
433 style={{ height: 400, minHeight: 400 }}
434 >
435 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
436 </SidebarProvider>,
437 );
438 const shelf = screen.container.querySelector<HTMLElement>(
439 '[data-sidebar-row="shelf:settled"]',
440 )!;
441 if (shelf.getAttribute("aria-expanded") === "false") await act(() => shelf.click());
442 const more = screen.getByRole("button", { name: "Show 25 more", exact: true });
443 await expect.element(more).toBeInTheDocument();
444 const moreButton = more.element() as HTMLButtonElement;
445 const viewport = moreButton.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
446 viewport.style.height = "300px";
447 viewport.style.maxHeight = "300px";
448 moreButton.scrollIntoView({ block: "nearest" });
449 const before = viewport.scrollTop;
450 expect(before).toBeGreaterThan(0);
451 moreButton.focus({ preventScroll: true });
452 await act(() => moreButton.click());
453 await expect
454 .element(screen.getByRole("button", { name: "Loading", exact: true }))
455 .toBeInTheDocument();
456 await expect
457 .element(screen.getByRole("button", { name: "Loading", exact: true }))
458 .toHaveFocus();
459 expect(viewport.scrollTop).toBe(before);
460 const loadedRows = screen.container.querySelectorAll("[data-thread-item]").length;
461 await act(() => moreButton.click());
462 expect(screen.container.querySelectorAll("[data-thread-item]")).toHaveLength(loadedRows);
463 });
464});