Open History to see the last commit
1import {
2 CommandId,
3 DEFAULT_SERVER_SETTINGS,
4 type DesktopBridge,
5 EnvironmentId,
6 type VcsStatusResult,
7 ProjectId,
8 type OrchestrationShellStreamItem,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 type ServerConfig,
12 type ServerProvider,
13 type TerminalEvent,
14 ThreadId,
15} from "@t3tools/contracts";
16import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
17
18import type { ContextMenuItem } from "@t3tools/contracts";
19
20const showContextMenuFallbackMock =
21 vi.fn<
22 <T extends string>(
23 items: readonly ContextMenuItem<T>[],
24 position?: { x: number; y: number },
25 ) => Promise<T | null>
26 >();
27
28function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
29 listeners.add(listener);
30 return () => {
31 listeners.delete(listener);
32 };
33}
34
35const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
36const shellStreamListeners = new Set<(event: OrchestrationShellStreamItem) => void>();
37const gitStatusListeners = new Set<(event: VcsStatusResult) => void>();
38
39const rpcClientMock = {
40 dispose: vi.fn(),
41 terminal: {
42 open: vi.fn(),
43 write: vi.fn(),
44 resize: vi.fn(),
45 clear: vi.fn(),
46 restart: vi.fn(),
47 close: vi.fn(),
48 onEvent: vi.fn((listener: (event: TerminalEvent) => void) =>
49 registerListener(terminalEventListeners, listener),
50 ),
51 },
52 projects: {
53 searchEntries: vi.fn(),
54 writeFile: vi.fn(),
55 },
56 filesystem: {
57 browse: vi.fn(),
58 },
59 sourceControl: {
60 lookupRepository: vi.fn(),
61 cloneRepository: vi.fn(),
62 publishRepository: vi.fn(),
63 },
64 shell: {
65 openInEditor: vi.fn(),
66 },
67 vcs: {
68 pull: vi.fn(),
69 refreshStatus: vi.fn(),
70 onStatus: vi.fn((input: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
71 registerListener(gitStatusListeners, listener),
72 ),
73 listRefs: vi.fn(),
74 createWorktree: vi.fn(),
75 removeWorktree: vi.fn(),
76 createRef: vi.fn(),
77 switchRef: vi.fn(),
78 init: vi.fn(),
79 },
80 git: {
81 runStackedAction: vi.fn(),
82 resolvePullRequest: vi.fn(),
83 preparePullRequestThread: vi.fn(),
84 },
85 server: {
86 getConfig: vi.fn(),
87 refreshProviders: vi.fn(),
88 updateProvider: vi.fn(),
89 upsertKeybinding: vi.fn(),
90 getSettings: vi.fn(),
91 updateSettings: vi.fn(),
92 subscribeConfig: vi.fn(),
93 subscribeLifecycle: vi.fn(),
94 subscribeAuthAccess: vi.fn(),
95 },
96 orchestration: {
97 dispatchCommand: vi.fn(),
98 getTurnDiff: vi.fn(),
99 getFullThreadDiff: vi.fn(),
100 subscribeShell: vi.fn((listener: (event: OrchestrationShellStreamItem) => void) =>
101 registerListener(shellStreamListeners, listener),
102 ),
103 subscribeThread: vi.fn(() => () => undefined),
104 },
105};
106
107vi.mock("./environments/runtime", () => ({
108 getPrimaryEnvironmentConnection: () => ({
109 kind: "primary" as const,
110 knownEnvironment: {
111 id: "environment-local",
112 label: "Primary",
113 source: "manual" as const,
114 target: {
115 httpBaseUrl: "http://localhost:3000",
116 wsBaseUrl: "ws://localhost:3000",
117 },
118 environmentId: EnvironmentId.make("environment-local"),
119 },
120 client: rpcClientMock,
121 environmentId: EnvironmentId.make("environment-local"),
122 ensureBootstrapped: async () => undefined,
123 reconnect: async () => undefined,
124 dispose: async () => undefined,
125 }),
126 resetEnvironmentServiceForTests: vi.fn(),
127 resetSavedEnvironmentRegistryStoreForTests: vi.fn(),
128 resetSavedEnvironmentRuntimeStoreForTests: vi.fn(),
129}));
130
131vi.mock("./contextMenuFallback", () => ({
132 showContextMenuFallback: showContextMenuFallbackMock,
133}));
134
135function emitEvent<T>(listeners: Set<(event: T) => void>, event: T) {
136 for (const listener of listeners) {
137 listener(event);
138 }
139}
140
141function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
142 const testGlobal = globalThis as typeof globalThis & {
143 window?: Window & typeof globalThis & { desktopBridge?: unknown };
144 };
145 if (!testGlobal.window) {
146 testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
147 }
148 return testGlobal.window;
149}
150
151function createLocalStorageStub(): Storage {
152 const store = new Map<string, string>();
153 return {
154 getItem: (key) => store.get(key) ?? null,
155 setItem: (key, value) => {
156 store.set(key, value);
157 },
158 removeItem: (key) => {
159 store.delete(key);
160 },
161 clear: () => {
162 store.clear();
163 },
164 key: (index) => [...store.keys()][index] ?? null,
165 get length() {
166 return store.size;
167 },
168 };
169}
170
171function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
172 return {
173 getAppBranding: () => null,
174 getLocalEnvironmentBootstrap: () => null,
175 getClientSettings: async () => null,
176 setClientSettings: async () => undefined,
177 getSavedEnvironmentRegistry: async () => [],
178 setSavedEnvironmentRegistry: async () => undefined,
179 getSavedEnvironmentSecret: async () => null,
180 setSavedEnvironmentSecret: async () => true,
181 removeSavedEnvironmentSecret: async () => undefined,
182 discoverSshHosts: async () => [],
183 ensureSshEnvironment: async () => {
184 throw new Error("ensureSshEnvironment not implemented in test");
185 },
186 disconnectSshEnvironment: async () => undefined,
187 fetchSshEnvironmentDescriptor: async () => {
188 throw new Error("fetchSshEnvironmentDescriptor not implemented in test");
189 },
190 bootstrapSshBearerSession: async () => {
191 throw new Error("bootstrapSshBearerSession not implemented in test");
192 },
193 fetchSshSessionState: async () => {
194 throw new Error("fetchSshSessionState not implemented in test");
195 },
196 issueSshWebSocketToken: async () => {
197 throw new Error("issueSshWebSocketToken not implemented in test");
198 },
199 onSshPasswordPrompt: () => () => undefined,
200 resolveSshPasswordPrompt: async () => undefined,
201 getServerExposureState: async () => ({
202 mode: "local-only",
203 endpointUrl: null,
204 advertisedHost: null,
205 tailscaleServeEnabled: false,
206 tailscaleServePort: 443,
207 }),
208 setServerExposureMode: async () => ({
209 mode: "local-only",
210 endpointUrl: null,
211 advertisedHost: null,
212 tailscaleServeEnabled: false,
213 tailscaleServePort: 443,
214 }),
215 setTailscaleServeEnabled: async (input) => ({
216 mode: "local-only",
217 endpointUrl: null,
218 advertisedHost: null,
219 tailscaleServeEnabled: input.enabled,
220 tailscaleServePort: input.port ?? 443,
221 }),
222 getAdvertisedEndpoints: async () => [],
223 pickFolder: async () => null,
224 confirm: async () => true,
225 setTheme: async () => undefined,
226 showContextMenu: async () => null,
227 openExternal: async () => true,
228 onMenuAction: () => () => undefined,
229 getUpdateState: async () => {
230 throw new Error("getUpdateState not implemented in test");
231 },
232 setUpdateChannel: async () => {
233 throw new Error("setUpdateChannel not implemented in test");
234 },
235 checkForUpdate: async () => {
236 throw new Error("checkForUpdate not implemented in test");
237 },
238 downloadUpdate: async () => {
239 throw new Error("downloadUpdate not implemented in test");
240 },
241 installUpdate: async () => {
242 throw new Error("installUpdate not implemented in test");
243 },
244 onUpdateState: () => () => undefined,
245 ...overrides,
246 };
247}
248
249const defaultProviders: ReadonlyArray<ServerProvider> = [
250 {
251 instanceId: ProviderInstanceId.make("codex"),
252 driver: ProviderDriverKind.make("codex"),
253 enabled: true,
254 installed: true,
255 version: "0.116.0",
256 status: "ready",
257 auth: { status: "authenticated" },
258 checkedAt: "2026-01-01T00:00:00.000Z",
259 models: [],
260 slashCommands: [],
261 skills: [],
262 },
263];
264
265const baseEnvironment = {
266 environmentId: EnvironmentId.make("environment-local"),
267 label: "Local environment",
268 platform: {
269 os: "darwin" as const,
270 arch: "arm64" as const,
271 },
272 serverVersion: "0.0.0-test",
273 capabilities: {
274 repositoryIdentity: true,
275 },
276};
277
278const baseServerConfig: ServerConfig = {
279 environment: baseEnvironment,
280 auth: {
281 policy: "loopback-browser",
282 bootstrapMethods: ["one-time-token"],
283 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
284 sessionCookieName: "t3_session",
285 },
286 cwd: "/tmp/workspace",
287 keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
288 keybindings: [],
289 issues: [],
290 providers: defaultProviders,
291 availableEditors: ["cursor"],
292 observability: {
293 logsDirectoryPath: "/tmp/workspace/.config/logs",
294 localTracingEnabled: true,
295 otlpTracesEnabled: false,
296 otlpMetricsEnabled: false,
297 },
298 settings: DEFAULT_SERVER_SETTINGS,
299};
300
301const baseGitStatus: VcsStatusResult = {
302 isRepo: true,
303 hasPrimaryRemote: true,
304 isDefaultRef: false,
305 refName: "feature/streamed",
306 hasWorkingTreeChanges: false,
307 workingTree: { files: [], insertions: 0, deletions: 0 },
308 hasUpstream: true,
309 aheadCount: 0,
310 behindCount: 0,
311 pr: null,
312};
313
314beforeEach(() => {
315 vi.resetModules();
316 vi.clearAllMocks();
317 showContextMenuFallbackMock.mockReset();
318 terminalEventListeners.clear();
319 shellStreamListeners.clear();
320 gitStatusListeners.clear();
321 const testWindow = getWindowForTest();
322 Reflect.deleteProperty(testWindow, "desktopBridge");
323 Object.defineProperty(testWindow, "localStorage", {
324 configurable: true,
325 value: createLocalStorageStub(),
326 });
327});
328
329afterEach(() => {
330 vi.restoreAllMocks();
331});
332
333describe("wsApi", () => {
334 it("forwards server config fetches directly to the RPC client", async () => {
335 rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
336 const { createLocalApi } = await import("./localApi");
337
338 const api = createLocalApi(rpcClientMock as never);
339
340 await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
341 expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
342 expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled();
343 expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
344 });
345
346 it("forwards terminal and shell stream events", async () => {
347 const { createEnvironmentApi } = await import("./environmentApi");
348
349 const api = createEnvironmentApi(rpcClientMock as never);
350 const onTerminalEvent = vi.fn();
351 const onShellEvent = vi.fn();
352
353 api.terminal.onEvent(onTerminalEvent);
354 api.orchestration.subscribeShell(onShellEvent);
355
356 const terminalEvent = {
357 threadId: "thread-1",
358 terminalId: "terminal-1",
359 createdAt: "2026-02-24T00:00:00.000Z",
360 type: "output",
361 data: "hello",
362 } as const;
363 emitEvent(terminalEventListeners, terminalEvent);
364
365 const shellEvent = {
366 kind: "project-upserted" as const,
367 sequence: 1,
368 project: {
369 id: ProjectId.make("project-1"),
370 title: "Project",
371 workspaceRoot: "/tmp/workspace",
372 defaultModelSelection: {
373 instanceId: ProviderInstanceId.make("codex"),
374 model: "gpt-5-codex",
375 },
376 scripts: [],
377 createdAt: "2026-02-24T00:00:00.000Z",
378 updatedAt: "2026-02-24T00:00:00.000Z",
379 },
380 } satisfies OrchestrationShellStreamItem;
381 emitEvent(shellStreamListeners, shellEvent);
382
383 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
384 expect(onShellEvent).toHaveBeenCalledWith(shellEvent);
385 });
386
387 it("forwards git status stream events", async () => {
388 const { createEnvironmentApi } = await import("./environmentApi");
389
390 const api = createEnvironmentApi(rpcClientMock as never);
391 const onStatus = vi.fn();
392
393 api.vcs.onStatus({ cwd: "/repo" }, onStatus);
394
395 const gitStatus = baseGitStatus;
396 emitEvent(gitStatusListeners, gitStatus);
397
398 expect(rpcClientMock.vcs.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
399 expect(onStatus).toHaveBeenCalledWith(gitStatus);
400 });
401
402 it("forwards git status refreshes directly to the RPC client", async () => {
403 rpcClientMock.vcs.refreshStatus.mockResolvedValue(baseGitStatus);
404 const { createEnvironmentApi } = await import("./environmentApi");
405
406 const api = createEnvironmentApi(rpcClientMock as never);
407
408 await api.vcs.refreshStatus({ cwd: "/repo" });
409
410 expect(rpcClientMock.vcs.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
411 });
412
413 it("forwards shell stream subscription options to the RPC client", async () => {
414 const { createEnvironmentApi } = await import("./environmentApi");
415
416 const api = createEnvironmentApi(rpcClientMock as never);
417 const onShellEvent = vi.fn();
418 const onResubscribe = vi.fn();
419
420 api.orchestration.subscribeShell(onShellEvent, { onResubscribe });
421
422 expect(rpcClientMock.orchestration.subscribeShell).toHaveBeenCalledWith(onShellEvent, {
423 onResubscribe,
424 });
425 });
426
427 it("sends orchestration dispatch commands as the direct RPC payload", async () => {
428 rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
429 const { createEnvironmentApi } = await import("./environmentApi");
430
431 const api = createEnvironmentApi(rpcClientMock as never);
432 const command = {
433 type: "project.create",
434 commandId: CommandId.make("cmd-1"),
435 projectId: ProjectId.make("project-1"),
436 title: "Project",
437 workspaceRoot: "/tmp/project",
438 defaultModelSelection: {
439 instanceId: ProviderInstanceId.make("codex"),
440 model: "gpt-5-codex",
441 },
442 createdAt: "2026-02-24T00:00:00.000Z",
443 } as const;
444 await api.orchestration.dispatchCommand(command);
445
446 expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command);
447 });
448
449 it("forwards workspace file writes to the project RPC", async () => {
450 rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" });
451 const { createEnvironmentApi } = await import("./environmentApi");
452
453 const api = createEnvironmentApi(rpcClientMock as never);
454 await api.projects.writeFile({
455 cwd: "/tmp/project",
456 relativePath: "plan.md",
457 contents: "# Plan\n",
458 });
459
460 expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({
461 cwd: "/tmp/project",
462 relativePath: "plan.md",
463 contents: "# Plan\n",
464 });
465 });
466
467 it("forwards filesystem browse requests to the RPC client", async () => {
468 rpcClientMock.filesystem.browse.mockResolvedValue({
469 parentPath: "/tmp/project/",
470 entries: [],
471 });
472 const { createEnvironmentApi } = await import("./environmentApi");
473
474 const api = createEnvironmentApi(rpcClientMock as never);
475 await api.filesystem.browse({
476 partialPath: "/tmp/project/",
477 cwd: "/tmp/project",
478 });
479
480 expect(rpcClientMock.filesystem.browse).toHaveBeenCalledWith({
481 partialPath: "/tmp/project/",
482 cwd: "/tmp/project",
483 });
484 });
485
486 it("forwards full-thread diff requests to the orchestration RPC", async () => {
487 rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
488 const { createEnvironmentApi } = await import("./environmentApi");
489
490 const api = createEnvironmentApi(rpcClientMock as never);
491 await api.orchestration.getFullThreadDiff({
492 threadId: ThreadId.make("thread-1"),
493 toTurnCount: 1,
494 });
495
496 expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({
497 threadId: "thread-1",
498 toTurnCount: 1,
499 });
500 });
501
502 it("forwards provider refreshes directly to the RPC client", async () => {
503 const nextProviders: ReadonlyArray<ServerProvider> = [
504 {
505 ...defaultProviders[0]!,
506 checkedAt: "2026-01-03T00:00:00.000Z",
507 },
508 ];
509 rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
510 const { createLocalApi } = await import("./localApi");
511
512 const api = createLocalApi(rpcClientMock as never);
513
514 await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
515 expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
516 });
517
518 it("forwards provider updates directly to the RPC client", async () => {
519 const nextProviders: ReadonlyArray<ServerProvider> = [
520 {
521 ...defaultProviders[0]!,
522 updateState: {
523 status: "succeeded",
524 startedAt: "2026-01-03T00:00:00.000Z",
525 finishedAt: "2026-01-03T00:00:01.000Z",
526 message: "Provider updated.",
527 output: null,
528 },
529 },
530 ];
531 rpcClientMock.server.updateProvider.mockResolvedValue({ providers: nextProviders });
532 const { createLocalApi } = await import("./localApi");
533
534 const api = createLocalApi(rpcClientMock as never);
535
536 await expect(
537 api.server.updateProvider({ provider: ProviderDriverKind.make("codex") }),
538 ).resolves.toEqual({
539 providers: nextProviders,
540 });
541 expect(rpcClientMock.server.updateProvider).toHaveBeenCalledWith({
542 provider: ProviderDriverKind.make("codex"),
543 });
544 });
545
546 it("forwards server settings updates directly to the RPC client", async () => {
547 const nextSettings = {
548 ...DEFAULT_SERVER_SETTINGS,
549 enableAssistantStreaming: true,
550 };
551 rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
552 const { createLocalApi } = await import("./localApi");
553
554 const api = createLocalApi(rpcClientMock as never);
555
556 await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
557 nextSettings,
558 );
559 expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({
560 enableAssistantStreaming: true,
561 });
562 });
563
564 it("forwards context menu metadata to the desktop bridge", async () => {
565 const showContextMenu = vi.fn().mockResolvedValue("delete");
566 getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
567
568 const { createLocalApi } = await import("./localApi");
569 const api = createLocalApi(rpcClientMock as never);
570 const items = [{ id: "delete", label: "Delete" }] as const;
571
572 await expect(api.contextMenu.show(items)).resolves.toBe("delete");
573 expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
574 });
575
576 it("forwards folder picker options to the desktop bridge", async () => {
577 const pickFolder = vi.fn().mockResolvedValue("/tmp/project");
578 getWindowForTest().desktopBridge = makeDesktopBridge({ pickFolder });
579
580 const { createLocalApi } = await import("./localApi");
581 const api = createLocalApi(rpcClientMock as never);
582
583 await expect(api.dialogs.pickFolder({ initialPath: "/tmp/workspace" })).resolves.toBe(
584 "/tmp/project",
585 );
586 expect(pickFolder).toHaveBeenCalledWith({ initialPath: "/tmp/workspace" });
587 });
588
589 it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
590 showContextMenuFallbackMock.mockResolvedValue("rename");
591 const { createLocalApi } = await import("./localApi");
592
593 const api = createLocalApi(rpcClientMock as never);
594 const items = [{ id: "rename", label: "Rename" }] as const;
595
596 await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
597 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
598 });
599
600 it("reads and writes persistence through the desktop bridge when available", async () => {
601 const clientSettings = {
602 autoOpenPlanSidebar: false,
603 confirmThreadArchive: true,
604 confirmThreadDelete: false,
605 dismissedProviderUpdateNotificationKeys: [],
606 diffIgnoreWhitespace: true,
607 diffWordWrap: true,
608 favorites: [],
609 providerModelPreferences: {},
610 sidebarProjectGroupingMode: "repository_path" as const,
611 sidebarProjectGroupingOverrides: {
612 "environment-local:/tmp/project": "separate" as const,
613 },
614 sidebarProjectSortOrder: "manual" as const,
615 sidebarThreadSortOrder: "created_at" as const,
616 sidebarThreadPreviewCount: 6,
617 timestampFormat: "24-hour" as const,
618 };
619 const getClientSettings = vi.fn().mockResolvedValue({
620 ...clientSettings,
621 });
622 const setClientSettings = vi.fn().mockResolvedValue(undefined);
623 const getSavedEnvironmentRegistry = vi.fn().mockResolvedValue([]);
624 const setSavedEnvironmentRegistry = vi.fn().mockResolvedValue(undefined);
625 const getSavedEnvironmentSecret = vi.fn().mockResolvedValue("bearer-token");
626 const setSavedEnvironmentSecret = vi.fn().mockResolvedValue(true);
627 const removeSavedEnvironmentSecret = vi.fn().mockResolvedValue(undefined);
628 getWindowForTest().desktopBridge = makeDesktopBridge({
629 getClientSettings,
630 setClientSettings,
631 getSavedEnvironmentRegistry,
632 setSavedEnvironmentRegistry,
633 getSavedEnvironmentSecret,
634 setSavedEnvironmentSecret,
635 removeSavedEnvironmentSecret,
636 });
637
638 const { createLocalApi } = await import("./localApi");
639 const api = createLocalApi(rpcClientMock as never);
640
641 await api.persistence.getClientSettings();
642 await api.persistence.setClientSettings(clientSettings);
643 await api.persistence.getSavedEnvironmentRegistry();
644 await api.persistence.setSavedEnvironmentRegistry([]);
645 await api.persistence.getSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
646 await api.persistence.setSavedEnvironmentSecret(
647 EnvironmentId.make("environment-local"),
648 "bearer-token",
649 );
650 await api.persistence.removeSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
651
652 expect(getClientSettings).toHaveBeenCalledWith();
653 expect(setClientSettings).toHaveBeenCalledWith(clientSettings);
654 expect(getSavedEnvironmentRegistry).toHaveBeenCalledWith();
655 expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
656 expect(getSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
657 expect(setSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local", "bearer-token");
658 expect(removeSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
659 });
660
661 it("falls back to browser storage for persistence when the desktop bridge is missing", async () => {
662 const { createLocalApi } = await import("./localApi");
663 const api = createLocalApi(rpcClientMock as never);
664 const clientSettings = {
665 autoOpenPlanSidebar: false,
666 confirmThreadArchive: true,
667 confirmThreadDelete: false,
668 dismissedProviderUpdateNotificationKeys: [],
669 diffIgnoreWhitespace: true,
670 diffWordWrap: true,
671 favorites: [],
672 providerModelPreferences: {},
673 sidebarProjectGroupingMode: "repository_path" as const,
674 sidebarProjectGroupingOverrides: {
675 "environment-local:/tmp/project": "separate" as const,
676 },
677 sidebarProjectSortOrder: "manual" as const,
678 sidebarThreadSortOrder: "created_at" as const,
679 sidebarThreadPreviewCount: 6,
680 timestampFormat: "24-hour" as const,
681 };
682
683 await api.persistence.setClientSettings(clientSettings);
684 await api.persistence.setSavedEnvironmentRegistry([
685 {
686 environmentId: EnvironmentId.make("environment-local"),
687 label: "Primary",
688 httpBaseUrl: "http://localhost:3000",
689 wsBaseUrl: "ws://localhost:3000",
690 createdAt: "2026-04-09T00:00:00.000Z",
691 lastConnectedAt: null,
692 },
693 ]);
694 await api.persistence.setSavedEnvironmentSecret(
695 EnvironmentId.make("environment-local"),
696 "bearer-token",
697 );
698
699 await expect(api.persistence.getClientSettings()).resolves.toEqual(clientSettings);
700 await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual([
701 {
702 environmentId: EnvironmentId.make("environment-local"),
703 label: "Primary",
704 httpBaseUrl: "http://localhost:3000",
705 wsBaseUrl: "ws://localhost:3000",
706 createdAt: "2026-04-09T00:00:00.000Z",
707 lastConnectedAt: null,
708 },
709 ]);
710 await expect(
711 api.persistence.getSavedEnvironmentSecret(EnvironmentId.make("environment-local")),
712 ).resolves.toBe("bearer-token");
713
714 await api.persistence.removeSavedEnvironmentSecret(EnvironmentId.make("environment-local"));
715
716 await expect(
717 api.persistence.getSavedEnvironmentSecret(EnvironmentId.make("environment-local")),
718 ).resolves.toBeNull();
719 });
720});