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

Sidebar.browser.test.tsx

192 lines7.7 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 { useTerminalUiStateStore } from "../terminalUiStateStore";
21import type { Project } from "../types";
22import Sidebar from "./Sidebar";
23import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic";
24import { SortableThreadRow } from "./sidebar/SidebarThreadRow";
25import { SidebarProvider } from "./ui/sidebar";
26​
27vi.mock("../state/entities", { spy: true });
28vi.mock("../hooks/useHandleNewThread", { spy: true });
29vi.mock("../hooks/useThreadRouteTarget", { spy: true });
30vi.mock("./sidebar/SidebarThreadRow", { spy: true });
31vi.mock(import("../state/server"), async (original) => {
32 const { Atom } = await import("effect/reactivity");
33 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
34 // The desktop defaults: holding Mod alone already matches a thread jump.
35 const keybindings = compileResolvedKeybindingsConfig([
36 { key: "mod+1", command: "thread.jump.1" },
37 { key: "mod+2", command: "thread.jump.2" },
38 ]);
39 return { ...(await original()), primaryServerKeybindingsAtom: Atom.make(keybindings) };
40});
41vi.mock("../commandPaletteBus", () => ({
42 openCommandPalette: vi.fn(),
43 isCommandPaletteOpen: () => false,
44}));
45vi.mock("./sidebar/SidebarChrome", () => ({
46 SidebarChromeHeader: () => null,
47 SidebarChromeFooter: () => null,
48}));
49​
50function project(id: string): Project {
51 return {
52 id: ProjectId.make(id),
53 environmentId: EnvironmentId.make("local"),
54 title: id,
55 workspaceRoot: `/projects/${id}`,
56 repositoryIdentity: null,
57 defaultModelSelection: null,
58 createdAt: "2026-01-01T00:00:00.000Z",
59 updatedAt: "2026-01-01T00:00:00.000Z",
60 scripts: [],
61 };
63​
64describe("sidebar header new thread", () => {
65 it.each([
66 { mode: "normal", count: 2, shift: false, picker: true },
67 { mode: "boring", count: 2, shift: false, picker: true },
68 { mode: "boring", count: 2, shift: true, picker: false },
69 { mode: "boring", count: 1, shift: false, picker: false },
70 ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => {
71 using stack = new DisposableStack();
72 const previousSettings = getClientSettings();
73 stack.defer(() => __setClientSettingsForTests(previousSettings));
74 __setClientSettingsForTests({
75 ...DEFAULT_CLIENT_SETTINGS,
76 boringSidebarEnabled: scenario.mode === "boring",
77 });
78 const projects = [project("active"), project("idle")].slice(0, scenario.count);
79 const currentProjectRef = {
80 environmentId: projects[0]!.environmentId,
81 projectId: projects[0]!.id,
82 };
83 const startThread = vi.fn().mockResolvedValue(null);
84 vi.mocked(useProjects).mockReturnValue(projects);
85 vi.mocked(useHandleNewThread).mockReturnValue({
86 activeDraftThread: null,
87 activeThread: null,
88 defaultProjectRef: currentProjectRef,
89 defaultProjectFallbackReady: true,
90 handleNewThread: startThread,
91 routeDraftId: null,
92 routeThreadRef: null,
93 });
94 vi.mocked(openCommandPalette).mockClear();
95 await using screen = await render(
96 <SidebarProvider>
97 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
98 </SidebarProvider>,
99 );
100​
101 await userEvent.click(screen.getByRole("button", { name: "New thread", exact: true }), {
102 modifiers: scenario.shift ? ["Shift"] : [],
103 });
104​
105 if (scenario.picker) {
106 expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "new-thread-in" });
107 expect(startThread).not.toHaveBeenCalled();
108 } else {
109 expect(openCommandPalette).not.toHaveBeenCalled();
110 expect(startThread).toHaveBeenCalledExactlyOnceWith(currentProjectRef);
111 }
112 });
113});
114​
115function threadShell(projectId: ProjectId, index: number): EnvironmentThreadShell {
116 return makeThreadFixture({
117 environmentId: EnvironmentId.make("local"),
118 id: ThreadId.make(`thread-${index}`),
119 projectId,
120 title: `Thread ${index}`,
121 });
123​
124describe("sidebar render isolation", () => {
125 // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads
126 it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => {
127 using stack = new DisposableStack();
128 const activeProject = project("active");
129 const threads = Array.from({ length: 5 }, (_, index) => threadShell(activeProject.id, index));
130 const routeThreadRef: ScopedThreadRef = {
131 environmentId: activeProject.environmentId,
132 threadId: threads[0]!.id,
133 };
134 vi.mocked(useProjects).mockReturnValue([activeProject]);
135 vi.mocked(useQuietThreadShells).mockReturnValue(threads);
136 vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef });
137 vi.mocked(useHandleNewThread).mockReturnValue({
138 activeDraftThread: null,
139 activeThread: null,
140 defaultProjectRef: {
141 environmentId: activeProject.environmentId,
142 projectId: activeProject.id,
143 },
144 defaultProjectFallbackReady: true,
145 handleNewThread: vi.fn().mockResolvedValue(null),
146 routeDraftId: null,
147 routeThreadRef,
148 });
149 const terminal = document.createElement("div");
150 terminal.dataset.terminalOwner = "drawer";
151 const terminalInput = document.createElement("textarea");
152 terminal.append(terminalInput);
153 document.body.append(terminal);
154 stack.defer(() => terminal.remove());
155 stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false));
156 await using screen = await render(
157 <SidebarProvider>
158 <Sidebar routeReveal={{ observedKey: null, pendingKey: null }} />
159 </SidebarProvider>,
160 );
161 await expect.element(screen.getByText("Thread 4").first()).toBeInTheDocument();
162 const rowRenders = () => vi.mocked(SortableThreadRow).mock.calls.length;
163​
164 using _timers = fakeTimers();
165 const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
166 const beforeShortcut = rowRenders();
167 await userEvent.keyboard(`{${modifier}>}`);
168 await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true));
169 await act(() => terminalInput.focus());
170 await userEvent.keyboard(`{/${modifier}}`);
171 await act(() => terminalInput.blur());
172 expect(
173 rowRenders() - beforeShortcut,
174 "thread rows re-rendered while opening the terminal with a quick Mod shortcut",
175 ).toBe(0);
176​
177 const jumpLabelsSince = (start: number) =>
178 vi
179 .mocked(SortableThreadRow)
180 .mock.calls.slice(start)
181 .map(([props]) => props.jumpLabel)
182 .filter((label) => label !== null);
183 const beforeHold = rowRenders();
184 await userEvent.keyboard(`{${modifier}>}`);
185 await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS));
186 expect(jumpLabelsSince(beforeHold), "holding Mod showed no jump hints").toHaveLength(2);
187 const beforeRelease = rowRenders();
188 await userEvent.keyboard(`{/${modifier}}`);
189 expect(rowRenders()).toBeGreaterThan(beforeRelease);
190 expect(jumpLabelsSince(beforeRelease)).toEqual([]);
191 });
192});