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