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