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 const onActionProgress = vi.fn();
243
244 api.terminal.onEvent(onTerminalEvent);
245 api.orchestration.onDomainEvent(onDomainEvent);
246 api.git.onActionProgress(onActionProgress);
247
248 const terminalEvent = {
249 threadId: "thread-1",
250 terminalId: "terminal-1",
251 createdAt: "2026-02-24T00:00:00.000Z",
252 type: "output",
253 data: "hello",
254 } as const;
255 emitPush(WS_CHANNELS.terminalEvent, terminalEvent);
256
257 const orchestrationEvent = {
258 sequence: 1,
259 eventId: EventId.makeUnsafe("event-1"),
260 aggregateKind: "project",
261 aggregateId: ProjectId.makeUnsafe("project-1"),
262 occurredAt: "2026-02-24T00:00:00.000Z",
263 commandId: null,
264 causationEventId: null,
265 correlationId: null,
266 metadata: {},
267 type: "project.created",
268 payload: {
269 projectId: ProjectId.makeUnsafe("project-1"),
270 title: "Project",
271 workspaceRoot: "/tmp/workspace",
272 defaultModel: null,
273 scripts: [],
274 createdAt: "2026-02-24T00:00:00.000Z",
275 updatedAt: "2026-02-24T00:00:00.000Z",
276 },
277 } satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
278 emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent);
279 emitPush(WS_CHANNELS.gitActionProgress, {
280 actionId: "action-1",
281 cwd: "/repo",
282 action: "commit",
283 kind: "phase_started",
284 phase: "commit",
285 label: "Committing...",
286 });
287
288 expect(onTerminalEvent).toHaveBeenCalledTimes(1);
289 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
290 expect(onDomainEvent).toHaveBeenCalledTimes(1);
291 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
292 expect(onActionProgress).toHaveBeenCalledTimes(1);
293 expect(onActionProgress).toHaveBeenCalledWith({
294 actionId: "action-1",
295 cwd: "/repo",
296 action: "commit",
297 kind: "phase_started",
298 phase: "commit",
299 label: "Committing...",
300 });
301 });
302
303 it("wraps orchestration dispatch commands in the command envelope", async () => {
304 requestMock.mockResolvedValue(undefined);
305 const { createWsNativeApi } = await import("./wsNativeApi");
306
307 const api = createWsNativeApi();
308 const command = {
309 type: "project.create",
310 commandId: CommandId.makeUnsafe("cmd-1"),
311 projectId: ProjectId.makeUnsafe("project-1"),
312 title: "Project",
313 workspaceRoot: "/tmp/project",
314 defaultModel: "gpt-5-codex",
315 createdAt: "2026-02-24T00:00:00.000Z",
316 } as const;
317 await api.orchestration.dispatchCommand(command);
318
319 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.dispatchCommand, {
320 command,
321 });
322 });
323
324 it("forwards workspace file writes to the websocket project method", async () => {
325 requestMock.mockResolvedValue({ relativePath: "plan.md" });
326 const { createWsNativeApi } = await import("./wsNativeApi");
327
328 const api = createWsNativeApi();
329 await api.projects.writeFile({
330 cwd: "/tmp/project",
331 relativePath: "plan.md",
332 contents: "# Plan\n",
333 });
334
335 expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, {
336 cwd: "/tmp/project",
337 relativePath: "plan.md",
338 contents: "# Plan\n",
339 });
340 });
341
342 it("uses no client timeout for git.runStackedAction", async () => {
343 requestMock.mockResolvedValue({
344 action: "commit",
345 branch: { status: "skipped_not_requested" },
346 commit: { status: "created", commitSha: "abc1234", subject: "Test" },
347 push: { status: "skipped_not_requested" },
348 pr: { status: "skipped_not_requested" },
349 });
350 const { createWsNativeApi } = await import("./wsNativeApi");
351
352 const api = createWsNativeApi();
353 await api.git.runStackedAction({ actionId: "action-1", cwd: "/repo", action: "commit" });
354
355 expect(requestMock).toHaveBeenCalledWith(
356 WS_METHODS.gitRunStackedAction,
357 { actionId: "action-1", cwd: "/repo", action: "commit" },
358 { timeoutMs: null },
359 );
360 });
361
362 it("forwards thread title generation requests to the websocket server method", async () => {
363 requestMock.mockResolvedValue({ title: "Fix sidebar naming" });
364 const { createWsNativeApi } = await import("./wsNativeApi");
365
366 const api = createWsNativeApi();
367 await api.server.generateThreadTitle({
368 threadId: ThreadId.makeUnsafe("thread-1"),
369 model: "gpt-5.4-mini",
370 });
371
372 expect(requestMock).toHaveBeenCalledWith(WS_METHODS.serverGenerateThreadTitle, {
373 threadId: "thread-1",
374 model: "gpt-5.4-mini",
375 });
376 });
377
378 it("forwards full-thread diff requests to the orchestration websocket method", async () => {
379 requestMock.mockResolvedValue({ diff: "patch" });
380 const { createWsNativeApi } = await import("./wsNativeApi");
381
382 const api = createWsNativeApi();
383 await api.orchestration.getFullThreadDiff({
384 threadId: ThreadId.makeUnsafe("thread-1"),
385 toTurnCount: 1,
386 });
387
388 expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.getFullThreadDiff, {
389 threadId: "thread-1",
390 toTurnCount: 1,
391 });
392 });
393
394 it("forwards context menu metadata to desktop bridge", async () => {
395 const showContextMenu = vi.fn().mockResolvedValue("delete");
396 Object.defineProperty(getWindowForTest(), "desktopBridge", {
397 configurable: true,
398 writable: true,
399 value: {
400 showContextMenu,
401 },
402 });
403
404 const { createWsNativeApi } = await import("./wsNativeApi");
405 const api = createWsNativeApi();
406 await api.contextMenu.show(
407 [
408 { id: "rename", label: "Rename thread" },
409 { id: "delete", label: "Delete", destructive: true },
410 ],
411 { x: 200, y: 300 },
412 );
413
414 expect(showContextMenu).toHaveBeenCalledWith(
415 [
416 { id: "rename", label: "Rename thread" },
417 { id: "delete", label: "Delete", destructive: true },
418 ],
419 { x: 200, y: 300 },
420 );
421 });
422
423 it("uses fallback context menu when desktop bridge is unavailable", async () => {
424 showContextMenuFallbackMock.mockResolvedValue("delete");
425 Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
426
427 const { createWsNativeApi } = await import("./wsNativeApi");
428 const api = createWsNativeApi();
429 await api.contextMenu.show([{ id: "delete", label: "Delete", destructive: true }], {
430 x: 20,
431 y: 30,
432 });
433
434 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
435 [{ id: "delete", label: "Delete", destructive: true }],
436 { x: 20, y: 30 },
437 );
438 });
439});