@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
tsx 311 lines 11.5 KB
Raw
1 import { threadKey } from "@t3tools/client-runtime/state/entities";
2 import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
3 import { describe, expect, it, vi } from "vite-plus/test";
4 import { page, userEvent } from "vite-plus/test/browser";
5
6 import { act, render } from "../../test/render";
7 import { openCommandPalette } from "../commandPaletteBus";
8 import { useCommandPaletteStore } from "../commandPaletteStore";
9 import { LAST_USED_PROJECT_STORAGE_KEY } from "../hooks/useHandleNewThread";
10 import { removeLocalStorageItem } from "../hooks/useLocalStorage";
11 import { makeThreadFixture } from "../test-fixtures";
12 import type { Project, Thread } from "../types";
13 import { CommandPalette } from "./CommandPalette";
14
15 const entities = vi.hoisted(() => ({
16 projects: [] as ReadonlyArray<Project>,
17 threads: [] as ReadonlyArray<Thread>,
18 activeThread: undefined as Thread | undefined,
19 delegatedUnderParent: new Set<string>() as ReadonlySet<string>,
20 handleNewThread: vi.fn(async () => undefined),
21 }));
22 vi.mock("../state/server", async (original) => {
23 const actual = await original<typeof import("../state/server")>();
24 const { Atom } = await import("effect/reactivity");
25 const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings");
26 const { THREAD_JUMP_KEYBINDING_COMMANDS } = await import("@t3tools/contracts");
27 // The default jump bindings are desktop-only; these hold in the browser too.
28 const jumpBindings = compileResolvedKeybindingsConfig(
29 THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
30 key: `mod+${index + 1}`,
31 command,
32 })),
33 );
34 return { ...actual, primaryServerKeybindingsAtom: Atom.make(jumpBindings) };
35 });
36 vi.mock("../hooks/useHandleNewThread", async (original) => {
37 const actual = await original<typeof import("../hooks/useHandleNewThread")>();
38 return {
39 ...actual,
40 useHandleNewThread: () => ({
41 ...actual.useHandleNewThread(),
42 activeThread: entities.activeThread,
43 handleNewThread: entities.handleNewThread,
44 }),
45 };
46 });
47 vi.mock("../state/entities", async (original) => ({
48 ...(await original<typeof import("../state/entities")>()),
49 useProjects: () => entities.projects,
50 useVisibleThreadShells: () => entities.threads,
51 useDelegatedUnderParent: () => entities.delegatedUnderParent,
52 }));
53
54 function setup(state: Partial<typeof entities> = {}) {
55 // Earlier browser test files share this origin's localStorage; a remembered project
56 // that is not listed here hides the default "New thread in <project>" row.
57 removeLocalStorageItem(LAST_USED_PROJECT_STORAGE_KEY);
58 useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true);
59 entities.projects = state.projects ?? [];
60 entities.threads = state.threads ?? [];
61 entities.activeThread = state.activeThread;
62 entities.delegatedUnderParent = state.delegatedUnderParent ?? new Set();
63 entities.handleNewThread.mockClear();
64 }
65
66 function makeProject(title: string): Project {
67 return {
68 id: ProjectId.make(title),
69 environmentId: EnvironmentId.make("local"),
70 title,
71 workspaceRoot: `/work/${title}`,
72 repositoryIdentity: null,
73 defaultModelSelection: null,
74 createdAt: "2026-03-01T00:00:00.000Z",
75 updatedAt: "2026-03-01T00:00:00.000Z",
76 scripts: [],
77 };
78 }
79
80 describe("CommandPalette open intents", () => {
81 it("drags a searched thread into the current composer without navigating", async () => {
82 const environmentId = EnvironmentId.make("remote");
83 const threadId = ThreadId.make("dragged-thread");
84 setup({
85 threads: [makeThreadFixture({ environmentId, id: threadId, title: "Drag this thread" })],
86 });
87 const onDrop = vi.fn();
88 await using screen = await render(
89 <CommandPalette>
90 <div
91 data-thread-context-drop="true"
92 ref={(node) => {
93 node?.addEventListener("t3-thread-context-drop", onDrop);
94 }}
95 style={{ position: "fixed", bottom: 0, width: 300, height: 100 }}
96 >
97 Composer
98 </div>
99 </CommandPalette>,
100 );
101 const pathname = screen.router?.state.location.pathname;
102 openCommandPalette({ query: "Drag this thread" });
103 const row = page.getByRole("option", { name: /Drag this thread/ });
104 await expect.element(row).toBeVisible();
105 const bounds = row.element().getBoundingClientRect();
106 const pointer = (type: string, x: number, y: number) =>
107 new PointerEvent(type, {
108 bubbles: true,
109 cancelable: true,
110 pointerId: 1,
111 isPrimary: true,
112 button: 0,
113 buttons: type === "pointerup" ? 0 : 1,
114 clientX: x,
115 clientY: y,
116 });
117 await act(() => {
118 row.element().dispatchEvent(pointer("pointerdown", bounds.x + 20, bounds.y + 10));
119 document.dispatchEvent(pointer("pointermove", bounds.x + 30, bounds.y + 20));
120 });
121 expect(useCommandPaletteStore.getState().open).toBe(false);
122 await act(() => {
123 document.dispatchEvent(pointer("pointermove", 50, window.innerHeight - 30));
124 document.dispatchEvent(pointer("pointerup", 50, window.innerHeight - 30));
125 });
126 expect(onDrop).toHaveBeenCalledOnce();
127 expect((onDrop.mock.calls[0]![0] as CustomEvent).detail).toEqual([
128 { environmentId, threadId, title: "Drag this thread" },
129 ]);
130 expect(screen.router?.state.location.pathname).toBe(pathname);
131 });
132
133 it("opens New thread in... with focus in the search input, not the Back button", async () => {
134 setup();
135 await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
136
137 openCommandPalette({ open: "new-thread-in" });
138
139 await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();
140 });
141
142 it("highlights the first project when New thread in... opens from the root list", async () => {
143 const environmentId = EnvironmentId.make("local");
144 const project = (id: string, title: string): Project => ({
145 id: ProjectId.make(id),
146 environmentId,
147 title,
148 workspaceRoot: `/work/${id}`,
149 repositoryIdentity: null,
150 defaultModelSelection: null,
151 createdAt: "2026-03-01T00:00:00.000Z",
152 updatedAt: "2026-03-01T00:00:00.000Z",
153 scripts: [],
154 });
155 setup({
156 projects: [project("acme", "Acme"), project("beta", "Beta"), project("gamma", "Gamma")],
157 });
158 await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
159
160 openCommandPalette({});
161 await expect
162 .element(page.getByPlaceholder("Search commands, projects, and threads..."))
163 .toHaveFocus();
164 await userEvent.keyboard("{ArrowDown}");
165 await expect
166 .element(page.getByRole("option", { name: /^New thread in\.\.\./ }))
167 .toHaveAttribute("data-highlighted");
168 await userEvent.keyboard("{Enter}");
169
170 await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();
171 await expect.element(page.getByRole("option").first()).toHaveAttribute("data-highlighted");
172 await expect.element(page.getByRole("option").nth(1)).not.toHaveAttribute("data-highlighted");
173 });
174
175 it("opens a search intent with its query in the focused input", async () => {
176 setup();
177 await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
178
179 openCommandPalette({ query: "acme" });
180
181 const input = page.getByPlaceholder("Search commands, projects, and threads...");
182 await expect.element(input).toHaveFocus();
183 await expect.element(input).toHaveValue("acme");
184 });
185
186 it("opens a searched project's latest listed thread, not a newer subagent, delegated task, or parked thread", async () => {
187 const environmentId = EnvironmentId.make("local");
188 const projectId = ProjectId.make("acme");
189 const parentId = ThreadId.make("parent");
190 const delegatedId = ThreadId.make("delegated");
191 setup({
192 delegatedUnderParent: new Set([threadKey({ environmentId, threadId: delegatedId })]),
193 projects: [
194 {
195 id: projectId,
196 environmentId,
197 title: "Acme",
198 workspaceRoot: "/work/acme",
199 repositoryIdentity: null,
200 defaultModelSelection: null,
201 createdAt: "2026-03-01T00:00:00.000Z",
202 updatedAt: "2026-03-01T00:00:00.000Z",
203 scripts: [],
204 },
205 ],
206 threads: [
207 makeThreadFixture({
208 id: parentId,
209 environmentId,
210 projectId,
211 latestUserMessageAt: "2026-03-02T00:00:00.000Z",
212 }),
213 makeThreadFixture({
214 id: ThreadId.make("subagent"),
215 environmentId,
216 projectId,
217 updatedAt: "2026-03-03T00:00:00.000Z",
218 lineage: {
219 rootThreadId: parentId,
220 parentThreadId: parentId,
221 relationshipToParent: "subagent",
222 },
223 }),
224 makeThreadFixture({
225 id: delegatedId,
226 environmentId,
227 projectId,
228 latestUserMessageAt: "2026-03-04T00:00:00.000Z",
229 }),
230 makeThreadFixture({
231 id: ThreadId.make("settled"),
232 environmentId,
233 projectId,
234 latestUserMessageAt: "2026-03-05T00:00:00.000Z",
235 settledOverride: "settled",
236 }),
237 makeThreadFixture({
238 id: ThreadId.make("snoozed"),
239 environmentId,
240 projectId,
241 latestUserMessageAt: "2026-03-06T00:00:00.000Z",
242 snoozedUntil: "2999-01-01T00:00:00.000Z",
243 }),
244 ],
245 });
246 await using screen = await render(<CommandPalette>{null}</CommandPalette>);
247
248 openCommandPalette({ query: "Acme" });
249 await page.getByRole("option", { name: /Acme/ }).first().click();
250
251 await vi.waitFor(() => expect(screen.router?.state.location.pathname).toBe("/local/parent"));
252 });
253
254 it("starts a thread in an open copy when the current project's copy is archived", async () => {
255 const repositoryIdentity = {
256 canonicalKey: "github.com/example/acme",
257 locator: {
258 source: "git-remote" as const,
259 remoteName: "origin",
260 remoteUrl: "https://github.com/example/acme.git",
261 },
262 };
263 const archived = {
264 ...makeProject("acme"),
265 repositoryIdentity,
266 archivedAt: "2026-03-02T00:00:00.000Z",
267 };
268 const open = {
269 ...makeProject("acme"),
270 environmentId: EnvironmentId.make("remote"),
271 repositoryIdentity,
272 };
273 setup({
274 projects: [archived, open],
275 activeThread: makeThreadFixture({
276 environmentId: archived.environmentId,
277 projectId: archived.id,
278 }),
279 });
280 await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
281
282 openCommandPalette({ open: "new-thread-in" });
283 await page.getByRole("option", { name: /acme/i }).click();
284
285 await vi.waitFor(() =>
286 expect(entities.handleNewThread).toHaveBeenCalledWith({
287 environmentId: open.environmentId,
288 projectId: open.id,
289 }),
290 );
291 });
292
293 it("numbers filtered New thread in... rows from 1 and jumps to them", async () => {
294 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
295 setup({ projects: [makeProject("server"), makeProject("lima")] });
296 await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
297
298 openCommandPalette({ open: "new-thread-in" });
299 await userEvent.fill(page.getByPlaceholder("Search..."), "li");
300 await expect.element(page.getByRole("option", { name: /server/ })).not.toBeInTheDocument();
301 await expect.element(page.getByRole("option", { name: /lima/ })).toMatchTextContent("Ctrl+1");
302 await userEvent.keyboard("{Control>}1{/Control}");
303
304 await vi.waitFor(() =>
305 expect(entities.handleNewThread).toHaveBeenCalledWith({
306 environmentId: EnvironmentId.make("local"),
307 projectId: ProjectId.make("lima"),
308 }),
309 );
310 });
311 });