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

KeybindingsToast.browser.tsx

387 lines10.3 KB

1import "../index.css";
2​
3import {
4 ORCHESTRATION_WS_METHODS,
5 type MessageId,
6 type OrchestrationReadModel,
7 type ProjectId,
8 type ServerConfig,
9 type ServerLifecycleWelcomePayload,
10 type ThreadId,
11 WS_METHODS,
12} from "@t3tools/contracts";
13import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
14import { ws, http, HttpResponse } from "msw";
15import { setupWorker } from "msw/browser";
16import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
17import { render } from "vitest-browser-react";
18​
19import { useComposerDraftStore } from "../composerDraftStore";
20import { __resetNativeApiForTests } from "../nativeApi";
21import { getRouter } from "../router";
22import { useStore } from "../store";
23import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
24​
25const THREAD_ID = "thread-kb-toast-test" as ThreadId;
26const PROJECT_ID = "project-1" as ProjectId;
27const NOW_ISO = "2026-03-04T12:00:00.000Z";
28​
29interface TestFixture {
30 snapshot: OrchestrationReadModel;
31 serverConfig: ServerConfig;
32 welcome: ServerLifecycleWelcomePayload;
34​
35let fixture: TestFixture;
36const rpcHarness = new BrowserWsRpcHarness();
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 void rpcHarness.connect(client);
183 client.addEventListener("message", (event) => {
184 const rawData = event.data;
185 if (typeof rawData !== "string") return;
186 void rpcHarness.onMessage(rawData);
187 });
188 }),
189 http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
190 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
191);
192​
193function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
194 rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
195 version: 1,
196 type: "keybindingsUpdated",
197 payload: { issues },
198 });
200​
201function queryToastTitles(): string[] {
202 return Array.from(document.querySelectorAll('[data-slot="toast-title"]')).map(
203 (el) => el.textContent ?? "",
204 );
206​
207async function waitForElement<T extends Element>(
208 query: () => T | null,
209 errorMessage: string,
210): Promise<T> {
211 let element: T | null = null;
212 await vi.waitFor(
213 () => {
214 element = query();
215 expect(element, errorMessage).toBeTruthy();
216 },
217 { timeout: 8_000, interval: 16 },
218 );
219 return element!;
221​
222async function waitForComposerEditor(): Promise<HTMLElement> {
223 return waitForElement(
224 () => document.querySelector<HTMLElement>('[data-testid="composer-editor"]'),
225 "App should render composer editor",
226 );
228​
229async function waitForToast(title: string, count = 1): Promise<void> {
230 await vi.waitFor(
231 () => {
232 const matches = queryToastTitles().filter((t) => t === title);
233 expect(matches.length, `Expected ${count} "${title}" toast(s)`).toBeGreaterThanOrEqual(count);
234 },
235 { timeout: 4_000, interval: 16 },
236 );
238​
239async function waitForNoToast(title: string): Promise<void> {
240 await vi.waitFor(
241 () => {
242 expect(queryToastTitles().filter((t) => t === title)).toHaveLength(0);
243 },
244 { timeout: 10_000, interval: 50 },
245 );
247​
248async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
249 const host = document.createElement("div");
250 host.style.position = "fixed";
251 host.style.inset = "0";
252 host.style.width = "100vw";
253 host.style.height = "100vh";
254 host.style.display = "grid";
255 host.style.overflow = "hidden";
256 document.body.append(host);
257​
258 const router = getRouter(createMemoryHistory({ initialEntries: [`/${THREAD_ID}`] }));
259​
260 const screen = await render(<RouterProvider router={router} />, { container: host });
261 await waitForComposerEditor();
262​
263 return {
264 cleanup: async () => {
265 await screen.unmount();
266 host.remove();
267 },
268 };
270​
271describe("Keybindings update toast", () => {
272 beforeAll(async () => {
273 fixture = buildFixture();
274 await worker.start({
275 onUnhandledRequest: "bypass",
276 quiet: true,
277 serviceWorker: { url: "/mockServiceWorker.js" },
278 });
279 });
280​
281 afterAll(async () => {
282 await rpcHarness.disconnect();
283 await worker.stop();
284 });
285​
286 beforeEach(async () => {
287 await rpcHarness.reset({
288 resolveUnary: (request) => resolveWsRpc(request._tag),
289 getInitialStreamValues: (request) => {
290 if (request._tag === WS_METHODS.subscribeServerLifecycle) {
291 return [
292 {
293 version: 1,
294 sequence: 1,
295 type: "welcome",
296 payload: fixture.welcome,
297 },
298 ];
299 }
300 if (request._tag === WS_METHODS.subscribeServerConfig) {
301 return [
302 {
303 version: 1,
304 type: "snapshot",
305 config: fixture.serverConfig,
306 },
307 ];
308 }
309 return [];
310 },
311 });
312 __resetNativeApiForTests();
313 localStorage.clear();
314 document.body.innerHTML = "";
315 useComposerDraftStore.setState({
316 draftsByThreadId: {},
317 draftThreadsByThreadId: {},
318 projectDraftThreadIdByProjectId: {},
319 });
320 useStore.setState({
321 projects: [],
322 threads: [],
323 bootstrapComplete: false,
324 });
325 });
326​
327 afterEach(() => {
328 document.body.innerHTML = "";
329 });
330​
331 it("shows a toast for each consecutive keybinding update with no issues", async () => {
332 const mounted = await mountApp();
333​
334 try {
335 sendServerConfigUpdatedPush([]);
336 await waitForToast("Keybindings updated", 1);
337​
338 // Each server push represents a distinct file change, so it should produce its own toast.
339 sendServerConfigUpdatedPush([]);
340 await waitForToast("Keybindings updated", 2);
341 } finally {
342 await mounted.cleanup();
343 }
344 });
345​
346 it("shows a warning toast when keybinding config has issues", async () => {
347 const mounted = await mountApp();
348​
349 try {
350 sendServerConfigUpdatedPush([
351 { kind: "keybindings.malformed-config", message: "Expected JSON array" },
352 ]);
353 await waitForToast("Invalid keybindings configuration");
354 } finally {
355 await mounted.cleanup();
356 }
357 });
358​
359 it("does not show a toast from the replayed cached value on subscribe", async () => {
360 const mounted = await mountApp();
361​
362 try {
363 sendServerConfigUpdatedPush([]);
364 await waitForToast("Keybindings updated");
365 await waitForNoToast("Keybindings updated");
366​
367 // Remount the app — onServerConfigUpdated replays the cached value
368 // synchronously on subscribe. This should NOT produce a toast.
369 await mounted.cleanup();
370 const remounted = await mountApp();
371​
372 // Give it a moment to process the replayed value
373 await new Promise((resolve) => setTimeout(resolve, 500));
374​
375 const titles = queryToastTitles();
376 expect(
377 titles.filter((t) => t === "Keybindings updated").length,
378 "Replayed cached value should not produce a toast",
379 ).toBe(0);
380​
381 await remounted.cleanup();
382 } catch (error) {
383 await mounted.cleanup().catch(() => {});
384 throw error;
385 }
386 });
387});