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

threadSettled.test.ts

417 lines13.7 KB

1import {
2 ProjectId,
3 ProviderInstanceId,
4 ThreadId,
5 TurnId,
6 type OrchestrationThreadShell,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "vite-plus/test";
9​
10import {
11 canSettle,
12 effectiveSettled,
13 hasQueuedTurnStart,
14 threadLastActivityAt,
15 type ChangeRequestStateLike,
16} from "./threadSettled.ts";
17​
18const NOW = "2026-04-10T00:00:00.000Z";
19const FRESH = "2026-04-09T00:00:00.000Z";
20const STALE = "2026-04-06T23:59:59.999Z";
21​
22function makeShell(input: {
23 readonly settledOverride?: "settled" | "active" | null;
24 readonly activityAt: string | null;
25 readonly sessionStatus?: "starting" | "running";
26 readonly pending?: "approval" | "user-input";
27}): OrchestrationThreadShell {
28 const threadId = ThreadId.make("thread-1");
29 return {
30 id: threadId,
31 projectId: ProjectId.make("project-1"),
32 title: "Thread",
33 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
34 runtimeMode: "full-access",
35 interactionMode: "default",
36 branch: null,
37 worktreePath: null,
38 latestTurn:
39 input.activityAt === null
40 ? null
41 : {
42 turnId: TurnId.make("turn-1"),
43 state: "completed",
44 requestedAt: input.activityAt,
45 startedAt: null,
46 completedAt: null,
47 assistantMessageId: null,
48 },
49 createdAt: "2026-04-01T00:00:00.000Z",
50 updatedAt: NOW,
51 archivedAt: null,
52 settledOverride: input.settledOverride ?? null,
53 settledAt: input.settledOverride === "settled" ? NOW : null,
54 session:
55 input.sessionStatus === undefined
56 ? null
57 : {
58 threadId,
59 status: input.sessionStatus,
60 providerName: "Codex",
61 runtimeMode: "full-access",
62 activeTurnId: null,
63 lastError: null,
64 updatedAt: NOW,
65 },
66 latestUserMessageAt: null,
67 hasPendingApprovals: input.pending === "approval",
68 hasPendingUserInput: input.pending === "user-input",
69 hasActionableProposedPlan: false,
70 };
72​
73describe("threadLastActivityAt", () => {
74 it("returns the latest real user or turn activity and ignores thread/session updates", () => {
75 const shell = makeShell({ activityAt: null, sessionStatus: "running" });
76 const withActivity: OrchestrationThreadShell = {
77 ...shell,
78 latestUserMessageAt: "2026-04-04T00:00:00.000Z",
79 latestTurn: {
80 turnId: TurnId.make("turn-1"),
81 state: "completed",
82 requestedAt: "2026-04-03T00:00:00.000Z",
83 startedAt: "2026-04-05T00:00:00.000Z",
84 completedAt: "2026-04-06T00:00:00.000Z",
85 assistantMessageId: null,
86 },
87 };
88​
89 expect(threadLastActivityAt(withActivity)).toBe("2026-04-06T00:00:00.000Z");
90 expect(threadLastActivityAt(shell)).toBeNull();
91 });
92});
93​
94describe("effectiveSettled", () => {
95 const overrideCases = [null, "settled", "active"] as const;
96 const changeRequestStates = [undefined, "open", "merged"] as const;
97 const inactivityCases = [
98 ["fresh", FRESH],
99 ["stale", STALE],
100 ["no-activity", null],
101 ] as const;
102 const runningCases = [false, true] as const;
103 const pendingCases = [undefined, "approval", "user-input"] as const;
104 const truthTable = overrideCases.flatMap((settledOverride) =>
105 changeRequestStates.flatMap((changeRequestState) =>
106 inactivityCases.flatMap(([inactivity, activityAt]) =>
107 runningCases.flatMap((running) =>
108 pendingCases.map((pending) => ({
109 settledOverride,
110 changeRequestState,
111 inactivity,
112 activityAt,
113 running,
114 pending,
115 // Settled iff nothing blocks (pending work / live session) AND
116 // the override says settled, or (with no override) a merged PR
117 // or staleness auto-settles. The "active" pin suppresses both
118 // auto signals.
119 expected:
120 pending === undefined &&
121 !running &&
122 (settledOverride === "settled" ||
123 (settledOverride === null &&
124 (changeRequestState === "merged" || inactivity === "stale"))),
125 })),
126 ),
127 ),
128 ),
129 );
130​
131 it.each(truthTable)(
132 "override=$settledOverride pr=$changeRequestState inactivity=$inactivity running=$running pending=$pending",
133 ({ settledOverride, changeRequestState, activityAt, running, pending, expected }) => {
134 const shell = makeShell({
135 settledOverride,
136 activityAt,
137 ...(running ? { sessionStatus: "running" as const } : {}),
138 ...(pending === undefined ? {} : { pending }),
139 });
140 const changeRequestOptions =
141 changeRequestState === undefined
142 ? {}
143 : { changeRequestState: changeRequestState as ChangeRequestStateLike };
144​
145 expect(
146 effectiveSettled(shell, {
147 now: NOW,
148 autoSettleAfterDays: 3,
149 ...changeRequestOptions,
150 }),
151 ).toBe(expected);
152 },
153 );
154​
155 it("treats closed change requests like merged ones", () => {
156 const shell = makeShell({ activityAt: null });
157 expect(
158 effectiveSettled(shell, {
159 now: NOW,
160 autoSettleAfterDays: null,
161 changeRequestState: "closed",
162 }),
163 ).toBe(true);
164 });
165​
166 it("settles immediately when a change request merges or closes", () => {
167 const recentlyActive = makeShell({ activityAt: "2026-04-09T23:59:59.999Z" });
168 for (const changeRequestState of ["merged", "closed"] as const) {
169 expect(
170 effectiveSettled(recentlyActive, {
171 now: NOW,
172 autoSettleAfterDays: null,
173 changeRequestState,
174 }),
175 ).toBe(true);
176 }
177 });
178​
179 it("keeps an explicitly un-settled merged-PR thread active", () => {
180 const shell = makeShell({
181 settledOverride: "active",
182 activityAt: "2026-04-09T23:59:59.999Z",
183 });
184 expect(
185 effectiveSettled(shell, {
186 now: NOW,
187 autoSettleAfterDays: null,
188 changeRequestState: "merged",
189 }),
190 ).toBe(false);
191 });
192​
193 it("never settles a starting session, even with a settled override", () => {
194 const shell = makeShell({
195 settledOverride: "settled",
196 activityAt: STALE,
197 sessionStatus: "starting",
198 });
199 expect(
200 effectiveSettled(shell, {
201 now: NOW,
202 autoSettleAfterDays: 3,
203 changeRequestState: "merged",
204 }),
205 ).toBe(false);
206 });
207​
208 it("keeps a new turn active from queued through starting and running", () => {
209 const requestedAt = "2026-04-09T12:00:00.000Z";
210 const transitionNow = "2026-04-09T12:00:30.000Z";
211 const base = makeShell({
212 settledOverride: null,
213 activityAt: STALE,
214 });
215 const queued: OrchestrationThreadShell = {
216 ...base,
217 latestUserMessageAt: requestedAt,
218 latestTurn: null,
219 session: null,
220 };
221 const starting: OrchestrationThreadShell = {
222 ...queued,
223 session: {
224 threadId: queued.id,
225 status: "starting",
226 providerName: "Codex",
227 runtimeMode: "full-access",
228 activeTurnId: null,
229 lastError: null,
230 updatedAt: requestedAt,
231 },
232 };
233 const running: OrchestrationThreadShell = {
234 ...starting,
235 session: {
236 ...starting.session!,
237 status: "running",
238 activeTurnId: TurnId.make("turn-new"),
239 },
240 };
241​
242 for (const shell of [queued, starting, running]) {
243 expect(
244 effectiveSettled(shell, {
245 now: transitionNow,
246 autoSettleAfterDays: 3,
247 changeRequestState: "merged",
248 }),
249 ).toBe(false);
250 }
251 });
252​
253 it("uses a strict inactivity boundary and honors a null threshold", () => {
254 const boundary = makeShell({
255 activityAt: "2026-04-07T00:00:00.000Z",
256 });
257 const stale = makeShell({ activityAt: STALE });
258​
259 expect(effectiveSettled(boundary, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
260 expect(effectiveSettled(stale, { now: NOW, autoSettleAfterDays: null })).toBe(false);
261 });
262});
263​
264describe("hasQueuedTurnStart", () => {
265 const QUEUED_AT = "2026-04-09T12:00:00.000Z";
266 // Within the adoption grace window of the queued message.
267 const JUST_AFTER = { now: "2026-04-09T12:00:30.000Z" };
268​
269 it("flags a user message no turn has picked up, within the grace window", () => {
270 const noTurn = { latestUserMessageAt: QUEUED_AT, latestTurn: null, session: null };
271 expect(hasQueuedTurnStart(noTurn, JUST_AFTER)).toBe(true);
272​
273 const staleTurn = {
274 ...makeShell({ activityAt: FRESH }),
275 latestUserMessageAt: QUEUED_AT,
276 };
277 expect(hasQueuedTurnStart(staleTurn, JUST_AFTER)).toBe(true);
278 });
279​
280 it("expires after the grace window: an unadopted message is a failed start, not queued work", () => {
281 const noTurn = { latestUserMessageAt: QUEUED_AT, latestTurn: null, session: null };
282 expect(hasQueuedTurnStart(noTurn, { now: "2026-04-09T12:03:00.000Z" })).toBe(false);
283 // Historical shells (e.g. from servers that never carried latestTurn)
284 // must never read as queued.
285 expect(hasQueuedTurnStart(noTurn, { now: NOW })).toBe(false);
286 });
287​
288 it("clears once a turn adopts the message or the start fails", () => {
289 const adopted = {
290 ...makeShell({ activityAt: QUEUED_AT }),
291 latestUserMessageAt: QUEUED_AT,
292 };
293 expect(hasQueuedTurnStart(adopted, JUST_AFTER)).toBe(false);
294​
295 const failed = makeShell({ activityAt: FRESH });
296 const failedShell = {
297 ...failed,
298 latestUserMessageAt: QUEUED_AT,
299 session: {
300 threadId: failed.id,
301 status: "error" as const,
302 providerName: "Codex",
303 runtimeMode: "full-access" as const,
304 activeTurnId: null,
305 lastError: "boom",
306 updatedAt: NOW,
307 },
308 };
309 expect(hasQueuedTurnStart(failedShell, JUST_AFTER)).toBe(false);
310 });
311​
312 it("is quiet without user messages", () => {
313 expect(hasQueuedTurnStart(makeShell({ activityAt: FRESH }), JUST_AFTER)).toBe(false);
314 });
315​
316 it("bounds the grace window in both directions: a future-stamped message is skew, not queued work", () => {
317 // Message timestamps originate on other devices; a clock an hour ahead
318 // must not hold the queued state for the whole skew.
319 const skewed = {
320 latestUserMessageAt: "2026-04-09T13:00:00.000Z",
321 latestTurn: null,
322 session: null,
323 };
324 expect(hasQueuedTurnStart(skewed, { now: "2026-04-09T12:00:00.000Z" })).toBe(false);
325 // A small negative age (within the grace window) still reads as queued.
326 const slightlyAhead = {
327 latestUserMessageAt: "2026-04-09T12:00:30.000Z",
328 latestTurn: null,
329 session: null,
330 };
331 expect(hasQueuedTurnStart(slightlyAhead, { now: "2026-04-09T12:00:00.000Z" })).toBe(true);
332 });
333});
334​
335describe("canSettle", () => {
336 it("blocks every state effectiveSettled refuses to classify as settled", () => {
337 expect(canSettle(makeShell({ activityAt: FRESH }), { now: NOW })).toBe(true);
338 expect(
339 canSettle(makeShell({ activityAt: FRESH, sessionStatus: "starting" }), { now: NOW }),
340 ).toBe(false);
341 expect(
342 canSettle(makeShell({ activityAt: FRESH, sessionStatus: "running" }), { now: NOW }),
343 ).toBe(false);
344 expect(canSettle(makeShell({ activityAt: FRESH, pending: "approval" }), { now: NOW })).toBe(
345 false,
346 );
347 expect(canSettle(makeShell({ activityAt: FRESH, pending: "user-input" }), { now: NOW })).toBe(
348 false,
349 );
350 });
351​
352 it("blocks settling a queued turn start, only within the grace window", () => {
353 const queued = {
354 ...makeShell({ activityAt: FRESH }),
355 latestUserMessageAt: "2026-04-09T12:00:00.000Z",
356 };
357 const justAfter = "2026-04-09T12:00:30.000Z";
358 expect(canSettle(queued, { now: justAfter })).toBe(false);
359 // effectiveSettled must agree: queued work never auto-settles either,
360 // even with a merged PR.
361 expect(
362 effectiveSettled(queued, {
363 now: justAfter,
364 autoSettleAfterDays: 3,
365 changeRequestState: "merged",
366 }),
367 ).toBe(false);
368 // Past the window the message is a failed/stale start: settleable again.
369 expect(canSettle(queued, { now: NOW })).toBe(true);
370 });
371​
372 it("lets a server-accepted settle overrule the clock-derived queued blocker", () => {
373 // The settle action ran with wall-clock `now` (past the grace window);
374 // the list partition re-evaluates with a minute-floored `now` that is
375 // still INSIDE the window. settledAt >= message time proves the server
376 // already adjudicated this exact message, so the row must not snap back
377 // to active until the coarser clock catches up.
378 const messageAt = "2026-04-09T12:00:00.000Z";
379 const flooredNow = "2026-04-09T12:01:00.000Z";
380 const base = makeShell({ settledOverride: "settled", activityAt: null });
381 const settledAfterMessage = {
382 ...base,
383 latestUserMessageAt: messageAt,
384 settledAt: "2026-04-09T12:02:10.000Z",
385 };
386 expect(hasQueuedTurnStart(settledAfterMessage, { now: flooredNow })).toBe(true);
387 expect(effectiveSettled(settledAfterMessage, { now: flooredNow, autoSettleAfterDays: 3 })).toBe(
388 true,
389 );
390​
391 // A message NEWER than settledAt is genuinely new work: still blocked
392 // until the server's auto-unsettle lands.
393 const messageAfterSettle = {
394 ...base,
395 latestUserMessageAt: "2026-04-09T12:03:00.000Z",
396 settledAt: "2026-04-09T12:02:10.000Z",
397 };
398 expect(
399 effectiveSettled(messageAfterSettle, {
400 now: "2026-04-09T12:03:30.000Z",
401 autoSettleAfterDays: 3,
402 }),
403 ).toBe(false);
404 });
405​
406 it("agrees with effectiveSettled's blockers for explicitly settled shells", () => {
407 // Anything canSettle rejects must render as active even when the user
408 // settled it earlier.
409 const blocked = makeShell({
410 settledOverride: "settled",
411 activityAt: FRESH,
412 pending: "user-input",
413 });
414 expect(canSettle(blocked, { now: NOW })).toBe(false);
415 expect(effectiveSettled(blocked, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
416 });
417});