The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 345 lines 11.5 KB
Raw
1 import {
2 DEFAULT_CLIENT_SETTINGS,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 type ModelSelection,
6 } from "@t3tools/contracts";
7 import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings";
8 import { useState } from "react";
9 import { expect, it, vi } from "vite-plus/test";
10 import { page, userEvent } from "vite-plus/test/browser";
11
12 import "~/index.css";
13
14 import { render } from "../../../test/render";
15 import { __setClientSettingsForTests } from "../../hooks/useSettings";
16 import { deriveProviderInstanceEntries } from "../../providerInstances";
17 import { ProviderModelPicker } from "./ProviderModelPicker";
18
19 it("keeps each registry image when adding a model from another ACP agent", async () => {
20 const icons = [
21 "https://cdn.agentclientprotocol.com/registry/icons/picker-explicit.svg",
22 "https://cdn.agentclientprotocol.com/registry/v1/latest/picker-by-id.svg",
23 ];
24 const cache = await caches.open("t3-acp-registry-icons-v1");
25 await using _cachedIcons = {
26 async [Symbol.asyncDispose]() {
27 await Promise.all(icons.map((url) => cache.delete(url)));
28 },
29 };
30 for (const [index, url] of icons.entries()) {
31 await cache.put(
32 url,
33 new Response(
34 `<svg xmlns="http://www.w3.org/2000/svg" width="${11 + index * 6}" height="10"><path d="M0 0h10v10H0z"/></svg>`,
35 { headers: { "content-type": "image/svg+xml" } },
36 ),
37 );
38 }
39 const entries = deriveProviderInstanceEntries(
40 ["First", "Second"].map((name) => ({
41 instanceId: ProviderInstanceId.make(name.toLowerCase()),
42 driver: ProviderDriverKind.make("acpRegistry"),
43 displayName: `${name} agent`,
44 enabled: true,
45 installed: true,
46 version: null,
47 status: "ready" as const,
48 auth: { status: "authenticated" as const },
49 checkedAt: "2026-01-01T00:00:00.000Z",
50 models: [
51 { slug: name.toLowerCase(), name: `${name} model`, isCustom: false, capabilities: {} },
52 ],
53 slashCommands: [],
54 skills: [],
55 })),
56 ).map((entry, index) => ({
57 ...entry,
58 ...(index === 0 ? { acpRegistryIconUrl: icons[0] } : { acpRegistryAgentId: "picker-by-id" }),
59 }));
60 const first = { instanceId: entries[0]!.instanceId, model: "first" };
61 const options = new Map(entries.map((entry) => [entry.instanceId, entry.models]));
62
63 function Picker() {
64 const [selection, setSelection] = useState<ReadonlyArray<ModelSelection>>([first]);
65 return (
66 <ProviderModelPicker
67 environmentId={null}
68 activeInstanceId={first.instanceId}
69 model={first.model}
70 {...(selection.length > 1 ? { selectedModels: selection } : {})}
71 lockedProvider={null}
72 instanceEntries={entries}
73 modelOptionsByInstance={options}
74 onToggleModel={(instanceId, model) => setSelection([...selection, { instanceId, model }])}
75 onInstanceModelChange={(instanceId, model) => setSelection([{ instanceId, model }])}
76 />
77 );
78 }
79
80 await using screen = await render(<Picker />);
81 const imageWidths = () =>
82 Array.from(
83 screen.container.querySelectorAll<HTMLImageElement>("[data-chat-provider-model-picker] img"),
84 (image) => image.naturalWidth,
85 );
86 await vi.waitFor(() => expect(imageWidths()).toEqual([11]));
87 await screen.getByRole("button", { name: "First model", exact: true }).click();
88 await page.getByRole("button", { name: "Second agent", exact: true }).click();
89 await userEvent.keyboard("{Shift>}");
90 try {
91 await page.getByRole("option", { name: /Second model/ }).click();
92 } finally {
93 await userEvent.keyboard("{/Shift}");
94 }
95 await userEvent.keyboard("{Escape}");
96 await vi.waitFor(() => expect(imageWidths()).toEqual([11, 17]));
97 });
98
99 it("keeps a docked picker open after a pick and hands focus to that model's effort", async () => {
100 const instanceId = ProviderInstanceId.make("codex");
101 const entries = deriveProviderInstanceEntries([
102 {
103 instanceId,
104 driver: ProviderDriverKind.make("codex"),
105 enabled: true,
106 installed: true,
107 version: null,
108 status: "ready",
109 auth: { status: "authenticated" },
110 checkedAt: "2026-01-01T00:00:00.000Z",
111 models: [],
112 slashCommands: [],
113 skills: [],
114 },
115 ]);
116 const options = new Map([
117 [
118 instanceId,
119 [
120 { slug: "original", name: "Original model" },
121 { slug: "second", name: "Second model" },
122 { slug: "plain", name: "Plain model" },
123 ],
124 ],
125 ]);
126 // The last level is the selected one; "plain" has no effort to pick.
127 const levels: Record<string, ReadonlyArray<string>> = {
128 original: ["Low", "High"],
129 second: ["Medium"],
130 plain: [],
131 };
132
133 function Picker() {
134 const [model, setModel] = useState("original");
135 return (
136 <ProviderModelPicker
137 environmentId={null}
138 activeInstanceId={instanceId}
139 model={model}
140 lockedProvider={null}
141 instanceEntries={entries}
142 modelOptionsByInstance={options}
143 triggerAriaLabel="Choose model"
144 onInstanceModelChange={(_, selected) => setModel(selected)}
145 effortColumn={(levels[model] ?? []).map((level, index, all) => (
146 <button
147 key={level}
148 type="button"
149 role="radio"
150 aria-checked={index === all.length - 1}
151 data-effort-row
152 data-effort-level
153 >
154 {level}
155 </button>
156 ))}
157 />
158 );
159 }
160
161 await using screen = await render(<Picker />);
162 await screen.getByRole("button", { name: "Choose model" }).click();
163 const search = page.getByPlaceholder("Search models...");
164 await expect.element(search).toHaveFocus();
165 await userEvent.keyboard("{ArrowRight}");
166 await expect.element(page.getByRole("radio", { name: "High" })).toHaveFocus();
167 await userEvent.keyboard("{ArrowLeft}");
168 await expect.element(search).toHaveFocus();
169
170 await page.getByRole("option", { name: /Second model/ }).click();
171 await expect.element(page.getByRole("radio", { name: "Medium" })).toHaveFocus();
172
173 await page.getByRole("option", { name: /Plain model/ }).click();
174 await page.getByRole("option", { name: /Second model/ }).click();
175 await expect.element(page.getByRole("radio", { name: "Medium" })).toHaveFocus();
176 await userEvent.keyboard("{Escape}");
177 await expect.element(search).not.toBeInTheDocument();
178 });
179
180 it("lists a model reported twice by one provider once, with contiguous jump shortcuts", async () => {
181 const instanceId = ProviderInstanceId.make("claude");
182 const entries = deriveProviderInstanceEntries([
183 {
184 instanceId,
185 driver: ProviderDriverKind.make("claudeAgent"),
186 enabled: true,
187 installed: true,
188 version: null,
189 status: "ready",
190 auth: { status: "authenticated" },
191 checkedAt: "2026-01-01T00:00:00.000Z",
192 models: [],
193 slashCommands: [],
194 skills: [],
195 },
196 ]);
197 const options = new Map([
198 [
199 instanceId,
200 ["a", "b", "c", "c", "d", "d"].map((slug) => ({
201 slug,
202 name: `Model ${slug.toUpperCase()}`,
203 })),
204 ],
205 ]);
206 const keybindings = compileResolvedKeybindingsConfig(
207 ([1, 2, 3, 4, 5, 6] as const).map((index) => ({
208 key: `mod+${index}`,
209 command: `modelPicker.jump.${index}` as const,
210 when: "modelPickerOpen",
211 })),
212 );
213
214 await using screen = await render(
215 <ProviderModelPicker
216 environmentId={null}
217 activeInstanceId={instanceId}
218 model="a"
219 lockedProvider={null}
220 instanceEntries={entries}
221 modelOptionsByInstance={options}
222 keybindings={keybindings}
223 triggerAriaLabel="Choose model"
224 onInstanceModelChange={() => {}}
225 />,
226 );
227 await screen.getByRole("button", { name: "Choose model" }).click();
228 await expect.element(page.getByRole("option", { name: /Model A/ })).toBeVisible();
229 await vi.waitFor(() =>
230 expect(
231 page
232 .getByRole("option")
233 .elements()
234 .map((row) => [
235 row.textContent?.match(/Model [A-Z]/)?.[0],
236 row.querySelector("kbd")?.textContent?.slice(-1),
237 ]),
238 ).toEqual([
239 ["Model A", "1"],
240 ["Model B", "2"],
241 ["Model C", "3"],
242 ["Model D", "4"],
243 ]),
244 );
245 });
246
247 it("opens on the active provider when every favorite belongs to a disabled provider", async () => {
248 const entries = deriveProviderInstanceEntries(
249 ["Codex", "Claude"].map((name) => ({
250 instanceId: ProviderInstanceId.make(name.toLowerCase()),
251 driver: ProviderDriverKind.make(name.toLowerCase()),
252 enabled: name === "Codex",
253 installed: true,
254 version: null,
255 status: "ready" as const,
256 auth: { status: "authenticated" as const },
257 checkedAt: "2026-01-01T00:00:00.000Z",
258 models: [
259 { slug: name.toLowerCase(), name: `${name} model`, isCustom: false, capabilities: {} },
260 ],
261 slashCommands: [],
262 skills: [],
263 })),
264 );
265 const [codex, claude] = entries;
266 __setClientSettingsForTests({
267 ...DEFAULT_CLIENT_SETTINGS,
268 favorites: [{ provider: claude!.instanceId, model: "claude" }],
269 });
270 using _settings = {
271 [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS),
272 };
273
274 await using screen = await render(
275 <ProviderModelPicker
276 environmentId={null}
277 activeInstanceId={codex!.instanceId}
278 model="codex"
279 lockedProvider={null}
280 instanceEntries={entries}
281 modelOptionsByInstance={new Map(entries.map((entry) => [entry.instanceId, entry.models]))}
282 triggerAriaLabel="Choose model"
283 onInstanceModelChange={() => {}}
284 />,
285 );
286 await screen.getByRole("button", { name: "Choose model" }).click();
287 await expect.element(page.getByRole("option", { name: /Codex model/ })).toBeVisible();
288 });
289
290 it("keeps the touch keyboard down while choosing a provider", async () => {
291 const entries = deriveProviderInstanceEntries(
292 ["Codex", "Claude"].map((name) => ({
293 instanceId: ProviderInstanceId.make(name.toLowerCase()),
294 driver: ProviderDriverKind.make(name.toLowerCase()),
295 enabled: true,
296 installed: true,
297 version: null,
298 status: "ready" as const,
299 auth: { status: "authenticated" as const },
300 checkedAt: "2026-01-01T00:00:00.000Z",
301 models: [
302 { slug: name.toLowerCase(), name: `${name} model`, isCustom: false, capabilities: {} },
303 ],
304 slashCommands: [],
305 skills: [],
306 })),
307 );
308 const [codex] = entries;
309 const matchMedia = window.matchMedia.bind(window);
310 using _touch = vi.spyOn(window, "matchMedia").mockImplementation((query) =>
311 query === "(pointer: coarse)"
312 ? ({
313 matches: true,
314 media: query,
315 onchange: null,
316 addEventListener: () => {},
317 removeEventListener: () => {},
318 addListener: () => {},
319 removeListener: () => {},
320 dispatchEvent: () => false,
321 } as MediaQueryList)
322 : matchMedia(query),
323 );
324
325 await using screen = await render(
326 <ProviderModelPicker
327 environmentId={null}
328 activeInstanceId={codex!.instanceId}
329 model="codex"
330 lockedProvider={null}
331 instanceEntries={entries}
332 modelOptionsByInstance={new Map(entries.map((entry) => [entry.instanceId, entry.models]))}
333 triggerAriaLabel="Choose model"
334 onInstanceModelChange={() => {}}
335 />,
336 );
337 await screen.getByRole("button", { name: "Choose model" }).click();
338 const search = page.getByPlaceholder("Search models...");
339 const popup = search.element().closest('[data-slot="popover-popup"]');
340 await vi.waitFor(() => expect(document.activeElement).toBe(popup));
341
342 await page.getByRole("button", { name: /^Claude/ }).click();
343 await expect.element(page.getByRole("option", { name: /Claude model/ })).toBeVisible();
344 await expect.element(search).not.toHaveFocus();
345 });