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

KeybindingsToast.browser.tsx

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