diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index 112e4a854..ee662b2c4 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -110,6 +110,8 @@ function runningSession(threadId: ThreadId): OrchestrationSession { function makeSnapshotQuery( threads: readonly OrchestrationThreadShell[], leadThreadId?: ThreadId, + /** A thread as read right before its archive, when it changed since the snapshot. */ + latest: Readonly> = {}, ): ProjectionSnapshotQueryShape { const shellSnapshot = { snapshotSequence: 1, @@ -154,7 +156,10 @@ function makeSnapshotQuery( listClaimedSettingsChanges: () => Effect.succeed([]), listSecretRequests: () => Effect.succeed([]), listThreadShells: () => Effect.succeed([]), - getThreadShellById: () => Effect.succeed(Option.none()), + getThreadShellById: (threadId) => + Effect.succeed( + Option.fromNullishOr(latest[threadId] ?? threads.find((entry) => entry.id === threadId)), + ), getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), @@ -180,6 +185,7 @@ describe("ThreadAutoArchiveSweeper", () => { readonly settingsShape?: ServerSettingsShape; /** The children each parent's archive takes along, as the decider would decide. */ readonly takesAlong?: Readonly>; + readonly latest?: Readonly>; }) { const dispatched: Array> = []; const stopped: string[] = []; @@ -265,7 +271,7 @@ describe("ThreadAutoArchiveSweeper", () => { Layer.provideMerge( Layer.succeed( ProjectionSnapshotQuery, - makeSnapshotQuery(input.threads, input.leadThreadId), + makeSnapshotQuery(input.threads, input.leadThreadId, input.latest), ), ), Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)), @@ -301,9 +307,10 @@ describe("ThreadAutoArchiveSweeper", () => { }); }); - it("stops the sessions of what it archives, and leaves a parent whose child is still at work", async () => { + it("stops the sessions of what it archives, and leaves a parent whose child is still at work or owes a check-back", async () => { const idleParent = thread("idle-parent"); const busyParent = thread("busy-parent"); + const waitingParent = thread("waiting-parent"); const busyChild = thread("busy-child", { parentThreadId: busyParent.id, attachedToParent: true, @@ -323,6 +330,22 @@ describe("ThreadAutoArchiveSweeper", () => { }), busyParent, { ...busyChild, session: runningSession(busyChild.id) }, + waitingParent, + // Idle, but set to come back in its session, which the archive would stop. + thread("check-back-child", { + parentThreadId: waitingParent.id, + attachedToParent: true, + checkBacks: [ + { + id: "cb-1", + participantId: null, + scheduledFor: new Date(NOW_MS + 20 * 60 * 1_000).toISOString(), + exact: true, + recurring: false, + durable: false, + }, + ], + }), ], takesAlong: { [idleParent.id]: ["idle-child"] }, }); @@ -332,8 +355,51 @@ describe("ThreadAutoArchiveSweeper", () => { expect.arrayContaining([idleParent.id]), ); expect(dispatched.map((command) => command.threadId)).not.toContain(busyParent.id); + expect(dispatched.map((command) => command.threadId)).not.toContain(waitingParent.id); expect(stopped).toEqual(expect.arrayContaining([idleParent.id, "idle-child"])); expect(stopped).not.toContain("separated-child"); + // Inactive long enough itself, but archiving it would end its check-back. + expect(dispatched.map((command) => command.threadId)).not.toContain("check-back-child"); + expect(stopped).not.toContain("check-back-child"); + }); + + it("stops counting a check-back once its time is long past, and checks again right before archiving", async () => { + const checkBack = (scheduledForMs: number) => ({ + id: "cb-1", + participantId: null, + scheduledFor: new Date(scheduledForMs).toISOString(), + exact: true, + recurring: false, + durable: false, + }); + const staleParent = thread("stale-parent"); + const changedSince = thread("changed-since"); + const { dispatched, sweeper } = await createHarness({ + inactiveDays: 30, + threads: [ + staleParent, + // Its runtime ended without the report landing: the entry is two days old. + thread("stale-check-back-child", { + parentThreadId: staleParent.id, + attachedToParent: true, + checkBacks: [checkBack(NOW_MS - 2 * 24 * 60 * 60 * 1_000)], + }), + changedSince, + ], + // Set a check-back after the sweep's snapshot was taken. + latest: { + [changedSince.id]: { + ...changedSince, + updatedAt: new Date(NOW_MS).toISOString(), + checkBacks: [checkBack(NOW_MS + 20 * 60 * 1_000)], + }, + }, + }); + + await runtime!.runPromise(sweeper.sweepNow()); + const archivedIds = dispatched.map((command) => command.threadId); + expect(archivedIds).toContain(staleParent.id); + expect(archivedIds).not.toContain(changedSince.id); }); it("does not archive protected or recently active threads", async () => { diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts index 4a914e3f0..b813ed37e 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -9,6 +9,7 @@ import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -80,8 +81,9 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti (thread) => thread.parentThreadId !== null && thread.attachedToParent && - // At work or waiting on the user (a pin is not work). - isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }) && + // At work, waiting on the user or set to check back (a pin is + // not work). + isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }, nowMs) && thread.archivedAt === null, ) .map((thread) => thread.parentThreadId), @@ -102,6 +104,23 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti let archivedCount = 0; for (const thread of candidates) { + // Read again right before: since the snapshot it may have started + // working or set a check-back. A child that did is the decider's to + // keep out of the archive (childArchivePlan). + const latest = yield* projectionSnapshotQuery.getThreadShellById(thread.id).pipe( + Effect.map(Option.getOrNull), + Effect.catch(() => Effect.succeed(null)), + ); + if ( + latest === null || + selectAutoArchiveCandidates({ + threads: [leadThreadIds.has(latest.id) ? { ...latest, lead: true } : latest], + inactiveDays, + nowMs, + }).length === 0 + ) { + continue; + } // `thread.archive` carries no timestamp: the decider stamps // `archivedAt` from its own clock when it accepts the command. const command = { diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 458bde5d8..171d8c67e 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -12,6 +12,7 @@ * `baseFor`. The rules for who may ask live in `@threadlines/shared/childThreads`, * shared with the room MCP server. */ +import { holdsRuntimeCheckBack } from "@threadlines/shared/checkBacks"; import { hasLiveCommandRun } from "@threadlines/shared/commandRuns"; import { hasLiveSideTurn } from "@threadlines/shared/sideTurns"; import { exceedsRuntimeMode, saferRuntimeMode } from "@threadlines/shared/runtimeMode"; @@ -1724,7 +1725,10 @@ function separationEvents( * nobody waits on (a dev server) and a command still going in its terminal. * Ask for it where the thread is about to be stopped and its terminals * closed (archiving a parent's family). A thread's move waits on the same - * pieces (threadMoveDecisions.ts, workWaits). + * pieces (threadMoveDecisions.ts, workWaits). A check-back is not work + * here: it doesn't keep a thread from wrapping up or being reported idle. + * Archiving, which stops the runtime it fires in, checks for one itself + * (childArchivePlan). */ export function childHasLiveWork( thread: OrchestrationThread, @@ -2087,9 +2091,13 @@ export function childArchivePlan( // A child its parent still has a request open for is at work for it, even // one with nothing running yet because it is still being set up. Archiving // stops a child's runtime and closes its terminals, so a dev server or a - // command still going in its terminal keeps it out too. + // command still going in its terminal keeps it out too, and so does a + // check-back its agent set that would die with the runtime: unarchiving + // brings the thread back, not the promise to come back. const live = (child: OrchestrationThread) => - childHasLiveWork(child, { running: true }) || requestsFor(parent, child.id).length > 0; + childHasLiveWork(child, { running: true }) || + requestsFor(parent, child.id).length > 0 || + holdsRuntimeCheckBack(child); return { archive: children.filter((child) => !live(child)), separate: children.filter(live), diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 35da10795..b72703894 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -10,6 +10,7 @@ import { EMPTY_CHILD_REQUEST_STATE, EventId, MessageId, + type OrchestrationCheckBack, type OrchestrationCommand, type OrchestrationCommandRun, type OrchestrationEvent, @@ -551,6 +552,35 @@ describe("decider child threads", () => { expect(threadIn(archived.model, ranEarlier.id).archivedAt).not.toBeNull(); }); + it("archiving a parent separates a child whose check-back would die with its runtime", async () => { + const checkBack = (id: string, durable: boolean): OrchestrationCheckBack => ({ + id, + participantId: null, + scheduledFor: at(20 * 60), + exact: true, + recurring: false, + durable, + }); + const child = (id: string, checkBacks: ReadonlyArray) => + thread(ThreadId.make(id), { parentThreadId: PARENT, attachedToParent: true, checkBacks }); + // Idle after answering, set to come back in its session. + const willCheckBack = child("will-check-back", [checkBack("cb-soon", false)]); + // Saved to disk: it outlives the session the archive stops. + const savedCheckBack = child("saved-check-back", [checkBack("cb-saved", true)]); + const archived = await run(readModel([thread(PARENT), willCheckBack, savedCheckBack]), { + type: "thread.archive", + commandId: CommandId.make("archive"), + threadId: PARENT, + }); + const eventsFor = (id: ThreadId) => + archived.events + .filter((event) => "threadId" in event.payload && event.payload.threadId === id) + .map((event) => event.type); + expect(eventsFor(willCheckBack.id)).toEqual(["thread.parent-attachment-set"]); + expect(eventsFor(savedCheckBack.id)).toEqual(["thread.archived"]); + expect(threadIn(archived.model, willCheckBack.id).archivedAt).toBeNull(); + }); + it("lets only the server start a thread as another's child, and never under a child", async () => { const childOfChild: OrchestrationCommand = { type: "thread.create", diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index 9da9d2392..ed7bbb5d6 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -12,6 +12,7 @@ import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import { runtimeCheckBackOwed } from "@threadlines/shared/checkBacks"; import { parseParticipantSessionKey, sessionKeyThreadId, @@ -37,14 +38,6 @@ import { ProviderService } from "../Services/ProviderService.ts"; const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000; const DEFAULT_BACKGROUND_TASK_GRACE_MS = 4 * 60 * 60 * 1000; -/** How long past a check-back's time its runtime is kept for it. Claude - * states a wake-up's exact time but may run a cron job up to 30 minutes - * late (its scheduler spreads jobs out). */ -const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; -const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; -/** Claude's repeating jobs expire after 7 days; an idle runtime is not kept - * for one longer than that. */ -const RECURRING_CHECK_BACK_IDLE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000; /** The check-backs an agent's runtime keeps alive: ones that die with it. */ const runtimeCheckBacks = ( @@ -61,14 +54,7 @@ const holdsForCheckBack = ( checkBacks: ReadonlyArray, nowMs: number, idleDurationMs: number, -) => - checkBacks.some((checkBack) => { - if (checkBack.recurring) return idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS; - const due = - Date.parse(checkBack.scheduledFor) + - (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); - return Number.isFinite(due) && nowMs < due; - }); +) => checkBacks.some((checkBack) => runtimeCheckBackOwed(checkBack, nowMs, idleDurationMs)); type ThreadShellWithSession = { readonly session?: OrchestrationSession | null; diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 8b456ca21..d5c163213 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -76,6 +76,7 @@ import { useShallow } from "zustand/react/shallow"; import { selectBootstrapCompleteForActiveEnvironment, selectProjectsAcrossEnvironments, + selectSidebarThreadSummaryByRef, selectSidebarThreadsAcrossEnvironments, useStore, } from "../../store"; @@ -2404,6 +2405,23 @@ export function ArchivedThreadsPanel({ hostedStatic }: { readonly hostedStatic: try { for (const thread of inactiveThreadCandidates) { + // Checked again as each goes: while the confirmation was open it may + // have started working or set a check-back. + const state = useStore.getState(); + const latest = selectSidebarThreadSummaryByRef( + state, + scopeThreadRef(thread.environmentId, thread.id), + ); + if ( + latest === undefined || + selectAutoArchiveCandidates({ + threads: [latest], + projects: selectProjectsAcrossEnvironments(state), + inactiveDays: autoArchivePreviewDays, + }).length === 0 + ) { + continue; + } const api = readEnvironmentApi(thread.environmentId); if (!api) { failedCount += 1; diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 2a9dd7737..4511789a9 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -59,7 +59,7 @@ These rules override anything in the sections below that disagrees with them. 5. **The user and a child's answer.** A user steer into the answering turn, or into its continuation, becomes part of that turn by design, and the answer includes it. A _new_ user turn in the child while the request is `awaiting_background` settles the request with the candidate before that turn runs. 6. **Room history and catch-up** name `fromThread` messages by origin ("Request from thread X", "Report from thread X") through one shared author renderer, instead of labelling them "User" (roomHistory.ts:91, roomCatchUp.ts:216). Cancellation marking (roomAgentRequests.ts:309) covers reports too. 7. **`handed-back`** is stamped only when the settle actually emits a report. Suppressed, cancelled and stopped outcomes never set it. -8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. Live children are separated; the rest are archived. +8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. A check-back that dies with the runtime counts too (`holdsRuntimeCheckBack` in packages/shared/src/checkBacks.ts: any one not saved to outlive it, however old, so the decider reads no clock): unarchiving would bring the thread back but not the check-back. A stale entry only leaves a child as its own thread. Live children are separated; the rest are archived. 9. **`archivedWithParentAt`** is set only on children this cascade newly archives. Any independent archive or unarchive of the child clears it. 10. **Revert** is refused in a parent while it has open child requests or queued reports. It's also refused in a child while a parent request is bound to it ("Finish or stop its threads first"), extending the room guard at decider.ts:2385. @@ -365,10 +365,12 @@ Each of these settles open requests and also unqueues the matching queued report - **Delete the parent.** Decider cascade (`decideCommandSequence`, like `project.delete`). Attached children are separated, unless the command carries `withChildren: true`, in which case they're deleted. The confirm dialog gets "Also delete its N threads". Deleting a child settles its open requests `cancelled` and unqueues its reports. - **Archive the parent.** The cascade is decided on the server: - - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal) are archived and stamped `archivedWithParentAt`; + - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal, no check-back owed that would die with their session) are archived and stamped `archivedWithParentAt`; - live attached children are separated first. - Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children, and otherwise uses the same cascade. Unarchive restores the parent plus the children stamped with its archive. + Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children (a child holding such a check-back included), and otherwise uses the same cascade. Auto-archive and Settings' "Archive inactive threads now" also skip any thread, child or not, whose check-back is still owed (`isAutoArchiveProtectedThread`, by the idle reaper's rule `runtimeCheckBackOwed`: a one-off until a little past its time, a repeating one until Claude would have dropped it). They read the clock, so an entry whose runtime ended unreported stops protecting the thread on its own. Each re-checks a thread right before archiving it; a check-back set between that check and the archive can still be cut off, and a child that sets one after the sweeper's snapshot is separated by the cascade rather than archived. A check-back doesn't keep a thread out of Wrapped (the snooze rule); this only keeps an archive from stopping the session it fires in. + + Known limit: a child on a linked computer that the parent still has a request open for is stopped there (`peer.thread.stop`, docs/design/fleet.md "Stop and wrap"), and that stop ends its runtime-only check-backs, as Stop and wrap on the parent do. Interrupting only its turn would leave background work running there that nothing here shows. Unarchive restores the parent plus the children stamped with its archive. - **Room participant leaves.** Its child requests settle `cancelled`, its queued reports are unqueued, and its pending notes are dropped. This is an extension of `cancelAgentRequestsForLeaving`. diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index 6c54b3c74..d744f4257 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -43,3 +43,50 @@ export function sameCheckBacks( }) ); } + +/** + * Whether any of a thread's agents holds a check-back that dies with its + * runtime (not saved to outlive it), however old. A parent's archive + * separates such a child instead of archiving it. The decider reads no + * clock, and a stale entry only leaves a child as its own thread. + */ +export function holdsRuntimeCheckBack(thread: { + readonly checkBacks?: ReadonlyArray> | undefined; +}): boolean { + return (thread.checkBacks ?? []).some((checkBack) => !checkBack.durable); +} + +/** How long past a check-back's time it is still owed. Claude states a + * wake-up's exact time but may run a cron job up to 30 minutes late (its + * scheduler spreads jobs out). */ +const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; +const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; +/** Claude's repeating jobs expire after 7 days; one idle longer is gone. */ +const RECURRING_CHECK_BACK_IDLE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000; + +/** The check-back fields runtimeCheckBackOwed reads. */ +export type OwedCheckBackFields = Pick< + OrchestrationCheckBack, + "durable" | "recurring" | "exact" | "scheduledFor" +>; + +/** + * Whether a check-back that dies with its runtime is still owed at `nowMs`, + * its agent idle for `idleDurationMs`: a repeating one until Claude would + * have expired it, a one-off until a little past its time. Stopping the + * runtime then cancels a promise its agent made. The idle reaper keeps such a + * runtime, and auto-archive skips such a thread; a stale entry, one whose + * runtime ended without its report landing, stops counting on its own. + */ +export function runtimeCheckBackOwed( + checkBack: OwedCheckBackFields, + nowMs: number, + idleDurationMs: number, +): boolean { + if (checkBack.durable) return false; + if (checkBack.recurring) return idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS; + const due = + Date.parse(checkBack.scheduledFor) + + (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); + return Number.isFinite(due) && nowMs < due; +} diff --git a/packages/shared/src/threadAutoArchive.test.ts b/packages/shared/src/threadAutoArchive.test.ts index 153787a36..7bce15e18 100644 --- a/packages/shared/src/threadAutoArchive.test.ts +++ b/packages/shared/src/threadAutoArchive.test.ts @@ -121,4 +121,32 @@ describe("thread auto-archive rules", () => { expect(candidates.map(({ id }) => id)).toEqual(["included"]); }); + + it("keeps a thread whose agent will check back in a session archiving would stop", () => { + const checkBack = (overrides: { durable?: boolean; recurring?: boolean; dueMs?: number }) => ({ + durable: overrides.durable ?? false, + recurring: overrides.recurring ?? false, + exact: true, + scheduledFor: new Date(overrides.dueMs ?? NOW_MS + 60 * 60 * 1_000).toISOString(), + }); + const candidates = selectAutoArchiveCandidates({ + threads: [ + thread("checks-back", { checkBacks: [checkBack({})] }), + // Saved to disk, it outlives the session. + thread("saved", { checkBacks: [checkBack({ durable: true })] }), + // Its runtime ended unreported: long past its time. + thread("stale", { checkBacks: [checkBack({ dueMs: NOW_MS - 24 * 60 * 60 * 1_000 })] }), + // Claude drops a repeating one after 7 days; this thread was idle 45. + thread("stale-repeating", { checkBacks: [checkBack({ recurring: true })] }), + ], + inactiveDays: 30, + nowMs: NOW_MS, + }); + + expect(candidates.map(({ id }) => id).toSorted()).toEqual([ + "saved", + "stale", + "stale-repeating", + ]); + }); }); diff --git a/packages/shared/src/threadAutoArchive.ts b/packages/shared/src/threadAutoArchive.ts index 18cfb318a..a4cbb5a50 100644 --- a/packages/shared/src/threadAutoArchive.ts +++ b/packages/shared/src/threadAutoArchive.ts @@ -1,3 +1,5 @@ +import { runtimeCheckBackOwed, type OwedCheckBackFields } from "./checkBacks.ts"; + export const AUTO_ARCHIVE_SUGGESTED_INACTIVE_DAYS = 30 as const; export interface AutoArchiveThreadFields { @@ -17,6 +19,8 @@ export interface AutoArchiveThreadFields { readonly awaitedChildThreadCount?: number | undefined; /** Child threads: threads its agent asked to start wait for the user. */ readonly pendingChildApproval?: boolean | undefined; + /** Times its agents set to come back (runtimeCheckBackOwed). */ + readonly checkBacks?: ReadonlyArray | undefined; readonly session: { readonly status: string; readonly orchestrationStatus?: string | undefined; @@ -31,7 +35,10 @@ export function getAutoArchiveThreadInactiveSince(thread: AutoArchiveThreadField return thread.updatedAt ?? thread.latestUserMessageAt ?? thread.createdAt; } -export function isAutoArchiveProtectedThread(thread: AutoArchiveThreadFields): boolean { +export function isAutoArchiveProtectedThread( + thread: AutoArchiveThreadFields, + nowMs: number = Date.now(), +): boolean { if (thread.archivedAt !== null || thread.pinnedAt !== null || thread.lead === true) { return true; } @@ -53,6 +60,17 @@ export function isAutoArchiveProtectedThread(thread: AutoArchiveThreadFields): b return true; } + // Its agent will come back in a runtime archiving would stop. A stale + // entry (its runtime ended unreported) runs out with its time. + const idleDurationMs = nowMs - Date.parse(getAutoArchiveThreadInactiveSince(thread)); + if ( + (thread.checkBacks ?? []).some((checkBack) => + runtimeCheckBackOwed(checkBack, nowMs, idleDurationMs), + ) + ) { + return true; + } + const session = thread.session; if (!session) { return false; @@ -78,10 +96,11 @@ export function selectAutoArchiveCandidates(i return []; } - const cutoffMs = (input.nowMs ?? Date.now()) - input.inactiveDays * 24 * 60 * 60 * 1_000; + const nowMs = input.nowMs ?? Date.now(); + const cutoffMs = nowMs - input.inactiveDays * 24 * 60 * 60 * 1_000; return input.threads .flatMap((thread): Array => { - if (input.isExcluded?.(thread) === true || isAutoArchiveProtectedThread(thread)) { + if (input.isExcluded?.(thread) === true || isAutoArchiveProtectedThread(thread, nowMs)) { return []; }