Open History to see the last commit
1import appCss from "../index.css?inline";
2import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
3import * as shelfHooks from "../state/olderSettledShelf";
4import { createWorkspaceFocusController, workspaceAreaProps } from "../lib/workspaceFocus";
5import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
6import {
7 DEFAULT_CLIENT_SETTINGS,
8 EnvironmentId,
9 ProjectId,
10 ThreadId,
11 type ScopedThreadRef,
12} from "@t3tools/contracts";
13import { isMacPlatform } from "@t3tools/shared/keybindings";
14import { describe, expect, it, vi } from "vite-plus/test";
15import { userEvent } from "vite-plus/test/browser";
16
17import { act, fakeTimers, render } from "../../test/render";
18import { openCommandPalette } from "../commandPaletteBus";
19import { makeThreadFixture } from "../test-fixtures";
20import { useHandleNewThread } from "../hooks/useHandleNewThread";
21import { useNowMinute } from "../hooks/useNowMinute";
22import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings";
23import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
24import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities";
25import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
26import { useOrchestrationCommand } from "../state/use-orchestration-command";
27import { useTerminalUiStateStore } from "../terminalUiStateStore";
28import type { Project } from "../types";
29import Sidebar from "./Sidebar";
30import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic";
31import { SortableThreadRow } from "./sidebar/SidebarThreadRow";
32import { SidebarProvider } from "./ui/sidebar";
33
34vi.mock(import("../state/olderSettledShelf"), async (original) => {
35 const actual = await original();
36 return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) };
37});
38vi.mock("../state/entities", { spy: true });
39vi.mock("../hooks/useHandleNewThread", { spy: true });
40vi.mock("../hooks/useNowMinute", { spy: true });
41vi.mock("../hooks/useThreadRouteTarget", { spy: true });
42vi.mock("./sidebar/SidebarThreadRow", { spy: true });
43vi.mock("../state/session", { spy: true });
44vi.mock("../state/use-orchestration-command", { spy: true });
45vi.mock(import("../state/server"), async (original) => {
46 const { Atom } = await import("effect/reactivity");
47 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
48 // The desktop defaults: holding Mod alone already matches a thread jump.
49 const keybindings = compileResolvedKeybindingsConfig([
50 { key: "mod+1", command: "thread.jump.1" },
51 { key: "mod+2", command: "thread.jump.2" },
52 ]);
53 return { ...(await original()), primaryServerKeybindingsAtom: Atom.make(keybindings) };
54});
55vi.mock("../commandPaletteBus", () => ({
56 openCommandPalette: vi.fn(),
57 isCommandPaletteOpen: () => false,
58}));
59vi.mock("./sidebar/SidebarChrome", () => ({
60 SidebarChromeHeader: () => null,
61 SidebarChromeFooter: () => null,
62}));
63
64function project(id: string): Project {
65 return {
66 id: ProjectId.make(id),
67 environmentId: EnvironmentId.make("local"),
68 title: id,
69 workspaceRoot: `/projects/${id}`,
70 repositoryIdentity: null,
71 defaultModelSelection: null,
72 createdAt: "2026-01-01T00:00:00.000Z",
73 updatedAt: "2026-01-01T00:00:00.000Z",
74 scripts: [],
75 };
76}
77
78describe("sidebar header new thread", () => {
79 it.each([
80 { mode: "normal", count: 2, shift: false, picker: true },
81 { mode: "boring", count: 2, shift: false, picker: true },
82 { mode: "boring", count: 2, shift: true, picker: false },
83 { mode: "boring", count: 1, shift: false, picker: false },
84 ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => {
85 using stack = new DisposableStack();
86 const previousSettings = getClientSettings();
87 stack.defer(() => __setClientSettingsForTests(previousSettings));
88 __setClientSettingsForTests({
89 ...DEFAULT_CLIENT_SETTINGS,
90 boringSidebarEnabled: scenario.mode === "boring",
91 });
92 const projects = [project("active"), project("idle")].slice(0, scenario.count);
93 const currentProjectRef = {
94 environmentId: projects[0]!.environmentId,
95 projectId: projects[0]!.id,
96 };
97 const startThread = vi.fn().mockResolvedValue(null);
98 vi.mocked(useProjects).mockReturnValue(projects);
99 vi.mocked(useHandleNewThread).mockReturnValue({
100 activeDraftThread: null,
101 activeThread: null,
102 defaultProjectRef: currentProjectRef,
103 defaultProjectFallbackReady: true,
104 handleNewThread: startThread,
105 routeDraftId: null,
106 routeThreadRef: null,
107 });
108 vi.mocked(openCommandPalette).mockClear();
109 await using screen = await render(
110 <SidebarProvider>
111 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
112 </SidebarProvider>,
113 );
114
115 await userEvent.click(screen.getByRole("button", { name: "New thread", exact: true }), {
116 modifiers: scenario.shift ? ["Shift"] : [],
117 });
118
119 if (scenario.picker) {
120 expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "new-thread-in" });
121 expect(startThread).not.toHaveBeenCalled();
122 } else {
123 expect(openCommandPalette).not.toHaveBeenCalled();
124 expect(startThread).toHaveBeenCalledExactlyOnceWith(currentProjectRef);
125 }
126 });
127});
128
129function threadShell(projectId: ProjectId, index: number): EnvironmentThreadShell {
130 return makeThreadFixture({
131 environmentId: EnvironmentId.make("local"),
132 id: ThreadId.make(`thread-${index}`),
133 projectId,
134 title: `Thread ${index}`,
135 });
136}
137
138describe("sidebar render isolation", () => {
139 // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads
140 it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => {
141 using stack = new DisposableStack();
142 const activeProject = project("active");
143 const threads = Array.from({ length: 5 }, (_, index) => threadShell(activeProject.id, index));
144 const routeThreadRef: ScopedThreadRef = {
145 environmentId: activeProject.environmentId,
146 threadId: threads[0]!.id,
147 };
148 threads.unshift(threadShell(activeProject.id, 100));
149 // A real wall-clock minute tick mid-test re-renders every row and reads as a leak.
150 vi.mocked(useNowMinute).mockReturnValue("2026-01-01T00:00");
151 vi.mocked(useProjects).mockReturnValue([activeProject]);
152 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
153 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef });
154 vi.mocked(useHandleNewThread).mockReturnValue({
155 activeDraftThread: null,
156 activeThread: null,
157 defaultProjectRef: {
158 environmentId: activeProject.environmentId,
159 projectId: activeProject.id,
160 },
161 defaultProjectFallbackReady: true,
162 handleNewThread: vi.fn().mockResolvedValue(null),
163 routeDraftId: null,
164 routeThreadRef,
165 });
166 const terminal = document.createElement("div");
167 terminal.dataset.terminalOwner = "drawer";
168 const terminalInput = document.createElement("textarea");
169 terminal.append(terminalInput);
170 document.body.append(terminal);
171 stack.defer(() => terminal.remove());
172 stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false));
173 await using screen = await render(
174 <SidebarProvider>
175 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
176 </SidebarProvider>,
177 );
178 await expect.element(screen.getByText("Thread 4").first()).toBeInTheDocument();
179 const rowRenders = () => vi.mocked(SortableThreadRow).mock.calls.length;
180
181 using _timers = fakeTimers();
182 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
183 const beforeShortcut = rowRenders();
184 await userEvent.keyboard(`{${modifier}>}`);
185 await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true));
186 await act(() => terminalInput.focus());
187 await userEvent.keyboard(`{/${modifier}}`);
188 await act(() => terminalInput.blur());
189 expect(
190 rowRenders() - beforeShortcut,
191 "thread rows re-rendered while opening the terminal with a quick Mod shortcut",
192 ).toBe(0);
193
194 const jumpLabelsSince = (start: number) =>
195 vi
196 .mocked(SortableThreadRow)
197 .mock.calls.slice(start)
198 .map(([props]) => props.jumpLabel)
199 .filter((label) => label !== null);
200 const beforeHold = rowRenders();
201 await userEvent.keyboard(`{${modifier}>}`);
202 await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS));
203 expect(jumpLabelsSince(beforeHold), "holding Mod showed no jump hints").toHaveLength(2);
204 const beforeRelease = rowRenders();
205 await userEvent.keyboard(`{/${modifier}}`);
206 expect(rowRenders()).toBeGreaterThan(beforeRelease);
207 expect(jumpLabelsSince(beforeRelease)).toEqual([]);
208 });
209});
210
211describe("sidebar thread rename", () => {
212 // regression: #35151 an untouched rename wrote back the title it opened with over a newer one
213 it.each(["{Enter}", "{Tab}"])(
214 "ending an untouched rename with %s keeps a title that arrived while it was open",
215 async (finish) => {
216 const activeProject = project("active");
217 const routeThreadRef: ScopedThreadRef = {
218 environmentId: activeProject.environmentId,
219 threadId: ThreadId.make("thread-0"),
220 };
221 const shellTitled = (title: string) => ({ ...threadShell(activeProject.id, 0), title });
222 const updateMetadata = vi.fn().mockResolvedValue({ _tag: "Success" });
223 vi.mocked(useOrchestrationCommand).mockReturnValue(updateMetadata);
224 vi.mocked(readEnvironmentScope).mockReturnValue(true);
225 vi.mocked(useEnvironmentScope).mockReturnValue(true);
226 vi.mocked(useProjects).mockReturnValue([activeProject]);
227 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Fix the login redirect")]);
228 vi.mocked(useThreadRouteTarget).mockReturnValue({
229 kind: "server",
230 threadRef: routeThreadRef,
231 });
232 vi.mocked(useHandleNewThread).mockReturnValue({
233 activeDraftThread: null,
234 activeThread: null,
235 defaultProjectRef: {
236 environmentId: activeProject.environmentId,
237 projectId: activeProject.id,
238 },
239 defaultProjectFallbackReady: true,
240 handleNewThread: vi.fn().mockResolvedValue(null),
241 routeDraftId: null,
242 routeThreadRef,
243 });
244 const tree = () => (
245 <SidebarProvider>
246 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
247 </SidebarProvider>
248 );
249 await using screen = await render(tree());
250 await userEvent.dblClick(screen.getByText("Fix the login redirect").first());
251 const input = screen.getByRole("textbox", { name: "Thread title" });
252 await expect.element(input).toHaveValue("Fix the login redirect");
253
254 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Generated title")]);
255 await screen.rerender(tree());
256 await userEvent.keyboard(finish);
257
258 await expect.element(input).not.toBeInTheDocument();
259 expect(updateMetadata).not.toHaveBeenCalled();
260 },
261 );
262});
263
264describe("sidebar settled pagination", () => {
265 it("keeps the viewport in place when showing more settled threads", async () => {
266 using stack = new DisposableStack();
267 const style = document.createElement("style");
268 style.textContent = appCss;
269 document.head.append(style);
270 stack.defer(() => style.remove());
271 const focusController = createWorkspaceFocusController(document);
272 stack.defer(() => focusController.dispose());
273 let loading = false;
274 const originalShelf = vi.mocked(shelfHooks.useOlderSettledShelf).getMockImplementation()!;
275 using _shelf = vi.spyOn(shelfHooks, "useOlderSettledShelf").mockImplementation((input) => ({
276 ...originalShelf(input),
277 loading,
278 retry: () => {
279 loading = true;
280 },
281 }));
282 const activeProject = project("active");
283 const threads = Array.from({ length: 70 }, (_, index) =>
284 makeThreadFixture({
285 environmentId: activeProject.environmentId,
286 projectId: activeProject.id,
287 id: ThreadId.make(`settled-${index}`),
288 title: `Settled thread ${index}`,
289 settledOverride: "settled",
290 settledAt: "2026-01-01T00:00:00.000Z",
291 }),
292 );
293 threads.unshift(threadShell(activeProject.id, 100));
294 vi.mocked(useProjects).mockReturnValue([activeProject]);
295 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
296 vi.mocked(useThreadRouteTarget).mockReturnValue({
297 kind: "server",
298 threadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id },
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: { environmentId: activeProject.environmentId, threadId: threads[0]!.id },
311 });
312 vi.mocked(useServerConfigs).mockReturnValue(
313 new Map([
314 [
315 activeProject.environmentId,
316 {
317 scratchWorkspaceRoot: null,
318 shellThreadFamilies: false,
319 } as unknown as EnvironmentServerConfig,
320 ],
321 ]),
322 );
323 await using screen = await render(
324 <SidebarProvider
325 {...workspaceAreaProps("sidebar", 0, "Threads")}
326 style={{ height: 400, minHeight: 400 }}
327 >
328 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
329 </SidebarProvider>,
330 );
331 const shelf = screen.container.querySelector<HTMLElement>(
332 '[data-sidebar-row="shelf:settled"]',
333 )!;
334 if (shelf.getAttribute("aria-expanded") === "false") await act(() => shelf.click());
335 const more = screen.getByRole("button", { name: "Show 25 more", exact: true });
336 await expect.element(more).toBeInTheDocument();
337 const moreButton = more.element() as HTMLButtonElement;
338 const viewport = moreButton.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
339 viewport.style.height = "300px";
340 viewport.style.maxHeight = "300px";
341 moreButton.scrollIntoView({ block: "nearest" });
342 const before = viewport.scrollTop;
343 expect(before).toBeGreaterThan(0);
344 moreButton.focus({ preventScroll: true });
345 await act(() => moreButton.click());
346 await expect
347 .element(screen.getByRole("button", { name: "Loading", exact: true }))
348 .toBeInTheDocument();
349 await expect
350 .element(screen.getByRole("button", { name: "Loading", exact: true }))
351 .toHaveFocus();
352 expect(viewport.scrollTop).toBe(before);
353 const loadedRows = screen.container.querySelectorAll("[data-thread-item]").length;
354 await act(() => moreButton.click());
355 expect(screen.container.querySelectorAll("[data-thread-item]")).toHaveLength(loadedRows);
356 });
357});