Open History to see the last commit
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 mockSavedEnvironmentRegistrySubscribe = vi.fn();
19
20function MockWsTransport() {
21 return undefined;
22}
23
24vi.mock("../primary", () => ({
25 getPrimaryKnownEnvironment: vi.fn(() => ({
26 id: "env-1",
27 label: "Primary environment",
28 source: "window-origin",
29 target: {
30 httpBaseUrl: "http://127.0.0.1:3000/",
31 wsBaseUrl: "ws://127.0.0.1:3000/",
32 },
33 environmentId: EnvironmentId.make("env-1"),
34 })),
35}));
36
37vi.mock("./catalog", () => ({
38 getSavedEnvironmentRecord: vi.fn(),
39 hasSavedEnvironmentRegistryHydrated: vi.fn(() => true),
40 listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
41 persistSavedEnvironmentRecord: vi.fn(),
42 readSavedEnvironmentBearerToken: vi.fn(),
43 removeSavedEnvironmentBearerToken: vi.fn(),
44 useSavedEnvironmentRegistryStore: {
45 subscribe: mockSavedEnvironmentRegistrySubscribe,
46 getState: () => ({
47 upsert: vi.fn(),
48 remove: vi.fn(),
49 markConnected: vi.fn(),
50 }),
51 },
52 useSavedEnvironmentRuntimeStore: {
53 getState: () => ({
54 ensure: vi.fn(),
55 patch: vi.fn(),
56 clear: vi.fn(),
57 }),
58 },
59 waitForSavedEnvironmentRegistryHydration: mockWaitForSavedEnvironmentRegistryHydration,
60 writeSavedEnvironmentBearerToken: vi.fn(),
61}));
62
63vi.mock("./connection", () => ({
64 createEnvironmentConnection: mockCreateEnvironmentConnection,
65}));
66
67vi.mock("../../rpc/wsRpcClient", () => ({
68 createWsRpcClient: mockCreateWsRpcClient,
69}));
70
71vi.mock("../../rpc/wsTransport", () => ({
72 WsTransport: MockWsTransport,
73}));
74
75function makeThreadShellSnapshot(params: {
76 readonly threadId: ThreadId;
77 readonly sessionStatus?:
78 | "idle"
79 | "starting"
80 | "running"
81 | "ready"
82 | "interrupted"
83 | "stopped"
84 | "error";
85 readonly hasPendingApprovals?: boolean;
86 readonly hasPendingUserInput?: boolean;
87 readonly hasActionableProposedPlan?: boolean;
88}): OrchestrationShellSnapshot {
89 const projectId = ProjectId.make("project-1");
90 const turnId = TurnId.make("turn-1");
91
92 return {
93 snapshotSequence: 1,
94 projects: [],
95 updatedAt: "2026-04-13T00:00:00.000Z",
96 threads: [
97 {
98 id: params.threadId,
99 projectId,
100 title: "Thread",
101 modelSelection: {
102 instanceId: ProviderInstanceId.make("codex"),
103 model: "gpt-5-codex",
104 },
105 runtimeMode: "full-access",
106 interactionMode: "default",
107 branch: null,
108 worktreePath: null,
109 latestTurn:
110 params.sessionStatus === "running"
111 ? {
112 turnId,
113 state: "running",
114 requestedAt: "2026-04-13T00:00:00.000Z",
115 startedAt: "2026-04-13T00:00:01.000Z",
116 completedAt: null,
117 assistantMessageId: null,
118 }
119 : null,
120 createdAt: "2026-04-13T00:00:00.000Z",
121 updatedAt: "2026-04-13T00:00:00.000Z",
122 archivedAt: null,
123 session: params.sessionStatus
124 ? {
125 threadId: params.threadId,
126 status: params.sessionStatus,
127 providerName: "codex",
128 runtimeMode: "full-access",
129 activeTurnId: params.sessionStatus === "running" ? turnId : null,
130 lastError: null,
131 updatedAt: "2026-04-13T00:00:00.000Z",
132 }
133 : null,
134 latestUserMessageAt: null,
135 hasPendingApprovals: params.hasPendingApprovals ?? false,
136 hasPendingUserInput: params.hasPendingUserInput ?? false,
137 hasActionableProposedPlan: params.hasActionableProposedPlan ?? false,
138 },
139 ],
140 };
141}
142
143describe("retainThreadDetailSubscription", () => {
144 beforeEach(() => {
145 vi.useFakeTimers();
146 vi.resetModules();
147 vi.clearAllMocks();
148
149 mockThreadUnsubscribe.mockImplementation(() => undefined);
150 mockSubscribeThread.mockImplementation(() => mockThreadUnsubscribe);
151 mockCreateWsRpcClient.mockReturnValue({
152 orchestration: {
153 subscribeThread: mockSubscribeThread,
154 },
155 });
156 mockCreateEnvironmentConnection.mockImplementation((input) => ({
157 kind: input.kind,
158 environmentId: input.knownEnvironment.environmentId,
159 knownEnvironment: input.knownEnvironment,
160 client: input.client,
161 ensureBootstrapped: vi.fn(async () => undefined),
162 reconnect: vi.fn(async () => undefined),
163 dispose: vi.fn(async () => undefined),
164 }));
165 mockSavedEnvironmentRegistrySubscribe.mockReturnValue(() => undefined);
166 mockWaitForSavedEnvironmentRegistryHydration.mockResolvedValue(undefined);
167 mockListSavedEnvironmentRecords.mockReturnValue([]);
168 });
169
170 afterEach(async () => {
171 const { resetEnvironmentServiceForTests } = await import("./service");
172 await resetEnvironmentServiceForTests();
173 vi.useRealTimers();
174 });
175
176 it("keeps thread detail subscriptions warm across releases until idle eviction", async () => {
177 const {
178 retainThreadDetailSubscription,
179 startEnvironmentConnectionService,
180 resetEnvironmentServiceForTests,
181 } = await import("./service");
182
183 const stop = startEnvironmentConnectionService(new QueryClient());
184 const environmentId = EnvironmentId.make("env-1");
185 const threadId = ThreadId.make("thread-1");
186
187 const releaseFirst = retainThreadDetailSubscription(environmentId, threadId);
188 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
189
190 releaseFirst();
191 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
192
193 const releaseSecond = retainThreadDetailSubscription(environmentId, threadId);
194 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
195
196 releaseSecond();
197 await vi.advanceTimersByTimeAsync(2 * 60 * 1000);
198 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
199
200 await vi.advanceTimersByTimeAsync(28 * 60 * 1000);
201 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
202
203 stop();
204 await resetEnvironmentServiceForTests();
205 });
206
207 it("keeps non-idle thread detail subscriptions attached until the thread becomes idle", async () => {
208 const {
209 retainThreadDetailSubscription,
210 startEnvironmentConnectionService,
211 resetEnvironmentServiceForTests,
212 } = await import("./service");
213
214 const stop = startEnvironmentConnectionService(new QueryClient());
215 const environmentId = EnvironmentId.make("env-1");
216 const threadId = ThreadId.make("thread-active");
217
218 const connectionInput = mockCreateEnvironmentConnection.mock.calls[0]?.[0];
219 expect(connectionInput).toBeDefined();
220
221 connectionInput.syncShellSnapshot(
222 makeThreadShellSnapshot({
223 threadId,
224 sessionStatus: "ready",
225 hasPendingApprovals: true,
226 }),
227 environmentId,
228 );
229
230 const release = retainThreadDetailSubscription(environmentId, threadId);
231 expect(mockSubscribeThread).toHaveBeenCalledTimes(1);
232
233 release();
234 await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
235 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
236
237 connectionInput.applyShellEvent(
238 {
239 kind: "thread-upserted",
240 sequence: 2,
241 thread: makeThreadShellSnapshot({
242 threadId,
243 sessionStatus: "idle",
244 }).threads[0]!,
245 },
246 environmentId,
247 );
248
249 await vi.advanceTimersByTimeAsync(30 * 60 * 1000);
250 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
251
252 stop();
253 await resetEnvironmentServiceForTests();
254 });
255
256 it("allows a larger idle cache before capacity eviction starts", async () => {
257 const {
258 retainThreadDetailSubscription,
259 startEnvironmentConnectionService,
260 resetEnvironmentServiceForTests,
261 } = await import("./service");
262
263 const stop = startEnvironmentConnectionService(new QueryClient());
264 const environmentId = EnvironmentId.make("env-1");
265
266 for (let index = 0; index < 12; index += 1) {
267 const release = retainThreadDetailSubscription(
268 environmentId,
269 ThreadId.make(`thread-${index + 1}`),
270 );
271 release();
272 }
273
274 expect(mockThreadUnsubscribe).not.toHaveBeenCalled();
275
276 stop();
277 await resetEnvironmentServiceForTests();
278 });
279
280 it("disposes cached thread detail subscriptions when the environment service resets", async () => {
281 const {
282 retainThreadDetailSubscription,
283 startEnvironmentConnectionService,
284 resetEnvironmentServiceForTests,
285 } = await import("./service");
286
287 const stop = startEnvironmentConnectionService(new QueryClient());
288 const environmentId = EnvironmentId.make("env-1");
289 const threadId = ThreadId.make("thread-2");
290
291 const release = retainThreadDetailSubscription(environmentId, threadId);
292 release();
293
294 await resetEnvironmentServiceForTests();
295 expect(mockThreadUnsubscribe).toHaveBeenCalledTimes(1);
296
297 stop();
298 });
299});