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

KeybindingsToast.browser.tsx

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