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