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 } 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;
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 },
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 };
103}
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 };
168}
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 };
188}
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 {};
210}
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 });
232}
233
234function queryToastTitles(): string[] {
235 return Array.from(document.querySelectorAll('[data-slot="toast-title"]')).map(
236 (el) => el.textContent ?? "",
237 );
238}
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!;
253}
254
255async function waitForComposerEditor(): Promise<HTMLElement> {
256 return waitForElement(
257 () => document.querySelector<HTMLElement>('[data-testid="composer-editor"]'),
258 "App should render composer editor",
259 );
260}
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 );
267}
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 );
276}
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 );
286}
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 );
295}
296
297async function waitForNoToasts(): Promise<void> {
298 await vi.waitFor(
299 () => {
300 expect(queryToastTitles()).toHaveLength(0);
301 },
302 { timeout: 8_000, interval: 16 },
303 );
304}
305
306async function warmServerConfigUpdateStream(): Promise<void> {
307 sendServerConfigUpdatedPush([]);
308 await new Promise((resolve) => setTimeout(resolve, 50));
309}
310
311async function waitForInitialWsSubscriptions(): Promise<void> {
312 await vi.waitFor(
313 () => {
314 expect(
315 rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerLifecycle),
316 ).toBe(true);
317 expect(
318 rpcHarness.requests.some((request) => request._tag === WS_METHODS.subscribeServerConfig),
319 ).toBe(true);
320 },
321 { timeout: 8_000, interval: 16 },
322 );
323}
324
325async function waitForServerConfigSnapshot(): Promise<void> {
326 await vi.waitFor(
327 () => {
328 expect(getServerConfig()).not.toBeNull();
329 },
330 { timeout: 8_000, interval: 16 },
331 );
332}
333
334async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
335 const host = document.createElement("div");
336 host.style.position = "fixed";
337 host.style.inset = "0";
338 host.style.width = "100vw";
339 host.style.height = "100vh";
340 host.style.display = "grid";
341 host.style.overflow = "hidden";
342 document.body.append(host);
343
344 const router = getRouter(
345 createMemoryHistory({ initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`] }),
346 );
347
348 const screen = await render(
349 <AppAtomRegistryProvider>
350 <RouterProvider router={router} />
351 </AppAtomRegistryProvider>,
352 { container: host },
353 );
354 await waitForComposerEditor();
355 await waitForToastViewport();
356 await waitForInitialWsSubscriptions();
357 await waitForWsConnection();
358 await waitForServerConfigSnapshot();
359 await waitForNoToasts();
360
361 return {
362 cleanup: async () => {
363 await screen.unmount();
364 host.remove();
365 },
366 };
367}
368
369describe("Keybindings update toast", () => {
370 beforeAll(async () => {
371 fixture = buildFixture();
372 await worker.start({
373 onUnhandledRequest: "bypass",
374 quiet: true,
375 serviceWorker: { url: "/mockServiceWorker.js" },
376 });
377 });
378
379 afterAll(async () => {
380 await rpcHarness.disconnect();
381 await worker.stop();
382 });
383
384 beforeEach(async () => {
385 await rpcHarness.reset({
386 resolveUnary: (request) => resolveWsRpc(request._tag),
387 getInitialStreamValues: (request) => {
388 if (request._tag === WS_METHODS.subscribeServerLifecycle) {
389 return [
390 {
391 version: 1,
392 sequence: 1,
393 type: "welcome",
394 payload: fixture.welcome,
395 },
396 ];
397 }
398 if (request._tag === WS_METHODS.subscribeServerConfig) {
399 return [
400 {
401 version: 1,
402 type: "snapshot",
403 config: fixture.serverConfig,
404 },
405 ];
406 }
407 return [];
408 },
409 });
410 await __resetLocalApiForTests();
411 localStorage.clear();
412 document.body.innerHTML = "";
413 useComposerDraftStore.setState({
414 draftsByThreadKey: {},
415 draftThreadsByThreadKey: {},
416 logicalProjectDraftThreadKeyByLogicalProjectKey: {},
417 });
418 useStore.setState({
419 activeEnvironmentId: null,
420 environmentStateById: {},
421 });
422 });
423
424 afterEach(() => {
425 document.body.innerHTML = "";
426 });
427
428 it("shows a toast for each consecutive keybinding update with no issues", async () => {
429 const mounted = await mountApp();
430
431 try {
432 await warmServerConfigUpdateStream();
433
434 sendServerConfigUpdatedPush([]);
435 await waitForToast("Keybindings updated", 1);
436
437 // Each server push represents a distinct file change, so it should produce its own toast.
438 sendServerConfigUpdatedPush([]);
439 await waitForToast("Keybindings updated", 2);
440 } finally {
441 await mounted.cleanup();
442 }
443 });
444
445 it("shows a warning toast when keybinding config has issues", async () => {
446 const mounted = await mountApp();
447
448 try {
449 sendServerConfigUpdatedPush([
450 { kind: "keybindings.malformed-config", message: "Expected JSON array" },
451 ]);
452 await waitForToast("Invalid keybindings configuration");
453 } finally {
454 await mounted.cleanup();
455 }
456 });
457
458 it("does not show a toast from the replayed cached value on subscribe", async () => {
459 const mounted = await mountApp();
460
461 try {
462 sendServerConfigUpdatedPush([]);
463 await waitForToast("Keybindings updated");
464 await waitForNoToast("Keybindings updated");
465
466 // Remount the app — onServerConfigUpdated replays the cached value
467 // synchronously on subscribe. This should NOT produce a toast.
468 await mounted.cleanup();
469 const remounted = await mountApp();
470
471 // Give it a moment to process the replayed value
472 await new Promise((resolve) => setTimeout(resolve, 500));
473
474 const titles = queryToastTitles();
475 expect(
476 titles.filter((t) => t === "Keybindings updated").length,
477 "Replayed cached value should not produce a toast",
478 ).toBe(0);
479
480 await remounted.cleanup();
481 } catch (error) {
482 await mounted.cleanup().catch(() => {});
483 throw error;
484 }
485 });
486});