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

wsNativeApi.test.ts

417 lines12.7 KB

1import {
2 CommandId,
3 DEFAULT_SERVER_SETTINGS,
4 type DesktopBridge,
5 EventId,
6 type GitStatusResult,
7 ProjectId,
8 type OrchestrationEvent,
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 orchestrationEventListeners = new Set<(event: OrchestrationEvent) => 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 shell: {
55 openInEditor: vi.fn(),
56 },
57 git: {
58 pull: vi.fn(),
59 refreshStatus: vi.fn(),
60 onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
61 registerListener(gitStatusListeners, listener),
62 ),
63 runStackedAction: vi.fn(),
64 listBranches: vi.fn(),
65 createWorktree: vi.fn(),
66 removeWorktree: vi.fn(),
67 createBranch: vi.fn(),
68 checkout: vi.fn(),
69 init: vi.fn(),
70 resolvePullRequest: vi.fn(),
71 preparePullRequestThread: vi.fn(),
72 },
73 server: {
74 getConfig: vi.fn(),
75 refreshProviders: vi.fn(),
76 upsertKeybinding: vi.fn(),
77 getSettings: vi.fn(),
78 updateSettings: vi.fn(),
79 subscribeConfig: vi.fn(),
80 subscribeLifecycle: vi.fn(),
81 },
82 orchestration: {
83 getSnapshot: vi.fn(),
84 dispatchCommand: vi.fn(),
85 getTurnDiff: vi.fn(),
86 getFullThreadDiff: vi.fn(),
87 replayEvents: vi.fn(),
88 onDomainEvent: vi.fn((listener: (event: OrchestrationEvent) => void) =>
89 registerListener(orchestrationEventListeners, listener),
90 ),
91 },
92};
93​
94vi.mock("./wsRpcClient", () => {
95 return {
96 getWsRpcClient: () => rpcClientMock,
97 __resetWsRpcClientForTests: vi.fn(),
98 };
99});
100​
101vi.mock("./contextMenuFallback", () => ({
102 showContextMenuFallback: showContextMenuFallbackMock,
103}));
104​
105function emitEvent<T>(listeners: Set<(event: T) => void>, event: T) {
106 for (const listener of listeners) {
107 listener(event);
108 }
110​
111function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
112 const testGlobal = globalThis as typeof globalThis & {
113 window?: Window & typeof globalThis & { desktopBridge?: unknown };
114 };
115 if (!testGlobal.window) {
116 testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
117 }
118 return testGlobal.window;
120​
121function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
122 return {
123 getWsUrl: () => null,
124 pickFolder: async () => null,
125 confirm: async () => true,
126 setTheme: async () => undefined,
127 showContextMenu: async () => null,
128 openExternal: async () => true,
129 onMenuAction: () => () => undefined,
130 getUpdateState: async () => {
131 throw new Error("getUpdateState not implemented in test");
132 },
133 checkForUpdate: async () => {
134 throw new Error("checkForUpdate not implemented in test");
135 },
136 downloadUpdate: async () => {
137 throw new Error("downloadUpdate not implemented in test");
138 },
139 installUpdate: async () => {
140 throw new Error("installUpdate not implemented in test");
141 },
142 onUpdateState: () => () => undefined,
143 ...overrides,
144 };
146​
147const defaultProviders: ReadonlyArray<ServerProvider> = [
148 {
149 provider: "codex",
150 enabled: true,
151 installed: true,
152 version: "0.116.0",
153 status: "ready",
154 auth: { status: "authenticated" },
155 checkedAt: "2026-01-01T00:00:00.000Z",
156 models: [],
157 },
158];
159​
160const baseServerConfig: ServerConfig = {
161 cwd: "/tmp/workspace",
162 keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
163 keybindings: [],
164 issues: [],
165 providers: defaultProviders,
166 availableEditors: ["cursor"],
167 observability: {
168 logsDirectoryPath: "/tmp/workspace/.config/logs",
169 localTracingEnabled: true,
170 otlpTracesEnabled: false,
171 otlpMetricsEnabled: false,
172 },
173 settings: DEFAULT_SERVER_SETTINGS,
174};
175​
176const baseGitStatus: GitStatusResult = {
177 isRepo: true,
178 hasOriginRemote: true,
179 isDefaultBranch: false,
180 branch: "feature/streamed",
181 hasWorkingTreeChanges: false,
182 workingTree: { files: [], insertions: 0, deletions: 0 },
183 hasUpstream: true,
184 aheadCount: 0,
185 behindCount: 0,
186 pr: null,
187};
188​
189beforeEach(() => {
190 vi.resetModules();
191 vi.clearAllMocks();
192 showContextMenuFallbackMock.mockReset();
193 terminalEventListeners.clear();
194 orchestrationEventListeners.clear();
195 gitStatusListeners.clear();
196 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
197});
198​
199afterEach(() => {
200 vi.restoreAllMocks();
201});
202​
203describe("wsNativeApi", () => {
204 it("forwards server config fetches directly to the RPC client", async () => {
205 rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
206 const { createWsNativeApi } = await import("./wsNativeApi");
207​
208 const api = createWsNativeApi();
209​
210 await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
211 expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
212 expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled();
213 expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
214 });
215​
216 it("forwards terminal and orchestration stream events", async () => {
217 const { createWsNativeApi } = await import("./wsNativeApi");
218​
219 const api = createWsNativeApi();
220 const onTerminalEvent = vi.fn();
221 const onDomainEvent = vi.fn();
222​
223 api.terminal.onEvent(onTerminalEvent);
224 api.orchestration.onDomainEvent(onDomainEvent);
225​
226 const terminalEvent = {
227 threadId: "thread-1",
228 terminalId: "terminal-1",
229 createdAt: "2026-02-24T00:00:00.000Z",
230 type: "output",
231 data: "hello",
232 } as const;
233 emitEvent(terminalEventListeners, terminalEvent);
234​
235 const orchestrationEvent = {
236 sequence: 1,
237 eventId: EventId.makeUnsafe("event-1"),
238 aggregateKind: "project",
239 aggregateId: ProjectId.makeUnsafe("project-1"),
240 occurredAt: "2026-02-24T00:00:00.000Z",
241 commandId: null,
242 causationEventId: null,
243 correlationId: null,
244 metadata: {},
245 type: "project.created",
246 payload: {
247 projectId: ProjectId.makeUnsafe("project-1"),
248 title: "Project",
249 workspaceRoot: "/tmp/workspace",
250 defaultModelSelection: {
251 provider: "codex",
252 model: "gpt-5-codex",
253 },
254 scripts: [],
255 createdAt: "2026-02-24T00:00:00.000Z",
256 updatedAt: "2026-02-24T00:00:00.000Z",
257 },
258 } satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
259 emitEvent(orchestrationEventListeners, orchestrationEvent);
260​
261 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
262 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
263 });
264​
265 it("forwards git status stream events", async () => {
266 const { createWsNativeApi } = await import("./wsNativeApi");
267​
268 const api = createWsNativeApi();
269 const onStatus = vi.fn();
270​
271 api.git.onStatus({ cwd: "/repo" }, onStatus);
272​
273 const gitStatus = baseGitStatus;
274 emitEvent(gitStatusListeners, gitStatus);
275​
276 expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
277 expect(onStatus).toHaveBeenCalledWith(gitStatus);
278 });
279​
280 it("forwards git status refreshes directly to the RPC client", async () => {
281 rpcClientMock.git.refreshStatus.mockResolvedValue(baseGitStatus);
282 const { createWsNativeApi } = await import("./wsNativeApi");
283​
284 const api = createWsNativeApi();
285​
286 await api.git.refreshStatus({ cwd: "/repo" });
287​
288 expect(rpcClientMock.git.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
289 });
290​
291 it("forwards orchestration stream subscription options to the RPC client", async () => {
292 const { createWsNativeApi } = await import("./wsNativeApi");
293​
294 const api = createWsNativeApi();
295 const onDomainEvent = vi.fn();
296 const onResubscribe = vi.fn();
297​
298 api.orchestration.onDomainEvent(onDomainEvent, { onResubscribe });
299​
300 expect(rpcClientMock.orchestration.onDomainEvent).toHaveBeenCalledWith(onDomainEvent, {
301 onResubscribe,
302 });
303 });
304​
305 it("sends orchestration dispatch commands as the direct RPC payload", async () => {
306 rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
307 const { createWsNativeApi } = await import("./wsNativeApi");
308​
309 const api = createWsNativeApi();
310 const command = {
311 type: "project.create",
312 commandId: CommandId.makeUnsafe("cmd-1"),
313 projectId: ProjectId.makeUnsafe("project-1"),
314 title: "Project",
315 workspaceRoot: "/tmp/project",
316 defaultModelSelection: {
317 provider: "codex",
318 model: "gpt-5-codex",
319 },
320 createdAt: "2026-02-24T00:00:00.000Z",
321 } as const;
322 await api.orchestration.dispatchCommand(command);
323​
324 expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command);
325 });
326​
327 it("forwards workspace file writes to the project RPC", async () => {
328 rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" });
329 const { createWsNativeApi } = await import("./wsNativeApi");
330​
331 const api = createWsNativeApi();
332 await api.projects.writeFile({
333 cwd: "/tmp/project",
334 relativePath: "plan.md",
335 contents: "# Plan\n",
336 });
337​
338 expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({
339 cwd: "/tmp/project",
340 relativePath: "plan.md",
341 contents: "# Plan\n",
342 });
343 });
344​
345 it("forwards full-thread diff requests to the orchestration RPC", async () => {
346 rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
347 const { createWsNativeApi } = await import("./wsNativeApi");
348​
349 const api = createWsNativeApi();
350 await api.orchestration.getFullThreadDiff({
351 threadId: ThreadId.makeUnsafe("thread-1"),
352 toTurnCount: 1,
353 });
354​
355 expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({
356 threadId: "thread-1",
357 toTurnCount: 1,
358 });
359 });
360​
361 it("forwards provider refreshes directly to the RPC client", async () => {
362 const nextProviders: ReadonlyArray<ServerProvider> = [
363 {
364 ...defaultProviders[0]!,
365 checkedAt: "2026-01-03T00:00:00.000Z",
366 },
367 ];
368 rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
369 const { createWsNativeApi } = await import("./wsNativeApi");
370​
371 const api = createWsNativeApi();
372​
373 await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
374 expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
375 });
376​
377 it("forwards server settings updates directly to the RPC client", async () => {
378 const nextSettings = {
379 ...DEFAULT_SERVER_SETTINGS,
380 enableAssistantStreaming: true,
381 };
382 rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
383 const { createWsNativeApi } = await import("./wsNativeApi");
384​
385 const api = createWsNativeApi();
386​
387 await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
388 nextSettings,
389 );
390 expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({
391 enableAssistantStreaming: true,
392 });
393 });
394​
395 it("forwards context menu metadata to the desktop bridge", async () => {
396 const showContextMenu = vi.fn().mockResolvedValue("delete");
397 getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
398​
399 const { createWsNativeApi } = await import("./wsNativeApi");
400 const api = createWsNativeApi();
401 const items = [{ id: "delete", label: "Delete" }] as const;
402​
403 await expect(api.contextMenu.show(items)).resolves.toBe("delete");
404 expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
405 });
406​
407 it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
408 showContextMenuFallbackMock.mockResolvedValue("rename");
409 const { createWsNativeApi } = await import("./wsNativeApi");
410​
411 const api = createWsNativeApi();
412 const items = [{ id: "rename", label: "Rename" }] as const;
413​
414 await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
415 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
416 });
417});