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

connection.test.ts

295 lines8.7 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { describe, expect, it, vi } from "vite-plus/test";
3​
4import { createEnvironmentConnection } from "./connection";
5import type { WsRpcClient } from "@t3tools/client-runtime";
6​
7function createTestClient(config?: { readonly emitInitialSnapshot?: boolean }) {
8 const lifecycleListeners = new Set<(event: any) => void>();
9 const configListeners = new Set<(event: any) => void>();
10 const shellListeners = new Set<(event: any) => void>();
11 let shellResubscribe: (() => void) | undefined;
12​
13 const client = {
14 dispose: vi.fn(async () => undefined),
15 reconnect: vi.fn(async () => {
16 shellResubscribe?.();
17 }),
18 server: {
19 getConfig: vi.fn(async () => ({
20 environment: {
21 environmentId: EnvironmentId.make("env-1"),
22 },
23 })),
24 subscribeConfig: vi.fn((listener: (event: any) => void) => {
25 configListeners.add(listener);
26 return () => configListeners.delete(listener);
27 }),
28 subscribeLifecycle: vi.fn((listener: (event: any) => void) => {
29 lifecycleListeners.add(listener);
30 return () => lifecycleListeners.delete(listener);
31 }),
32 subscribeAuthAccess: () => () => undefined,
33 refreshProviders: vi.fn(async () => undefined),
34 upsertKeybinding: vi.fn(async () => undefined),
35 getSettings: vi.fn(async () => undefined),
36 updateSettings: vi.fn(async () => undefined),
37 },
38 orchestration: {
39 dispatchCommand: vi.fn(async () => undefined),
40 getTurnDiff: vi.fn(async () => undefined),
41 getFullThreadDiff: vi.fn(async () => undefined),
42 subscribeShell: vi.fn(
43 (listener: (event: any) => void, options?: { onResubscribe?: () => void }) => {
44 shellListeners.add(listener);
45 shellResubscribe = options?.onResubscribe;
46 if (config?.emitInitialSnapshot !== false) {
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 }
59 return () => {
60 shellListeners.delete(listener);
61 if (shellResubscribe === options?.onResubscribe) {
62 shellResubscribe = undefined;
63 }
64 };
65 },
66 ),
67 subscribeThread: vi.fn(() => () => undefined),
68 },
69 terminal: {
70 open: vi.fn(async () => undefined),
71 attach: vi.fn(() => () => undefined),
72 write: vi.fn(async () => undefined),
73 resize: vi.fn(async () => undefined),
74 clear: vi.fn(async () => undefined),
75 restart: vi.fn(async () => undefined),
76 close: vi.fn(async () => undefined),
77 onEvent: vi.fn(() => () => undefined),
78 onMetadata: vi.fn(() => () => undefined),
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 runStackedAction: vi.fn(async () => ({}) as any),
89 resolvePullRequest: vi.fn(async () => undefined),
90 preparePullRequestThread: vi.fn(async () => undefined),
91 },
92 review: {
93 getDiffPreview: vi.fn(async () => undefined),
94 },
95 } as unknown as WsRpcClient;
96​
97 return {
98 client,
99 emitWelcome: (environmentId: EnvironmentId) => {
100 for (const listener of lifecycleListeners) {
101 listener({
102 type: "welcome",
103 payload: {
104 environment: {
105 environmentId,
106 },
107 },
108 });
109 }
110 },
111 emitConfigSnapshot: (environmentId: EnvironmentId) => {
112 for (const listener of configListeners) {
113 listener({
114 type: "snapshot",
115 config: {
116 environment: {
117 environmentId,
118 },
119 },
120 });
121 }
122 },
123 emitShellSnapshot: (snapshotSequence: number) => {
124 for (const listener of shellListeners) {
125 listener({
126 kind: "snapshot",
127 snapshot: {
128 snapshotSequence,
129 projects: [],
130 threads: [],
131 updatedAt: "2026-04-12T00:00:00.000Z",
132 },
133 });
134 }
135 },
136 };
138​
139describe("createEnvironmentConnection", () => {
140 it("bootstraps from the shell subscription snapshot", async () => {
141 const environmentId = EnvironmentId.make("env-1");
142 const { client } = createTestClient();
143 const syncShellSnapshot = vi.fn();
144​
145 const connection = createEnvironmentConnection({
146 kind: "saved",
147 knownEnvironment: {
148 id: "env-1",
149 label: "Remote env",
150 source: "manual",
151 target: {
152 httpBaseUrl: "http://example.test",
153 wsBaseUrl: "ws://example.test",
154 },
155 environmentId,
156 },
157 client,
158 applyShellEvent: vi.fn(),
159 syncShellSnapshot,
160 });
161​
162 await connection.ensureBootstrapped();
163​
164 expect(syncShellSnapshot).toHaveBeenCalledWith(
165 expect.objectContaining({ snapshotSequence: 1 }),
166 environmentId,
167 );
168​
169 await connection.dispose();
170 });
171​
172 it("rejects welcome/config identity drift", async () => {
173 const environmentId = EnvironmentId.make("env-1");
174 const { client, emitWelcome } = createTestClient();
175​
176 const connection = createEnvironmentConnection({
177 kind: "saved",
178 knownEnvironment: {
179 id: "env-1",
180 label: "Remote env",
181 source: "manual",
182 target: {
183 httpBaseUrl: "http://example.test",
184 wsBaseUrl: "ws://example.test",
185 },
186 environmentId,
187 },
188 client,
189 applyShellEvent: vi.fn(),
190 syncShellSnapshot: vi.fn(),
191 });
192​
193 expect(() => emitWelcome(EnvironmentId.make("env-2"))).toThrow(
194 "Environment connection env-1 changed identity to env-2 via server lifecycle welcome.",
195 );
196​
197 await connection.dispose();
198 });
199​
200 it("waits for a fresh shell snapshot after reconnect", async () => {
201 const environmentId = EnvironmentId.make("env-1");
202 const { client, emitShellSnapshot } = createTestClient();
203 const syncShellSnapshot = vi.fn();
204​
205 const connection = createEnvironmentConnection({
206 kind: "saved",
207 knownEnvironment: {
208 id: "env-1",
209 label: "Remote env",
210 source: "manual",
211 target: {
212 httpBaseUrl: "http://example.test",
213 wsBaseUrl: "ws://example.test",
214 },
215 environmentId,
216 },
217 client,
218 applyShellEvent: vi.fn(),
219 syncShellSnapshot,
220 });
221​
222 await connection.ensureBootstrapped();
223​
224 const reconnectPromise = connection.reconnect();
225 await Promise.resolve();
226 expect(syncShellSnapshot).toHaveBeenCalledTimes(1);
227​
228 emitShellSnapshot(2);
229 await reconnectPromise;
230​
231 expect(client.reconnect).toHaveBeenCalledTimes(1);
232 expect(syncShellSnapshot).toHaveBeenCalledTimes(2);
233 expect(syncShellSnapshot).toHaveBeenLastCalledWith(
234 expect.objectContaining({ snapshotSequence: 2 }),
235 environmentId,
236 );
237​
238 await connection.dispose();
239 });
240​
241 it("skips primary lifecycle/config subscriptions when no handlers are registered", async () => {
242 const environmentId = EnvironmentId.make("env-1");
243 const { client } = createTestClient();
244​
245 const connection = createEnvironmentConnection({
246 kind: "primary",
247 knownEnvironment: {
248 id: "env-1",
249 label: "Local env",
250 source: "manual",
251 target: {
252 httpBaseUrl: "http://example.test",
253 wsBaseUrl: "ws://example.test",
254 },
255 environmentId,
256 },
257 client,
258 applyShellEvent: vi.fn(),
259 syncShellSnapshot: vi.fn(),
260 applyTerminalEvent: vi.fn(),
261 });
262​
263 expect(client.server.subscribeLifecycle).not.toHaveBeenCalled();
264 expect(client.server.subscribeConfig).not.toHaveBeenCalled();
265 expect(client.orchestration.subscribeShell).toHaveBeenCalledOnce();
266​
267 await connection.dispose();
268 });
269​
270 it("rejects bootstrap waits when a pending connection is disposed", async () => {
271 const environmentId = EnvironmentId.make("env-1");
272 const { client } = createTestClient({ emitInitialSnapshot: false });
273 const connection = createEnvironmentConnection({
274 kind: "saved",
275 knownEnvironment: {
276 id: "env-1",
277 label: "Remote env",
278 source: "manual",
279 target: {
280 httpBaseUrl: "http://example.test",
281 wsBaseUrl: "ws://example.test",
282 },
283 environmentId,
284 },
285 client,
286 applyShellEvent: vi.fn(),
287 syncShellSnapshot: vi.fn(),
288 });
289 const pendingBootstrap = connection.ensureBootstrapped();
290​
291 await connection.dispose();
292​
293 await expect(pendingBootstrap).rejects.toThrow("was disposed before it finished bootstrapping");
294 });
295});