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 runStackedAction: vi.fn(async () => ({}) as any),
89 resolvePullRequest: vi.fn(async () => undefined),
90 preparePullRequestThread: vi.fn(async () => undefined),
91 },
92 } as unknown as WsRpcClient;
93
94 return {
95 client,
96 emitWelcome: (environmentId: EnvironmentId) => {
97 for (const listener of lifecycleListeners) {
98 listener({
99 type: "welcome",
100 payload: {
101 environment: {
102 environmentId,
103 },
104 },
105 });
106 }
107 },
108 emitConfigSnapshot: (environmentId: EnvironmentId) => {
109 for (const listener of configListeners) {
110 listener({
111 type: "snapshot",
112 config: {
113 environment: {
114 environmentId,
115 },
116 },
117 });
118 }
119 },
120 emitShellSnapshot: (snapshotSequence: number) => {
121 for (const listener of shellListeners) {
122 listener({
123 kind: "snapshot",
124 snapshot: {
125 snapshotSequence,
126 projects: [],
127 threads: [],
128 updatedAt: "2026-04-12T00:00:00.000Z",
129 },
130 });
131 }
132 },
133 };
134}
135
136describe("createEnvironmentConnection", () => {
137 it("bootstraps from the shell subscription snapshot", async () => {
138 const environmentId = EnvironmentId.make("env-1");
139 const { client } = createTestClient();
140 const syncShellSnapshot = vi.fn();
141
142 const connection = createEnvironmentConnection({
143 kind: "saved",
144 knownEnvironment: {
145 id: "env-1",
146 label: "Remote env",
147 source: "manual",
148 target: {
149 httpBaseUrl: "http://example.test",
150 wsBaseUrl: "ws://example.test",
151 },
152 environmentId,
153 },
154 client,
155 applyShellEvent: vi.fn(),
156 syncShellSnapshot,
157 applyTerminalEvent: vi.fn(),
158 });
159
160 await connection.ensureBootstrapped();
161
162 expect(syncShellSnapshot).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.make("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 applyShellEvent: vi.fn(),
188 syncShellSnapshot: vi.fn(),
189 applyTerminalEvent: vi.fn(),
190 });
191
192 expect(() => emitWelcome(EnvironmentId.make("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("waits for a fresh shell snapshot after reconnect", async () => {
200 const environmentId = EnvironmentId.make("env-1");
201 const { client, emitShellSnapshot } = createTestClient();
202 const syncShellSnapshot = vi.fn();
203
204 const connection = createEnvironmentConnection({
205 kind: "saved",
206 knownEnvironment: {
207 id: "env-1",
208 label: "Remote env",
209 source: "manual",
210 target: {
211 httpBaseUrl: "http://example.test",
212 wsBaseUrl: "ws://example.test",
213 },
214 environmentId,
215 },
216 client,
217 applyShellEvent: vi.fn(),
218 syncShellSnapshot,
219 applyTerminalEvent: vi.fn(),
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});