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