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

KeybindingsToast.browser.tsx

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