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
@@ -1,5 +1,8 @@
import {
type CommandId,
EventId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationSession,
type OrchestrationThreadShell,
ProjectId,
Expand Down Expand Up @@ -156,9 +159,31 @@ describe("ThreadAutoArchiveSweeper", () => {
readonly threads: readonly OrchestrationThreadShell[];
readonly failingThreadIds?: ReadonlySet<ThreadId>;
readonly settingsShape?: ServerSettingsShape;
/** The children each parent's archive takes along, as the decider would decide. */
readonly takesAlong?: Readonly<Record<string, readonly string[]>>;
}) {
const dispatched: Array<Extract<OrchestrationCommand, { type: "thread.archive" }>> = [];
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.
Expand All @@ -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) => {
Expand All @@ -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 };
}),
),
);
},
Expand Down Expand Up @@ -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());
Expand All @@ -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 () => {
Expand Down
39 changes: 28 additions & 11 deletions apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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({
Expand Down
34 changes: 34 additions & 0 deletions apps/server/src/orchestration/archivedWithParent.ts
Original file line number Diff line number Diff line change
@@ -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<OrchestrationEngineShape, "readEvents">,
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<OrchestrationEvent, { type: "thread.archived" }> =>
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<ThreadId> => Array.from(threadIds)),
);
27 changes: 22 additions & 5 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 { hasLiveCommandRun } from "@threadlines/shared/commandRuns";
import { hasLiveSideTurn } from "@threadlines/shared/sideTurns";
import { exceedsRuntimeMode, saferRuntimeMode } from "@threadlines/shared/runtimeMode";
import {
Expand Down Expand Up @@ -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<OrchestrationEvent, "sequence">;
/** Event fields for an event on `threadId`'s aggregate, from the command being decided. */
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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),
Expand Down
52 changes: 52 additions & 0 deletions apps/server/src/orchestration/decider.childThreads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import {
ChildRequestBatchId,
ChildRequestId,
CommandId,
CommandRunId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EMPTY_AGENT_REQUEST_STATE,
EnvironmentId,
EMPTY_CHILD_REQUEST_STATE,
EventId,
MessageId,
type OrchestrationCommand,
type OrchestrationCommandRun,
type OrchestrationEvent,
type OrchestrationReadModel,
type OrchestrationSession,
Expand Down Expand Up @@ -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<OrchestrationThread>) =>
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",
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/orchestration/sessionBackgroundTasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<OrchestrationSession, "pendingBackgroundTaskCount" | "awaitedBackgroundTaskCount">
| 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;
Expand Down
17 changes: 4 additions & 13 deletions apps/server/src/orchestration/threadMoveDecisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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"));
}
Expand Down
Loading
Loading