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