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