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

threadSettled.test.ts

434 lines14.8 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("does not re-settle a warm thread on the merge signal: a message sent in a settled thread keeps it active until idle", () => {
167 // The merge signal never clears, so without the idle guard a follow-up
168 // message would un-settle the row only until its turn completed, then
169 // snap straight back into the settled tail.
170 const justActive = makeShell({ activityAt: "2026-04-09T23:30:00.000Z" });
171 // The idle gate is strict: activity exactly one hour old is still warm.
172 const boundary = makeShell({ activityAt: "2026-04-09T23:00:00.000Z" });
173 const idle = makeShell({ activityAt: "2026-04-09T22:59:59.999Z" });
174​
175 for (const changeRequestState of ["merged", "closed"] as const) {
176 expect(
177 effectiveSettled(justActive, {
178 now: NOW,
179 autoSettleAfterDays: null,
180 changeRequestState,
181 }),
182 ).toBe(false);
183 expect(
184 effectiveSettled(boundary, {
185 now: NOW,
186 autoSettleAfterDays: null,
187 changeRequestState,
188 }),
189 ).toBe(false);
190 expect(
191 effectiveSettled(idle, {
192 now: NOW,
193 autoSettleAfterDays: null,
194 changeRequestState,
195 }),
196 ).toBe(true);
197 }
198 });
199​
200 it("re-settles a merged-PR thread once the follow-up burst goes idle", () => {
201 // Same shell, advancing clock: active while warm, settled again after
202 // the idle window passes — the burst cools and the merge signal wins.
203 const shell = makeShell({ activityAt: "2026-04-09T23:30:00.000Z" });
204 const options = { autoSettleAfterDays: null, changeRequestState: "merged" as const };
205​
206 expect(effectiveSettled(shell, { ...options, now: NOW })).toBe(false);
207 expect(effectiveSettled(shell, { ...options, now: "2026-04-10T00:30:00.001Z" })).toBe(true);
208 });
209​
210 it("never settles a starting session, even with a settled override", () => {
211 const shell = makeShell({
212 settledOverride: "settled",
213 activityAt: STALE,
214 sessionStatus: "starting",
215 });
216 expect(
217 effectiveSettled(shell, {
218 now: NOW,
219 autoSettleAfterDays: 3,
220 changeRequestState: "merged",
221 }),
222 ).toBe(false);
223 });
224​
225 it("keeps a new turn active from queued through starting and running", () => {
226 const requestedAt = "2026-04-09T12:00:00.000Z";
227 const transitionNow = "2026-04-09T12:00:30.000Z";
228 const base = makeShell({
229 settledOverride: null,
230 activityAt: STALE,
231 });
232 const queued: OrchestrationThreadShell = {
233 ...base,
234 latestUserMessageAt: requestedAt,
235 latestTurn: null,
236 session: null,
237 };
238 const starting: OrchestrationThreadShell = {
239 ...queued,
240 session: {
241 threadId: queued.id,
242 status: "starting",
243 providerName: "Codex",
244 runtimeMode: "full-access",
245 activeTurnId: null,
246 lastError: null,
247 updatedAt: requestedAt,
248 },
249 };
250 const running: OrchestrationThreadShell = {
251 ...starting,
252 session: {
253 ...starting.session!,
254 status: "running",
255 activeTurnId: TurnId.make("turn-new"),
256 },
257 };
258​
259 for (const shell of [queued, starting, running]) {
260 expect(
261 effectiveSettled(shell, {
262 now: transitionNow,
263 autoSettleAfterDays: 3,
264 changeRequestState: "merged",
265 }),
266 ).toBe(false);
267 }
268 });
269​
270 it("uses a strict inactivity boundary and honors a null threshold", () => {
271 const boundary = makeShell({
272 activityAt: "2026-04-07T00:00:00.000Z",
273 });
274 const stale = makeShell({ activityAt: STALE });
275​
276 expect(effectiveSettled(boundary, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
277 expect(effectiveSettled(stale, { now: NOW, autoSettleAfterDays: null })).toBe(false);
278 });
279});
280​
281describe("hasQueuedTurnStart", () => {
282 const QUEUED_AT = "2026-04-09T12:00:00.000Z";
283 // Within the adoption grace window of the queued message.
284 const JUST_AFTER = { now: "2026-04-09T12:00:30.000Z" };
285​
286 it("flags a user message no turn has picked up, within the grace window", () => {
287 const noTurn = { latestUserMessageAt: QUEUED_AT, latestTurn: null, session: null };
288 expect(hasQueuedTurnStart(noTurn, JUST_AFTER)).toBe(true);
289​
290 const staleTurn = {
291 ...makeShell({ activityAt: FRESH }),
292 latestUserMessageAt: QUEUED_AT,
293 };
294 expect(hasQueuedTurnStart(staleTurn, JUST_AFTER)).toBe(true);
295 });
296​
297 it("expires after the grace window: an unadopted message is a failed start, not queued work", () => {
298 const noTurn = { latestUserMessageAt: QUEUED_AT, latestTurn: null, session: null };
299 expect(hasQueuedTurnStart(noTurn, { now: "2026-04-09T12:03:00.000Z" })).toBe(false);
300 // Historical shells (e.g. from servers that never carried latestTurn)
301 // must never read as queued.
302 expect(hasQueuedTurnStart(noTurn, { now: NOW })).toBe(false);
303 });
304​
305 it("clears once a turn adopts the message or the start fails", () => {
306 const adopted = {
307 ...makeShell({ activityAt: QUEUED_AT }),
308 latestUserMessageAt: QUEUED_AT,
309 };
310 expect(hasQueuedTurnStart(adopted, JUST_AFTER)).toBe(false);
311​
312 const failed = makeShell({ activityAt: FRESH });
313 const failedShell = {
314 ...failed,
315 latestUserMessageAt: QUEUED_AT,
316 session: {
317 threadId: failed.id,
318 status: "error" as const,
319 providerName: "Codex",
320 runtimeMode: "full-access" as const,
321 activeTurnId: null,
322 lastError: "boom",
323 updatedAt: NOW,
324 },
325 };
326 expect(hasQueuedTurnStart(failedShell, JUST_AFTER)).toBe(false);
327 });
328​
329 it("is quiet without user messages", () => {
330 expect(hasQueuedTurnStart(makeShell({ activityAt: FRESH }), JUST_AFTER)).toBe(false);
331 });
332​
333 it("bounds the grace window in both directions: a future-stamped message is skew, not queued work", () => {
334 // Message timestamps originate on other devices; a clock an hour ahead
335 // must not hold the queued state for the whole skew.
336 const skewed = {
337 latestUserMessageAt: "2026-04-09T13:00:00.000Z",
338 latestTurn: null,
339 session: null,
340 };
341 expect(hasQueuedTurnStart(skewed, { now: "2026-04-09T12:00:00.000Z" })).toBe(false);
342 // A small negative age (within the grace window) still reads as queued.
343 const slightlyAhead = {
344 latestUserMessageAt: "2026-04-09T12:00:30.000Z",
345 latestTurn: null,
346 session: null,
347 };
348 expect(hasQueuedTurnStart(slightlyAhead, { now: "2026-04-09T12:00:00.000Z" })).toBe(true);
349 });
350});
351​
352describe("canSettle", () => {
353 it("blocks every state effectiveSettled refuses to classify as settled", () => {
354 expect(canSettle(makeShell({ activityAt: FRESH }), { now: NOW })).toBe(true);
355 expect(
356 canSettle(makeShell({ activityAt: FRESH, sessionStatus: "starting" }), { now: NOW }),
357 ).toBe(false);
358 expect(
359 canSettle(makeShell({ activityAt: FRESH, sessionStatus: "running" }), { now: NOW }),
360 ).toBe(false);
361 expect(canSettle(makeShell({ activityAt: FRESH, pending: "approval" }), { now: NOW })).toBe(
362 false,
363 );
364 expect(canSettle(makeShell({ activityAt: FRESH, pending: "user-input" }), { now: NOW })).toBe(
365 false,
366 );
367 });
368​
369 it("blocks settling a queued turn start, only within the grace window", () => {
370 const queued = {
371 ...makeShell({ activityAt: FRESH }),
372 latestUserMessageAt: "2026-04-09T12:00:00.000Z",
373 };
374 const justAfter = "2026-04-09T12:00:30.000Z";
375 expect(canSettle(queued, { now: justAfter })).toBe(false);
376 // effectiveSettled must agree: queued work never auto-settles either,
377 // even with a merged PR.
378 expect(
379 effectiveSettled(queued, {
380 now: justAfter,
381 autoSettleAfterDays: 3,
382 changeRequestState: "merged",
383 }),
384 ).toBe(false);
385 // Past the window the message is a failed/stale start: settleable again.
386 expect(canSettle(queued, { now: NOW })).toBe(true);
387 });
388​
389 it("lets a server-accepted settle overrule the clock-derived queued blocker", () => {
390 // The settle action ran with wall-clock `now` (past the grace window);
391 // the list partition re-evaluates with a minute-floored `now` that is
392 // still INSIDE the window. settledAt >= message time proves the server
393 // already adjudicated this exact message, so the row must not snap back
394 // to active until the coarser clock catches up.
395 const messageAt = "2026-04-09T12:00:00.000Z";
396 const flooredNow = "2026-04-09T12:01:00.000Z";
397 const base = makeShell({ settledOverride: "settled", activityAt: null });
398 const settledAfterMessage = {
399 ...base,
400 latestUserMessageAt: messageAt,
401 settledAt: "2026-04-09T12:02:10.000Z",
402 };
403 expect(hasQueuedTurnStart(settledAfterMessage, { now: flooredNow })).toBe(true);
404 expect(effectiveSettled(settledAfterMessage, { now: flooredNow, autoSettleAfterDays: 3 })).toBe(
405 true,
406 );
407​
408 // A message NEWER than settledAt is genuinely new work: still blocked
409 // until the server's auto-unsettle lands.
410 const messageAfterSettle = {
411 ...base,
412 latestUserMessageAt: "2026-04-09T12:03:00.000Z",
413 settledAt: "2026-04-09T12:02:10.000Z",
414 };
415 expect(
416 effectiveSettled(messageAfterSettle, {
417 now: "2026-04-09T12:03:30.000Z",
418 autoSettleAfterDays: 3,
419 }),
420 ).toBe(false);
421 });
422​
423 it("agrees with effectiveSettled's blockers for explicitly settled shells", () => {
424 // Anything canSettle rejects must render as active even when the user
425 // settled it earlier.
426 const blocked = makeShell({
427 settledOverride: "settled",
428 activityAt: FRESH,
429 pending: "user-input",
430 });
431 expect(canSettle(blocked, { now: NOW })).toBe(false);
432 expect(effectiveSettled(blocked, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
433 });
434});