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

service.savedEnvironments.test.ts

326 lines9.9 KB

1import { QueryClient } from "@tanstack/react-query";
2import { EnvironmentId } from "@t3tools/contracts";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4​
5const mockCreateEnvironmentConnection = vi.fn();
6const mockCreateWsRpcClient = vi.fn();
7const mockFetchRemoteSessionState = vi.fn();
8const mockWaitForSavedEnvironmentRegistryHydration = vi.fn();
9const mockListSavedEnvironmentRecords = vi.fn();
10const mockSavedEnvironmentRegistrySubscribe = vi.fn();
11const mockReadSavedEnvironmentBearerToken = vi.fn();
12const mockGetSavedEnvironmentRecord = vi.fn();
13​
14function MockWsTransport() {
15 return undefined;
17​
18vi.mock("../primary", () => ({
19 getPrimaryKnownEnvironment: vi.fn(() => ({
20 id: "env-1",
21 label: "Primary environment",
22 source: "window-origin",
23 target: {
24 httpBaseUrl: "http://127.0.0.1:3000/",
25 wsBaseUrl: "ws://127.0.0.1:3000/",
26 },
27 environmentId: EnvironmentId.make("env-1"),
28 })),
29}));
30​
31vi.mock("../remote/api", () => ({
32 bootstrapRemoteBearerSession: vi.fn(),
33 fetchRemoteEnvironmentDescriptor: vi.fn(),
34 fetchRemoteSessionState: mockFetchRemoteSessionState,
35 resolveRemoteWebSocketConnectionUrl: vi.fn(() => "ws://remote.example.test"),
36}));
37​
38vi.mock("./catalog", () => ({
39 getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
40 hasSavedEnvironmentRegistryHydrated: vi.fn(() => true),
41 listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
42 persistSavedEnvironmentRecord: vi.fn(),
43 readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
44 removeSavedEnvironmentBearerToken: vi.fn(),
45 useSavedEnvironmentRegistryStore: {
46 subscribe: mockSavedEnvironmentRegistrySubscribe,
47 getState: () => ({
48 upsert: vi.fn(),
49 remove: vi.fn(),
50 markConnected: vi.fn(),
51 rename: vi.fn(),
52 }),
53 },
54 useSavedEnvironmentRuntimeStore: {
55 getState: () => ({
56 ensure: vi.fn(),
57 patch: vi.fn(),
58 clear: vi.fn(),
59 }),
60 },
61 waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration,
62 writeSavedEnvironmentBearerToken: vi.fn(),
63}));
64​
65vi.mock("./connection", () => ({
66 createEnvironmentConnection: mockCreateEnvironmentConnection,
67}));
68​
69vi.mock("../../rpc/wsRpcClient", () => ({
70 createWsRpcClient: mockCreateWsRpcClient,
71}));
72​
73vi.mock("../../rpc/wsTransport", () => ({
74 WsTransport: MockWsTransport,
75}));
76​
77vi.mock("~/composerDraftStore", () => ({
78 markPromotedDraftThreadByRef: vi.fn(),
79 markPromotedDraftThreadsByRef: vi.fn(),
80 useComposerDraftStore: {
81 getState: () => ({
82 getDraftThreadByRef: vi.fn(() => null),
83 clearDraftThread: vi.fn(),
84 }),
85 },
86}));
87​
88vi.mock("~/localApi", () => ({
89 ensureLocalApi: vi.fn(() => ({
90 persistence: {
91 setSavedEnvironmentRegistry: vi.fn(async () => undefined),
92 },
93 })),
94}));
95​
96vi.mock("~/lib/terminalStateCleanup", () => ({
97 collectActiveTerminalThreadIds: vi.fn(() => []),
98}));
99​
100vi.mock("~/orchestrationEventEffects", () => ({
101 deriveOrchestrationBatchEffects: vi.fn(() => ({
102 promotedThreadRefs: [],
103 invalidatedProviderState: false,
104 })),
105}));
106​
107vi.mock("~/lib/projectReactQuery", () => ({
108 projectQueryKeys: {
109 all: ["projects"],
110 },
111}));
112​
113vi.mock("~/lib/providerReactQuery", () => ({
114 providerQueryKeys: {
115 all: ["providers"],
116 },
117}));
118​
119vi.mock("~/store", () => ({
120 useStore: {
121 getState: () => ({
122 syncServerShellSnapshot: vi.fn(),
123 syncServerThreadDetail: vi.fn(),
124 removeServerThreadDetail: vi.fn(),
125 applyServerShellEvent: vi.fn(),
126 }),
127 },
128 selectProjectsAcrossEnvironments: vi.fn(() => []),
129 selectSidebarThreadSummaryByRef: vi.fn(() => null),
130 selectThreadByRef: vi.fn(() => null),
131 selectThreadsAcrossEnvironments: vi.fn(() => []),
132}));
133​
134vi.mock("~/terminalStateStore", () => ({
135 useTerminalStateStore: {
136 getState: () => ({
137 applyTerminalEvent: vi.fn(),
138 removeTerminalState: vi.fn(),
139 clearTerminalSelection: vi.fn(),
140 }),
141 },
142}));
143​
144vi.mock("~/uiStateStore", () => ({
145 useUiStateStore: {
146 getState: () => ({
147 clearThreadUi: vi.fn(),
148 syncPromotedDraftThreadRefs: vi.fn(),
149 }),
150 },
151}));
152​
153const savedRecord = {
154 environmentId: EnvironmentId.make("env-saved"),
155 label: "Remote environment",
156 httpBaseUrl: "https://remote.example.test/",
157 wsBaseUrl: "wss://remote.example.test/",
158};
159​
160const configSnapshot = {
161 environment: {
162 environmentId: savedRecord.environmentId,
163 label: "Remote environment",
164 },
165};
166​
167function createClient() {
168 return {
169 dispose: vi.fn(async () => undefined),
170 reconnect: vi.fn(async () => undefined),
171 server: {
172 getConfig: vi.fn(async () => configSnapshot),
173 subscribeConfig: vi.fn(() => () => undefined),
174 subscribeLifecycle: vi.fn(() => () => undefined),
175 subscribeAuthAccess: vi.fn(() => () => undefined),
176 refreshProviders: vi.fn(async () => undefined),
177 upsertKeybinding: vi.fn(async () => undefined),
178 getSettings: vi.fn(async () => undefined),
179 updateSettings: vi.fn(async () => undefined),
180 },
181 orchestration: {
182 subscribeShell: vi.fn(() => () => undefined),
183 subscribeThread: vi.fn(() => () => undefined),
184 dispatchCommand: vi.fn(async () => undefined),
185 getTurnDiff: vi.fn(async () => undefined),
186 getFullThreadDiff: vi.fn(async () => undefined),
187 },
188 terminal: {
189 open: vi.fn(async () => undefined),
190 write: vi.fn(async () => undefined),
191 resize: vi.fn(async () => undefined),
192 clear: vi.fn(async () => undefined),
193 restart: vi.fn(async () => undefined),
194 close: vi.fn(async () => undefined),
195 onEvent: vi.fn(() => () => undefined),
196 },
197 projects: {
198 searchEntries: vi.fn(async () => []),
199 writeFile: vi.fn(async () => undefined),
200 },
201 shell: {
202 openInEditor: vi.fn(async () => undefined),
203 },
204 git: {
205 pull: vi.fn(async () => undefined),
206 refreshStatus: vi.fn(async () => undefined),
207 onStatus: vi.fn(() => () => undefined),
208 runStackedAction: vi.fn(async () => ({})),
209 listBranches: vi.fn(async () => []),
210 createWorktree: vi.fn(async () => undefined),
211 removeWorktree: vi.fn(async () => undefined),
212 createBranch: vi.fn(async () => undefined),
213 checkout: vi.fn(async () => undefined),
214 init: vi.fn(async () => undefined),
215 resolvePullRequest: vi.fn(async () => undefined),
216 preparePullRequestThread: vi.fn(async () => undefined),
217 },
218 };
220​
221describe("saved environment startup", () => {
222 beforeEach(() => {
223 vi.useFakeTimers();
224 vi.resetModules();
225 vi.clearAllMocks();
226​
227 mockFetchRemoteSessionState.mockResolvedValue({
228 authenticated: true,
229 role: "owner",
230 });
231 mockGetSavedEnvironmentRecord.mockImplementation((environmentId: EnvironmentId) =>
232 environmentId === savedRecord.environmentId ? savedRecord : null,
233 );
234 mockListSavedEnvironmentRecords.mockReturnValue([savedRecord]);
235 mockSavedEnvironmentRegistrySubscribe.mockReturnValue(() => undefined);
236 mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined);
237 mockReadSavedEnvironmentBearerToken.mockResolvedValue("saved-bearer-token");
238 mockCreateWsRpcClient.mockImplementation(() => createClient());
239 mockCreateEnvironmentConnection.mockImplementation((input) => {
240 if (input.kind === "saved") {
241 queueMicrotask(() => {
242 input.onConfigSnapshot?.(configSnapshot);
243 });
244 }
245​
246 return {
247 kind: input.kind,
248 environmentId: input.knownEnvironment.environmentId,
249 knownEnvironment: input.knownEnvironment,
250 client: input.client,
251 ensureBootstrapped: vi.fn(async () => undefined),
252 reconnect: vi.fn(async () => undefined),
253 dispose: vi.fn(async () => undefined),
254 };
255 });
256 });
257​
258 afterEach(async () => {
259 const { resetEnvironmentServiceForTests } = await import("./service");
260 await resetEnvironmentServiceForTests();
261 vi.useRealTimers();
262 });
263​
264 it("uses the initial config snapshot instead of issuing an extra getConfig call", async () => {
265 const { startEnvironmentConnectionService, resetEnvironmentServiceForTests } =
266 await import("./service");
267​
268 const stop = startEnvironmentConnectionService(new QueryClient());
269 await vi.runAllTimersAsync();
270​
271 const savedConnectionCall = mockCreateEnvironmentConnection.mock.calls.find(
272 ([input]) => input.kind === "saved",
273 );
274 expect(savedConnectionCall).toBeDefined();
275​
276 const savedClient = savedConnectionCall?.[0]?.client;
277 expect(savedClient.server.getConfig).not.toHaveBeenCalled();
278 expect(mockFetchRemoteSessionState).toHaveBeenCalledTimes(1);
279​
280 stop();
281 await resetEnvironmentServiceForTests();
282 });
283​
284 it("coalesces hydration and registry sync so the initial saved connection only starts once", async () => {
285 let finishHydration!: () => void;
286 let finishTokenRead!: (token: string) => void;
287​
288 mockWaitForSavedEnvironmentRegistryHydration.mockImplementation(
289 () =>
290 new Promise<void>((resolve) => {
291 finishHydration = () => resolve();
292 }),
293 );
294 mockReadSavedEnvironmentBearerToken.mockImplementation(
295 () =>
296 new Promise<string>((resolve) => {
297 finishTokenRead = resolve;
298 }),
299 );
300​
301 const { startEnvironmentConnectionService, resetEnvironmentServiceForTests } =
302 await import("./service");
303​
304 const stop = startEnvironmentConnectionService(new QueryClient());
305 const registryListener = mockSavedEnvironmentRegistrySubscribe.mock.calls[0]?.[0];
306 expect(registryListener).toBeTypeOf("function");
307​
308 registryListener?.();
309 finishHydration();
310 await vi.waitFor(() => {
311 expect(mockReadSavedEnvironmentBearerToken).toHaveBeenCalledTimes(1);
312 });
313​
314 finishTokenRead("saved-bearer-token");
315 await vi.runAllTimersAsync();
316​
317 const savedConnectionCalls = mockCreateEnvironmentConnection.mock.calls.filter(
318 ([input]) => input.kind === "saved",
319 );
320 expect(savedConnectionCalls).toHaveLength(1);
321 expect(mockFetchRemoteSessionState).toHaveBeenCalledTimes(1);
322​
323 stop();
324 await resetEnvironmentServiceForTests();
325 });
326});