Open History to see the last commit
1import {
2 CommandId,
3 DEFAULT_SERVER_SETTINGS,
4 type DesktopBridge,
5 EnvironmentId,
6 EventId,
7 type GitStatusResult,
8 ProjectId,
9 type OrchestrationEvent,
10 type ServerConfig,
11 type ServerProvider,
12 type TerminalEvent,
13 ThreadId,
14} from "@t3tools/contracts";
15import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16
17import type { ContextMenuItem } from "@t3tools/contracts";
18
19const showContextMenuFallbackMock =
20 vi.fn<
21 <T extends string>(
22 items: readonly ContextMenuItem<T>[],
23 position?: { x: number; y: number },
24 ) => Promise<T | null>
25 >();
26
27function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
28 listeners.add(listener);
29 return () => {
30 listeners.delete(listener);
31 };
32}
33
34const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
35const orchestrationEventListeners = new Set<(event: OrchestrationEvent) => void>();
36const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
37
38const rpcClientMock = {
39 dispose: vi.fn(),
40 terminal: {
41 open: vi.fn(),
42 write: vi.fn(),
43 resize: vi.fn(),
44 clear: vi.fn(),
45 restart: vi.fn(),
46 close: vi.fn(),
47 onEvent: vi.fn((listener: (event: TerminalEvent) => void) =>
48 registerListener(terminalEventListeners, listener),
49 ),
50 },
51 projects: {
52 searchEntries: vi.fn(),
53 writeFile: vi.fn(),
54 },
55 shell: {
56 openInEditor: vi.fn(),
57 },
58 git: {
59 pull: vi.fn(),
60 refreshStatus: vi.fn(),
61 onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
62 registerListener(gitStatusListeners, listener),
63 ),
64 runStackedAction: vi.fn(),
65 listBranches: vi.fn(),
66 createWorktree: vi.fn(),
67 removeWorktree: vi.fn(),
68 createBranch: vi.fn(),
69 checkout: vi.fn(),
70 init: vi.fn(),
71 resolvePullRequest: vi.fn(),
72 preparePullRequestThread: vi.fn(),
73 },
74 server: {
75 getConfig: vi.fn(),
76 refreshProviders: vi.fn(),
77 upsertKeybinding: vi.fn(),
78 getSettings: vi.fn(),
79 updateSettings: vi.fn(),
80 subscribeConfig: vi.fn(),
81 subscribeLifecycle: vi.fn(),
82 subscribeAuthAccess: vi.fn(),
83 },
84 orchestration: {
85 getSnapshot: vi.fn(),
86 dispatchCommand: vi.fn(),
87 getTurnDiff: vi.fn(),
88 getFullThreadDiff: vi.fn(),
89 replayEvents: vi.fn(),
90 onDomainEvent: vi.fn((listener: (event: OrchestrationEvent) => void) =>
91 registerListener(orchestrationEventListeners, listener),
92 ),
93 },
94};
95
96vi.mock("./environments/runtime", () => ({
97 getPrimaryEnvironmentConnection: () => ({
98 kind: "primary" as const,
99 knownEnvironment: {
100 id: "environment-local",
101 label: "Primary",
102 source: "manual" as const,
103 target: {
104 httpBaseUrl: "http://localhost:3000",
105 wsBaseUrl: "ws://localhost:3000",
106 },
107 environmentId: EnvironmentId.makeUnsafe("environment-local"),
108 },
109 client: rpcClientMock,
110 environmentId: EnvironmentId.makeUnsafe("environment-local"),
111 ensureBootstrapped: async () => undefined,
112 reconnect: async () => undefined,
113 dispose: async () => undefined,
114 }),
115 resetEnvironmentServiceForTests: vi.fn(),
116 resetSavedEnvironmentRegistryStoreForTests: vi.fn(),
117 resetSavedEnvironmentRuntimeStoreForTests: vi.fn(),
118}));
119
120vi.mock("./contextMenuFallback", () => ({
121 showContextMenuFallback: showContextMenuFallbackMock,
122}));
123
124function emitEvent<T>(listeners: Set<(event: T) => void>, event: T) {
125 for (const listener of listeners) {
126 listener(event);
127 }
128}
129
130function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
131 const testGlobal = globalThis as typeof globalThis & {
132 window?: Window & typeof globalThis & { desktopBridge?: unknown };
133 };
134 if (!testGlobal.window) {
135 testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
136 }
137 return testGlobal.window;
138}
139
140function createLocalStorageStub(): Storage {
141 const store = new Map<string, string>();
142 return {
143 getItem: (key) => store.get(key) ?? null,
144 setItem: (key, value) => {
145 store.set(key, value);
146 },
147 removeItem: (key) => {
148 store.delete(key);
149 },
150 clear: () => {
151 store.clear();
152 },
153 key: (index) => [...store.keys()][index] ?? null,
154 get length() {
155 return store.size;
156 },
157 };
158}
159
160function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
161 return {
162 getLocalEnvironmentBootstrap: () => null,
163 getClientSettings: async () => null,
164 setClientSettings: async () => undefined,
165 getSavedEnvironmentRegistry: async () => [],
166 setSavedEnvironmentRegistry: async () => undefined,
167 getSavedEnvironmentSecret: async () => null,
168 setSavedEnvironmentSecret: async () => true,
169 removeSavedEnvironmentSecret: async () => undefined,
170 getServerExposureState: async () => ({
171 mode: "local-only",
172 endpointUrl: null,
173 advertisedHost: null,
174 }),
175 setServerExposureMode: async () => ({
176 mode: "local-only",
177 endpointUrl: null,
178 advertisedHost: null,
179 }),
180 pickFolder: async () => null,
181 confirm: async () => true,
182 setTheme: async () => undefined,
183 showContextMenu: async () => null,
184 openExternal: async () => true,
185 onMenuAction: () => () => undefined,
186 getUpdateState: async () => {
187 throw new Error("getUpdateState not implemented in test");
188 },
189 checkForUpdate: async () => {
190 throw new Error("checkForUpdate not implemented in test");
191 },
192 downloadUpdate: async () => {
193 throw new Error("downloadUpdate not implemented in test");
194 },
195 installUpdate: async () => {
196 throw new Error("installUpdate not implemented in test");
197 },
198 onUpdateState: () => () => undefined,
199 ...overrides,
200 };
201}
202
203const defaultProviders: ReadonlyArray<ServerProvider> = [
204 {
205 provider: "codex",
206 enabled: true,
207 installed: true,
208 version: "0.116.0",
209 status: "ready",
210 auth: { status: "authenticated" },
211 checkedAt: "2026-01-01T00:00:00.000Z",
212 models: [],
213 },
214];
215
216const baseEnvironment = {
217 environmentId: EnvironmentId.makeUnsafe("environment-local"),
218 label: "Local environment",
219 platform: {
220 os: "darwin" as const,
221 arch: "arm64" as const,
222 },
223 serverVersion: "0.0.0-test",
224 capabilities: {
225 repositoryIdentity: true,
226 },
227};
228
229const baseServerConfig: ServerConfig = {
230 environment: baseEnvironment,
231 auth: {
232 policy: "loopback-browser",
233 bootstrapMethods: ["one-time-token"],
234 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
235 sessionCookieName: "t3_session",
236 },
237 cwd: "/tmp/workspace",
238 keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json",
239 keybindings: [],
240 issues: [],
241 providers: defaultProviders,
242 availableEditors: ["cursor"],
243 observability: {
244 logsDirectoryPath: "/tmp/workspace/.config/logs",
245 localTracingEnabled: true,
246 otlpTracesEnabled: false,
247 otlpMetricsEnabled: false,
248 },
249 settings: DEFAULT_SERVER_SETTINGS,
250};
251
252const baseGitStatus: GitStatusResult = {
253 isRepo: true,
254 hasOriginRemote: true,
255 isDefaultBranch: false,
256 branch: "feature/streamed",
257 hasWorkingTreeChanges: false,
258 workingTree: { files: [], insertions: 0, deletions: 0 },
259 hasUpstream: true,
260 aheadCount: 0,
261 behindCount: 0,
262 pr: null,
263};
264
265beforeEach(() => {
266 vi.resetModules();
267 vi.clearAllMocks();
268 showContextMenuFallbackMock.mockReset();
269 terminalEventListeners.clear();
270 orchestrationEventListeners.clear();
271 gitStatusListeners.clear();
272 const testWindow = getWindowForTest();
273 Reflect.deleteProperty(testWindow, "desktopBridge");
274 Object.defineProperty(testWindow, "localStorage", {
275 configurable: true,
276 value: createLocalStorageStub(),
277 });
278});
279
280afterEach(() => {
281 vi.restoreAllMocks();
282});
283
284describe("wsApi", () => {
285 it("forwards server config fetches directly to the RPC client", async () => {
286 rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig);
287 const { createLocalApi } = await import("./localApi");
288
289 const api = createLocalApi(rpcClientMock as never);
290
291 await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig);
292 expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith();
293 expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled();
294 expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled();
295 });
296
297 it("forwards terminal and orchestration stream events", async () => {
298 const { createEnvironmentApi } = await import("./environmentApi");
299
300 const api = createEnvironmentApi(rpcClientMock as never);
301 const onTerminalEvent = vi.fn();
302 const onDomainEvent = vi.fn();
303
304 api.terminal.onEvent(onTerminalEvent);
305 api.orchestration.onDomainEvent(onDomainEvent);
306
307 const terminalEvent = {
308 threadId: "thread-1",
309 terminalId: "terminal-1",
310 createdAt: "2026-02-24T00:00:00.000Z",
311 type: "output",
312 data: "hello",
313 } as const;
314 emitEvent(terminalEventListeners, terminalEvent);
315
316 const orchestrationEvent = {
317 sequence: 1,
318 eventId: EventId.makeUnsafe("event-1"),
319 aggregateKind: "project",
320 aggregateId: ProjectId.makeUnsafe("project-1"),
321 occurredAt: "2026-02-24T00:00:00.000Z",
322 commandId: null,
323 causationEventId: null,
324 correlationId: null,
325 metadata: {},
326 type: "project.created",
327 payload: {
328 projectId: ProjectId.makeUnsafe("project-1"),
329 title: "Project",
330 workspaceRoot: "/tmp/workspace",
331 defaultModelSelection: {
332 provider: "codex",
333 model: "gpt-5-codex",
334 },
335 scripts: [],
336 createdAt: "2026-02-24T00:00:00.000Z",
337 updatedAt: "2026-02-24T00:00:00.000Z",
338 },
339 } satisfies Extract<OrchestrationEvent, { type: "project.created" }>;
340 emitEvent(orchestrationEventListeners, orchestrationEvent);
341
342 expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent);
343 expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent);
344 });
345
346 it("forwards git status stream events", async () => {
347 const { createEnvironmentApi } = await import("./environmentApi");
348
349 const api = createEnvironmentApi(rpcClientMock as never);
350 const onStatus = vi.fn();
351
352 api.git.onStatus({ cwd: "/repo" }, onStatus);
353
354 const gitStatus = baseGitStatus;
355 emitEvent(gitStatusListeners, gitStatus);
356
357 expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
358 expect(onStatus).toHaveBeenCalledWith(gitStatus);
359 });
360
361 it("forwards git status refreshes directly to the RPC client", async () => {
362 rpcClientMock.git.refreshStatus.mockResolvedValue(baseGitStatus);
363 const { createEnvironmentApi } = await import("./environmentApi");
364
365 const api = createEnvironmentApi(rpcClientMock as never);
366
367 await api.git.refreshStatus({ cwd: "/repo" });
368
369 expect(rpcClientMock.git.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
370 });
371
372 it("forwards orchestration stream subscription options to the RPC client", async () => {
373 const { createEnvironmentApi } = await import("./environmentApi");
374
375 const api = createEnvironmentApi(rpcClientMock as never);
376 const onDomainEvent = vi.fn();
377 const onResubscribe = vi.fn();
378
379 api.orchestration.onDomainEvent(onDomainEvent, { onResubscribe });
380
381 expect(rpcClientMock.orchestration.onDomainEvent).toHaveBeenCalledWith(onDomainEvent, {
382 onResubscribe,
383 });
384 });
385
386 it("sends orchestration dispatch commands as the direct RPC payload", async () => {
387 rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 });
388 const { createEnvironmentApi } = await import("./environmentApi");
389
390 const api = createEnvironmentApi(rpcClientMock as never);
391 const command = {
392 type: "project.create",
393 commandId: CommandId.makeUnsafe("cmd-1"),
394 projectId: ProjectId.makeUnsafe("project-1"),
395 title: "Project",
396 workspaceRoot: "/tmp/project",
397 defaultModelSelection: {
398 provider: "codex",
399 model: "gpt-5-codex",
400 },
401 createdAt: "2026-02-24T00:00:00.000Z",
402 } as const;
403 await api.orchestration.dispatchCommand(command);
404
405 expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command);
406 });
407
408 it("forwards workspace file writes to the project RPC", async () => {
409 rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" });
410 const { createEnvironmentApi } = await import("./environmentApi");
411
412 const api = createEnvironmentApi(rpcClientMock as never);
413 await api.projects.writeFile({
414 cwd: "/tmp/project",
415 relativePath: "plan.md",
416 contents: "# Plan\n",
417 });
418
419 expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({
420 cwd: "/tmp/project",
421 relativePath: "plan.md",
422 contents: "# Plan\n",
423 });
424 });
425
426 it("forwards full-thread diff requests to the orchestration RPC", async () => {
427 rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" });
428 const { createEnvironmentApi } = await import("./environmentApi");
429
430 const api = createEnvironmentApi(rpcClientMock as never);
431 await api.orchestration.getFullThreadDiff({
432 threadId: ThreadId.makeUnsafe("thread-1"),
433 toTurnCount: 1,
434 });
435
436 expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({
437 threadId: "thread-1",
438 toTurnCount: 1,
439 });
440 });
441
442 it("forwards provider refreshes directly to the RPC client", async () => {
443 const nextProviders: ReadonlyArray<ServerProvider> = [
444 {
445 ...defaultProviders[0]!,
446 checkedAt: "2026-01-03T00:00:00.000Z",
447 },
448 ];
449 rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders });
450 const { createLocalApi } = await import("./localApi");
451
452 const api = createLocalApi(rpcClientMock as never);
453
454 await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders });
455 expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
456 });
457
458 it("forwards server settings updates directly to the RPC client", async () => {
459 const nextSettings = {
460 ...DEFAULT_SERVER_SETTINGS,
461 enableAssistantStreaming: true,
462 };
463 rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings);
464 const { createLocalApi } = await import("./localApi");
465
466 const api = createLocalApi(rpcClientMock as never);
467
468 await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual(
469 nextSettings,
470 );
471 expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({
472 enableAssistantStreaming: true,
473 });
474 });
475
476 it("forwards context menu metadata to the desktop bridge", async () => {
477 const showContextMenu = vi.fn().mockResolvedValue("delete");
478 getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu });
479
480 const { createLocalApi } = await import("./localApi");
481 const api = createLocalApi(rpcClientMock as never);
482 const items = [{ id: "delete", label: "Delete" }] as const;
483
484 await expect(api.contextMenu.show(items)).resolves.toBe("delete");
485 expect(showContextMenu).toHaveBeenCalledWith(items, undefined);
486 });
487
488 it("falls back to the browser context menu helper when the desktop bridge is missing", async () => {
489 showContextMenuFallbackMock.mockResolvedValue("rename");
490 const { createLocalApi } = await import("./localApi");
491
492 const api = createLocalApi(rpcClientMock as never);
493 const items = [{ id: "rename", label: "Rename" }] as const;
494
495 await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
496 expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
497 });
498
499 it("reads and writes persistence through the desktop bridge when available", async () => {
500 const getClientSettings = vi.fn().mockResolvedValue({
501 confirmThreadArchive: true,
502 confirmThreadDelete: false,
503 diffWordWrap: true,
504 sidebarProjectSortOrder: "manual",
505 sidebarThreadSortOrder: "created_at",
506 timestampFormat: "24-hour",
507 });
508 const setClientSettings = vi.fn().mockResolvedValue(undefined);
509 const getSavedEnvironmentRegistry = vi.fn().mockResolvedValue([]);
510 const setSavedEnvironmentRegistry = vi.fn().mockResolvedValue(undefined);
511 const getSavedEnvironmentSecret = vi.fn().mockResolvedValue("bearer-token");
512 const setSavedEnvironmentSecret = vi.fn().mockResolvedValue(true);
513 const removeSavedEnvironmentSecret = vi.fn().mockResolvedValue(undefined);
514 getWindowForTest().desktopBridge = makeDesktopBridge({
515 getClientSettings,
516 setClientSettings,
517 getSavedEnvironmentRegistry,
518 setSavedEnvironmentRegistry,
519 getSavedEnvironmentSecret,
520 setSavedEnvironmentSecret,
521 removeSavedEnvironmentSecret,
522 });
523
524 const { createLocalApi } = await import("./localApi");
525 const api = createLocalApi(rpcClientMock as never);
526
527 await api.persistence.getClientSettings();
528 await api.persistence.setClientSettings({
529 confirmThreadArchive: true,
530 confirmThreadDelete: false,
531 diffWordWrap: true,
532 sidebarProjectSortOrder: "manual",
533 sidebarThreadSortOrder: "created_at",
534 timestampFormat: "24-hour",
535 });
536 await api.persistence.getSavedEnvironmentRegistry();
537 await api.persistence.setSavedEnvironmentRegistry([]);
538 await api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local"));
539 await api.persistence.setSavedEnvironmentSecret(
540 EnvironmentId.makeUnsafe("environment-local"),
541 "bearer-token",
542 );
543 await api.persistence.removeSavedEnvironmentSecret(
544 EnvironmentId.makeUnsafe("environment-local"),
545 );
546
547 expect(getClientSettings).toHaveBeenCalledWith();
548 expect(setClientSettings).toHaveBeenCalledWith({
549 confirmThreadArchive: true,
550 confirmThreadDelete: false,
551 diffWordWrap: true,
552 sidebarProjectSortOrder: "manual",
553 sidebarThreadSortOrder: "created_at",
554 timestampFormat: "24-hour",
555 });
556 expect(getSavedEnvironmentRegistry).toHaveBeenCalledWith();
557 expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
558 expect(getSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
559 expect(setSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local", "bearer-token");
560 expect(removeSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
561 });
562
563 it("falls back to browser storage for persistence when the desktop bridge is missing", async () => {
564 const { createLocalApi } = await import("./localApi");
565 const api = createLocalApi(rpcClientMock as never);
566
567 await api.persistence.setClientSettings({
568 confirmThreadArchive: true,
569 confirmThreadDelete: false,
570 diffWordWrap: true,
571 sidebarProjectSortOrder: "manual",
572 sidebarThreadSortOrder: "created_at",
573 timestampFormat: "24-hour",
574 });
575 await api.persistence.setSavedEnvironmentRegistry([
576 {
577 environmentId: EnvironmentId.makeUnsafe("environment-local"),
578 label: "Primary",
579 httpBaseUrl: "http://localhost:3000",
580 wsBaseUrl: "ws://localhost:3000",
581 createdAt: "2026-04-09T00:00:00.000Z",
582 lastConnectedAt: null,
583 },
584 ]);
585 await api.persistence.setSavedEnvironmentSecret(
586 EnvironmentId.makeUnsafe("environment-local"),
587 "bearer-token",
588 );
589
590 await expect(api.persistence.getClientSettings()).resolves.toEqual({
591 confirmThreadArchive: true,
592 confirmThreadDelete: false,
593 diffWordWrap: true,
594 sidebarProjectSortOrder: "manual",
595 sidebarThreadSortOrder: "created_at",
596 timestampFormat: "24-hour",
597 });
598 await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual([
599 {
600 environmentId: EnvironmentId.makeUnsafe("environment-local"),
601 label: "Primary",
602 httpBaseUrl: "http://localhost:3000",
603 wsBaseUrl: "ws://localhost:3000",
604 createdAt: "2026-04-09T00:00:00.000Z",
605 lastConnectedAt: null,
606 },
607 ]);
608 await expect(
609 api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local")),
610 ).resolves.toBe("bearer-token");
611
612 await api.persistence.removeSavedEnvironmentSecret(
613 EnvironmentId.makeUnsafe("environment-local"),
614 );
615
616 await expect(
617 api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local")),
618 ).resolves.toBeNull();
619 });
620});