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