Open History to see the last commit
1import { QueryClient } from "@tanstack/react-query";
2import type { WsRpcClient } from "@t3tools/client-runtime";
3import {
4 EnvironmentId,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 TurnId,
9 type OrchestrationShellSnapshot,
10} from "@t3tools/contracts";
11import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
12
13const mockSubscribeThread = vi.fn();
14const mockThreadUnsubscribe = vi.fn();
15const mockCreateEnvironmentConnection = vi.fn();
16const mockCreateWsRpcClient = vi.fn();
17const mockWaitForSavedEnvironmentRegistryHydration = vi.fn();
18const mockListSavedEnvironmentRecords = vi.fn();
19const mockGetSavedEnvironmentRecord = vi.fn();
20const mockReadSavedEnvironmentBearerToken = vi.fn();
21const mockSavedEnvironmentRegistrySubscribe = vi.fn();
22const mockGetPrimaryKnownEnvironment = vi.hoisted(() => vi.fn());
23const mockFetchRemoteSessionState = vi.fn();
24const mockResolveRemoteWebSocketConnectionUrl = vi.fn(async () => "ws://remote.example.test/ws");
25const mockRemoteHttpRunPromise = vi.fn((effect: Promise<unknown>) => effect);
26const mockConnectionReconnects: Array<ReturnType<typeof vi.fn>> = [];
27let savedEnvironmentRegistryListener: (() => void) | null = null;
28
29function MockWsTransport() {
30 return undefined;
31}
32
33vi.mock("../primary", () => ({
34 getPrimaryKnownEnvironment: mockGetPrimaryKnownEnvironment,
35}));
36
37vi.mock("../../lib/runtime", () => ({
38 remoteHttpRuntime: {
39 runPromise: mockRemoteHttpRunPromise,
40 },
41}));
42
43vi.mock("./catalog", () => ({
44 getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
45 hasSavedEnvironmentRegistryHydrated: vi.fn(() => true),
46 listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
47 persistSavedEnvironmentRecord: vi.fn(),
48 readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
49 removeSavedEnvironmentBearerToken: vi.fn(),
50 useSavedEnvironmentRegistryStore: {
51 subscribe: mockSavedEnvironmentRegistrySubscribe,
52 getState: () => ({
53 upsert: vi.fn(),
54 remove: vi.fn(),
55 markConnected: vi.fn(),
56 rename: vi.fn(),
57 }),
58 },
59 useSavedEnvironmentRuntimeStore: {
60 getState: () => ({
61 ensure: vi.fn(),
62 patch: vi.fn(),
63 clear: vi.fn(),
64 }),
65 },
66 waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration,
67 writeSavedEnvironmentBearerToken: vi.fn(),
68}));
69
70vi.mock("./connection", async (importOriginal) => ({
71 ...(await importOriginal<typeof import("./connection")>()),
72 createEnvironmentConnection: mockCreateEnvironmentConnection,
73}));
74
75vi.mock("@t3tools/client-runtime", async (importOriginal) => {
76 const actual = await importOriginal<typeof import("@t3tools/client-runtime")>();
77 const stubWsClient: WsRpcClient = {
78 dispose: async () => undefined,
79 reconnect: async () => undefined,
80 isHeartbeatFresh: () => false,
81 orchestration: {
82 dispatchCommand: vi.fn(),
83 getTurnDiff: vi.fn(),
84 getFullThreadDiff: vi.fn(),
85 getArchivedShellSnapshot: vi.fn(),
86 subscribeShell: vi.fn(() => () => undefined),
87 subscribeThread: mockSubscribeThread,
88 },
89 terminal: {
90 open: vi.fn(),
91 attach: vi.fn(() => () => undefined),
92 write: vi.fn(),
93 resize: vi.fn(),
94 clear: vi.fn(),
95 restart: vi.fn(),
96 close: vi.fn(),
97 onEvent: vi.fn(() => () => undefined),
98 onMetadata: vi.fn(() => () => undefined),
99 },
100 projects: {
101 searchEntries: vi.fn(),
102 writeFile: vi.fn(),
103 },
104 filesystem: {
105 browse: vi.fn(),
106 },
107 sourceControl: {
108 lookupRepository: vi.fn(),
109 cloneRepository: vi.fn(),
110 publishRepository: vi.fn(),
111 },
112 shell: {
113 openInEditor: vi.fn(),
114 },
115 vcs: {
116 pull: vi.fn(),
117 refreshStatus: vi.fn(),
118 onStatus: vi.fn(() => () => undefined),
119 listRefs: vi.fn(),
120 createWorktree: vi.fn(),
121 removeWorktree: vi.fn(),
122 createRef: vi.fn(),
123 switchRef: vi.fn(),
124 init: vi.fn(),
125 },
126 git: {
127 runStackedAction: vi.fn(),
128 resolvePullRequest: vi.fn(),
129 preparePullRequestThread: vi.fn(),
130 },
131 review: {
132 getDiffPreview: vi.fn(),
133 },
134 server: {
135 getConfig: vi.fn(),
136 refreshProviders: vi.fn(),
137 discoverSourceControl: vi.fn(),
138 updateProvider: vi.fn(),
139 upsertKeybinding: vi.fn(),
140 removeKeybinding: vi.fn(),
141 getSettings: vi.fn(),
142 updateSettings: vi.fn(),
143 subscribeConfig: vi.fn(() => () => undefined),
144 subscribeLifecycle: vi.fn(() => () => undefined),
145 subscribeAuthAccess: vi.fn(() => () => undefined),
146 getTraceDiagnostics: vi.fn(),
147 getProcessDiagnostics: vi.fn(),
148 getProcessResourceHistory: vi.fn(),
149 signalProcess: vi.fn(),
150 },
151 };
152 return {
153 ...actual,
154 createWsRpcClient: vi.fn(() => stubWsClient),
155 fetchRemoteSessionState: mockFetchRemoteSessionState,
156 resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl,
157 };
158});
159
160vi.mock("../../rpc/wsTransport", () => ({
161 WsTransport: MockWsTransport,
162}));
163
164function makeThreadShellSnapshot(params: {
165 readonly threadId: ThreadId;
166 readonly sessionStatus?:
167 | "idle"
168 | "starting"
169 | "running"
170 | "ready"
171 | "interrupted"
172 | "stopped"
173 | "error";
174 readonly hasPendingApprovals?: boolean;
175 readonly hasPendingUserInput?: boolean;
176 readonly hasActionableProposedPlan?: boolean;
177}): OrchestrationShellSnapshot {
178 const projectId = ProjectId.make("project-1");
179 const turnId = TurnId.make("turn-1");
180
181 return {
182 snapshotSequence: 1,
183 projects: [],
184 updatedAt: "2026-04-13T00:00:00.000Z",
185 threads: [
186 {
187 id: params.threadId,
188 projectId,
189 title: "Thread",
190 modelSelection: {
191 instanceId: ProviderInstanceId.make("codex"),
192 model: "gpt-5-codex",
193 },
194 runtimeMode: "full-access",
195 interactionMode: "default",
196 branch: null,
197 worktreePath: null,
198 latestTurn:
199 params.sessionStatus === "running"
200 ? {
201 turnId,
202 state: "running",
203 requestedAt: "2026-04-13T00:00:00.000Z",
204 startedAt: "2026-04-13T00:00:01.000Z",
205 completedAt: null,
206 assistantMessageId: null,
207 }
208 : null,
209 createdAt: "2026-04-13T00:00:00.000Z",
210 updatedAt: "2026-04-13T00:00:00.000Z",
211 archivedAt: null,
212 session: params.sessionStatus
213 ? {
214 threadId: params.threadId,
215 status: params.sessionStatus,
216 providerName: "codex",
217 runtimeMode: "full-access",
218 activeTurnId: params.sessionStatus === "running" ? turnId : null,
219 lastError: null,
220 updatedAt: "2026-04-13T00:00:00.000Z",
221 }
222 : null,
223 latestUserMessageAt: null,
224 hasPendingApprovals: params.hasPendingApprovals ?? false,
225 hasPendingUserInput: params.hasPendingUserInput ?? false,
226 hasActionableProposedPlan: params.hasActionableProposedPlan ?? false,
227 },
228 ],
229 };
230}
231
232describe("retainThreadDetailSubscription", () => {
233 beforeEach(() => {
234 vi.useFakeTimers();
235 vi.resetModules();
236 vi.clearAllMocks();
237 mockGetPrimaryKnownEnvironment.mockReturnValue({
238 id: "env-1",
239 label: "Primary environment",
240 source: "window-origin",
241 target: {
242 httpBaseUrl: "http://127.0.0.1:3000/",
243 wsBaseUrl: "ws://127.0.0.1:3000/",
244 },
245 environmentId: EnvironmentId.make("env-1"),
246 });
247
248 mockThreadUnsubscribe.mockImplementation(() => undefined);
249 mockSubscribeThread.mockImplementation(() => mockThreadUnsubscribe);
250 mockCreateWsRpcClient.mockReturnValue({
251 server: {
252 getConfig: vi.fn(async () => ({
253 environment: {
254 environmentId: EnvironmentId.make("env-remote"),
255 label: "Remote env",
256 platform: { os: "darwin", arch: "arm64" },
257 serverVersion: "0.0.0-test",
258 capabilities: { repositoryIdentity: true },
259 },
260 })),
261 },
262 isHeartbeatFresh: vi.fn(() => true),
263 orchestration: {
264 subscribeThread: mockSubscribeThread,
265 },
266 });
267 mockCreateEnvironmentConnection.mockImplementation((input) => {
268 const reconnect = vi.fn(async () => undefined);
269 mockConnectionReconnects.push(reconnect);
270 queueMicrotask(() => {
271 input.onConfigSnapshot?.({
272 environment: {
273 environmentId: input.knownEnvironment.environmentId,
274 label: input.knownEnvironment.label,
275 platform: { os: "darwin", arch: "arm64" },
276 serverVersion: "0.0.0-test",
277 capabilities: { repositoryIdentity: true },
278 },
279 });
280 });
281 return {
282 kind: input.kind,
283 environmentId: input.knownEnvironment.environmentId,
284 knownEnvironment: input.knownEnvironment,
285 client: input.client,
286 ensureBootstrapped: vi.fn(async () => undefined),
287 reconnect,
288 dispose: vi.fn(async () => undefined),
289 };
290 });
291 savedEnvironmentRegistryListener = null;
292 mockSavedEnvironmentRegistrySubscribe.mockImplementation((listener: () => void) => {
293 savedEnvironmentRegistryListener = listener;
294 return () => {
295 if (savedEnvironmentRegistryListener === listener) {
296 savedEnvironmentRegistryListener = null;
297 }
298 };
299 });
300 mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined);
301 mockListSavedEnvironmentRecords.mockReturnValue([]);
302 mockGetSavedEnvironmentRecord.mockReturnValue(null);
303 mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
304 mockFetchRemoteSessionState.mockResolvedValue({
305 authenticated: true,
306 scopes: ["orchestration:read"],
307 });
308 mockConnectionReconnects.length = 0;
309 });
310
311 afterEach(async () => {
312 const { resetEnvironmentServiceForTests } = await import("./service");
313 await resetEnvironmentServiceForTests();
314 vi.unstubAllGlobals();
315 vi.useRealTimers();
316 });
317
318 it("keeps thread detail subscriptions warm across releases until idle eviction", async () => {
319 const {
320 retainThreadDetailSubscription,
321 startEnvironmentConnectionService,
322 resetEnvironmentServiceForTests,
323 } = await import("./service");
324
325 const stop = startEnvironmentConnectionService(new QueryClient());
326 const environmentId = EnvironmentId.make("env-1");
327 const threadId = ThreadId.make("thread-1");
328
329 const releaseFirst = retainThreadDetailSubscription(environmentId, threadId);
330 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
331
332 releaseFirst();
333 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
334
335 const releaseSecond = retainThreadDetailSubscription(environmentId, threadId);
336 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
337
338 releaseSecond();
339 await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
340 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
341
342 await vi.advanceTimersByTimeAsync(28 * 60 * 1000);
343 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
344
345 stop();
346 await resetEnvironmentServiceForTests();
347 });
348
349 it("does not start the primary connection until the known environment has an id", async () => {
350 mockGetPrimaryKnownEnvironment.mockReturnValue({
351 id: "env-1",
352 label: "Primary environment",
353 source: "window-origin",
354 target: {
355 httpBaseUrl: "http://127.0.0.1:3000/",
356 wsBaseUrl: "ws://127.0.0.1:3000/",
357 },
358 });
359 const {
360 listEnvironmentConnections,
361 resetEnvironmentServiceForTests,
362 startEnvironmentConnectionService,
363 } = await import("./service");
364
365 const stop = startEnvironmentConnectionService(new QueryClient());
366
367 expect(mockCreateEnvironmentConnection).not.toHaveBeenCalled();
368 expect(listEnvironmentConnections()).toEqual([]);
369
370 stop();
371 await resetEnvironmentServiceForTests();
372 });
373
374 it("keeps non-idle thread detail subscriptions attached until the thread becomes idle", async () => {
375 const {
376 retainThreadDetailSubscription,
377 startEnvironmentConnectionService,
378 resetEnvironmentServiceForTests,
379 } = await import("./service");
380
381 const stop = startEnvironmentConnectionService(new QueryClient());
382 const environmentId = EnvironmentId.make("env-1");
383 const threadId = ThreadId.make("thread-active");
384
385 const connectionInput = mockCreateEnvironmentConnection.mock.calls[0]?.[0];
386 expect(connectionInput).toBeDefined();
387
388 connectionInput.syncShellSnapshot(
389 makeThreadShellSnapshot({
390 threadId,
391 sessionStatus: "ready",
392 hasPendingApprovals: true,
393 }),
394 environmentId,
395 );
396
397 const release = retainThreadDetailSubscription(environmentId, threadId);
398 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
399
400 release();
401 await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
402 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
403
404 connectionInput.applyShellEvent(
405 {
406 kind: "thread-upserted",
407 sequence: 2,
408 thread: makeThreadShellSnapshot({
409 threadId,
410 sessionStatus: "idle",
411 }).threads[0]!,
412 },
413 environmentId,
414 );
415
416 await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
417 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
418
419 stop();
420 await resetEnvironmentServiceForTests();
421 });
422
423 it("reattaches retained thread detail subscriptions after a saved environment reconnect replaces the client", async () => {
424 const environmentId = EnvironmentId.make("env-remote");
425 const threadId = ThreadId.make("thread-reconnect");
426 const record = {
427 environmentId,
428 label: "Remote env",
429 httpBaseUrl: "http://remote.example.test",
430 wsBaseUrl: "ws://remote.example.test",
431 createdAt: "2026-05-01T00:00:00.000Z",
432 lastConnectedAt: "2026-05-01T00:00:00.000Z",
433 };
434 mockListSavedEnvironmentRecords.mockReturnValue([record]);
435 mockGetSavedEnvironmentRecord.mockReturnValue(record);
436 mockReadSavedEnvironmentBearerToken.mockResolvedValue("bearer-token");
437
438 const {
439 disconnectSavedEnvironment,
440 listEnvironmentConnections,
441 reconnectSavedEnvironment,
442 retainThreadDetailSubscription,
443 startEnvironmentConnectionService,
444 resetEnvironmentServiceForTests,
445 } = await import("./service");
446
447 const stop = startEnvironmentConnectionService(new QueryClient());
448 savedEnvironmentRegistryListener?.();
449 await vi.waitFor(() => {
450 expect(
451 listEnvironmentConnections().some(
452 (connection) => connection.environmentId === environmentId,
453 ),
454 ).toBe(true);
455 });
456 const createConnectionCallsBeforeReconnect = mockCreateEnvironmentConnection.mock.calls.length;
457
458 const release = retainThreadDetailSubscription(environmentId, threadId);
459 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
460
461 await disconnectSavedEnvironment(environmentId);
462 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
463 expect(
464 listEnvironmentConnections().some((connection) => connection.environmentId === environmentId),
465 ).toBe(false);
466
467 const reconnectPromise = reconnectSavedEnvironment(environmentId);
468 await vi.advanceTimersByTimeAsync(200);
469 await reconnectPromise;
470 await vi.waitFor(() => {
471 expect(mockCreateEnvironmentConnection).toHaveBeenCalledTimes(
472 createConnectionCallsBeforeReconnect + 1,
473 );
474 expect(mockSubscribeThread).toHaveBeenCalledTimes(2);
475 });
476
477 release();
478 stop();
479 await resetEnvironmentServiceForTests();
480 });
481
482 it("keeps healthy environment streams connected when the browser resumes from the background", async () => {
483 let visibilityState: DocumentVisibilityState = "visible";
484 const documentTarget = new EventTarget();
485 const windowTarget = new EventTarget();
486 vi.stubGlobal("document", {
487 addEventListener: documentTarget.addEventListener.bind(documentTarget),
488 removeEventListener: documentTarget.removeEventListener.bind(documentTarget),
489 get visibilityState() {
490 return visibilityState;
491 },
492 });
493 vi.stubGlobal("window", {
494 addEventListener: windowTarget.addEventListener.bind(windowTarget),
495 removeEventListener: windowTarget.removeEventListener.bind(windowTarget),
496 });
497
498 const { resetEnvironmentServiceForTests, startEnvironmentConnectionService } =
499 await import("./service");
500 mockCreateEnvironmentConnection.mockImplementation((input) => {
501 const reconnect = vi.fn(async () => undefined);
502 mockConnectionReconnects.push(reconnect);
503 queueMicrotask(() => {
504 input.onConfigSnapshot?.({
505 environment: {
506 environmentId: input.knownEnvironment.environmentId,
507 label: input.knownEnvironment.label,
508 platform: { os: "darwin", arch: "arm64" },
509 serverVersion: "0.0.0-test",
510 capabilities: { repositoryIdentity: true },
511 },
512 });
513 });
514 return {
515 kind: input.kind,
516 environmentId: input.knownEnvironment.environmentId,
517 knownEnvironment: input.knownEnvironment,
518 client: {
519 ...input.client,
520 isHeartbeatFresh: vi.fn(() => true),
521 },
522 ensureBootstrapped: vi.fn(async () => undefined),
523 reconnect,
524 dispose: vi.fn(async () => undefined),
525 };
526 });
527
528 const stop = startEnvironmentConnectionService(new QueryClient());
529 expect(mockConnectionReconnects).toHaveLength(1);
530
531 visibilityState = "hidden";
532 documentTarget.dispatchEvent(new Event("visibilitychange"));
533 expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
534
535 visibilityState = "visible";
536 documentTarget.dispatchEvent(new Event("visibilitychange"));
537 expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
538
539 stop();
540 await resetEnvironmentServiceForTests();
541 });
542
543 it("reconnects stale environment streams when the browser resumes from the background", async () => {
544 let visibilityState: DocumentVisibilityState = "visible";
545 const documentTarget = new EventTarget();
546 const windowTarget = new EventTarget();
547 vi.stubGlobal("document", {
548 addEventListener: documentTarget.addEventListener.bind(documentTarget),
549 removeEventListener: documentTarget.removeEventListener.bind(documentTarget),
550 get visibilityState() {
551 return visibilityState;
552 },
553 });
554 vi.stubGlobal("window", {
555 addEventListener: windowTarget.addEventListener.bind(windowTarget),
556 removeEventListener: windowTarget.removeEventListener.bind(windowTarget),
557 });
558 mockCreateWsRpcClient.mockReturnValue({
559 server: {
560 getConfig: vi.fn(async () => ({
561 environment: {
562 environmentId: EnvironmentId.make("env-remote"),
563 label: "Remote env",
564 platform: { os: "darwin", arch: "arm64" },
565 serverVersion: "0.0.0-test",
566 capabilities: { repositoryIdentity: true },
567 },
568 })),
569 },
570 isHeartbeatFresh: vi.fn(() => false),
571 orchestration: {
572 subscribeThread: mockSubscribeThread,
573 },
574 });
575
576 const { resetEnvironmentServiceForTests, startEnvironmentConnectionService } =
577 await import("./service");
578
579 const stop = startEnvironmentConnectionService(new QueryClient());
580 expect(mockConnectionReconnects).toHaveLength(1);
581
582 visibilityState = "hidden";
583 documentTarget.dispatchEvent(new Event("visibilitychange"));
584 expect(mockConnectionReconnects[0]).not.toHaveBeenCalled();
585
586 visibilityState = "visible";
587 documentTarget.dispatchEvent(new Event("visibilitychange"));
588 expect(mockConnectionReconnects[0]).toHaveBeenCalledTimes(1);
589
590 stop();
591 await resetEnvironmentServiceForTests();
592 });
593
594 it("allows a larger idle cache before capacity eviction starts", async () => {
595 const {
596 retainThreadDetailSubscription,
597 startEnvironmentConnectionService,
598 resetEnvironmentServiceForTests,
599 } = await import("./service");
600
601 const stop = startEnvironmentConnectionService(new QueryClient());
602 const environmentId = EnvironmentId.make("env-1");
603
604 for (let index = 0; index < 12; index += 1) {
605 const release = retainThreadDetailSubscription(
606 environmentId,
607 ThreadId.make(`thread-${index + 1}`),
608 );
609 release();
610 }
611
612 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
613
614 stop();
615 await resetEnvironmentServiceForTests();
616 });
617
618 it("disposes cached thread detail subscriptions when the environment service resets", async () => {
619 const {
620 retainThreadDetailSubscription,
621 startEnvironmentConnectionService,
622 resetEnvironmentServiceForTests,
623 } = await import("./service");
624
625 const stop = startEnvironmentConnectionService(new QueryClient());
626 const environmentId = EnvironmentId.make("env-1");
627 const threadId = ThreadId.make("thread-2");
628
629 const release = retainThreadDetailSubscription(environmentId, threadId);
630 release();
631
632 await resetEnvironmentServiceForTests();
633 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
634
635 stop();
636 });
637});