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

threadSettled.test.ts

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