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

service.threadSubscriptions.test.ts

462 lines15.0 KB

1import { QueryClient } from "@tanstack/react-query";
2import {
3 EnvironmentId,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 TurnId,
8 type OrchestrationShellSnapshot,
9} from "@t3tools/contracts";
10import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11​
12const mockSubscribeThread = vi.fn();
13const mockThreadUnsubscribe = vi.fn();
14const mockCreateEnvironmentConnection = vi.fn();
15const mockCreateWsRpcClient = vi.fn();
16const mockWaitForSavedEnvironmentRegistryHydration = vi.fn();
17const mockListSavedEnvironmentRecords = vi.fn();
18const mockGetSavedEnvironmentRecord = vi.fn();
19const mockReadSavedEnvironmentBearerToken = vi.fn();
20const mockSavedEnvironmentRegistrySubscribe = vi.fn();
21const mockGetPrimaryKnownEnvironment = vi.hoisted(() => vi.fn());
22const mockFetchRemoteSessionState = vi.fn();
23const mockConnectionReconnects: Array<ReturnType<typeof vi.fn>> = [];
24let savedEnvironmentRegistryListener: (() => void) | null = null;
25​
26function MockWsTransport() {
27 return undefined;
29​
30vi.mock("../primary", () => ({
31 getPrimaryKnownEnvironment: mockGetPrimaryKnownEnvironment,
32}));
33​
34vi.mock("../remote/api", () => ({
35 bootstrapRemoteBearerSession: vi.fn(),
36 fetchRemoteEnvironmentDescriptor: vi.fn(),
37 fetchRemoteSessionState: mockFetchRemoteSessionState,
38 isRemoteEnvironmentAuthHttpError: vi.fn(() => false),
39 resolveRemoteWebSocketConnectionUrl: vi.fn(async () => "ws://remote.example.test/ws"),
40}));
41​
42vi.mock("./catalog", () => ({
43 getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
44 hasSavedEnvironmentRegistryHydrated: vi.fn(() => true),
45 listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
46 persistSavedEnvironmentRecord: vi.fn(),
47 readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
48 removeSavedEnvironmentBearerToken: vi.fn(),
49 useSavedEnvironmentRegistryStore: {
50 subscribe: mockSavedEnvironmentRegistrySubscribe,
51 getState: () => ({
52 upsert: vi.fn(),
53 remove: vi.fn(),
54 markConnected: vi.fn(),
55 rename: vi.fn(),
56 }),
57 },
58 useSavedEnvironmentRuntimeStore: {
59 getState: () => ({
60 ensure: vi.fn(),
61 patch: vi.fn(),
62 clear: vi.fn(),
63 }),
64 },
65 waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration,
66 writeSavedEnvironmentBearerToken: vi.fn(),
67}));
68​
69vi.mock("./connection", () => ({
70 createEnvironmentConnection: mockCreateEnvironmentConnection,
71}));
72​
73vi.mock("../../rpc/wsRpcClient", () => ({
74 createWsRpcClient: mockCreateWsRpcClient,
75}));
76​
77vi.mock("../../rpc/wsTransport", () => ({
78 WsTransport: MockWsTransport,
79}));
80​
81function makeThreadShellSnapshot(params: {
82 readonly threadId: ThreadId;
83 readonly sessionStatus?:
84 | "idle"
85 | "starting"
86 | "running"
87 | "ready"
88 | "interrupted"
89 | "stopped"
90 | "error";
91 readonly hasPendingApprovals?: boolean;
92 readonly hasPendingUserInput?: boolean;
93 readonly hasActionableProposedPlan?: boolean;
94}): OrchestrationShellSnapshot {
95 const projectId = ProjectId.make("project-1");
96 const turnId = TurnId.make("turn-1");
97​
98 return {
99 snapshotSequence: 1,
100 projects: [],
101 updatedAt: "2026-04-13T00:00:00.000Z",
102 threads: [
103 {
104 id: params.threadId,
105 projectId,
106 title: "Thread",
107 modelSelection: {
108 instanceId: ProviderInstanceId.make("codex"),
109 model: "gpt-5-codex",
110 },
111 runtimeMode: "full-access",
112 interactionMode: "default",
113 branch: null,
114 worktreePath: null,
115 latestTurn:
116 params.sessionStatus === "running"
117 ? {
118 turnId,
119 state: "running",
120 requestedAt: "2026-04-13T00:00:00.000Z",
121 startedAt: "2026-04-13T00:00:01.000Z",
122 completedAt: null,
123 assistantMessageId: null,
124 }
125 : null,
126 createdAt: "2026-04-13T00:00:00.000Z",
127 updatedAt: "2026-04-13T00:00:00.000Z",
128 archivedAt: null,
129 session: params.sessionStatus
130 ? {
131 threadId: params.threadId,
132 status: params.sessionStatus,
133 providerName: "codex",
134 runtimeMode: "full-access",
135 activeTurnId: params.sessionStatus === "running" ? turnId : null,
136 lastError: null,
137 updatedAt: "2026-04-13T00:00:00.000Z",
138 }
139 : null,
140 latestUserMessageAt: null,
141 hasPendingApprovals: params.hasPendingApprovals ?? false,
142 hasPendingUserInput: params.hasPendingUserInput ?? false,
143 hasActionableProposedPlan: params.hasActionableProposedPlan ?? false,
144 },
145 ],
146 };
148​
149describe("retainThreadDetailSubscription", () => {
150 beforeEach(() => {
151 vi.useFakeTimers();
152 vi.resetModules();
153 vi.clearAllMocks();
154 mockGetPrimaryKnownEnvironment.mockReturnValue({
155 id: "env-1",
156 label: "Primary environment",
157 source: "window-origin",
158 target: {
159 httpBaseUrl: "http://127.0.0.1:3000/",
160 wsBaseUrl: "ws://127.0.0.1:3000/",
161 },
162 environmentId: EnvironmentId.make("env-1"),
163 });
164​
165 mockThreadUnsubscribe.mockImplementation(() => undefined);
166 mockSubscribeThread.mockImplementation(() => mockThreadUnsubscribe);
167 mockCreateWsRpcClient.mockReturnValue({
168 server: {
169 getConfig: vi.fn(async () => ({
170 environment: {
171 environmentId: EnvironmentId.make("env-remote"),
172 label: "Remote env",
173 platform: { os: "darwin", arch: "arm64" },
174 serverVersion: "0.0.0-test",
175 capabilities: { repositoryIdentity: true },
176 },
177 })),
178 },
179 orchestration: {
180 subscribeThread: mockSubscribeThread,
181 },
182 });
183 mockCreateEnvironmentConnection.mockImplementation((input) => {
184 const reconnect = vi.fn(async () => undefined);
185 mockConnectionReconnects.push(reconnect);
186 return {
187 kind: input.kind,
188 environmentId: input.knownEnvironment.environmentId,
189 knownEnvironment: input.knownEnvironment,
190 client: input.client,
191 ensureBootstrapped: vi.fn(async () => undefined),
192 reconnect,
193 dispose: vi.fn(async () => undefined),
194 };
195 });
196 savedEnvironmentRegistryListener = null;
197 mockSavedEnvironmentRegistrySubscribe.mockImplementation((listener: () => void) => {
198 savedEnvironmentRegistryListener = listener;
199 return () => {
200 if (savedEnvironmentRegistryListener === listener) {
201 savedEnvironmentRegistryListener = null;
202 }
203 };
204 });
205 mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined);
206 mockListSavedEnvironmentRecords.mockReturnValue([]);
207 mockGetSavedEnvironmentRecord.mockReturnValue(null);
208 mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
209 mockFetchRemoteSessionState.mockResolvedValue({
210 authenticated: true,
211 role: "client",
212 });
213 mockConnectionReconnects.length = 0;
214 });
215​
216 afterEach(async () => {
217 const { resetEnvironmentServiceForTests } = await import("./service");
218 await resetEnvironmentServiceForTests();
219 vi.unstubAllGlobals();
220 vi.useRealTimers();
221 });
222​
223 it("keeps thread detail subscriptions warm across releases until idle eviction", async () => {
224 const {
225 retainThreadDetailSubscription,
226 startEnvironmentConnectionService,
227 resetEnvironmentServiceForTests,
228 } = await import("./service");
229​
230 const stop = startEnvironmentConnectionService(new QueryClient());
231 const environmentId = EnvironmentId.make("env-1");
232 const threadId = ThreadId.make("thread-1");
233​
234 const releaseFirst = retainThreadDetailSubscription(environmentId, threadId);
235 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
236​
237 releaseFirst();
238 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
239​
240 const releaseSecond = retainThreadDetailSubscription(environmentId, threadId);
241 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
242​
243 releaseSecond();
244 await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
245 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
246​
247 await vi.advanceTimersByTimeAsync(28 * 60 * 1000);
248 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
249​
250 stop();
251 await resetEnvironmentServiceForTests();
252 });
253​
254 it("does not start the primary connection until the known environment has an id", async () => {
255 mockGetPrimaryKnownEnvironment.mockReturnValue({
256 id: "env-1",
257 label: "Primary environment",
258 source: "window-origin",
259 target: {
260 httpBaseUrl: "http://127.0.0.1:3000/",
261 wsBaseUrl: "ws://127.0.0.1:3000/",
262 },
263 });
264 const {
265 listEnvironmentConnections,
266 resetEnvironmentServiceForTests,
267 startEnvironmentConnectionService,
268 } = await import("./service");
269​
270 const stop = startEnvironmentConnectionService(new QueryClient());
271​
272 expect(mockCreateEnvironmentConnection).not.toHaveBeenCalled();
273 expect(listEnvironmentConnections()).toEqual([]);
274​
275 stop();
276 await resetEnvironmentServiceForTests();
277 });
278​
279 it("keeps non-idle thread detail subscriptions attached until the thread becomes idle", async () => {
280 const {
281 retainThreadDetailSubscription,
282 startEnvironmentConnectionService,
283 resetEnvironmentServiceForTests,
284 } = await import("./service");
285​
286 const stop = startEnvironmentConnectionService(new QueryClient());
287 const environmentId = EnvironmentId.make("env-1");
288 const threadId = ThreadId.make("thread-active");
289​
290 const connectionInput = mockCreateEnvironmentConnection.mock.calls[0]?.[0];
291 expect(connectionInput).toBeDefined();
292​
293 connectionInput.syncShellSnapshot(
294 makeThreadShellSnapshot({
295 threadId,
296 sessionStatus: "ready",
297 hasPendingApprovals: true,
298 }),
299 environmentId,
300 );
301​
302 const release = retainThreadDetailSubscription(environmentId, threadId);
303 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
304​
305 release();
306 await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
307 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
308​
309 connectionInput.applyShellEvent(
310 {
311 kind: "thread-upserted",
312 sequence: 2,
313 thread: makeThreadShellSnapshot({
314 threadId,
315 sessionStatus: "idle",
316 }).threads[0]!,
317 },
318 environmentId,
319 );
320​
321 await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
322 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
323​
324 stop();
325 await resetEnvironmentServiceForTests();
326 });
327​
328 it("reattaches retained thread detail subscriptions after a saved environment reconnect replaces the client", async () => {
329 const environmentId = EnvironmentId.make("env-remote");
330 const threadId = ThreadId.make("thread-reconnect");
331 const record = {
332 environmentId,
333 label: "Remote env",
334 httpBaseUrl: "http://remote.example.test",
335 wsBaseUrl: "ws://remote.example.test",
336 createdAt: "2026-05-01T00:00:00.000Z",
337 lastConnectedAt: "2026-05-01T00:00:00.000Z",
338 };
339 mockListSavedEnvironmentRecords.mockReturnValue([record]);
340 mockGetSavedEnvironmentRecord.mockReturnValue(record);
341 mockReadSavedEnvironmentBearerToken.mockResolvedValue("bearer-token");
342​
343 const {
344 disconnectSavedEnvironment,
345 listEnvironmentConnections,
346 reconnectSavedEnvironment,
347 retainThreadDetailSubscription,
348 startEnvironmentConnectionService,
349 resetEnvironmentServiceForTests,
350 } = await import("./service");
351​
352 const stop = startEnvironmentConnectionService(new QueryClient());
353 savedEnvironmentRegistryListener?.();
354 await vi.waitFor(() => {
355 expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(2);
356 expect(
357 listEnvironmentConnections().some(
358 (connection) => connection.environmentId === environmentId,
359 ),
360 ).toBe(true);
361 });
362​
363 const release = retainThreadDetailSubscription(environmentId, threadId);
364 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
365​
366 await disconnectSavedEnvironment(environmentId);
367 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
368 expect(
369 listEnvironmentConnections().some((connection) => connection.environmentId === environmentId),
370 ).toBe(false);
371​
372 const reconnectPromise = reconnectSavedEnvironment(environmentId);
373 await vi.advanceTimersByTimeAsync(200);
374 await reconnectPromise;
375 await vi.waitFor(() => {
376 expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(3);
377 expect(mockSubscribeThread).toHaveBeenCalledTimes(2);
378 });
379​
380 release();
381 stop();
382 await resetEnvironmentServiceForTests();
383 });
384​
385 it("reconnects environment streams when the browser resumes from the background", async () => {
386 let visibilityState: DocumentVisibilityState = "visible";
387 const documentTarget = new EventTarget();
388 const windowTarget = new EventTarget();
389 vi.stubGlobal("document", {
390 addEventListener: documentTarget.addEventListener.bind(documentTarget),
391 removeEventListener: documentTarget.removeEventListener.bind(documentTarget),
392 get visibilityState() {
393 return visibilityState;
394 },
395 });
396 vi.stubGlobal("window", {
397 addEventListener: windowTarget.addEventListener.bind(windowTarget),
398 removeEventListener: windowTarget.removeEventListener.bind(windowTarget),
399 });
400​
401 const { resetEnvironmentServiceForTests, startEnvironmentConnectionService } =
402 await import("./service");
403​
404 const stop = startEnvironmentConnectionService(new QueryClient());
405 expect(mockConnectionReconnects).toHaveLength(1);
406​
407 visibilityState = "hidden";
408 documentTarget.dispatchEvent(new Event("visibilitychange"));
409 expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
410​
411 visibilityState = "visible";
412 documentTarget.dispatchEvent(new Event("visibilitychange"));
413 expect(mockConnectionReconnects[0]).toHaveBeenCalledTimes(1);
414​
415 stop();
416 await resetEnvironmentServiceForTests();
417 });
418​
419 it("allows a larger idle cache before capacity eviction starts", async () => {
420 const {
421 retainThreadDetailSubscription,
422 startEnvironmentConnectionService,
423 resetEnvironmentServiceForTests,
424 } = await import("./service");
425​
426 const stop = startEnvironmentConnectionService(new QueryClient());
427 const environmentId = EnvironmentId.make("env-1");
428​
429 for (let index = 0; index < 12; index += 1) {
430 const release = retainThreadDetailSubscription(
431 environmentId,
432 ThreadId.make(`thread-${index + 1}`),
433 );
434 release();
435 }
436​
437 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
438​
439 stop();
440 await resetEnvironmentServiceForTests();
441 });
442​
443 it("disposes cached thread detail subscriptions when the environment service resets", async () => {
444 const {
445 retainThreadDetailSubscription,
446 startEnvironmentConnectionService,
447 resetEnvironmentServiceForTests,
448 } = await import("./service");
449​
450 const stop = startEnvironmentConnectionService(new QueryClient());
451 const environmentId = EnvironmentId.make("env-1");
452 const threadId = ThreadId.make("thread-2");
453​
454 const release = retainThreadDetailSubscription(environmentId, threadId);
455 release();
456​
457 await resetEnvironmentServiceForTests();
458 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
459​
460 stop();
461 });
462});