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