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

KeybindingsToast.browser.tsx

635 lines17.7 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 ProviderDriverKind,
11 ProviderInstanceId,
12 type ServerConfig,
13 type ServerLifecycleWelcomePayload,
14 ServerConfig as ServerConfigSchema,
15 ServerSettings,
16 type ThreadId,
17 WS_METHODS,
18} from "@t3tools/contracts";
19import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
20import { ws, http, HttpResponse } from "msw";
21import { setupWorker } from "msw/browser";
22import * as Schema from "effect/Schema";
23import {
24 afterAll,
25 afterEach,
26 beforeAll,
27 beforeEach,
28 describe,
29 expect,
30 it,
31 vi,
32} from "vite-plus/test";
33import { render } from "vitest-browser-react";
34​
35import { useComposerDraftStore } from "../composerDraftStore";
36import { __resetLocalApiForTests } from "../localApi";
37import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
38import { getServerConfig, getServerConfigUpdatedNotification } from "../rpc/serverState";
39import { getWsConnectionStatus } from "../rpc/wsConnectionState";
40import { getRouter } from "../router";
41import { useStore } from "../store";
42import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers";
43import { BrowserWsRpcHarness } from "../../test/wsRpcHarness";
44​
45vi.mock("../lib/vcsStatusState", () => {
46 const status = {
47 data: {
48 isRepo: true,
49 sourceControlProvider: {
50 kind: "github",
51 name: "GitHub",
52 baseUrl: "https://github.com",
53 },
54 hasPrimaryRemote: true,
55 isDefaultRef: true,
56 refName: "main",
57 hasWorkingTreeChanges: false,
58 workingTree: { files: [], insertions: 0, deletions: 0 },
59 hasUpstream: true,
60 aheadCount: 0,
61 behindCount: 0,
62 pr: null,
63 },
64 error: null,
65 cause: null,
66 isPending: false,
67 };
68​
69 return {
70 getVcsStatusSnapshot: () => status,
71 useVcsStatus: () => status,
72 useVcsStatuses: () => new Map(),
73 refreshVcsStatus: () => Promise.resolve(null),
74 resetVcsStatusStateForTests: () => undefined,
75 };
76});
77​
78const THREAD_ID = "thread-kb-toast-test" as ThreadId;
79const PROJECT_ID = "project-1" as ProjectId;
80const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
81const NOW_ISO = "2026-03-04T12:00:00.000Z";
82​
83interface TestFixture {
84 snapshot: OrchestrationReadModel;
85 serverConfig: ServerConfig;
86 welcome: ServerLifecycleWelcomePayload;
88​
89let fixture: TestFixture;
90const rpcHarness = new BrowserWsRpcHarness();
91const encodeServerConfig = Schema.encodeSync(ServerConfigSchema);
92const encodeServerSettings = Schema.encodeSync(ServerSettings);
93​
94const wsLink = ws.link(/ws(s)?:\/\/.*/);
95​
96function createBaseServerConfig(): ServerConfig {
97 return {
98 environment: {
99 environmentId: LOCAL_ENVIRONMENT_ID,
100 label: "Local environment",
101 platform: { os: "darwin" as const, arch: "arm64" as const },
102 serverVersion: "0.0.0-test",
103 capabilities: { repositoryIdentity: true },
104 },
105 auth: {
106 policy: "loopback-browser",
107 bootstrapMethods: ["one-time-token"],
108 sessionMethods: ["browser-session-cookie", "bearer-access-token"],
109 sessionCookieName: "t3_session",
110 },
111 cwd: "/repo/project",
112 keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
113 keybindings: [],
114 issues: [],
115 providers: [
116 {
117 driver: ProviderDriverKind.make("codex"),
118 instanceId: ProviderInstanceId.make("codex"),
119 enabled: true,
120 installed: true,
121 version: "0.116.0",
122 status: "ready",
123 auth: { status: "authenticated" },
124 checkedAt: NOW_ISO,
125 models: [],
126 slashCommands: [],
127 skills: [],
128 },
129 ],
130 availableEditors: [],
131 observability: {
132 logsDirectoryPath: "/repo/project/.t3/logs",
133 localTracingEnabled: true,
134 otlpTracesEnabled: false,
135 otlpMetricsEnabled: false,
136 },
137 settings: {
138 ...DEFAULT_SERVER_SETTINGS,
139 enableAssistantStreaming: false,
140 defaultThreadEnvMode: "local" as const,
141 textGenerationModelSelection: {
142 instanceId: ProviderInstanceId.make("codex"),
143 model: "gpt-5.4-mini",
144 },
145 providers: {
146 codex: {
147 enabled: true,
148 binaryPath: "",
149 homePath: "",
150 shadowHomePath: "",
151 customModels: [],
152 },
153 claudeAgent: {
154 enabled: true,
155 binaryPath: "",
156 homePath: "",
157 customModels: [],
158 launchArgs: "",
159 },
160 cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] },
161 opencode: {
162 enabled: true,
163 binaryPath: "",
164 serverUrl: "",
165 serverPassword: "",
166 customModels: [],
167 },
168 },
169 },
170 };
172​
173function createMinimalSnapshot(): OrchestrationReadModel {
174 return {
175 snapshotSequence: 1,
176 projects: [
177 {
178 id: PROJECT_ID,
179 title: "Project",
180 workspaceRoot: "/repo/project",
181 defaultModelSelection: {
182 instanceId: ProviderInstanceId.make("codex"),
183 model: "gpt-5",
184 },
185 scripts: [],
186 createdAt: NOW_ISO,
187 updatedAt: NOW_ISO,
188 deletedAt: null,
189 },
190 ],
191 threads: [
192 {
193 id: THREAD_ID,
194 projectId: PROJECT_ID,
195 title: "Test thread",
196 modelSelection: {
197 instanceId: ProviderInstanceId.make("codex"),
198 model: "gpt-5",
199 },
200 interactionMode: "default",
201 runtimeMode: "full-access",
202 branch: "main",
203 worktreePath: null,
204 latestTurn: null,
205 createdAt: NOW_ISO,
206 updatedAt: NOW_ISO,
207 archivedAt: null,
208 deletedAt: null,
209 messages: [
210 {
211 id: "msg-1" as MessageId,
212 role: "user",
213 text: "hello",
214 turnId: null,
215 streaming: false,
216 createdAt: NOW_ISO,
217 updatedAt: NOW_ISO,
218 },
219 ],
220 activities: [],
221 proposedPlans: [],
222 checkpoints: [],
223 session: {
224 threadId: THREAD_ID,
225 status: "ready",
226 providerName: "codex",
227 runtimeMode: "full-access",
228 activeTurnId: null,
229 lastError: null,
230 updatedAt: NOW_ISO,
231 },
232 },
233 ],
234 updatedAt: NOW_ISO,
235 };
237​
238function toShellSnapshot(snapshot: OrchestrationReadModel) {
239 return {
240 snapshotSequence: snapshot.snapshotSequence,
241 projects: snapshot.projects.map((project) => ({
242 id: project.id,
243 title: project.title,
244 workspaceRoot: project.workspaceRoot,
245 repositoryIdentity: project.repositoryIdentity ?? null,
246 defaultModelSelection: project.defaultModelSelection,
247 scripts: project.scripts,
248 createdAt: project.createdAt,
249 updatedAt: project.updatedAt,
250 })),
251 threads: snapshot.threads.map((thread) => ({
252 id: thread.id,
253 projectId: thread.projectId,
254 title: thread.title,
255 modelSelection: thread.modelSelection,
256 runtimeMode: thread.runtimeMode,
257 interactionMode: thread.interactionMode,
258 branch: thread.branch,
259 worktreePath: thread.worktreePath,
260 latestTurn: thread.latestTurn,
261 createdAt: thread.createdAt,
262 updatedAt: thread.updatedAt,
263 archivedAt: thread.archivedAt,
264 session: thread.session,
265 latestUserMessageAt:
266 thread.messages.findLast((message) => message.role === "user")?.createdAt ?? null,
267 hasPendingApprovals: false,
268 hasPendingUserInput: false,
269 hasActionableProposedPlan: false,
270 })),
271 updatedAt: snapshot.updatedAt,
272 };
274​
275function buildFixture(): TestFixture {
276 return {
277 snapshot: createMinimalSnapshot(),
278 serverConfig: createBaseServerConfig(),
279 welcome: {
280 environment: {
281 environmentId: LOCAL_ENVIRONMENT_ID,
282 label: "Local environment",
283 platform: { os: "darwin" as const, arch: "arm64" as const },
284 serverVersion: "0.0.0-test",
285 capabilities: { repositoryIdentity: true },
286 },
287 cwd: "/repo/project",
288 projectName: "Project",
289 bootstrapProjectId: PROJECT_ID,
290 bootstrapThreadId: THREAD_ID,
291 },
292 };
294​
295function resolveWsRpc(tag: string): unknown {
296 if (tag === WS_METHODS.serverGetConfig) {
297 return encodeServerConfig(fixture.serverConfig);
298 }
299 if (tag === WS_METHODS.vcsListRefs) {
300 return {
301 isRepo: true,
302 hasPrimaryRemote: true,
303 nextCursor: null,
304 totalCount: 1,
305 refs: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
306 };
307 }
308 if (tag === WS_METHODS.projectsSearchEntries) {
309 return { entries: [], truncated: false };
310 }
311 return {};
313​
314const worker = setupWorker(
315 wsLink.addEventListener("connection", ({ client }) => {
316 void rpcHarness.connect(client);
317 client.addEventListener("message", (event) => {
318 const rawData = event.data;
319 if (typeof rawData !== "string") return;
320 void rpcHarness.onMessage(rawData);
321 });
322 }),
323 ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth),
324 http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })),
325 http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })),
326);
327​
328function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
329 rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
330 version: 1,
331 type: "keybindingsUpdated",
332 payload: { keybindings: fixture.serverConfig.keybindings, issues },
333 });
335​
336function queryToastTitles(): string[] {
337 return Array.from(document.querySelectorAll('[data-slot="toast-title"]')).map(
338 (el) => el.textContent ?? "",
339 );
341​
342async function waitForElement<T extends Element>(
343 query: () => T | null,
344 errorMessage: string,
345): Promise<T> {
346 let element: T | null = null;
347 await vi.waitFor(
348 () => {
349 element = query();
350 expect(element, errorMessage).toBeTruthy();
351 },
352 { timeout: 8_000, interval: 16 },
353 );
354 return element!;
356​
357async function waitForComposerEditor(): Promise<HTMLElement> {
358 return waitForElement(
359 () => document.querySelector<HTMLElement>('[data-testid="composer-editor"]'),
360 "App should render composer editor",
361 );
363​
364async function waitForToastViewport(): Promise<HTMLElement> {
365 return waitForElement(
366 () => document.querySelector<HTMLElement>('[data-slot="toast-viewport"]'),
367 "App should render the toast viewport before server config updates are pushed",
368 );
370​
371async function waitForWsConnection(): Promise<void> {
372 await vi.waitFor(
373 () => {
374 expect(getWsConnectionStatus().phase).toBe("connected");
375 },
376 { timeout: 8_000, interval: 16 },
377 );
379​
380async function waitForToast(title: string, count = 1): Promise<void> {
381 await vi.waitFor(
382 () => {
383 const matches = queryToastTitles().filter((t) => t === title);
384 expect(matches.length, `Expected ${count} "${title}" toast(s)`).toBeGreaterThanOrEqual(count);
385 },
386 { timeout: 4_000, interval: 16 },
387 );
389​
390async function waitForNoToast(title: string): Promise<void> {
391 await vi.waitFor(
392 () => {
393 expect(queryToastTitles().filter((t) => t === title)).toHaveLength(0);
394 },
395 { timeout: 10_000, interval: 50 },
396 );
398​
399async function waitForNoToasts(): Promise<void> {
400 await vi.waitFor(
401 () => {
402 expect(queryToastTitles()).toHaveLength(0);
403 },
404 { timeout: 8_000, interval: 16 },
405 );
407​
408async function waitForInitialWsSubscriptions(): Promise<void> {
409 await vi.waitFor(
410 () => {
411 expect(
412 rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
413 ).toBe(true);
414 expect(
415 rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerConfig),
416 ).toBe(true);
417 },
418 { timeout: 8_000, interval: 16 },
419 );
421​
422async function waitForServerConfigSnapshot(): Promise<void> {
423 await vi.waitFor(
424 () => {
425 expect(getServerConfig()).not.toBeNull();
426 },
427 { timeout: 8_000, interval: 16 },
428 );
430​
431async function waitForServerConfigStreamReady(): Promise<void> {
432 const previousNotificationId = getServerConfigUpdatedNotification()?.id ?? 0;
433 for (let attempt = 0; attempt < 20; attempt += 1) {
434 rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
435 version: 1,
436 type: "settingsUpdated",
437 payload: { settings: encodeServerSettings(fixture.serverConfig.settings) },
438 });
439​
440 try {
441 await vi.waitFor(
442 () => {
443 const notification = getServerConfigUpdatedNotification();
444 expect(notification?.id).toBeGreaterThan(previousNotificationId);
445 expect(notification?.source).toBe("settingsUpdated");
446 },
447 { timeout: 200, interval: 16 },
448 );
449 return;
450 } catch {
451 await new Promise((resolve) => setTimeout(resolve, 25));
452 }
453 }
454​
455 throw new Error("Timed out waiting for the server config stream to deliver updates.");
457​
458async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
459 const host = document.createElement("div");
460 host.style.position = "fixed";
461 host.style.inset = "0";
462 host.style.width = "100vw";
463 host.style.height = "100vh";
464 host.style.display = "grid";
465 host.style.overflow = "hidden";
466 document.body.append(host);
467​
468 const router = getRouter(
469 createMemoryHistory({ initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`] }),
470 );
471​
472 const screen = await render(
473 <AppAtomRegistryProvider>
474 <RouterProvider router={router} />
475 </AppAtomRegistryProvider>,
476 { container: host },
477 );
478 await waitForComposerEditor();
479 await waitForToastViewport();
480 await waitForInitialWsSubscriptions();
481 await waitForWsConnection();
482 await waitForServerConfigSnapshot();
483 await waitForServerConfigStreamReady();
484 await waitForNoToasts();
485​
486 return {
487 cleanup: async () => {
488 await screen.unmount();
489 host.remove();
490 },
491 };
493​
494describe("Keybindings update toast", () => {
495 beforeAll(async () => {
496 fixture = buildFixture();
497 await worker.start({
498 onUnhandledRequest: "bypass",
499 quiet: true,
500 serviceWorker: { url: "/mockServiceWorker.js" },
501 });
502 });
503​
504 afterAll(async () => {
505 await rpcHarness.disconnect();
506 await worker.stop();
507 });
508​
509 beforeEach(async () => {
510 await rpcHarness.reset({
511 resolveUnary: (request) => resolveWsRpc(request._tag),
512 getInitialStreamValues: (request) => {
513 if (request._tag === WS_METHODS.subscribeServerLifecycle) {
514 return [
515 {
516 version: 1,
517 sequence: 1,
518 type: "welcome",
519 payload: fixture.welcome,
520 },
521 ];
522 }
523 if (request._tag === WS_METHODS.subscribeServerConfig) {
524 return [
525 {
526 version: 1,
527 type: "snapshot",
528 config: encodeServerConfig(fixture.serverConfig),
529 },
530 ];
531 }
532 if (request._tag === ORCHESTRATION_WS_METHODS.subscribeShell) {
533 return [
534 {
535 kind: "snapshot",
536 snapshot: toShellSnapshot(fixture.snapshot),
537 },
538 ];
539 }
540 if (
541 request._tag === ORCHESTRATION_WS_METHODS.subscribeThread &&
542 request.threadId === THREAD_ID
543 ) {
544 return [
545 {
546 kind: "snapshot",
547 snapshot: {
548 snapshotSequence: fixture.snapshot.snapshotSequence,
549 thread: fixture.snapshot.threads[0],
550 },
551 },
552 ];
553 }
554 return [];
555 },
556 });
557 await __resetLocalApiForTests();
558 localStorage.clear();
559 document.body.innerHTML = "";
560 useComposerDraftStore.setState({
561 draftsByThreadKey: {},
562 draftThreadsByThreadKey: {},
563 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
564 });
565 useStore.setState({
566 activeEnvironmentId: null,
567 environmentStateById: {},
568 });
569 });
570​
571 afterEach(() => {
572 document.body.innerHTML = "";
573 });
574​
575 it("coalesces rapid consecutive keybinding update toasts with no issues", async () => {
576 const mounted = await mountApp();
577​
578 try {
579 sendServerConfigUpdatedPush([]);
580 await waitForToast("Keybindings updated", 1);
581​
582 // A single edit can produce several reload notifications as the direct update and
583 // filesystem watcher settle, so avoid stacking identical success toasts.
584 sendServerConfigUpdatedPush([]);
585 await new Promise((resolve) => setTimeout(resolve, 250));
586​
587 const titles = queryToastTitles();
588 expect(titles.filter((title) => title === "Keybindings updated")).toHaveLength(1);
589 } finally {
590 await mounted.cleanup();
591 }
592 });
593​
594 it("shows a warning toast when keybinding config has issues", async () => {
595 const mounted = await mountApp();
596​
597 try {
598 sendServerConfigUpdatedPush([
599 { kind: "keybindings.malformed-config", message: "Expected JSON array" },
600 ]);
601 await waitForToast("Invalid keybindings configuration");
602 } finally {
603 await mounted.cleanup();
604 }
605 });
606​
607 it("does not show a toast from the replayed cached value on subscribe", async () => {
608 const mounted = await mountApp();
609​
610 try {
611 sendServerConfigUpdatedPush([]);
612 await waitForToast("Keybindings updated");
613 await waitForNoToast("Keybindings updated");
614​
615 // Remount the app — onServerConfigUpdated replays the cached value
616 // synchronously on subscribe. This should NOT produce a toast.
617 await mounted.cleanup();
618 const remounted = await mountApp();
619​
620 // Give it a moment to process the replayed value
621 await new Promise((resolve) => setTimeout(resolve, 500));
622​
623 const titles = queryToastTitles();
624 expect(
625 titles.filter((t) => t === "Keybindings updated").length,
626 "Replayed cached value should not produce a toast",
627 ).toBe(0);
628​
629 await remounted.cleanup();
630 } catch (error) {
631 await mounted.cleanup().catch(() => {});
632 throw error;
633 }
634 });
635});