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

wsNativeApi.test.ts

421 lines13.2 KB

1import {
2 CommandId,
3 type ContextMenuItem,
4 ORCHESTRATION_WS_CHANNELS,
5 ORCHESTRATION_WS_METHODS,
6 ProjectId,
7 ThreadId,
8 WS_CHANNELS,
9 WS_METHODS,
10 type ServerProviderStatus,
11} from "@t3tools/contracts";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13​
14const requestMock = vi.fn<(...args: Array<unknown>) => Promise<unknown>>();
15const showContextMenuFallbackMock = vi.fn<
16 <T extends string>(
17 items: readonly ContextMenuItem<T>[],
18 position?: { x: number; y: number },
19 ) => Promise<T | null>
20>();
21const channelListeners = new Map<string, Set<(data: unknown) => void>>();
22const subscribeMock = vi.fn<(channel: string, listener: (data: unknown) => void) => () => void>(
23 (channel, listener) => {
24 const listeners = channelListeners.get(channel) ?? new Set<(data: unknown) => void>();
25 listeners.add(listener);
26 channelListeners.set(channel, listeners);
27 return () => {
28 listeners.delete(listener);
29 if (listeners.size === 0) {
30 channelListeners.delete(channel);
31 }
32 };
33 },
34);
35​
36vi.mock("./wsTransport", () => {
37 return {
38 WsTransport: class MockWsTransport {
39 request = requestMock;
40 subscribe = subscribeMock;
41 },
42 };
43});
44​
45vi.mock("./contextMenuFallback", () => ({
46 showContextMenuFallback: showContextMenuFallbackMock,
47}));
48​
49function emitPush(channel: string, data: unknown): void {
50 const listeners = channelListeners.get(channel);
51 if (!listeners) return;
52 for (const listener of listeners) {
53 listener(data);
54 }
56​
57function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
58 const testGlobal = globalThis as typeof globalThis & {
59 window?: Window & typeof globalThis & { desktopBridge?: unknown };
60 };
61 if (!testGlobal.window) {
62 testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
63 }
64 return testGlobal.window;
66​
67const defaultProviders: ReadonlyArray<ServerProviderStatus> = [
68 {
69 provider: "codex",
70 status: "ready",
71 available: true,
72 authStatus: "authenticated",
73 checkedAt: "2026-01-01T00:00:00.000Z",
74 },
75];
76​
77beforeEach(() => {
78 vi.resetModules();
79 requestMock.mockReset();
80 showContextMenuFallbackMock.mockReset();
81 subscribeMock.mockClear();
82 channelListeners.clear();
83 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
84});
85​
86afterEach(() => {
87 vi.restoreAllMocks();
88});
89​
90describe("wsNativeApi", () => {
91 it("delivers and caches valid server.welcome payloads", async () => {
92 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
93 const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
94​
95 createWsNativeApi();
96 const listener = vi.fn();
97 onServerWelcome(listener);
98​
99 const payload = { cwd: "/tmp/workspace", projectName: "t3-code" };
100 emitPush(WS_CHANNELS.serverWelcome, payload);
101​
102 expect(listener).toHaveBeenCalledTimes(1);
103 expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
104​
105 const lateListener = vi.fn();
106 onServerWelcome(lateListener);
107​
108 expect(lateListener).toHaveBeenCalledTimes(1);
109 expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
110 expect(warnSpy).not.toHaveBeenCalled();
111 });
112​
113 it("preserves bootstrap ids from server.welcome payloads", async () => {
114 const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
115​
116 createWsNativeApi();
117 const listener = vi.fn();
118 onServerWelcome(listener);
119​
120 emitPush(WS_CHANNELS.serverWelcome, {
121 cwd: "/tmp/workspace",
122 projectName: "t3-code",
123 bootstrapProjectId: "project-1",
124 bootstrapThreadId: "thread-1",
125 });
126​
127 expect(listener).toHaveBeenCalledTimes(1);
128 expect(listener).toHaveBeenCalledWith(
129 expect.objectContaining({
130 cwd: "/tmp/workspace",
131 projectName: "t3-code",
132 bootstrapProjectId: "project-1",
133 bootstrapThreadId: "thread-1",
134 }),
135 );
136 });
137​
138 it("ignores invalid server.welcome payloads and keeps subscription active", async () => {
139 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
140 const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
141​
142 createWsNativeApi();
143 const listener = vi.fn();
144 onServerWelcome(listener);
145​
146 emitPush(WS_CHANNELS.serverWelcome, { cwd: 42, projectName: "t3-code" });
147 emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
148​
149 expect(listener).toHaveBeenCalledTimes(1);
150 expect(listener).toHaveBeenCalledWith(
151 expect.objectContaining({ cwd: "/tmp/workspace", projectName: "t3-code" }),
152 );
153 expect(warnSpy).toHaveBeenCalledTimes(1);
154 expect(warnSpy).toHaveBeenCalledWith("Dropped inbound WebSocket push payload", {
155 reason: "decode-failed",
156 raw: { cwd: 42, projectName: "t3-code" },
157 issue: expect.stringContaining("SchemaError"),
158 });
159 });
160​
161 it("delivers and caches valid server.configUpdated payloads", async () => {
162 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
163 const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
164​
165 createWsNativeApi();
166 const listener = vi.fn();
167 onServerConfigUpdated(listener);
168​
169 const payload = {
170 changedSections: ["keybindings"],
171 keybindingsIssues: [
172 {
173 kind: "keybindings.invalid-entry",
174 index: 1,
175 message: "Entry at index 1 is invalid.",
176 },
177 ],
178 appearanceIssues: [],
179 providers: defaultProviders,
180 } as const;
181 emitPush(WS_CHANNELS.serverConfigUpdated, payload);
182​
183 expect(listener).toHaveBeenCalledTimes(1);
184 expect(listener).toHaveBeenCalledWith(payload);
185​
186 const lateListener = vi.fn();
187 onServerConfigUpdated(lateListener);
188 expect(lateListener).toHaveBeenCalledTimes(1);
189 expect(lateListener).toHaveBeenCalledWith(payload);
190 expect(warnSpy).not.toHaveBeenCalled();
191 });
192​
193 it("drops malformed server.configUpdated payloads", async () => {
194 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
195 const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
196​
197 createWsNativeApi();
198 const listener = vi.fn();
199 onServerConfigUpdated(listener);
200​
201 emitPush(WS_CHANNELS.serverConfigUpdated, {
202 changedSections: ["keybindings"],
203 keybindingsIssues: [{ kind: "keybindings.invalid-entry", message: "missing index" }],
204 appearanceIssues: [],
205 providers: defaultProviders,
206 });
207 emitPush(WS_CHANNELS.serverConfigUpdated, {
208 changedSections: ["keybindings"],
209 keybindingsIssues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
210 appearanceIssues: [],
211 providers: defaultProviders,
212 });
213​
214 expect(listener).toHaveBeenCalledTimes(1);
215 expect(listener).toHaveBeenCalledWith({
216 changedSections: ["keybindings"],
217 keybindingsIssues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
218 appearanceIssues: [],
219 providers: defaultProviders,
220 });
221 expect(warnSpy).toHaveBeenCalledTimes(1);
222 });
223​
224 it("forwards valid terminal and orchestration events", async () => {
225 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
226 const { createWsNativeApi } = await import("./wsNativeApi");
227​
228 const api = createWsNativeApi();
229 const onTerminalEvent = vi.fn();
230 const onDomainEvent = vi.fn();
231​
232 api.terminal.onEvent(onTerminalEvent);
233 api.orchestration.onDomainEvent(onDomainEvent);
234​
235 const terminalEvent = {
236 threadId: "thread-1",
237 terminalId: "terminal-1",
238 createdAt: "2026-02-24T00:00:00.000Z",
239 type: "output",
240 data: "hello",
241 } as const;
242 emitPush(WS_CHANNELS.terminalEvent, terminalEvent);
243​
244 const orchestrationEvent = {
245 sequence: 1,
246 eventId: "event-1",
247 aggregateKind: "project",
248 aggregateId: "project-1",
249 occurredAt: "2026-02-24T00:00:00.000Z",
250 commandId: null,
251 causationEventId: null,
252 correlationId: null,
253 metadata: {},
254 type: "project.created",
255 payload: {
256 projectId: "project-1",
257 title: "Project",
258 workspaceRoot: "/tmp/workspace",
259 defaultModel: null,
260 scripts: [],
261 createdAt: "2026-02-24T00:00:00.000Z",
262 updatedAt: "2026-02-24T00:00:00.000Z",
263 },
264 } as const;
265 emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
266​
267 expect(onTerminalEvent).toHaveBeenCalledTimes(1);
268 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
269 expect(onDomainEvent).toHaveBeenCalledTimes(1);
270 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
271 expect(warnSpy).not.toHaveBeenCalled();
272 });
273​
274 it("drops malformed terminal and orchestration push payloads", async () => {
275 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
276 const { createWsNativeApi } = await import("./wsNativeApi");
277​
278 const api = createWsNativeApi();
279 const onTerminalEvent = vi.fn();
280 const onDomainEvent = vi.fn();
281​
282 api.terminal.onEvent(onTerminalEvent);
283 api.orchestration.onDomainEvent(onDomainEvent);
284​
285 emitPush(WS_CHANNELS.terminalEvent, {
286 threadId: "thread-1",
287 terminalId: "",
288 createdAt: "2026-02-24T00:00:00.000Z",
289 type: "output",
290 data: "hello",
291 });
292 emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, {
293 sequence: -1,
294 type: "project.created",
295 });
296​
297 expect(onTerminalEvent).not.toHaveBeenCalled();
298 expect(onDomainEvent).not.toHaveBeenCalled();
299 expect(warnSpy).toHaveBeenCalledTimes(2);
300 expect(warnSpy).toHaveBeenNthCalledWith(1, "Dropped inbound WebSocket push payload", {
301 reason: "decode-failed",
302 raw: {
303 threadId: "thread-1",
304 terminalId: "",
305 createdAt: "2026-02-24T00:00:00.000Z",
306 type: "output",
307 data: "hello",
308 },
309 issue: expect.stringContaining("SchemaError"),
310 });
311 expect(warnSpy).toHaveBeenNthCalledWith(2, "Dropped inbound WebSocket push payload", {
312 reason: "decode-failed",
313 raw: {
314 sequence: -1,
315 type: "project.created",
316 },
317 issue: expect.stringContaining("SchemaError"),
318 });
319 });
320​
321 it("wraps orchestration dispatch commands in the command envelope", async () => {
322 requestMock.mockResolvedValue(undefined);
323 const { createWsNativeApi } = await import("./wsNativeApi");
324​
325 const api = createWsNativeApi();
326 const command = {
327 type: "project.create",
328 commandId: CommandId.makeUnsafe("cmd-1"),
329 projectId: ProjectId.makeUnsafe("project-1"),
330 title: "Project",
331 workspaceRoot: "/tmp/project",
332 defaultModel: "gpt-5-codex",
333 createdAt: "2026-02-24T00:00:00.000Z",
334 } as const;
335 await api.orchestration.dispatchCommand(command);
336​
337 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.dispatchCommand, {
338 command,
339 });
340 });
341​
342 it("forwards workspace file writes to the websocket project method", async () => {
343 requestMock.mockResolvedValue({ relativePath: "plan.md" });
344 const { createWsNativeApi } = await import("./wsNativeApi");
345​
346 const api = createWsNativeApi();
347 await api.projects.writeFile({
348 cwd: "/tmp/project",
349 relativePath: "plan.md",
350 contents: "# Plan\n",
351 });
352​
353 expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, {
354 cwd: "/tmp/project",
355 relativePath: "plan.md",
356 contents: "# Plan\n",
357 });
358 });
359​
360 it("forwards full-thread diff requests to the orchestration websocket method", async () => {
361 requestMock.mockResolvedValue({ diff: "patch" });
362 const { createWsNativeApi } = await import("./wsNativeApi");
363​
364 const api = createWsNativeApi();
365 await api.orchestration.getFullThreadDiff({
366 threadId: ThreadId.makeUnsafe("thread-1"),
367 toTurnCount: 1,
368 });
369​
370 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.getFullThreadDiff, {
371 threadId: "thread-1",
372 toTurnCount: 1,
373 });
374 });
375​
376 it("forwards context menu metadata to desktop bridge", async () => {
377 const showContextMenu = vi.fn().mockResolvedValue("delete");
378 Object.defineProperty(getWindowForTest(), "desktopBridge", {
379 configurable: true,
380 writable: true,
381 value: {
382 showContextMenu,
383 },
384 });
385​
386 const { createWsNativeApi } = await import("./wsNativeApi");
387 const api = createWsNativeApi();
388 await api.contextMenu.show(
389 [
390 { id: "rename", label: "Rename thread" },
391 { id: "delete", label: "Delete", destructive: true },
392 ],
393 { x: 200, y: 300 },
394 );
395​
396 expect(showContextMenu).toHaveBeenCalledWith(
397 [
398 { id: "rename", label: "Rename thread" },
399 { id: "delete", label: "Delete", destructive: true },
400 ],
401 { x: 200, y: 300 },
402 );
403 });
404​
405 it("uses fallback context menu when desktop bridge is unavailable", async () => {
406 showContextMenuFallbackMock.mockResolvedValue("delete");
407 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
408​
409 const { createWsNativeApi } = await import("./wsNativeApi");
410 const api = createWsNativeApi();
411 await api.contextMenu.show(
412 [{ id: "delete", label: "Delete", destructive: true }],
413 { x: 20, y: 30 },
414 );
415​
416 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
417 [{ id: "delete", label: "Delete", destructive: true }],
418 { x: 20, y: 30 },
419 );
420 });
421});