Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

localApi.test.ts

638 lines20.8 KB

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