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