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

wsNativeApi.test.ts

352 lines10.7 KB

1import {
2 CommandId,
3 DEFAULT_SERVER_SETTINGS,
4 type DesktopBridge,
5 EventId,
6 ProjectId,
7 type OrchestrationEvent,
8 type ServerConfig,
9 type ServerProvider,
10 type TerminalEvent,
11 ThreadId,
12} from "@t3tools/contracts";
13import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14​
15import type { ContextMenuItem } from "@t3tools/contracts";
16​
17const showContextMenuFallbackMock =
18 vi.fn<
19 <T extends string>(
20 items: readonly ContextMenuItem<T>[],
21 position?: { x: number; y: number },
22 ) => Promise<T | null>
23 >();
24​
25function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
26 listeners.add(listener);
27 return () => {
28 listeners.delete(listener);
29 };
31​
32const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
33const orchestrationEventListeners = new Set<(event: OrchestrationEvent) => void>();
34​
35const rpcClientMock = {
36 dispose: vi.fn(),
37 terminal: {
38 open: vi.fn(),
39 write: vi.fn(),
40 resize: vi.fn(),
41 clear: vi.fn(),
42 restart: vi.fn(),
43 close: vi.fn(),
44 onEvent: vi.fn((listener: (event: TerminalEvent) => void) =>
45 registerListener(terminalEventListeners, listener),
46 ),
47 },
48 projects: {
49 searchEntries: vi.fn(),
50 writeFile: vi.fn(),
51 },
52 shell: {
53 openInEditor: vi.fn(),
54 },
55 git: {
56 pull: vi.fn(),
57 status: vi.fn(),
58 runStackedAction: vi.fn(),
59 listBranches: vi.fn(),
60 createWorktree: vi.fn(),
61 removeWorktree: vi.fn(),
62 createBranch: vi.fn(),
63 checkout: vi.fn(),
64 init: vi.fn(),
65 resolvePullRequest: vi.fn(),
66 preparePullRequestThread: vi.fn(),
67 },
68 server: {
69 getConfig: vi.fn(),
70 refreshProviders: vi.fn(),
71 upsertKeybinding: vi.fn(),
72 getSettings: vi.fn(),
73 updateSettings: vi.fn(),
74 subscribeConfig: vi.fn(),
75 subscribeLifecycle: vi.fn(),
76 },
77 orchestration: {
78 getSnapshot: vi.fn(),
79 dispatchCommand: vi.fn(),
80 getTurnDiff: vi.fn(),
81 getFullThreadDiff: vi.fn(),
82 replayEvents: vi.fn(),
83 onDomainEvent: vi.fn((listener: (event: OrchestrationEvent) => void) =>
84 registerListener(orchestrationEventListeners, listener),
85 ),
86 },
87};
88​
89vi.mock("./wsRpcClient", () => {
90 return {
91 getWsRpcClient: () => rpcClientMock,
92 __resetWsRpcClientForTests: vi.fn(),
93 };
94});
95​
96vi.mock("./contextMenuFallback", () => ({
97 showContextMenuFallback: showContextMenuFallbackMock,
98}));
99​
100function emitEvent<T>(listeners: Set<(event: T) => void>, event: T) {
101 for (const listener of listeners) {
102 listener(event);
103 }
105​
106function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
107 const testGlobal = globalThis as typeof globalThis & {
108 window?: Window & typeof globalThis & { desktopBridge?: unknown };
109 };
110 if (!testGlobal.window) {
111 testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
112 }
113 return testGlobal.window;
115​
116function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
117 return {
118 getWsUrl: () => null,
119 pickFolder: async () => null,
120 confirm: async () => true,
121 setTheme: async () => undefined,
122 showContextMenu: async () => null,
123 openExternal: async () => true,
124 onMenuAction: () => () => undefined,
125 getUpdateState: async () => {
126 throw new Error("getUpdateState not implemented in test");
127 },
128 checkForUpdate: async () => {
129 throw new Error("checkForUpdate not implemented in test");
130 },
131 downloadUpdate: async () => {
132 throw new Error("downloadUpdate not implemented in test");
133 },
134 installUpdate: async () => {
135 throw new Error("installUpdate not implemented in test");
136 },
137 onUpdateState: () => () => undefined,
138 ...overrides,
139 };
141​
142const defaultProviders: ReadonlyArray<ServerProvider> = [
143 {
144 provider: "codex",
145 enabled: true,
146 installed: true,
147 version: "0.116.0",
148 status: "ready",
149 auth: { status: "authenticated" },
150 checkedAt: "2026-01-01T00:00:00.000Z",
151 models: [],
152 },
153];
154​
155const baseServerConfig: ServerConfig = {
156 cwd: "/tmp/workspace",
157 keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
158 keybindings: [],
159 issues: [],
160 providers: defaultProviders,
161 availableEditors: ["cursor"],
162 settings: DEFAULT_SERVER_SETTINGS,
163};
164​
165beforeEach(() => {
166 vi.resetModules();
167 vi.clearAllMocks();
168 showContextMenuFallbackMock.mockReset();
169 terminalEventListeners.clear();
170 orchestrationEventListeners.clear();
171 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
172});
173​
174afterEach(() => {
175 vi.restoreAllMocks();
176});
177​
178describe("wsNativeApi", () => {
179 it("forwards server config fetches directly to the RPC client", async () => {
180 rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
181 const { createWsNativeApi } = await import("./wsNativeApi");
182​
183 const api = createWsNativeApi();
184​
185 await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
186 expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
187 expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled();
188 expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
189 });
190​
191 it("forwards terminal and orchestration stream events", async () => {
192 const { createWsNativeApi } = await import("./wsNativeApi");
193​
194 const api = createWsNativeApi();
195 const onTerminalEvent = vi.fn();
196 const onDomainEvent = vi.fn();
197​
198 api.terminal.onEvent(onTerminalEvent);
199 api.orchestration.onDomainEvent(onDomainEvent);
200​
201 const terminalEvent = {
202 threadId: "thread-1",
203 terminalId: "terminal-1",
204 createdAt: "2026-02-24T00:00:00.000Z",
205 type: "output",
206 data: "hello",
207 } as const;
208 emitEvent(terminalEventListeners, terminalEvent);
209​
210 const orchestrationEvent = {
211 sequence: 1,
212 eventId: EventId.makeUnsafe("event-1"),
213 aggregateKind: "project",
214 aggregateId: ProjectId.makeUnsafe("project-1"),
215 occurredAt: "2026-02-24T00:00:00.000Z",
216 commandId: null,
217 causationEventId: null,
218 correlationId: null,
219 metadata: {},
220 type: "project.created",
221 payload: {
222 projectId: ProjectId.makeUnsafe("project-1"),
223 title: "Project",
224 workspaceRoot: "/tmp/workspace",
225 defaultModelSelection: {
226 provider: "codex",
227 model: "gpt-5-codex",
228 },
229 scripts: [],
230 createdAt: "2026-02-24T00:00:00.000Z",
231 updatedAt: "2026-02-24T00:00:00.000Z",
232 },
233 } satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
234 emitEvent(orchestrationEventListeners, orchestrationEvent);
235​
236 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
237 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
238 });
239​
240 it("sends orchestration dispatch commands as the direct RPC payload", async () => {
241 rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
242 const { createWsNativeApi } = await import("./wsNativeApi");
243​
244 const api = createWsNativeApi();
245 const command = {
246 type: "project.create",
247 commandId: CommandId.makeUnsafe("cmd-1"),
248 projectId: ProjectId.makeUnsafe("project-1"),
249 title: "Project",
250 workspaceRoot: "/tmp/project",
251 defaultModelSelection: {
252 provider: "codex",
253 model: "gpt-5-codex",
254 },
255 createdAt: "2026-02-24T00:00:00.000Z",
256 } as const;
257 await api.orchestration.dispatchCommand(command);
258​
259 expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command);
260 });
261​
262 it("forwards workspace file writes to the project RPC", async () => {
263 rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" });
264 const { createWsNativeApi } = await import("./wsNativeApi");
265​
266 const api = createWsNativeApi();
267 await api.projects.writeFile({
268 cwd: "/tmp/project",
269 relativePath: "plan.md",
270 contents: "# Plan\n",
271 });
272​
273 expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({
274 cwd: "/tmp/project",
275 relativePath: "plan.md",
276 contents: "# Plan\n",
277 });
278 });
279​
280 it("forwards full-thread diff requests to the orchestration RPC", async () => {
281 rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
282 const { createWsNativeApi } = await import("./wsNativeApi");
283​
284 const api = createWsNativeApi();
285 await api.orchestration.getFullThreadDiff({
286 threadId: ThreadId.makeUnsafe("thread-1"),
287 toTurnCount: 1,
288 });
289​
290 expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({
291 threadId: "thread-1",
292 toTurnCount: 1,
293 });
294 });
295​
296 it("forwards provider refreshes directly to the RPC client", async () => {
297 const nextProviders: ReadonlyArray<ServerProvider> = [
298 {
299 ...defaultProviders[0]!,
300 checkedAt: "2026-01-03T00:00:00.000Z",
301 },
302 ];
303 rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
304 const { createWsNativeApi } = await import("./wsNativeApi");
305​
306 const api = createWsNativeApi();
307​
308 await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
309 expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
310 });
311​
312 it("forwards server settings updates directly to the RPC client", async () => {
313 const nextSettings = {
314 ...DEFAULT_SERVER_SETTINGS,
315 enableAssistantStreaming: true,
316 };
317 rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
318 const { createWsNativeApi } = await import("./wsNativeApi");
319​
320 const api = createWsNativeApi();
321​
322 await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
323 nextSettings,
324 );
325 expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({
326 enableAssistantStreaming: true,
327 });
328 });
329​
330 it("forwards context menu metadata to the desktop bridge", async () => {
331 const showContextMenu = vi.fn().mockResolvedValue("delete");
332 getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
333​
334 const { createWsNativeApi } = await import("./wsNativeApi");
335 const api = createWsNativeApi();
336 const items = [{ id: "delete", label: "Delete" }] as const;
337​
338 await expect(api.contextMenu.show(items)).resolves.toBe("delete");
339 expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
340 });
341​
342 it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
343 showContextMenuFallbackMock.mockResolvedValue("rename");
344 const { createWsNativeApi } = await import("./wsNativeApi");
345​
346 const api = createWsNativeApi();
347 const items = [{ id: "rename", label: "Rename" }] as const;
348​
349 await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
350 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
351 });
352});