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

KeybindingsToast.browser.tsx

507 lines14.2 KB

1import "../index.css";
2​
3import {
4 DEFAULT_SERVER_SETTINGS,
5 EnvironmentId,
6 ORCHESTRATION_WS_METHODS,
7 type MessageId,
8 type OrchestrationReadModel,
9 type ProjectId,
10 type ServerConfig,
11 type ServerLifecycleWelcomePayload,
12 type ThreadId,
13 WS_METHODS,
14} from "@t3tools/contracts";
15import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
16import { ws, http, HttpResponse } from "msw";
17import { setupWorker } from "msw/browser";
18import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
19import { render } from "vitest-browser-react";
20​
21import { useComposerDraftStore } from "../composerDraftStore";
22import { __resetLocalApiForTests } from "../localApi";
23import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
24import { getServerConfig, getServerConfigUpdatedNotification } from "../rpc/serverState";
25import { getWsConnectionStatus } from "../rpc/wsConnectionState";
26import { getRouter } from "../router";
27import { useStore } from "../store";
28import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
29import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
30​
31vi.mock("../lib/gitStatusState", () => ({
32 useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }),
33 useGitStatuses: () => new Map(),
34 refreshGitStatus: () => Promise.resolve(null),
35 resetGitStatusStateForTests: () => undefined,
36}));
37​
38const THREAD_ID = "thread-kb-toast-test" as ThreadId;
39const PROJECT_ID = "project-1" as ProjectId;
40const LOCAL_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
41const NOW_ISO = "2026-03-04T12:00:00.000Z";
42​
43interface TestFixture {
44 snapshot: OrchestrationReadModel;
45 serverConfig: ServerConfig;
46 welcome: ServerLifecycleWelcomePayload;
48​
49let fixture: TestFixture;
50const rpcHarness = new BrowserWsRpcHarness();
51​
52const wsLink = ws.link(/ws(s)?:\/\/.*/);
53​
54function createBaseServerConfig(): ServerConfig {
55 return {
56 environment: {
57 environmentId: LOCAL_ENVIRONMENT_ID,
58 label: "Local environment",
59 platform: { os: "darwin" as const, arch: "arm64" as const },
60 serverVersion: "0.0.0-test",
61 capabilities: { repositoryIdentity: true },
62 },
63 auth: {
64 policy: "loopback-browser",
65 bootstrapMethods: ["one-time-token"],
66 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
67 sessionCookieName: "t3_session",
68 },
69 cwd: "/repo/project",
70 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
71 keybindings: [],
72 issues: [],
73 providers: [
74 {
75 provider: "codex",
76 enabled: true,
77 installed: true,
78 version: "0.116.0",
79 status: "ready",
80 auth: { status: "authenticated" },
81 checkedAt: NOW_ISO,
82 models: [],
83 },
84 ],
85 availableEditors: [],
86 observability: {
87 logsDirectoryPath: "/repo/project/.t3/logs",
88 localTracingEnabled: true,
89 otlpTracesEnabled: false,
90 otlpMetricsEnabled: false,
91 },
92 settings: {
93 ...DEFAULT_SERVER_SETTINGS,
94 enableAssistantStreaming: false,
95 defaultThreadEnvMode: "local" as const,
96 textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
97 providers: {
98 codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
99 claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
100 },
101 },
102 };
104​
105function createMinimalSnapshot(): OrchestrationReadModel {
106 return {
107 snapshotSequence: 1,
108 projects: [
109 {
110 id: PROJECT_ID,
111 title: "Project",
112 workspaceRoot: "/repo/project",
113 defaultModelSelection: {
114 provider: "codex",
115 model: "gpt-5",
116 },
117 scripts: [],
118 createdAt: NOW_ISO,
119 updatedAt: NOW_ISO,
120 deletedAt: null,
121 },
122 ],
123 threads: [
124 {
125 id: THREAD_ID,
126 projectId: PROJECT_ID,
127 title: "Test thread",
128 modelSelection: {
129 provider: "codex",
130 model: "gpt-5",
131 },
132 interactionMode: "default",
133 runtimeMode: "full-access",
134 branch: "main",
135 worktreePath: null,
136 latestTurn: null,
137 createdAt: NOW_ISO,
138 updatedAt: NOW_ISO,
139 archivedAt: null,
140 deletedAt: null,
141 messages: [
142 {
143 id: "msg-1" as MessageId,
144 role: "user",
145 text: "hello",
146 turnId: null,
147 streaming: false,
148 createdAt: NOW_ISO,
149 updatedAt: NOW_ISO,
150 },
151 ],
152 activities: [],
153 proposedPlans: [],
154 checkpoints: [],
155 session: {
156 threadId: THREAD_ID,
157 status: "ready",
158 providerName: "codex",
159 runtimeMode: "full-access",
160 activeTurnId: null,
161 lastError: null,
162 updatedAt: NOW_ISO,
163 },
164 },
165 ],
166 updatedAt: NOW_ISO,
167 };
169​
170function buildFixture(): TestFixture {
171 return {
172 snapshot: createMinimalSnapshot(),
173 serverConfig: createBaseServerConfig(),
174 welcome: {
175 environment: {
176 environmentId: LOCAL_ENVIRONMENT_ID,
177 label: "Local environment",
178 platform: { os: "darwin" as const, arch: "arm64" as const },
179 serverVersion: "0.0.0-test",
180 capabilities: { repositoryIdentity: true },
181 },
182 cwd: "/repo/project",
183 projectName: "Project",
184 bootstrapProjectId: PROJECT_ID,
185 bootstrapThreadId: THREAD_ID,
186 },
187 };
189​
190function resolveWsRpc(tag: string): unknown {
191 if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
192 return fixture.snapshot;
193 }
194 if (tag === WS_METHODS.serverGetConfig) {
195 return fixture.serverConfig;
196 }
197 if (tag === WS_METHODS.gitListBranches) {
198 return {
199 isRepo: true,
200 hasOriginRemote: true,
201 nextCursor: null,
202 totalCount: 1,
203 branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
204 };
205 }
206 if (tag === WS_METHODS.projectsSearchEntries) {
207 return { entries: [], truncated: false };
208 }
209 return {};
211​
212const worker = setupWorker(
213 wsLink.addEventListener("connection", ({ client }) => {
214 void rpcHarness.connect(client);
215 client.addEventListener("message", (event) => {
216 const rawData = event.data;
217 if (typeof rawData !== "string") return;
218 void rpcHarness.onMessage(rawData);
219 });
220 }),
221 ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth),
222 http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
223 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
224);
225​
226function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
227 rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
228 version: 1,
229 type: "keybindingsUpdated",
230 payload: { issues },
231 });
233​
234function queryToastTitles(): string[] {
235 return Array.from(document.querySelectorAll('[data-slot="toast-title"]')).map(
236 (el) => el.textContent ?? "",
237 );
239​
240async function waitForElement<T extends Element>(
241 query: () => T | null,
242 errorMessage: string,
243): Promise<T> {
244 let element: T | null = null;
245 await vi.waitFor(
246 () => {
247 element = query();
248 expect(element, errorMessage).toBeTruthy();
249 },
250 { timeout: 8_000, interval: 16 },
251 );
252 return element!;
254​
255async function waitForComposerEditor(): Promise<HTMLElement> {
256 return waitForElement(
257 () => document.querySelector<HTMLElement>('[data-testid="composer-editor"]'),
258 "App should render composer editor",
259 );
261​
262async function waitForToastViewport(): Promise<HTMLElement> {
263 return waitForElement(
264 () => document.querySelector<HTMLElement>('[data-slot="toast-viewport"]'),
265 "App should render the toast viewport before server config updates are pushed",
266 );
268​
269async function waitForWsConnection(): Promise<void> {
270 await vi.waitFor(
271 () => {
272 expect(getWsConnectionStatus().phase).toBe("connected");
273 },
274 { timeout: 8_000, interval: 16 },
275 );
277​
278async function waitForToast(title: string, count = 1): Promise<void> {
279 await vi.waitFor(
280 () => {
281 const matches = queryToastTitles().filter((t) => t === title);
282 expect(matches.length, `Expected ${count} "${title}" toast(s)`).toBeGreaterThanOrEqual(count);
283 },
284 { timeout: 4_000, interval: 16 },
285 );
287​
288async function waitForNoToast(title: string): Promise<void> {
289 await vi.waitFor(
290 () => {
291 expect(queryToastTitles().filter((t) => t === title)).toHaveLength(0);
292 },
293 { timeout: 10_000, interval: 50 },
294 );
296​
297async function waitForNoToasts(): Promise<void> {
298 await vi.waitFor(
299 () => {
300 expect(queryToastTitles()).toHaveLength(0);
301 },
302 { timeout: 8_000, interval: 16 },
303 );
305​
306async function waitForInitialWsSubscriptions(): Promise<void> {
307 await vi.waitFor(
308 () => {
309 expect(
310 rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
311 ).toBe(true);
312 expect(
313 rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerConfig),
314 ).toBe(true);
315 },
316 { timeout: 8_000, interval: 16 },
317 );
319​
320async function waitForServerConfigSnapshot(): Promise<void> {
321 await vi.waitFor(
322 () => {
323 expect(getServerConfig()).not.toBeNull();
324 },
325 { timeout: 8_000, interval: 16 },
326 );
328​
329async function waitForServerConfigStreamReady(): Promise<void> {
330 const previousNotificationId = getServerConfigUpdatedNotification()?.id ?? 0;
331 for (let attempt = 0; attempt < 20; attempt += 1) {
332 rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
333 version: 1,
334 type: "settingsUpdated",
335 payload: { settings: fixture.serverConfig.settings },
336 });
337​
338 try {
339 await vi.waitFor(
340 () => {
341 const notification = getServerConfigUpdatedNotification();
342 expect(notification?.id).toBeGreaterThan(previousNotificationId);
343 expect(notification?.source).toBe("settingsUpdated");
344 },
345 { timeout: 200, interval: 16 },
346 );
347 return;
348 } catch {
349 await new Promise((resolve) => setTimeout(resolve, 25));
350 }
351 }
352​
353 throw new Error("Timed out waiting for the server config stream to deliver updates.");
355​
356async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
357 const host = document.createElement("div");
358 host.style.position = "fixed";
359 host.style.inset = "0";
360 host.style.width = "100vw";
361 host.style.height = "100vh";
362 host.style.display = "grid";
363 host.style.overflow = "hidden";
364 document.body.append(host);
365​
366 const router = getRouter(
367 createMemoryHistory({ initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`] }),
368 );
369​
370 const screen = await render(
371 <AppAtomRegistryProvider>
372 <RouterProvider router={router} />
373 </AppAtomRegistryProvider>,
374 { container: host },
375 );
376 await waitForComposerEditor();
377 await waitForToastViewport();
378 await waitForInitialWsSubscriptions();
379 await waitForWsConnection();
380 await waitForServerConfigSnapshot();
381 await waitForServerConfigStreamReady();
382 await waitForNoToasts();
383​
384 return {
385 cleanup: async () => {
386 await screen.unmount();
387 host.remove();
388 },
389 };
391​
392describe("Keybindings update toast", () => {
393 beforeAll(async () => {
394 fixture = buildFixture();
395 await worker.start({
396 onUnhandledRequest: "bypass",
397 quiet: true,
398 serviceWorker: { url: "/mockServiceWorker.js" },
399 });
400 });
401​
402 afterAll(async () => {
403 await rpcHarness.disconnect();
404 await worker.stop();
405 });
406​
407 beforeEach(async () => {
408 await rpcHarness.reset({
409 resolveUnary: (request) => resolveWsRpc(request._tag),
410 getInitialStreamValues: (request) => {
411 if (request._tag === WS_METHODS.subscribeServerLifecycle) {
412 return [
413 {
414 version: 1,
415 sequence: 1,
416 type: "welcome",
417 payload: fixture.welcome,
418 },
419 ];
420 }
421 if (request._tag === WS_METHODS.subscribeServerConfig) {
422 return [
423 {
424 version: 1,
425 type: "snapshot",
426 config: fixture.serverConfig,
427 },
428 ];
429 }
430 return [];
431 },
432 });
433 await __resetLocalApiForTests();
434 localStorage.clear();
435 document.body.innerHTML = "";
436 useComposerDraftStore.setState({
437 draftsByThreadKey: {},
438 draftThreadsByThreadKey: {},
439 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
440 });
441 useStore.setState({
442 activeEnvironmentId: null,
443 environmentStateById: {},
444 });
445 });
446​
447 afterEach(() => {
448 document.body.innerHTML = "";
449 });
450​
451 it("shows a toast for each consecutive keybinding update with no issues", async () => {
452 const mounted = await mountApp();
453​
454 try {
455 sendServerConfigUpdatedPush([]);
456 await waitForToast("Keybindings updated", 1);
457​
458 // Each server push represents a distinct file change, so it should produce its own toast.
459 sendServerConfigUpdatedPush([]);
460 await waitForToast("Keybindings updated", 2);
461 } finally {
462 await mounted.cleanup();
463 }
464 });
465​
466 it("shows a warning toast when keybinding config has issues", async () => {
467 const mounted = await mountApp();
468​
469 try {
470 sendServerConfigUpdatedPush([
471 { kind: "keybindings.malformed-config", message: "Expected JSON array" },
472 ]);
473 await waitForToast("Invalid keybindings configuration");
474 } finally {
475 await mounted.cleanup();
476 }
477 });
478​
479 it("does not show a toast from the replayed cached value on subscribe", async () => {
480 const mounted = await mountApp();
481​
482 try {
483 sendServerConfigUpdatedPush([]);
484 await waitForToast("Keybindings updated");
485 await waitForNoToast("Keybindings updated");
486​
487 // Remount the app — onServerConfigUpdated replays the cached value
488 // synchronously on subscribe. This should NOT produce a toast.
489 await mounted.cleanup();
490 const remounted = await mountApp();
491​
492 // Give it a moment to process the replayed value
493 await new Promise((resolve) => setTimeout(resolve, 500));
494​
495 const titles = queryToastTitles();
496 expect(
497 titles.filter((t) => t === "Keybindings updated").length,
498 "Replayed cached value should not produce a toast",
499 ).toBe(0);
500​
501 await remounted.cleanup();
502 } catch (error) {
503 await mounted.cleanup().catch(() => {});
504 throw error;
505 }
506 });
507});