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

wsNativeApi.test.ts

454 lines13.4 KB

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 ServerProvider,
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 }
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;
94​
95const defaultProviders: ReadonlyArray<ServerProvider> = [
96 {
97 provider: "codex",
98 enabled: true,
99 installed: true,
100 version: "0.116.0",
101 status: "ready",
102 auth: { status: "authenticated" },
103 checkedAt: "2026-01-01T00:00:00.000Z",
104 models: [],
105 },
106];
107​
108beforeEach(() => {
109 vi.resetModules();
110 requestMock.mockReset();
111 showContextMenuFallbackMock.mockReset();
112 subscribeMock.mockClear();
113 channelListeners.clear();
114 latestPushByChannel.clear();
115 nextPushSequence = 1;
116 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
117});
118​
119afterEach(() => {
120 vi.restoreAllMocks();
121});
122​
123describe("wsNativeApi", () => {
124 it("delivers and caches valid server.welcome payloads", async () => {
125 const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
126​
127 createWsNativeApi();
128 const listener = vi.fn();
129 onServerWelcome(listener);
130​
131 const payload = { cwd: "/tmp/workspace", projectName: "t3-code" };
132 emitPush(WS_CHANNELS.serverWelcome, payload);
133​
134 expect(listener).toHaveBeenCalledTimes(1);
135 expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload));
136​
137 const lateListener = vi.fn();
138 onServerWelcome(lateListener);
139​
140 expect(lateListener).toHaveBeenCalledTimes(1);
141 expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload));
142 });
143​
144 it("preserves bootstrap ids from server.welcome payloads", async () => {
145 const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
146​
147 createWsNativeApi();
148 const listener = vi.fn();
149 onServerWelcome(listener);
150​
151 emitPush(WS_CHANNELS.serverWelcome, {
152 cwd: "/tmp/workspace",
153 projectName: "t3-code",
154 bootstrapProjectId: ProjectId.makeUnsafe("project-1"),
155 bootstrapThreadId: ThreadId.makeUnsafe("thread-1"),
156 });
157​
158 expect(listener).toHaveBeenCalledTimes(1);
159 expect(listener).toHaveBeenCalledWith(
160 expect.objectContaining({
161 cwd: "/tmp/workspace",
162 projectName: "t3-code",
163 bootstrapProjectId: "project-1",
164 bootstrapThreadId: "thread-1",
165 }),
166 );
167 });
168​
169 it("delivers successive server.welcome payloads to active listeners", async () => {
170 const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi");
171​
172 createWsNativeApi();
173 const listener = vi.fn();
174 onServerWelcome(listener);
175​
176 emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/one", projectName: "one" });
177 emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" });
178​
179 expect(listener).toHaveBeenCalledTimes(2);
180 expect(listener).toHaveBeenLastCalledWith(
181 expect.objectContaining({
182 cwd: "/tmp/workspace",
183 projectName: "t3-code",
184 }),
185 );
186 });
187​
188 it("delivers and caches valid server.configUpdated payloads", async () => {
189 const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
190​
191 createWsNativeApi();
192 const listener = vi.fn();
193 onServerConfigUpdated(listener);
194​
195 const payload = {
196 issues: [
197 {
198 kind: "keybindings.invalid-entry",
199 index: 1,
200 message: "Entry at index 1 is invalid.",
201 },
202 ],
203 } as const;
204 emitPush(WS_CHANNELS.serverConfigUpdated, payload);
205​
206 expect(listener).toHaveBeenCalledTimes(1);
207 expect(listener).toHaveBeenCalledWith(payload);
208​
209 const lateListener = vi.fn();
210 onServerConfigUpdated(lateListener);
211 expect(lateListener).toHaveBeenCalledTimes(1);
212 expect(lateListener).toHaveBeenCalledWith(payload);
213 });
214​
215 it("delivers successive server.configUpdated payloads to active listeners", async () => {
216 const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi");
217​
218 createWsNativeApi();
219 const listener = vi.fn();
220 onServerConfigUpdated(listener);
221​
222 emitPush(WS_CHANNELS.serverConfigUpdated, {
223 issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
224 });
225 emitPush(WS_CHANNELS.serverConfigUpdated, {
226 issues: [],
227 });
228​
229 expect(listener).toHaveBeenCalledTimes(2);
230 expect(listener).toHaveBeenLastCalledWith({
231 issues: [],
232 });
233 });
234​
235 it("delivers and caches valid server.providersUpdated payloads", async () => {
236 const { createWsNativeApi, onServerProvidersUpdated } = await import("./wsNativeApi");
237​
238 createWsNativeApi();
239 const listener = vi.fn();
240 onServerProvidersUpdated(listener);
241​
242 const payload = {
243 providers: defaultProviders,
244 } as const;
245 emitPush(WS_CHANNELS.serverProvidersUpdated, payload);
246​
247 expect(listener).toHaveBeenCalledTimes(1);
248 expect(listener).toHaveBeenCalledWith(payload);
249​
250 const lateListener = vi.fn();
251 onServerProvidersUpdated(lateListener);
252 expect(lateListener).toHaveBeenCalledTimes(1);
253 expect(lateListener).toHaveBeenCalledWith(payload);
254 });
255​
256 it("forwards valid terminal and orchestration events", async () => {
257 const { createWsNativeApi } = await import("./wsNativeApi");
258​
259 const api = createWsNativeApi();
260 const onTerminalEvent = vi.fn();
261 const onDomainEvent = vi.fn();
262 const onActionProgress = vi.fn();
263​
264 api.terminal.onEvent(onTerminalEvent);
265 api.orchestration.onDomainEvent(onDomainEvent);
266 api.git.onActionProgress(onActionProgress);
267​
268 const terminalEvent = {
269 threadId: "thread-1",
270 terminalId: "terminal-1",
271 createdAt: "2026-02-24T00:00:00.000Z",
272 type: "output",
273 data: "hello",
274 } as const;
275 emitPush(WS_CHANNELS.terminalEvent, terminalEvent);
276​
277 const orchestrationEvent = {
278 sequence: 1,
279 eventId: EventId.makeUnsafe("event-1"),
280 aggregateKind: "project",
281 aggregateId: ProjectId.makeUnsafe("project-1"),
282 occurredAt: "2026-02-24T00:00:00.000Z",
283 commandId: null,
284 causationEventId: null,
285 correlationId: null,
286 metadata: {},
287 type: "project.created",
288 payload: {
289 projectId: ProjectId.makeUnsafe("project-1"),
290 title: "Project",
291 workspaceRoot: "/tmp/workspace",
292 defaultModelSelection: null,
293 scripts: [],
294 createdAt: "2026-02-24T00:00:00.000Z",
295 updatedAt: "2026-02-24T00:00:00.000Z",
296 },
297 } satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
298 emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
299 emitPush(WS_CHANNELS.gitActionProgress, {
300 actionId: "action-1",
301 cwd: "/repo",
302 action: "commit",
303 kind: "phase_started",
304 phase: "commit",
305 label: "Committing...",
306 });
307​
308 expect(onTerminalEvent).toHaveBeenCalledTimes(1);
309 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
310 expect(onDomainEvent).toHaveBeenCalledTimes(1);
311 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
312 expect(onActionProgress).toHaveBeenCalledTimes(1);
313 expect(onActionProgress).toHaveBeenCalledWith({
314 actionId: "action-1",
315 cwd: "/repo",
316 action: "commit",
317 kind: "phase_started",
318 phase: "commit",
319 label: "Committing...",
320 });
321 });
322​
323 it("wraps orchestration dispatch commands in the command envelope", async () => {
324 requestMock.mockResolvedValue(undefined);
325 const { createWsNativeApi } = await import("./wsNativeApi");
326​
327 const api = createWsNativeApi();
328 const command = {
329 type: "project.create",
330 commandId: CommandId.makeUnsafe("cmd-1"),
331 projectId: ProjectId.makeUnsafe("project-1"),
332 title: "Project",
333 workspaceRoot: "/tmp/project",
334 defaultModelSelection: {
335 provider: "codex",
336 model: "gpt-5-codex",
337 },
338 createdAt: "2026-02-24T00:00:00.000Z",
339 } as const;
340 await api.orchestration.dispatchCommand(command);
341​
342 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.dispatchCommand, {
343 command,
344 });
345 });
346​
347 it("forwards workspace file writes to the websocket project method", async () => {
348 requestMock.mockResolvedValue({ relativePath: "plan.md" });
349 const { createWsNativeApi } = await import("./wsNativeApi");
350​
351 const api = createWsNativeApi();
352 await api.projects.writeFile({
353 cwd: "/tmp/project",
354 relativePath: "plan.md",
355 contents: "# Plan\n",
356 });
357​
358 expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, {
359 cwd: "/tmp/project",
360 relativePath: "plan.md",
361 contents: "# Plan\n",
362 });
363 });
364​
365 it("uses no client timeout for git.runStackedAction", async () => {
366 requestMock.mockResolvedValue({
367 action: "commit",
368 branch: { status: "skipped_not_requested" },
369 commit: { status: "created", commitSha: "abc1234", subject: "Test" },
370 push: { status: "skipped_not_requested" },
371 pr: { status: "skipped_not_requested" },
372 });
373 const { createWsNativeApi } = await import("./wsNativeApi");
374​
375 const api = createWsNativeApi();
376 await api.git.runStackedAction({
377 actionId: "action-1",
378 cwd: "/repo",
379 action: "commit",
380 });
381​
382 expect(requestMock).toHaveBeenCalledWith(
383 WS_METHODS.gitRunStackedAction,
384 {
385 actionId: "action-1",
386 cwd: "/repo",
387 action: "commit",
388 },
389 { timeoutMs: null },
390 );
391 });
392​
393 it("forwards full-thread diff requests to the orchestration websocket method", async () => {
394 requestMock.mockResolvedValue({ diff: "patch" });
395 const { createWsNativeApi } = await import("./wsNativeApi");
396​
397 const api = createWsNativeApi();
398 await api.orchestration.getFullThreadDiff({
399 threadId: ThreadId.makeUnsafe("thread-1"),
400 toTurnCount: 1,
401 });
402​
403 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.getFullThreadDiff, {
404 threadId: "thread-1",
405 toTurnCount: 1,
406 });
407 });
408​
409 it("forwards context menu metadata to desktop bridge", async () => {
410 const showContextMenu = vi.fn().mockResolvedValue("delete");
411 Object.defineProperty(getWindowForTest(), "desktopBridge", {
412 configurable: true,
413 writable: true,
414 value: {
415 showContextMenu,
416 },
417 });
418​
419 const { createWsNativeApi } = await import("./wsNativeApi");
420 const api = createWsNativeApi();
421 await api.contextMenu.show(
422 [
423 { id: "rename", label: "Rename thread" },
424 { id: "delete", label: "Delete", destructive: true },
425 ],
426 { x: 200, y: 300 },
427 );
428​
429 expect(showContextMenu).toHaveBeenCalledWith(
430 [
431 { id: "rename", label: "Rename thread" },
432 { id: "delete", label: "Delete", destructive: true },
433 ],
434 { x: 200, y: 300 },
435 );
436 });
437​
438 it("uses fallback context menu when desktop bridge is unavailable", async () => {
439 showContextMenuFallbackMock.mockResolvedValue("delete");
440 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
441​
442 const { createWsNativeApi } = await import("./wsNativeApi");
443 const api = createWsNativeApi();
444 await api.contextMenu.show([{ id: "delete", label: "Delete", destructive: true }], {
445 x: 20,
446 y: 30,
447 });
448​
449 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
450 [{ id: "delete", label: "Delete", destructive: true }],
451 { x: 20, y: 30 },
452 );
453 });
454});