diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index 5f8485b7f..8348c7cae 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -1,5 +1,8 @@ import { + type CommandId, + EventId, type OrchestrationCommand, + type OrchestrationEvent, type OrchestrationSession, type OrchestrationThreadShell, ProjectId, @@ -156,9 +159,31 @@ describe("ThreadAutoArchiveSweeper", () => { readonly threads: readonly OrchestrationThreadShell[]; readonly failingThreadIds?: ReadonlySet; readonly settingsShape?: ServerSettingsShape; + /** The children each parent's archive takes along, as the decider would decide. */ + readonly takesAlong?: Readonly>; }) { const dispatched: Array> = []; const stopped: string[] = []; + // What the archives wrote: each child taken along gets its own archived event. + const written: OrchestrationEvent[] = []; + const writeArchived = (commandId: CommandId, threadId: string) => + written.push({ + sequence: written.length + 2, + eventId: EventId.make(`event-${written.length}`), + type: "thread.archived", + aggregateKind: "thread", + aggregateId: ThreadId.make(threadId), + occurredAt: new Date(NOW_MS).toISOString(), + commandId, + causationEventId: null, + correlationId: null, + metadata: {}, + payload: { + threadId: ThreadId.make(threadId), + archivedAt: new Date(NOW_MS).toISOString(), + updatedAt: new Date(NOW_MS).toISOString(), + }, + } as OrchestrationEvent); let onDispatch: (() => void) | null = null; // Bounded so a regression that never dispatches fails in seconds instead // of hanging until the suite-wide timeout. @@ -171,7 +196,8 @@ describe("ThreadAutoArchiveSweeper", () => { }; }); const orchestrationEngine: OrchestrationEngineShape = { - readEvents: () => Stream.empty, + readEvents: (fromSequenceExclusive) => + Stream.fromIterable(written.filter((event) => event.sequence > fromSequenceExclusive)), readThreadEvents: () => Effect.succeed([]), getCommandReceipt: () => Effect.succeed(Option.none()), dispatch: (command) => { @@ -196,7 +222,13 @@ describe("ThreadAutoArchiveSweeper", () => { detail: "test dispatch failure", }), ) - : Effect.succeed({ sequence: dispatched.length }), + : Effect.sync(() => { + writeArchived(command.commandId, command.threadId); + for (const child of input.takesAlong?.[command.threadId] ?? []) { + writeArchived(command.commandId, child); + } + return { sequence: written.length + 1 }; + }), ), ); }, @@ -257,9 +289,18 @@ describe("ThreadAutoArchiveSweeper", () => { threads: [ idleParent, thread("idle-child", { parentThreadId: idleParent.id, attachedToParent: true }), + // Its archive separates this one (a command still running in its + // terminal), so it keeps running. + thread("separated-child", { + parentThreadId: idleParent.id, + attachedToParent: true, + updatedAt: daysAgo(1), + latestUserMessageAt: daysAgo(1), + }), busyParent, { ...busyChild, session: runningSession(busyChild.id) }, ], + takesAlong: { [idleParent.id]: ["idle-child"] }, }); await runtime!.runPromise(sweeper.sweepNow()); @@ -268,6 +309,7 @@ describe("ThreadAutoArchiveSweeper", () => { ); expect(dispatched.map((command) => command.threadId)).not.toContain(busyParent.id); expect(stopped).toEqual(expect.arrayContaining([idleParent.id, "idle-child"])); + expect(stopped).not.toContain("separated-child"); }); 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 6a30cfd17..90be6d41c 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -17,6 +17,7 @@ import * as Stream from "effect/Stream"; import { ServerSettingsService } from "../../serverSettings.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; +import { threadsArchivedWith } from "../archivedWithParent.ts"; import { ThreadAutoArchiveSweeper, type ThreadAutoArchiveSweeperShape, @@ -101,26 +102,42 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti commandId: CommandId.make(`thread-auto-archive:${thread.id}:${randomUUID()}`), threadId: thread.id, }; + // Where the event log stood before the archive, so the children it + // took along can be read back from what it wrote. + const cursor = yield* projectionSnapshotQuery.getSnapshotSequence().pipe( + Effect.map(({ snapshotSequence }) => snapshotSequence), + Effect.catch(() => Effect.succeed(null)), + ); const archived = yield* orchestrationEngine.dispatch(command).pipe( - Effect.as(true), Effect.catchCause((cause) => Effect.logWarning("thread.auto-archive.dispatch-failed", { threadId: thread.id, cause, - }).pipe(Effect.as(false)), + }).pipe(Effect.as(null)), ), ); - if (archived) { + if (archived !== null) { archivedCount += 1; // Archiving stops what the thread had running, as it does from the - // sidebar: its runtimes and its settled children's, which the - // archive took with it. - const family = [ - thread.id, - ...snapshot.threads - .filter((entry) => entry.parentThreadId === thread.id && entry.attachedToParent) - .map((entry) => entry.id), - ]; + // sidebar: its runtimes and those of the settled children the + // archive took with it. A child it separated keeps running. + const takenAlong = + cursor === null + ? [] + : yield* threadsArchivedWith(orchestrationEngine, { + commandId: command.commandId, + threadId: thread.id, + fromSequenceExclusive: cursor, + throughSequence: archived.sequence, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("thread.auto-archive.archived-children-read-failed", { + threadId: thread.id, + cause, + }).pipe(Effect.as([])), + ), + ); + const family = [thread.id, ...takenAlong]; for (const threadId of family) { yield* orchestrationEngine .dispatch({ diff --git a/apps/server/src/orchestration/archivedWithParent.ts b/apps/server/src/orchestration/archivedWithParent.ts new file mode 100644 index 000000000..864f4428b --- /dev/null +++ b/apps/server/src/orchestration/archivedWithParent.ts @@ -0,0 +1,34 @@ +import type { CommandId, OrchestrationEvent, ThreadId } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; + +import type { OrchestrationEngineShape } from "./Services/OrchestrationEngine.ts"; + +/** + * The threads an archive took along with the thread it named (a parent's + * settled children), read back from the events that command wrote between + * the two sequences. Whoever archived cleans these up as it does the named + * thread; a child the archive separated instead keeps running, so it is not + * here. A retried command that wrote nothing finds none. + */ +export const threadsArchivedWith = ( + engine: Pick, + input: { + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly fromSequenceExclusive: number; + readonly throughSequence: number; + }, +) => + engine.readEvents(input.fromSequenceExclusive).pipe( + Stream.takeWhile((event) => event.sequence <= input.throughSequence), + Stream.filter( + (event): event is Extract => + event.type === "thread.archived" && + event.commandId === input.commandId && + event.payload.threadId !== input.threadId, + ), + Stream.map((event) => event.payload.threadId), + Stream.runCollect, + Effect.map((threadIds): ReadonlyArray => Array.from(threadIds)), + ); diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index db805f1eb..495ed5cab 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 { hasLiveCommandRun } from "@threadlines/shared/commandRuns"; import { hasLiveSideTurn } from "@threadlines/shared/sideTurns"; import { exceedsRuntimeMode, saferRuntimeMode } from "@threadlines/shared/runtimeMode"; import { @@ -59,6 +60,7 @@ import { isProjectLeadThread } from "./commandInvariants.ts"; import { checkoutSelectedEvents } from "./threadCheckout.ts"; import { currentAgentModel, messageAgentModels } from "./messageAgentModels.ts"; +import { hasBackgroundWork } from "./sessionBackgroundTasks.ts"; type PlannedEvent = Omit; /** Event fields for an event on `threadId`'s aggregate, from the command being decided. */ @@ -1601,9 +1603,21 @@ function separationEvents( ]; } -/** Whether a child has work going: a turn, a start, background work, or work it asked for. */ -export function childHasLiveWork(thread: OrchestrationThread): boolean { +/** + * Whether a child has work going: a turn, a start, background work its agent + * waits on, or work it asked for. `running` also counts what keeps running + * without its agent and dies with its runtime or terminal: background work + * 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). + */ +export function childHasLiveWork( + thread: OrchestrationThread, + options: { readonly running?: boolean } = {}, +): boolean { const session = thread.session; + const running = options.running === true; const latestTurnId = thread.latestTurn?.turnId ?? null; return ( // Waiting on the user counts too: an approval, a question, a plan to act on. @@ -1619,7 +1633,8 @@ export function childHasLiveWork(thread: OrchestrationThread): boolean { thread.latestTurn?.state === "running" || session?.status === "running" || session?.status === "starting" || - (session?.awaitedBackgroundTaskCount ?? session?.pendingBackgroundTaskCount ?? 0) > 0 || + hasBackgroundWork(session, running ? "any" : "awaited") || + (running && hasLiveCommandRun(thread.commandRuns)) || (thread.queuedFollowUps ?? []).length > 0 || hasLiveSideTurn(thread) || thread.childRequests.open.length > 0 @@ -1929,9 +1944,11 @@ export function childArchivePlan( (child) => child.archivedAt === null, ); // 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. + // 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. const live = (child: OrchestrationThread) => - childHasLiveWork(child) || requestsFor(parent, child.id).length > 0; + childHasLiveWork(child, { running: true }) || requestsFor(parent, child.id).length > 0; 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 21debc5d0..86e587f22 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -3,6 +3,7 @@ import { ChildRequestBatchId, ChildRequestId, CommandId, + CommandRunId, DEFAULT_PROVIDER_INTERACTION_MODE, EMPTY_AGENT_REQUEST_STATE, EnvironmentId, @@ -10,6 +11,7 @@ import { EventId, MessageId, type OrchestrationCommand, + type OrchestrationCommandRun, type OrchestrationEvent, type OrchestrationReadModel, type OrchestrationSession, @@ -499,6 +501,56 @@ describe("decider child threads", () => { expect(threadIn(unarchived.model, settled.id).archivedAt).toBeNull(); }); + it("archiving a parent separates a child with a dev server or a terminal command still running", async () => { + // Archiving stops each archived child's runtime and closes its terminals. + const commandRun = (status: OrchestrationCommandRun["status"]): OrchestrationCommandRun => ({ + runId: CommandRunId.make(`run-${status}`), + terminalId: "terminal-1", + mode: "run", + dialect: "posix", + command: "pnpm dev", + source: { kind: "message", messageId: MessageId.make("reply-1") }, + turnId: TurnId.make("child-turn-1"), + participantId: null, + cwd: "/repo", + autoSend: false, + status, + startedAt: now, + finishedAt: status === "finished" ? now : null, + exitCode: status === "finished" ? 0 : null, + error: null, + hasOutput: true, + heldReason: null, + outputSentAt: null, + outputMessageId: null, + createdAt: now, + updatedAt: now, + }); + const child = (id: string, overrides: Partial) => + thread(ThreadId.make(id), { parentThreadId: PARENT, attachedToParent: true, ...overrides }); + // A dev server its agent doesn't wait on: the turn is over. + const devServer = child("dev-server", { + session: session(ThreadId.make("dev-server"), { + status: "ready", + activeTurnId: null, + pendingBackgroundTaskCount: 1, + awaitedBackgroundTaskCount: 0, + }), + }); + const inTerminal = child("in-terminal", { commandRuns: [commandRun("running")] }); + const ranEarlier = child("ran-earlier", { commandRuns: [commandRun("finished")] }); + const archived = await run(readModel([thread(PARENT), devServer, inTerminal, ranEarlier]), { + type: "thread.archive", + commandId: CommandId.make("archive"), + threadId: PARENT, + }); + for (const live of [devServer, inTerminal]) { + expect(threadIn(archived.model, live.id).archivedAt).toBeNull(); + expect(threadIn(archived.model, live.id).attachedToParent).toBe(false); + } + expect(threadIn(archived.model, ranEarlier.id).archivedAt).not.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/orchestration/sessionBackgroundTasks.ts b/apps/server/src/orchestration/sessionBackgroundTasks.ts index b1e893a39..7488983bb 100644 --- a/apps/server/src/orchestration/sessionBackgroundTasks.ts +++ b/apps/server/src/orchestration/sessionBackgroundTasks.ts @@ -45,6 +45,26 @@ export function carriedBackgroundTasks( }; } +/** + * Whether a session has background work running: `awaited`, the tasks its + * agent waits on (it wakes when they finish); `any`, every task its runtime + * holds, a dev server it left running included. Stopping the runtime kills + * them all. + */ +export function hasBackgroundWork( + session: + | Pick + | null + | undefined, + which: "awaited" | "any", +): boolean { + const { pendingBackgroundTaskCount, awaitedBackgroundTaskCount } = + carriedBackgroundTasks(session); + return which === "awaited" + ? awaitedBackgroundTaskCount > 0 + : pendingBackgroundTaskCount > 0 || awaitedBackgroundTaskCount > 0; +} + /** Longest task description a session carries. The provider allows far more * (Claude: 1000 characters), and the sidebar shows one line of it. */ const AWAITED_TASK_DESCRIPTION_MAX_LENGTH = 120; diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 572d2c5d1..7f4cc350d 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -37,6 +37,7 @@ import { type ThreadNativeSessionFellBackPayload, type ThreadPendingMove, } from "@threadlines/contracts"; +import { hasLiveCommandRun } from "@threadlines/shared/commandRuns"; import { threadPullRequestAutomationArmed } from "@threadlines/shared/linkedPullRequests"; import { APPROVAL_ACTIVITY_KINDS, @@ -51,6 +52,7 @@ import { arrivalMessageText, resumedGoalMessageText } from "../moves/arrivalMess import { decideAgentChainStop } from "./agentRequestDecisions.ts"; import { derivedUuid } from "./childRequestIds.ts"; import { cameHomeEvents, leftBehindEvents, movedAloneEvents } from "./childThreadDecisions.ts"; +import { hasBackgroundWork } from "./sessionBackgroundTasks.ts"; import { drainsWhileMoveWaits, interruptedOf, @@ -487,19 +489,8 @@ function workWaits( found.push(wait("background", FAMILY_WAIT_WORDS)); } } - if ( - (session?.pendingBackgroundTaskCount ?? 0) > 0 || - (session?.awaitedBackgroundTaskCount ?? 0) > 0 - ) { - found.push(wait("background")); - } - if ( - (thread.commandRuns ?? []).some((run) => - ["starting", "running", "waiting"].includes(run.status), - ) - ) { - found.push(wait("command_run")); - } + if (hasBackgroundWork(session, "any")) found.push(wait("background")); + if (hasLiveCommandRun(thread.commandRuns)) found.push(wait("command_run")); if ((thread.workflowRuns ?? []).some((run) => run.status === "running")) { found.push(wait("workflow_run")); } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 4f8e2ab23..e12d9ebd3 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -98,6 +98,7 @@ import { } from "./orchestration/messageSentFrom.ts"; import { RealtimeVoiceDevices } from "./orchestration/Services/RealtimeVoiceDevices.ts"; import { coalesceLatestAggregateEvents } from "./orchestration/shellStreamCoalescing.ts"; +import { threadsArchivedWith } from "./orchestration/archivedWithParent.ts"; import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts"; import { ProviderCommandReactor } from "./orchestration/Services/ProviderCommandReactor.ts"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; @@ -1238,17 +1239,7 @@ const makeCoreRpcLayer = ( readonly throughSequence: number; }) => Effect.gen(function* () { - const archived = yield* orchestrationEngine.readEvents(input.fromSequenceExclusive).pipe( - Stream.takeWhile((event) => event.sequence <= input.throughSequence), - Stream.filter( - (event): event is Extract => - event.type === "thread.archived" && - event.commandId === input.commandId && - event.payload.threadId !== input.threadId, - ), - Stream.map((event) => event.payload.threadId), - Stream.runCollect, - ); + const archived = yield* threadsArchivedWith(orchestrationEngine, input); if (archived.length === 0) { return; } diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 8a8bff56d..cc57ab042 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 awaited background work, queued or pending starts, and open child requests). 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. 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. @@ -352,7 +352,7 @@ 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) 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) 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. diff --git a/packages/shared/src/commandRuns.ts b/packages/shared/src/commandRuns.ts index 4048992f8..4e063076f 100644 --- a/packages/shared/src/commandRuns.ts +++ b/packages/shared/src/commandRuns.ts @@ -32,6 +32,16 @@ export function isCommandRunSettled(status: CommandRunStatus): boolean { return FINAL_RUN_STATUSES.has(status); } +/** + * A run still going in the thread's terminal: opening, running, or typed in + * and waiting for the user's Enter. Closing the terminal ends it. + */ +export function hasLiveCommandRun( + runs: ReadonlyArray> | undefined, +): boolean { + return (runs ?? []).some((run) => !isCommandRunSettled(run.status)); +} + /** Output still due to go to its agent by itself. */ export function commandRunAwaitsAutoSend( run: Pick,