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

localApi.test.ts

618 lines20.0 KB

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