Open History to see the last commit
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 };
32}
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.makeUnsafe("environment-local"),
108 },
109 client: rpcClientMock,
110 environmentId: EnvironmentId.makeUnsafe("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 }
128}
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;
138}
139
140function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
141 return {
142 getLocalEnvironmentBootstrap: () => null,
143 getServerExposureState: async () => ({
144 mode: "local-only",
145 endpointUrl: null,
146 advertisedHost: null,
147 }),
148 setServerExposureMode: async () => ({
149 mode: "local-only",
150 endpointUrl: null,
151 advertisedHost: null,
152 }),
153 pickFolder: async () => null,
154 confirm: async () => true,
155 setTheme: async () => undefined,
156 showContextMenu: async () => null,
157 openExternal: async () => true,
158 onMenuAction: () => () => undefined,
159 getUpdateState: async () => {
160 throw new Error("getUpdateState not implemented in test");
161 },
162 checkForUpdate: async () => {
163 throw new Error("checkForUpdate not implemented in test");
164 },
165 downloadUpdate: async () => {
166 throw new Error("downloadUpdate not implemented in test");
167 },
168 installUpdate: async () => {
169 throw new Error("installUpdate not implemented in test");
170 },
171 onUpdateState: () => () => undefined,
172 ...overrides,
173 };
174}
175
176const defaultProviders: ReadonlyArray<ServerProvider> = [
177 {
178 provider: "codex",
179 enabled: true,
180 installed: true,
181 version: "0.116.0",
182 status: "ready",
183 auth: { status: "authenticated" },
184 checkedAt: "2026-01-01T00:00:00.000Z",
185 models: [],
186 },
187];
188
189const baseEnvironment = {
190 environmentId: EnvironmentId.makeUnsafe("environment-local"),
191 label: "Local environment",
192 platform: {
193 os: "darwin" as const,
194 arch: "arm64" as const,
195 },
196 serverVersion: "0.0.0-test",
197 capabilities: {
198 repositoryIdentity: true,
199 },
200};
201
202const baseServerConfig: ServerConfig = {
203 environment: baseEnvironment,
204 auth: {
205 policy: "loopback-browser",
206 bootstrapMethods: ["one-time-token"],
207 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
208 sessionCookieName: "t3_session",
209 },
210 cwd: "/tmp/workspace",
211 keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
212 keybindings: [],
213 issues: [],
214 providers: defaultProviders,
215 availableEditors: ["cursor"],
216 observability: {
217 logsDirectoryPath: "/tmp/workspace/.config/logs",
218 localTracingEnabled: true,
219 otlpTracesEnabled: false,
220 otlpMetricsEnabled: false,
221 },
222 settings: DEFAULT_SERVER_SETTINGS,
223};
224
225const baseGitStatus: GitStatusResult = {
226 isRepo: true,
227 hasOriginRemote: true,
228 isDefaultBranch: false,
229 branch: "feature/streamed",
230 hasWorkingTreeChanges: false,
231 workingTree: { files: [], insertions: 0, deletions: 0 },
232 hasUpstream: true,
233 aheadCount: 0,
234 behindCount: 0,
235 pr: null,
236};
237
238beforeEach(() => {
239 vi.resetModules();
240 vi.clearAllMocks();
241 showContextMenuFallbackMock.mockReset();
242 terminalEventListeners.clear();
243 orchestrationEventListeners.clear();
244 gitStatusListeners.clear();
245 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
246});
247
248afterEach(() => {
249 vi.restoreAllMocks();
250});
251
252describe("wsApi", () => {
253 it("forwards server config fetches directly to the RPC client", async () => {
254 rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
255 const { createLocalApi } = await import("./localApi");
256
257 const api = createLocalApi(rpcClientMock as never);
258
259 await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
260 expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
261 expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled();
262 expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
263 });
264
265 it("forwards terminal and orchestration stream events", async () => {
266 const { createEnvironmentApi } = await import("./environmentApi");
267
268 const api = createEnvironmentApi(rpcClientMock as never);
269 const onTerminalEvent = vi.fn();
270 const onDomainEvent = vi.fn();
271
272 api.terminal.onEvent(onTerminalEvent);
273 api.orchestration.onDomainEvent(onDomainEvent);
274
275 const terminalEvent = {
276 threadId: "thread-1",
277 terminalId: "terminal-1",
278 createdAt: "2026-02-24T00:00:00.000Z",
279 type: "output",
280 data: "hello",
281 } as const;
282 emitEvent(terminalEventListeners, terminalEvent);
283
284 const orchestrationEvent = {
285 sequence: 1,
286 eventId: EventId.makeUnsafe("event-1"),
287 aggregateKind: "project",
288 aggregateId: ProjectId.makeUnsafe("project-1"),
289 occurredAt: "2026-02-24T00:00:00.000Z",
290 commandId: null,
291 causationEventId: null,
292 correlationId: null,
293 metadata: {},
294 type: "project.created",
295 payload: {
296 projectId: ProjectId.makeUnsafe("project-1"),
297 title: "Project",
298 workspaceRoot: "/tmp/workspace",
299 defaultModelSelection: {
300 provider: "codex",
301 model: "gpt-5-codex",
302 },
303 scripts: [],
304 createdAt: "2026-02-24T00:00:00.000Z",
305 updatedAt: "2026-02-24T00:00:00.000Z",
306 },
307 } satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
308 emitEvent(orchestrationEventListeners, orchestrationEvent);
309
310 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
311 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
312 });
313
314 it("forwards git status stream events", async () => {
315 const { createEnvironmentApi } = await import("./environmentApi");
316
317 const api = createEnvironmentApi(rpcClientMock as never);
318 const onStatus = vi.fn();
319
320 api.git.onStatus({ cwd: "/repo" }, onStatus);
321
322 const gitStatus = baseGitStatus;
323 emitEvent(gitStatusListeners, gitStatus);
324
325 expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
326 expect(onStatus).toHaveBeenCalledWith(gitStatus);
327 });
328
329 it("forwards git status refreshes directly to the RPC client", async () => {
330 rpcClientMock.git.refreshStatus.mockResolvedValue(baseGitStatus);
331 const { createEnvironmentApi } = await import("./environmentApi");
332
333 const api = createEnvironmentApi(rpcClientMock as never);
334
335 await api.git.refreshStatus({ cwd: "/repo" });
336
337 expect(rpcClientMock.git.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
338 });
339
340 it("forwards orchestration stream subscription options to the RPC client", async () => {
341 const { createEnvironmentApi } = await import("./environmentApi");
342
343 const api = createEnvironmentApi(rpcClientMock as never);
344 const onDomainEvent = vi.fn();
345 const onResubscribe = vi.fn();
346
347 api.orchestration.onDomainEvent(onDomainEvent, { onResubscribe });
348
349 expect(rpcClientMock.orchestration.onDomainEvent).toHaveBeenCalledWith(onDomainEvent, {
350 onResubscribe,
351 });
352 });
353
354 it("sends orchestration dispatch commands as the direct RPC payload", async () => {
355 rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
356 const { createEnvironmentApi } = await import("./environmentApi");
357
358 const api = createEnvironmentApi(rpcClientMock as never);
359 const command = {
360 type: "project.create",
361 commandId: CommandId.makeUnsafe("cmd-1"),
362 projectId: ProjectId.makeUnsafe("project-1"),
363 title: "Project",
364 workspaceRoot: "/tmp/project",
365 defaultModelSelection: {
366 provider: "codex",
367 model: "gpt-5-codex",
368 },
369 createdAt: "2026-02-24T00:00:00.000Z",
370 } as const;
371 await api.orchestration.dispatchCommand(command);
372
373 expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command);
374 });
375
376 it("forwards workspace file writes to the project RPC", async () => {
377 rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" });
378 const { createEnvironmentApi } = await import("./environmentApi");
379
380 const api = createEnvironmentApi(rpcClientMock as never);
381 await api.projects.writeFile({
382 cwd: "/tmp/project",
383 relativePath: "plan.md",
384 contents: "# Plan\n",
385 });
386
387 expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({
388 cwd: "/tmp/project",
389 relativePath: "plan.md",
390 contents: "# Plan\n",
391 });
392 });
393
394 it("forwards full-thread diff requests to the orchestration RPC", async () => {
395 rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
396 const { createEnvironmentApi } = await import("./environmentApi");
397
398 const api = createEnvironmentApi(rpcClientMock as never);
399 await api.orchestration.getFullThreadDiff({
400 threadId: ThreadId.makeUnsafe("thread-1"),
401 toTurnCount: 1,
402 });
403
404 expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({
405 threadId: "thread-1",
406 toTurnCount: 1,
407 });
408 });
409
410 it("forwards provider refreshes directly to the RPC client", async () => {
411 const nextProviders: ReadonlyArray<ServerProvider> = [
412 {
413 ...defaultProviders[0]!,
414 checkedAt: "2026-01-03T00:00:00.000Z",
415 },
416 ];
417 rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
418 const { createLocalApi } = await import("./localApi");
419
420 const api = createLocalApi(rpcClientMock as never);
421
422 await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
423 expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
424 });
425
426 it("forwards server settings updates directly to the RPC client", async () => {
427 const nextSettings = {
428 ...DEFAULT_SERVER_SETTINGS,
429 enableAssistantStreaming: true,
430 };
431 rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
432 const { createLocalApi } = await import("./localApi");
433
434 const api = createLocalApi(rpcClientMock as never);
435
436 await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
437 nextSettings,
438 );
439 expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({
440 enableAssistantStreaming: true,
441 });
442 });
443
444 it("forwards context menu metadata to the desktop bridge", async () => {
445 const showContextMenu = vi.fn().mockResolvedValue("delete");
446 getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
447
448 const { createLocalApi } = await import("./localApi");
449 const api = createLocalApi(rpcClientMock as never);
450 const items = [{ id: "delete", label: "Delete" }] as const;
451
452 await expect(api.contextMenu.show(items)).resolves.toBe("delete");
453 expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
454 });
455
456 it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
457 showContextMenuFallbackMock.mockResolvedValue("rename");
458 const { createLocalApi } = await import("./localApi");
459
460 const api = createLocalApi(rpcClientMock as never);
461 const items = [{ id: "rename", label: "Rename" }] as const;
462
463 await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
464 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
465 });
466});