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

connection.test.ts

347 lines9.8 KB

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(options?: {
8 readonly getSnapshot?: () => Promise<{ readonly snapshotSequence: number }>;
9 readonly replayEvents?: () => Promise<ReadonlyArray<any>>;
10}) {
11 const lifecycleListeners = new Set<(event: any) => void>();
12 const configListeners = new Set<(event: any) => void>();
13 const terminalListeners = new Set<(event: any) => void>();
14 let domainResubscribe: (() => void) | undefined;
15​
16 const getSnapshot = vi.fn(
17 options?.getSnapshot ??
18 (async () =>
19 ({
20 snapshotSequence: 1,
21 projects: [],
22 threads: [],
23 }) as any),
24 );
25 const replayEvents = vi.fn(options?.replayEvents ?? (async () => []));
26​
27 const client = {
28 dispose: vi.fn(async () => undefined),
29 reconnect: vi.fn(async () => undefined),
30 server: {
31 getConfig: vi.fn(async () => ({
32 environment: {
33 environmentId: EnvironmentId.makeUnsafe("env-1"),
34 },
35 })),
36 subscribeConfig: (listener: (event: any) => void) => {
37 configListeners.add(listener);
38 return () => configListeners.delete(listener);
39 },
40 subscribeLifecycle: (listener: (event: any) => void) => {
41 lifecycleListeners.add(listener);
42 return () => lifecycleListeners.delete(listener);
43 },
44 subscribeAuthAccess: () => () => undefined,
45 refreshProviders: vi.fn(async () => undefined),
46 upsertKeybinding: vi.fn(async () => undefined),
47 getSettings: vi.fn(async () => undefined),
48 updateSettings: vi.fn(async () => undefined),
49 },
50 orchestration: {
51 getSnapshot,
52 dispatchCommand: vi.fn(async () => undefined),
53 getTurnDiff: vi.fn(async () => undefined),
54 getFullThreadDiff: vi.fn(async () => undefined),
55 replayEvents,
56 onDomainEvent: vi.fn((_: (event: any) => void, options?: { onResubscribe?: () => void }) => {
57 domainResubscribe = options?.onResubscribe;
58 return () => {
59 if (domainResubscribe === options?.onResubscribe) {
60 domainResubscribe = undefined;
61 }
62 };
63 }),
64 },
65 terminal: {
66 open: vi.fn(async () => undefined),
67 write: vi.fn(async () => undefined),
68 resize: vi.fn(async () => undefined),
69 clear: vi.fn(async () => undefined),
70 restart: vi.fn(async () => undefined),
71 close: vi.fn(async () => undefined),
72 onEvent: (listener: (event: any) => void) => {
73 terminalListeners.add(listener);
74 return () => terminalListeners.delete(listener);
75 },
76 },
77 projects: {
78 searchEntries: vi.fn(async () => []),
79 writeFile: vi.fn(async () => undefined),
80 },
81 shell: {
82 openInEditor: vi.fn(async () => undefined),
83 },
84 git: {
85 pull: vi.fn(async () => undefined),
86 refreshStatus: vi.fn(async () => undefined),
87 onStatus: vi.fn(() => () => undefined),
88 runStackedAction: vi.fn(async () => ({}) as any),
89 listBranches: vi.fn(async () => []),
90 createWorktree: vi.fn(async () => undefined),
91 removeWorktree: vi.fn(async () => undefined),
92 createBranch: vi.fn(async () => undefined),
93 checkout: vi.fn(async () => undefined),
94 init: vi.fn(async () => undefined),
95 resolvePullRequest: vi.fn(async () => undefined),
96 preparePullRequestThread: vi.fn(async () => undefined),
97 },
98 } as unknown as WsRpcClient;
99​
100 return {
101 client,
102 getSnapshot,
103 replayEvents,
104 emitWelcome: (environmentId: EnvironmentId) => {
105 for (const listener of lifecycleListeners) {
106 listener({
107 type: "welcome",
108 payload: {
109 environment: {
110 environmentId,
111 },
112 },
113 });
114 }
115 },
116 emitConfigSnapshot: (environmentId: EnvironmentId) => {
117 for (const listener of configListeners) {
118 listener({
119 type: "snapshot",
120 config: {
121 environment: {
122 environmentId,
123 },
124 },
125 });
126 }
127 },
128 triggerDomainResubscribe: () => {
129 domainResubscribe?.();
130 },
131 };
133​
134describe("createEnvironmentConnection", () => {
135 it("bootstraps a snapshot immediately for a new connection", async () => {
136 const environmentId = EnvironmentId.makeUnsafe("env-1");
137 const { client, getSnapshot } = createTestClient();
138 const syncSnapshot = vi.fn();
139​
140 const connection = createEnvironmentConnection({
141 kind: "saved",
142 knownEnvironment: {
143 id: "env-1",
144 label: "Remote env",
145 source: "manual",
146 target: {
147 httpBaseUrl: "http://example.test",
148 wsBaseUrl: "ws://example.test",
149 },
150 environmentId,
151 },
152 client,
153 applyEventBatch: vi.fn(),
154 syncSnapshot,
155 applyTerminalEvent: vi.fn(),
156 });
157​
158 await Promise.resolve();
159 await Promise.resolve();
160​
161 expect(getSnapshot).toHaveBeenCalledTimes(1);
162 expect(syncSnapshot).toHaveBeenCalledWith(
163 expect.objectContaining({ snapshotSequence: 1 }),
164 environmentId,
165 );
166​
167 await connection.dispose();
168 });
169​
170 it("rejects welcome/config identity drift", async () => {
171 const environmentId = EnvironmentId.makeUnsafe("env-1");
172 const { client, emitWelcome } = createTestClient();
173​
174 const connection = createEnvironmentConnection({
175 kind: "saved",
176 knownEnvironment: {
177 id: "env-1",
178 label: "Remote env",
179 source: "manual",
180 target: {
181 httpBaseUrl: "http://example.test",
182 wsBaseUrl: "ws://example.test",
183 },
184 environmentId,
185 },
186 client,
187 applyEventBatch: vi.fn(),
188 syncSnapshot: vi.fn(),
189 applyTerminalEvent: vi.fn(),
190 });
191​
192 expect(() => emitWelcome(EnvironmentId.makeUnsafe("env-2"))).toThrow(
193 "Environment connection env-1 changed identity to env-2 via server lifecycle welcome.",
194 );
195​
196 await connection.dispose();
197 });
198​
199 it("rejects ensureBootstrapped when snapshot recovery fails", async () => {
200 const environmentId = EnvironmentId.makeUnsafe("env-1");
201 const snapshotError = new Error("snapshot failed");
202 const { client } = createTestClient({
203 getSnapshot: async () => {
204 throw snapshotError;
205 },
206 });
207​
208 const connection = createEnvironmentConnection({
209 kind: "saved",
210 knownEnvironment: {
211 id: "env-1",
212 label: "Remote env",
213 source: "manual",
214 target: {
215 httpBaseUrl: "http://example.test",
216 wsBaseUrl: "ws://example.test",
217 },
218 environmentId,
219 },
220 client,
221 applyEventBatch: vi.fn(),
222 syncSnapshot: vi.fn(),
223 applyTerminalEvent: vi.fn(),
224 });
225​
226 await expect(connection.ensureBootstrapped()).rejects.toThrow("snapshot failed");
227​
228 await connection.dispose();
229 });
230​
231 it("retries replay recovery after transport disconnects during resubscribe", async () => {
232 const environmentId = EnvironmentId.makeUnsafe("env-1");
233 let replayAttempts = 0;
234 const applyEventBatch = vi.fn();
235 const { client, replayEvents, triggerDomainResubscribe } = createTestClient({
236 replayEvents: async () => {
237 replayAttempts += 1;
238 if (replayAttempts === 1) {
239 throw new Error("SocketCloseError: 1006");
240 }
241​
242 return [
243 {
244 sequence: 2,
245 type: "thread.created",
246 payload: {},
247 },
248 ];
249 },
250 });
251​
252 const connection = createEnvironmentConnection({
253 kind: "saved",
254 knownEnvironment: {
255 id: "env-1",
256 label: "Remote env",
257 source: "manual",
258 target: {
259 httpBaseUrl: "http://example.test",
260 wsBaseUrl: "ws://example.test",
261 },
262 environmentId,
263 },
264 client,
265 applyEventBatch,
266 syncSnapshot: vi.fn(),
267 applyTerminalEvent: vi.fn(),
268 });
269​
270 await Promise.resolve();
271 await Promise.resolve();
272​
273 triggerDomainResubscribe();
274​
275 await vi.waitFor(() => {
276 expect(replayEvents).toHaveBeenCalledTimes(2);
277 expect(applyEventBatch).toHaveBeenCalledWith(
278 [
279 expect.objectContaining({
280 sequence: 2,
281 }),
282 ],
283 environmentId,
284 );
285 });
286​
287 await connection.dispose();
288 });
289 it("swallows replay recovery failures triggered by resubscribe", async () => {
290 const environmentId = EnvironmentId.makeUnsafe("env-1");
291 const snapshotError = new Error("snapshot failed");
292 let snapshotCalls = 0;
293 const { client, triggerDomainResubscribe } = createTestClient({
294 getSnapshot: async () => {
295 snapshotCalls += 1;
296 if (snapshotCalls === 1) {
297 return {
298 snapshotSequence: 1,
299 projects: [],
300 threads: [],
301 } as any;
302 }
303​
304 throw snapshotError;
305 },
306 replayEvents: async () => {
307 throw new Error("SocketCloseError: 1006");
308 },
309 });
310​
311 const connection = createEnvironmentConnection({
312 kind: "saved",
313 knownEnvironment: {
314 id: "env-1",
315 label: "Remote env",
316 source: "manual",
317 target: {
318 httpBaseUrl: "http://example.test",
319 wsBaseUrl: "ws://example.test",
320 },
321 environmentId,
322 },
323 client,
324 applyEventBatch: vi.fn(),
325 syncSnapshot: vi.fn(),
326 applyTerminalEvent: vi.fn(),
327 });
328​
329 await Promise.resolve();
330 await Promise.resolve();
331​
332 const onUnhandledRejection = vi.fn();
333 process.on("unhandledRejection", onUnhandledRejection);
334​
335 try {
336 triggerDomainResubscribe();
337 await new Promise((resolve) => setTimeout(resolve, 0));
338 await new Promise((resolve) => setTimeout(resolve, 0));
339 } finally {
340 process.off("unhandledRejection", onUnhandledRejection);
341 }
342​
343 expect(onUnhandledRejection).not.toHaveBeenCalled();
344​
345 await connection.dispose();
346 });
347});