Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { describe, expect, it, vi } from "vitest";
3
4import { createEnvironmentConnection } from "./connection";
5import type { WsRpcClient } from "~/rpc/wsRpcClient";
6
7function createTestClient() {
8 const lifecycleListeners = new Set<(event: any) => void>();
9 const configListeners = new Set<(event: any) => void>();
10 const terminalListeners = new Set<(event: any) => void>();
11 const shellListeners = new Set<(event: any) => void>();
12 let shellResubscribe: (() => void) | undefined;
13
14 const client = {
15 dispose: vi.fn(async () => undefined),
16 reconnect: vi.fn(async () => {
17 shellResubscribe?.();
18 }),
19 server: {
20 getConfig: vi.fn(async () => ({
21 environment: {
22 environmentId: EnvironmentId.make("env-1"),
23 },
24 })),
25 subscribeConfig: (listener: (event: any) => void) => {
26 configListeners.add(listener);
27 return () => configListeners.delete(listener);
28 },
29 subscribeLifecycle: (listener: (event: any) => void) => {
30 lifecycleListeners.add(listener);
31 return () => lifecycleListeners.delete(listener);
32 },
33 subscribeAuthAccess: () => () => undefined,
34 refreshProviders: vi.fn(async () => undefined),
35 upsertKeybinding: vi.fn(async () => undefined),
36 getSettings: vi.fn(async () => undefined),
37 updateSettings: vi.fn(async () => undefined),
38 },
39 orchestration: {
40 dispatchCommand: vi.fn(async () => undefined),
41 getTurnDiff: vi.fn(async () => undefined),
42 getFullThreadDiff: vi.fn(async () => undefined),
43 subscribeShell: vi.fn(
44 (listener: (event: any) => void, options?: { onResubscribe?: () => void }) => {
45 shellListeners.add(listener);
46 shellResubscribe = options?.onResubscribe;
47 queueMicrotask(() => {
48 listener({
49 kind: "snapshot",
50 snapshot: {
51 snapshotSequence: 1,
52 projects: [],
53 threads: [],
54 updatedAt: "2026-04-12T00:00:00.000Z",
55 },
56 });
57 });
58 return () => {
59 shellListeners.delete(listener);
60 if (shellResubscribe === options?.onResubscribe) {
61 shellResubscribe = undefined;
62 }
63 };
64 },
65 ),
66 subscribeThread: vi.fn(() => () => undefined),
67 },
68 terminal: {
69 open: vi.fn(async () => undefined),
70 write: vi.fn(async () => undefined),
71 resize: vi.fn(async () => undefined),
72 clear: vi.fn(async () => undefined),
73 restart: vi.fn(async () => undefined),
74 close: vi.fn(async () => undefined),
75 onEvent: (listener: (event: any) => void) => {
76 terminalListeners.add(listener);
77 return () => terminalListeners.delete(listener);
78 },
79 },
80 projects: {
81 searchEntries: vi.fn(async () => []),
82 writeFile: vi.fn(async () => undefined),
83 },
84 shell: {
85 openInEditor: vi.fn(async () => undefined),
86 },
87 git: {
88 pull: vi.fn(async () => undefined),
89 refreshStatus: vi.fn(async () => undefined),
90 onStatus: vi.fn(() => () => undefined),
91 runStackedAction: vi.fn(async () => ({}) as any),
92 listBranches: vi.fn(async () => []),
93 createWorktree: vi.fn(async () => undefined),
94 removeWorktree: vi.fn(async () => undefined),
95 createBranch: vi.fn(async () => undefined),
96 checkout: vi.fn(async () => undefined),
97 init: vi.fn(async () => undefined),
98 resolvePullRequest: vi.fn(async () => undefined),
99 preparePullRequestThread: vi.fn(async () => undefined),
100 },
101 } as unknown as WsRpcClient;
102
103 return {
104 client,
105 emitWelcome: (environmentId: EnvironmentId) => {
106 for (const listener of lifecycleListeners) {
107 listener({
108 type: "welcome",
109 payload: {
110 environment: {
111 environmentId,
112 },
113 },
114 });
115 }
116 },
117 emitConfigSnapshot: (environmentId: EnvironmentId) => {
118 for (const listener of configListeners) {
119 listener({
120 type: "snapshot",
121 config: {
122 environment: {
123 environmentId,
124 },
125 },
126 });
127 }
128 },
129 emitShellSnapshot: (snapshotSequence: number) => {
130 for (const listener of shellListeners) {
131 listener({
132 kind: "snapshot",
133 snapshot: {
134 snapshotSequence,
135 projects: [],
136 threads: [],
137 updatedAt: "2026-04-12T00:00:00.000Z",
138 },
139 });
140 }
141 },
142 };
143}
144
145describe("createEnvironmentConnection", () => {
146 it("bootstraps from the shell subscription snapshot", async () => {
147 const environmentId = EnvironmentId.make("env-1");
148 const { client } = createTestClient();
149 const syncShellSnapshot = vi.fn();
150
151 const connection = createEnvironmentConnection({
152 kind: "saved",
153 knownEnvironment: {
154 id: "env-1",
155 label: "Remote env",
156 source: "manual",
157 target: {
158 httpBaseUrl: "http://example.test",
159 wsBaseUrl: "ws://example.test",
160 },
161 environmentId,
162 },
163 client,
164 applyShellEvent: vi.fn(),
165 syncShellSnapshot,
166 applyTerminalEvent: vi.fn(),
167 });
168
169 await connection.ensureBootstrapped();
170
171 expect(syncShellSnapshot).toHaveBeenCalledWith(
172 expect.objectContaining({ snapshotSequence: 1 }),
173 environmentId,
174 );
175
176 await connection.dispose();
177 });
178
179 it("rejects welcome/config identity drift", async () => {
180 const environmentId = EnvironmentId.make("env-1");
181 const { client, emitWelcome } = createTestClient();
182
183 const connection = createEnvironmentConnection({
184 kind: "saved",
185 knownEnvironment: {
186 id: "env-1",
187 label: "Remote env",
188 source: "manual",
189 target: {
190 httpBaseUrl: "http://example.test",
191 wsBaseUrl: "ws://example.test",
192 },
193 environmentId,
194 },
195 client,
196 applyShellEvent: vi.fn(),
197 syncShellSnapshot: vi.fn(),
198 applyTerminalEvent: vi.fn(),
199 });
200
201 expect(() => emitWelcome(EnvironmentId.make("env-2"))).toThrow(
202 "Environment connection env-1 changed identity to env-2 via server lifecycle welcome.",
203 );
204
205 await connection.dispose();
206 });
207
208 it("waits for a fresh shell snapshot after reconnect", async () => {
209 const environmentId = EnvironmentId.make("env-1");
210 const { client, emitShellSnapshot } = createTestClient();
211 const syncShellSnapshot = vi.fn();
212
213 const connection = createEnvironmentConnection({
214 kind: "saved",
215 knownEnvironment: {
216 id: "env-1",
217 label: "Remote env",
218 source: "manual",
219 target: {
220 httpBaseUrl: "http://example.test",
221 wsBaseUrl: "ws://example.test",
222 },
223 environmentId,
224 },
225 client,
226 applyShellEvent: vi.fn(),
227 syncShellSnapshot,
228 applyTerminalEvent: vi.fn(),
229 });
230
231 await connection.ensureBootstrapped();
232
233 const reconnectPromise = connection.reconnect();
234 await Promise.resolve();
235 expect(syncShellSnapshot).toHaveBeenCalledTimes(1);
236
237 emitShellSnapshot(2);
238 await reconnectPromise;
239
240 expect(client.reconnect).toHaveBeenCalledTimes(1);
241 expect(syncShellSnapshot).toHaveBeenCalledTimes(2);
242 expect(syncShellSnapshot).toHaveBeenLastCalledWith(
243 expect.objectContaining({ snapshotSequence: 2 }),
244 environmentId,
245 );
246
247 await connection.dispose();
248 });
249});