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