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