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