Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<string, OrchestrationThreadShell>> = {},
): ProjectionSnapshotQueryShape {
const shellSnapshot = {
snapshotSequence: 1,
Expand Down Expand Up @@ -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),
Expand All @@ -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<Record<string, readonly string[]>>;
readonly latest?: Readonly<Record<string, OrchestrationThreadShell>>;
}) {
const dispatched: Array<Extract<OrchestrationCommand, { type: "thread.archive" }>> = [];
const stopped: string[] = [];
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -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,
Expand All @@ -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"] },
});
Expand All @@ -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 () => {
Expand Down
23 changes: 21 additions & 2 deletions apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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),
Expand All @@ -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 = {
Expand Down
14 changes: 11 additions & 3 deletions apps/server/src/orchestration/childThreadDecisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/orchestration/decider.childThreads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
EMPTY_CHILD_REQUEST_STATE,
EventId,
MessageId,
type OrchestrationCheckBack,
type OrchestrationCommand,
type OrchestrationCommandRun,
type OrchestrationEvent,
Expand Down Expand Up @@ -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<OrchestrationCheckBack>) =>
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",
Expand Down
18 changes: 2 additions & 16 deletions apps/server/src/provider/Layers/ProviderSessionReaper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 = (
Expand All @@ -61,14 +54,7 @@ const holdsForCheckBack = (
checkBacks: ReadonlyArray<OrchestrationCheckBack>,
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;
Expand Down
18 changes: 18 additions & 0 deletions apps/web/src/components/settings/SettingsPanels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import { useShallow } from "zustand/react/shallow";
import {
selectBootstrapCompleteForActiveEnvironment,
selectProjectsAcrossEnvironments,
selectSidebarThreadSummaryByRef,
selectSidebarThreadsAcrossEnvironments,
useStore,
} from "../../store";
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 5 additions & 3 deletions docs/design/child-threads.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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`.

Expand Down
Loading
Loading