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