Open History to see the last commit
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 }
55}
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;
65}
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 issues: [
171 {
172 kind: "keybindings.invalid-entry",
173 index: 1,
174 message: "Entry at index 1 is invalid.",
175 },
176 ],
177 providers: defaultProviders,
178 } as const;
179 emitPush(WS_CHANNELS.serverConfigUpdated, payload);
180
181 expect(listener).toHaveBeenCalledTimes(1);
182 expect(listener).toHaveBeenCalledWith(payload);
183
184 const lateListener = vi.fn();
185 onServerConfigUpdated(lateListener);
186 expect(lateListener).toHaveBeenCalledTimes(1);
187 expect(lateListener).toHaveBeenCalledWith(payload);
188 expect(warnSpy).not.toHaveBeenCalled();
189 });
190
191 it("drops malformed server.configUpdated payloads", async () => {
192 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
193 const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
194
195 createWsNativeApi();
196 const listener = vi.fn();
197 onServerConfigUpdated(listener);
198
199 emitPush(WS_CHANNELS.serverConfigUpdated, {
200 issues: [{ kind: "keybindings.invalid-entry", message: "missing index" }],
201 providers: defaultProviders,
202 });
203 emitPush(WS_CHANNELS.serverConfigUpdated, {
204 issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
205 providers: defaultProviders,
206 });
207
208 expect(listener).toHaveBeenCalledTimes(1);
209 expect(listener).toHaveBeenCalledWith({
210 issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
211 providers: defaultProviders,
212 });
213 expect(warnSpy).toHaveBeenCalledTimes(1);
214 });
215
216 it("forwards valid terminal and orchestration events", async () => {
217 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
218 const { createWsNativeApi } = await import("./wsNativeApi");
219
220 const api = createWsNativeApi();
221 const onTerminalEvent = vi.fn();
222 const onDomainEvent = vi.fn();
223
224 api.terminal.onEvent(onTerminalEvent);
225 api.orchestration.onDomainEvent(onDomainEvent);
226
227 const terminalEvent = {
228 threadId: "thread-1",
229 terminalId: "terminal-1",
230 createdAt: "2026-02-24T00:00:00.000Z",
231 type: "output",
232 data: "hello",
233 } as const;
234 emitPush(WS_CHANNELS.terminalEvent, terminalEvent);
235
236 const orchestrationEvent = {
237 sequence: 1,
238 eventId: "event-1",
239 aggregateKind: "project",
240 aggregateId: "project-1",
241 occurredAt: "2026-02-24T00:00:00.000Z",
242 commandId: null,
243 causationEventId: null,
244 correlationId: null,
245 metadata: {},
246 type: "project.created",
247 payload: {
248 projectId: "project-1",
249 title: "Project",
250 workspaceRoot: "/tmp/workspace",
251 defaultModel: null,
252 scripts: [],
253 createdAt: "2026-02-24T00:00:00.000Z",
254 updatedAt: "2026-02-24T00:00:00.000Z",
255 },
256 } as const;
257 emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
258
259 expect(onTerminalEvent).toHaveBeenCalledTimes(1);
260 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
261 expect(onDomainEvent).toHaveBeenCalledTimes(1);
262 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
263 expect(warnSpy).not.toHaveBeenCalled();
264 });
265
266 it("drops malformed terminal and orchestration push payloads", async () => {
267 const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
268 const { createWsNativeApi } = await import("./wsNativeApi");
269
270 const api = createWsNativeApi();
271 const onTerminalEvent = vi.fn();
272 const onDomainEvent = vi.fn();
273
274 api.terminal.onEvent(onTerminalEvent);
275 api.orchestration.onDomainEvent(onDomainEvent);
276
277 emitPush(WS_CHANNELS.terminalEvent, {
278 threadId: "thread-1",
279 terminalId: "",
280 createdAt: "2026-02-24T00:00:00.000Z",
281 type: "output",
282 data: "hello",
283 });
284 emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, {
285 sequence: -1,
286 type: "project.created",
287 });
288
289 expect(onTerminalEvent).not.toHaveBeenCalled();
290 expect(onDomainEvent).not.toHaveBeenCalled();
291 expect(warnSpy).toHaveBeenCalledTimes(2);
292 expect(warnSpy).toHaveBeenNthCalledWith(1, "Dropped inbound WebSocket push payload", {
293 reason: "decode-failed",
294 raw: {
295 threadId: "thread-1",
296 terminalId: "",
297 createdAt: "2026-02-24T00:00:00.000Z",
298 type: "output",
299 data: "hello",
300 },
301 issue: expect.stringContaining("SchemaError"),
302 });
303 expect(warnSpy).toHaveBeenNthCalledWith(2, "Dropped inbound WebSocket push payload", {
304 reason: "decode-failed",
305 raw: {
306 sequence: -1,
307 type: "project.created",
308 },
309 issue: expect.stringContaining("SchemaError"),
310 });
311 });
312
313 it("wraps orchestration dispatch commands in the command envelope", async () => {
314 requestMock.mockResolvedValue(undefined);
315 const { createWsNativeApi } = await import("./wsNativeApi");
316
317 const api = createWsNativeApi();
318 const command = {
319 type: "project.create",
320 commandId: CommandId.makeUnsafe("cmd-1"),
321 projectId: ProjectId.makeUnsafe("project-1"),
322 title: "Project",
323 workspaceRoot: "/tmp/project",
324 defaultModel: "gpt-5-codex",
325 createdAt: "2026-02-24T00:00:00.000Z",
326 } as const;
327 await api.orchestration.dispatchCommand(command);
328
329 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.dispatchCommand, {
330 command,
331 });
332 });
333
334 it("forwards workspace file writes to the websocket project method", async () => {
335 requestMock.mockResolvedValue({ relativePath: "plan.md" });
336 const { createWsNativeApi } = await import("./wsNativeApi");
337
338 const api = createWsNativeApi();
339 await api.projects.writeFile({
340 cwd: "/tmp/project",
341 relativePath: "plan.md",
342 contents: "# Plan\n",
343 });
344
345 expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, {
346 cwd: "/tmp/project",
347 relativePath: "plan.md",
348 contents: "# Plan\n",
349 });
350 });
351
352 it("forwards full-thread diff requests to the orchestration websocket method", async () => {
353 requestMock.mockResolvedValue({ diff: "patch" });
354 const { createWsNativeApi } = await import("./wsNativeApi");
355
356 const api = createWsNativeApi();
357 await api.orchestration.getFullThreadDiff({
358 threadId: ThreadId.makeUnsafe("thread-1"),
359 toTurnCount: 1,
360 });
361
362 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.getFullThreadDiff, {
363 threadId: "thread-1",
364 toTurnCount: 1,
365 });
366 });
367
368 it("forwards context menu metadata to desktop bridge", async () => {
369 const showContextMenu = vi.fn().mockResolvedValue("delete");
370 Object.defineProperty(getWindowForTest(), "desktopBridge", {
371 configurable: true,
372 writable: true,
373 value: {
374 showContextMenu,
375 },
376 });
377
378 const { createWsNativeApi } = await import("./wsNativeApi");
379 const api = createWsNativeApi();
380 await api.contextMenu.show(
381 [
382 { id: "rename", label: "Rename thread" },
383 { id: "delete", label: "Delete", destructive: true },
384 ],
385 { x: 200, y: 300 },
386 );
387
388 expect(showContextMenu).toHaveBeenCalledWith(
389 [
390 { id: "rename", label: "Rename thread" },
391 { id: "delete", label: "Delete", destructive: true },
392 ],
393 { x: 200, y: 300 },
394 );
395 });
396
397 it("uses fallback context menu when desktop bridge is unavailable", async () => {
398 showContextMenuFallbackMock.mockResolvedValue("delete");
399 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
400
401 const { createWsNativeApi } = await import("./wsNativeApi");
402 const api = createWsNativeApi();
403 await api.contextMenu.show(
404 [{ id: "delete", label: "Delete", destructive: true }],
405 { x: 20, y: 30 },
406 );
407
408 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
409 [{ id: "delete", label: "Delete", destructive: true }],
410 { x: 20, y: 30 },
411 );
412 });
413});