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

wsNativeApi.test.ts

310 lines9.8 KB

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