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

KeybindingsToast.browser.tsx

390 lines10.2 KB

1import "../index.css";
2​
3import {
4 ORCHESTRATION_WS_METHODS,
5 type MessageId,
6 type OrchestrationReadModel,
7 type ProjectId,
8 type ServerConfig,
9 type ThreadId,
10 type WsWelcomePayload,
11 WS_CHANNELS,
12 WS_METHODS,
13} from "@t3tools/contracts";
14import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
15import { ws, http, HttpResponse } from "msw";
16import { setupWorker } from "msw/browser";
17import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
18import { render } from "vitest-browser-react";
19​
20import { useComposerDraftStore } from "../composerDraftStore";
21import { getRouter } from "../router";
22import { useStore } from "../store";
23​
24const THREAD_ID = "thread-kb-toast-test" as ThreadId;
25const PROJECT_ID = "project-1" as ProjectId;
26const NOW_ISO = "2026-03-04T12:00:00.000Z";
27​
28interface TestFixture {
29 snapshot: OrchestrationReadModel;
30 serverConfig: ServerConfig;
31 welcome: WsWelcomePayload;
33​
34let fixture: TestFixture;
35let wsClient: { send: (data: string) => void } | null = null;
36let pushSequence = 1;
37​
38const wsLink = ws.link(/ws(s)?:\/\/.*/);
39​
40function createBaseServerConfig(): ServerConfig {
41 return {
42 cwd: "/repo/project",
43 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
44 keybindings: [],
45 issues: [],
46 providers: [
47 {
48 provider: "codex",
49 enabled: true,
50 installed: true,
51 version: "0.116.0",
52 status: "ready",
53 auth: { status: "authenticated" },
54 checkedAt: NOW_ISO,
55 models: [],
56 },
57 ],
58 availableEditors: [],
59 settings: {
60 enableAssistantStreaming: false,
61 defaultThreadEnvMode: "local" as const,
62 textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
63 providers: {
64 codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
65 claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
66 },
67 },
68 };
70​
71function createMinimalSnapshot(): OrchestrationReadModel {
72 return {
73 snapshotSequence: 1,
74 projects: [
75 {
76 id: PROJECT_ID,
77 title: "Project",
78 workspaceRoot: "/repo/project",
79 defaultModelSelection: {
80 provider: "codex",
81 model: "gpt-5",
82 },
83 scripts: [],
84 createdAt: NOW_ISO,
85 updatedAt: NOW_ISO,
86 deletedAt: null,
87 },
88 ],
89 threads: [
90 {
91 id: THREAD_ID,
92 projectId: PROJECT_ID,
93 title: "Test thread",
94 modelSelection: {
95 provider: "codex",
96 model: "gpt-5",
97 },
98 interactionMode: "default",
99 runtimeMode: "full-access",
100 branch: "main",
101 worktreePath: null,
102 latestTurn: null,
103 createdAt: NOW_ISO,
104 updatedAt: NOW_ISO,
105 archivedAt: null,
106 deletedAt: null,
107 messages: [
108 {
109 id: "msg-1" as MessageId,
110 role: "user",
111 text: "hello",
112 turnId: null,
113 streaming: false,
114 createdAt: NOW_ISO,
115 updatedAt: NOW_ISO,
116 },
117 ],
118 activities: [],
119 proposedPlans: [],
120 checkpoints: [],
121 session: {
122 threadId: THREAD_ID,
123 status: "ready",
124 providerName: "codex",
125 runtimeMode: "full-access",
126 activeTurnId: null,
127 lastError: null,
128 updatedAt: NOW_ISO,
129 },
130 },
131 ],
132 updatedAt: NOW_ISO,
133 };
135​
136function buildFixture(): TestFixture {
137 return {
138 snapshot: createMinimalSnapshot(),
139 serverConfig: createBaseServerConfig(),
140 welcome: {
141 cwd: "/repo/project",
142 projectName: "Project",
143 bootstrapProjectId: PROJECT_ID,
144 bootstrapThreadId: THREAD_ID,
145 },
146 };
148​
149function resolveWsRpc(tag: string): unknown {
150 if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
151 return fixture.snapshot;
152 }
153 if (tag === WS_METHODS.serverGetConfig) {
154 return fixture.serverConfig;
155 }
156 if (tag === WS_METHODS.gitListBranches) {
157 return {
158 isRepo: true,
159 hasOriginRemote: true,
160 branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
161 };
162 }
163 if (tag === WS_METHODS.gitStatus) {
164 return {
165 branch: "main",
166 hasWorkingTreeChanges: false,
167 workingTree: { files: [], insertions: 0, deletions: 0 },
168 hasUpstream: true,
169 aheadCount: 0,
170 behindCount: 0,
171 pr: null,
172 };
173 }
174 if (tag === WS_METHODS.projectsSearchEntries) {
175 return { entries: [], truncated: false };
176 }
177 return {};
179​
180const worker = setupWorker(
181 wsLink.addEventListener("connection", ({ client }) => {
182 wsClient = client;
183 pushSequence = 1;
184 client.send(
185 JSON.stringify({
186 type: "push",
187 sequence: pushSequence++,
188 channel: WS_CHANNELS.serverWelcome,
189 data: fixture.welcome,
190 }),
191 );
192 client.addEventListener("message", (event) => {
193 const rawData = event.data;
194 if (typeof rawData !== "string") return;
195 let request: { id: string; body: { _tag: string; [key: string]: unknown } };
196 try {
197 request = JSON.parse(rawData);
198 } catch {
199 return;
200 }
201 const method = request.body?._tag;
202 if (typeof method !== "string") return;
203 client.send(
204 JSON.stringify({
205 id: request.id,
206 result: resolveWsRpc(method),
207 }),
208 );
209 });
210 }),
211 http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
212 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
213);
214​
215function sendServerConfigUpdatedPush(issues: Array<{ kind: string; message: string }>) {
216 if (!wsClient) throw new Error("WebSocket client not connected");
217 wsClient.send(
218 JSON.stringify({
219 type: "push",
220 sequence: pushSequence++,
221 channel: WS_CHANNELS.serverConfigUpdated,
222 data: {
223 issues,
224 providers: fixture.serverConfig.providers,
225 },
226 }),
227 );
229​
230function queryToastTitles(): string[] {
231 return Array.from(document.querySelectorAll('[data-slot="toast-title"]')).map(
232 (el) => el.textContent ?? "",
233 );
235​
236async function waitForElement<T extends Element>(
237 query: () => T | null,
238 errorMessage: string,
239): Promise<T> {
240 let element: T | null = null;
241 await vi.waitFor(
242 () => {
243 element = query();
244 expect(element, errorMessage).toBeTruthy();
245 },
246 { timeout: 8_000, interval: 16 },
247 );
248 return element!;
250​
251async function waitForComposerEditor(): Promise<HTMLElement> {
252 return waitForElement(
253 () => document.querySelector<HTMLElement>('[data-testid="composer-editor"]'),
254 "App should render composer editor",
255 );
257​
258async function waitForToast(title: string, count = 1): Promise<void> {
259 await vi.waitFor(
260 () => {
261 const matches = queryToastTitles().filter((t) => t === title);
262 expect(matches.length, `Expected ${count} "${title}" toast(s)`).toBeGreaterThanOrEqual(count);
263 },
264 { timeout: 4_000, interval: 16 },
265 );
267​
268async function waitForNoToast(title: string): Promise<void> {
269 await vi.waitFor(
270 () => {
271 expect(queryToastTitles().filter((t) => t === title)).toHaveLength(0);
272 },
273 { timeout: 10_000, interval: 50 },
274 );
276​
277async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
278 const host = document.createElement("div");
279 host.style.position = "fixed";
280 host.style.inset = "0";
281 host.style.width = "100vw";
282 host.style.height = "100vh";
283 host.style.display = "grid";
284 host.style.overflow = "hidden";
285 document.body.append(host);
286​
287 const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] }));
288​
289 const screen = await render(<RouterProvider router={router} />, { container: host });
290 await waitForComposerEditor();
291​
292 return {
293 cleanup: async () => {
294 await screen.unmount();
295 host.remove();
296 },
297 };
299​
300describe("Keybindings update toast", () => {
301 beforeAll(async () => {
302 fixture = buildFixture();
303 await worker.start({
304 onUnhandledRequest: "bypass",
305 quiet: true,
306 serviceWorker: { url: "/mockServiceWorker.js" },
307 });
308 });
309​
310 afterAll(async () => {
311 await worker.stop();
312 });
313​
314 beforeEach(() => {
315 localStorage.clear();
316 document.body.innerHTML = "";
317 pushSequence = 1;
318 useComposerDraftStore.setState({
319 draftsByThreadId: {},
320 draftThreadsByThreadId: {},
321 projectDraftThreadIdByProjectId: {},
322 });
323 useStore.setState({
324 projects: [],
325 threads: [],
326 bootstrapComplete: false,
327 });
328 });
329​
330 afterEach(() => {
331 document.body.innerHTML = "";
332 });
333​
334 it("shows a toast for each consecutive keybinding update with no issues", async () => {
335 const mounted = await mountApp();
336​
337 try {
338 sendServerConfigUpdatedPush([]);
339 await waitForToast("Keybindings updated", 1);
340​
341 // Each server push represents a distinct file change, so it should produce its own toast.
342 sendServerConfigUpdatedPush([]);
343 await waitForToast("Keybindings updated", 2);
344 } finally {
345 await mounted.cleanup();
346 }
347 });
348​
349 it("shows a warning toast when keybinding config has issues", async () => {
350 const mounted = await mountApp();
351​
352 try {
353 sendServerConfigUpdatedPush([
354 { kind: "keybindings.malformed-config", message: "Expected JSON array" },
355 ]);
356 await waitForToast("Invalid keybindings configuration");
357 } finally {
358 await mounted.cleanup();
359 }
360 });
361​
362 it("does not show a toast from the replayed cached value on subscribe", async () => {
363 const mounted = await mountApp();
364​
365 try {
366 sendServerConfigUpdatedPush([]);
367 await waitForToast("Keybindings updated");
368 await waitForNoToast("Keybindings updated");
369​
370 // Remount the app — onServerConfigUpdated replays the cached value
371 // synchronously on subscribe. This should NOT produce a toast.
372 await mounted.cleanup();
373 const remounted = await mountApp();
374​
375 // Give it a moment to process the replayed value
376 await new Promise((resolve) => setTimeout(resolve, 500));
377​
378 const titles = queryToastTitles();
379 expect(
380 titles.filter((t) => t === "Keybindings updated").length,
381 "Replayed cached value should not produce a toast",
382 ).toBe(0);
383​
384 await remounted.cleanup();
385 } catch (error) {
386 await mounted.cleanup().catch(() => {});
387 throw error;
388 }
389 });
390});