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