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

service.threadSubscriptions.test.ts

298 lines9.0 KB

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