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

Sidebar.browser.test.tsx

249 lines10.2 KB

1import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2import {
3 DEFAULT_CLIENT_SETTINGS,
4 EnvironmentId,
5 ProjectId,
6 ThreadId,
7 type ScopedThreadRef,
8} from "@t3tools/contracts";
9import { isMacPlatform } from "@t3tools/shared/keybindings";
10import { describe, expect, it, vi } from "vite-plus/test";
11import { userEvent } from "vite-plus/test/browser";
12​
13import { act, fakeTimers, render } from "../../test/render";
14import { openCommandPalette } from "../commandPaletteBus";
15import { makeThreadFixture } from "../test-fixtures";
16import { useHandleNewThread } from "../hooks/useHandleNewThread";
17import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings";
18import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
19import { useProjects, useQuietThreadShells } from "../state/entities";
20import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
21import { useOrchestrationCommand } from "../state/use-orchestration-command";
22import { useTerminalUiStateStore } from "../terminalUiStateStore";
23import type { Project } from "../types";
24import Sidebar from "./Sidebar";
25import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic";
26import { SortableThreadRow } from "./sidebar/SidebarThreadRow";
27import { SidebarProvider } from "./ui/sidebar";
28​
29vi.mock("../state/entities", { spy: true });
30vi.mock("../hooks/useHandleNewThread", { spy: true });
31vi.mock("../hooks/useThreadRouteTarget", { spy: true });
32vi.mock("./sidebar/SidebarThreadRow", { spy: true });
33vi.mock("../state/session", { spy: true });
34vi.mock("../state/use-orchestration-command", { spy: true });
35vi.mock(import("../state/server"), async (original) => {
36 const { Atom } = await import("effect/reactivity");
37 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
38 // The desktop defaults: holding Mod alone already matches a thread jump.
39 const keybindings = compileResolvedKeybindingsConfig([
40 { key: "mod+1", command: "thread.jump.1" },
41 { key: "mod+2", command: "thread.jump.2" },
42 ]);
43 return { ...(await original()), primaryServerKeybindingsAtom: Atom.make(keybindings) };
44});
45vi.mock("../commandPaletteBus", () => ({
46 openCommandPalette: vi.fn(),
47 isCommandPaletteOpen: () => false,
48}));
49vi.mock("./sidebar/SidebarChrome", () => ({
50 SidebarChromeHeader: () => null,
51 SidebarChromeFooter: () => null,
52}));
53​
54function project(id: string): Project {
55 return {
56 id: ProjectId.make(id),
57 environmentId: EnvironmentId.make("local"),
58 title: id,
59 workspaceRoot: `/projects/${id}`,
60 repositoryIdentity: null,
61 defaultModelSelection: null,
62 createdAt: "2026-01-01T00:00:00.000Z",
63 updatedAt: "2026-01-01T00:00:00.000Z",
64 scripts: [],
65 };
67​
68describe("sidebar header new thread", () => {
69 it.each([
70 { mode: "normal", count: 2, shift: false, picker: true },
71 { mode: "boring", count: 2, shift: false, picker: true },
72 { mode: "boring", count: 2, shift: true, picker: false },
73 { mode: "boring", count: 1, shift: false, picker: false },
74 ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => {
75 using stack = new DisposableStack();
76 const previousSettings = getClientSettings();
77 stack.defer(() => __setClientSettingsForTests(previousSettings));
78 __setClientSettingsForTests({
79 ...DEFAULT_CLIENT_SETTINGS,
80 boringSidebarEnabled: scenario.mode === "boring",
81 });
82 const projects = [project("active"), project("idle")].slice(0, scenario.count);
83 const currentProjectRef = {
84 environmentId: projects[0]!.environmentId,
85 projectId: projects[0]!.id,
86 };
87 const startThread = vi.fn().mockResolvedValue(null);
88 vi.mocked(useProjects).mockReturnValue(projects);
89 vi.mocked(useHandleNewThread).mockReturnValue({
90 activeDraftThread: null,
91 activeThread: null,
92 defaultProjectRef: currentProjectRef,
93 defaultProjectFallbackReady: true,
94 handleNewThread: startThread,
95 routeDraftId: null,
96 routeThreadRef: null,
97 });
98 vi.mocked(openCommandPalette).mockClear();
99 await using screen = await render(
100 <SidebarProvider>
101 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
102 </SidebarProvider>,
103 );
104​
105 await userEvent.click(screen.getByRole("button", { name: "New thread", exact: true }), {
106 modifiers: scenario.shift ? ["Shift"] : [],
107 });
108​
109 if (scenario.picker) {
110 expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "new-thread-in" });
111 expect(startThread).not.toHaveBeenCalled();
112 } else {
113 expect(openCommandPalette).not.toHaveBeenCalled();
114 expect(startThread).toHaveBeenCalledExactlyOnceWith(currentProjectRef);
115 }
116 });
117});
118​
119function threadShell(projectId: ProjectId, index: number): EnvironmentThreadShell {
120 return makeThreadFixture({
121 environmentId: EnvironmentId.make("local"),
122 id: ThreadId.make(`thread-${index}`),
123 projectId,
124 title: `Thread ${index}`,
125 });
127​
128describe("sidebar render isolation", () => {
129 // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads
130 it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => {
131 using stack = new DisposableStack();
132 const activeProject = project("active");
133 const threads = Array.from({ length: 5 }, (_, index) => threadShell(activeProject.id, index));
134 const routeThreadRef: ScopedThreadRef = {
135 environmentId: activeProject.environmentId,
136 threadId: threads[0]!.id,
137 };
138 vi.mocked(useProjects).mockReturnValue([activeProject]);
139 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
140 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef });
141 vi.mocked(useHandleNewThread).mockReturnValue({
142 activeDraftThread: null,
143 activeThread: null,
144 defaultProjectRef: {
145 environmentId: activeProject.environmentId,
146 projectId: activeProject.id,
147 },
148 defaultProjectFallbackReady: true,
149 handleNewThread: vi.fn().mockResolvedValue(null),
150 routeDraftId: null,
151 routeThreadRef,
152 });
153 const terminal = document.createElement("div");
154 terminal.dataset.terminalOwner = "drawer";
155 const terminalInput = document.createElement("textarea");
156 terminal.append(terminalInput);
157 document.body.append(terminal);
158 stack.defer(() => terminal.remove());
159 stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false));
160 await using screen = await render(
161 <SidebarProvider>
162 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
163 </SidebarProvider>,
164 );
165 await expect.element(screen.getByText("Thread 4").first()).toBeInTheDocument();
166 const rowRenders = () => vi.mocked(SortableThreadRow).mock.calls.length;
167​
168 using _timers = fakeTimers();
169 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
170 const beforeShortcut = rowRenders();
171 await userEvent.keyboard(`{${modifier}>}`);
172 await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true));
173 await act(() => terminalInput.focus());
174 await userEvent.keyboard(`{/${modifier}}`);
175 await act(() => terminalInput.blur());
176 expect(
177 rowRenders() - beforeShortcut,
178 "thread rows re-rendered while opening the terminal with a quick Mod shortcut",
179 ).toBe(0);
180​
181 const jumpLabelsSince = (start: number) =>
182 vi
183 .mocked(SortableThreadRow)
184 .mock.calls.slice(start)
185 .map(([props]) => props.jumpLabel)
186 .filter((label) => label !== null);
187 const beforeHold = rowRenders();
188 await userEvent.keyboard(`{${modifier}>}`);
189 await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS));
190 expect(jumpLabelsSince(beforeHold), "holding Mod showed no jump hints").toHaveLength(2);
191 const beforeRelease = rowRenders();
192 await userEvent.keyboard(`{/${modifier}}`);
193 expect(rowRenders()).toBeGreaterThan(beforeRelease);
194 expect(jumpLabelsSince(beforeRelease)).toEqual([]);
195 });
196});
197​
198describe("sidebar thread rename", () => {
199 // regression: #35151 an untouched rename wrote back the title it opened with over a newer one
200 it.each(["{Enter}", "{Tab}"])(
201 "ending an untouched rename with %s keeps a title that arrived while it was open",
202 async (finish) => {
203 const activeProject = project("active");
204 const routeThreadRef: ScopedThreadRef = {
205 environmentId: activeProject.environmentId,
206 threadId: ThreadId.make("thread-0"),
207 };
208 const shellTitled = (title: string) => ({ ...threadShell(activeProject.id, 0), title });
209 const updateMetadata = vi.fn().mockResolvedValue({ _tag: "Success" });
210 vi.mocked(useOrchestrationCommand).mockReturnValue(updateMetadata);
211 vi.mocked(readEnvironmentScope).mockReturnValue(true);
212 vi.mocked(useEnvironmentScope).mockReturnValue(true);
213 vi.mocked(useProjects).mockReturnValue([activeProject]);
214 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Fix the login redirect")]);
215 vi.mocked(useThreadRouteTarget).mockReturnValue({
216 kind: "server",
217 threadRef: routeThreadRef,
218 });
219 vi.mocked(useHandleNewThread).mockReturnValue({
220 activeDraftThread: null,
221 activeThread: null,
222 defaultProjectRef: {
223 environmentId: activeProject.environmentId,
224 projectId: activeProject.id,
225 },
226 defaultProjectFallbackReady: true,
227 handleNewThread: vi.fn().mockResolvedValue(null),
228 routeDraftId: null,
229 routeThreadRef,
230 });
231 const tree = () => (
232 <SidebarProvider>
233 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
234 </SidebarProvider>
235 );
236 await using screen = await render(tree());
237 await userEvent.dblClick(screen.getByText("Fix the login redirect").first());
238 const input = screen.getByRole("textbox", { name: "Thread title" });
239 await expect.element(input).toHaveValue("Fix the login redirect");
240​
241 vi.mocked(useQuietThreadShells).mockReturnValue([shellTitled("Generated title")]);
242 await screen.rerender(tree());
243 await userEvent.keyboard(finish);
244​
245 await expect.element(input).not.toBeInTheDocument();
246 expect(updateMetadata).not.toHaveBeenCalled();
247 },
248 );
249});