diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index a8f65c96e..4df06188b 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -59,6 +59,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/L import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts"; import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts"; import { ChildThreadReactor } from "../src/orchestration/Services/ChildThreadReactor.ts"; +import { GoalWaitReactor } from "../src/orchestration/Services/GoalWaitReactor.ts"; import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts"; import { ThreadContextSeedBuilderLive } from "../src/provider/contextSeed/ThreadContextSeedBuilder.ts"; import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts"; @@ -416,6 +417,12 @@ export const makeOrchestrationIntegrationHarness = ( drain: Effect.void, }), ), + Layer.provideMerge( + Layer.succeed(GoalWaitReactor, { + start: () => Effect.void, + drain: Effect.void, + }), + ), Layer.provideMerge( Layer.succeed(ThreadDiffStatBaselineReactor, { start: () => Effect.void, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index db35768c5..f847cdeca 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -57,6 +57,8 @@ While an agent works, the arrow beside the send button picks how a message goes: After a reply to your message, Claude or Codex can suggest what you might send next: gray text in the empty message box, taken with Tab (Use on a phone), hidden with Escape. Claude makes its own and skips them when you're on track to run out of usage early, unless {place:threads.claudeSuggestions} is on. Codex's are made by Threadlines with one extra Codex answer each, only after messages you sent, never while a usage limit is 90% used, and {place:threads.codexSuggestions} turns them off. +A goal (type /goal and what to reach in the message box) keeps the agent working toward it across turns; the bar above the message box shows it, with pause, resume and clear. A Codex goal pauses by itself while the thread waits for your answer on a card or for threads it started to report back, so it doesn't spend turns asking whether you answered yet; the bar says why, and it carries on once the wait is over. Pausing, resuming or clearing it yourself in between is yours to keep. Claude's goals have no pause and carry on as before. + When Claude or Codex asks multiple-choice questions, a card takes the place of the message box. Besides answering, you can Skip a question, close the card with its X (the agent goes on without answers), or choose Reply in chat: the message box comes back, and the next message you send, text only, is your answer. The agent is told exactly which you did. Questions from other agents, such as a yes/no confirmation, still need an answer or Stop. When a thread is done it wraps up and moves to the Wrapped shelf at the bottom of the sidebar; {place:threads.whenDone} says when that happens on its own. An agent coming back later (a check-back) doesn't keep a thread out of Wrapped: the thread returns to the list when the agent does. Old threads can be archived for you: {place:archived.cleanup}. diff --git a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts new file mode 100644 index 000000000..bb03a8d6b --- /dev/null +++ b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts @@ -0,0 +1,206 @@ +import { randomUUID } from "node:crypto"; + +import { + CommandId, + type OrchestrationEvent, + type OrchestrationThread, + type ThreadId, +} from "@threadlines/contracts"; +import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; +import { goalWaitOf, goalWaitStep, turnAboutToStart } from "@threadlines/shared/goalWaitPause"; +import { sessionSlotParticipantId } from "@threadlines/shared/threadParticipants"; +import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; + +import { ProviderService } from "../../provider/Services/ProviderService.ts"; +import { ScheduledTasks } from "../../scheduled/ScheduledTasks.ts"; +import { GoalWaitReactor, type GoalWaitReactorShape } from "../Services/GoalWaitReactor.ts"; +import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; + +const nowIso = Effect.map(DateTime.now, DateTime.formatIso); + +/** + * Events that can change what a thread waits on, or its goal: its cards (the + * threads, settings, invites and commands its agent asked for), the threads + * it started, its queue and session (a turn about to start or running) and + * its goal. + * Everything else (streamed text, tool calls) leaves both alone. + */ +const WAIT_EVENT_PREFIXES = [ + "thread.child-request", + "thread.child-requests-reset", + "thread.child-deliveries-cancelled", + "thread.remote-child-updated", + "thread.settings-change-", + "thread.agent-request", + "thread.command-request", + "thread.command-run-", + "thread.follow-up-", + "thread.session-set", + // A revert can take a waiting command card or its run away. + "thread.reverted", + // An agent leaving takes its invite and its requests with it. + "thread.participant-", + "thread.goal-state-set", +] as const; + +const changesWait = (event: OrchestrationEvent): boolean => + event.aggregateKind === "thread" && + WAIT_EVENT_PREFIXES.some((prefix) => event.type.startsWith(prefix)); + +/** + * The user acted on the goal: paused, resumed, edited or cleared it, or + * pressed Stop. The decider sees most of these itself; a thread whose only + * wait is a scheduled-task card it can't see, so this says so. + */ +const userActedOnGoal = (event: OrchestrationEvent): boolean => + (event.type === "thread.goal-set-requested" && event.payload.origin !== "automatic") || + event.type === "thread.goal-clear-requested" || + event.type === "thread.turn-interrupt-requested" || + event.type === "thread.session-stop-requested"; + +/** What a look at a thread carries besides its state. */ +interface SyncFlags { + readonly userActed: boolean; + readonly retryResume: boolean; +} + +export const make = Effect.gen(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const providerService = yield* ProviderService; + const scheduledTasks = yield* Effect.serviceOption(ScheduledTasks); + + const scheduleWaiting = Option.isSome(scheduledTasks) + ? scheduledTasks.value.waitingThreadIds + : Effect.succeed(new Set() as ReadonlySet); + + /** + * Only a provider that can pause a goal gets one paused (Codex). Claude's + * goal is a hook inside one turn with no pause; the others have no goals. + */ + const canPauseGoal = (thread: OrchestrationThread) => { + const holderId = sessionSlotParticipantId(thread.session); + const instanceId = + thread.session?.providerInstanceId ?? + thread.participants.find((entry) => entry.id === holderId)?.modelSelection.instanceId ?? + thread.modelSelection.instanceId; + return providerService.getCapabilities(instanceId).pipe( + Effect.map( + (capabilities) => + capabilities.threadGoals === "supported" && + capabilities.threadGoalPause !== "unsupported", + ), + Effect.orElseSucceed(() => false), + ); + }; + + const syncThread = Effect.fn("GoalWaitReactor.syncThread")(function* ( + threadId: ThreadId, + flags: SyncFlags, + ) { + const thread = yield* projectionSnapshotQuery.getThreadDetailById(threadId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + if (thread === undefined || thread.goal === null || thread.deletedAt !== null) return; + const scheduleAnswerWaiting = (yield* scheduleWaiting).has(threadId); + // The decider decides again, from the thread as it stands then; this + // only spares it a command when nothing would change. + const step = goalWaitStep({ + goal: thread.goal, + waiting: goalWaitOf(thread, scheduleAnswerWaiting) !== null, + turnStarting: turnAboutToStart(thread), + userActed: flags.userActed, + retryResume: flags.retryResume, + }); + // Forgetting a mark sends the provider nothing; a pause or resume needs + // a provider that has one. + if (step === null || (step.send !== null && !(yield* canPauseGoal(thread)))) return; + yield* orchestrationEngine + .dispatch({ + type: "thread.goal.wait.sync", + commandId: CommandId.make(`goal-wait-sync:${threadId}:${randomUUID()}`), + threadId, + scheduleAnswerWaiting, + ...(flags.userActed ? { userActed: true } : {}), + ...(flags.retryResume ? { retryResume: true } : {}), + createdAt: yield* nowIso, + }) + .pipe( + Effect.asVoid, + Effect.catchCause((cause) => + Effect.logWarning("goal wait sync failed", { threadId, cause: Cause.pretty(cause) }), + ), + ); + }); + + // A thread already queued is looked at once, read as it stands then; the + // flags of every request for it in between add up. + const queued = new Map(); + const worker = yield* makeDrainableWorker((threadId: ThreadId) => + Effect.suspend(() => { + const flags = queued.get(threadId) ?? { userActed: false, retryResume: false }; + queued.delete(threadId); + return syncThread(threadId, flags); + }), + ); + const enqueue = (threadId: ThreadId, flags: Partial = {}) => + Effect.suspend(() => { + const pending = queued.get(threadId); + const next = { + userActed: (pending?.userActed ?? false) || flags.userActed === true, + retryResume: (pending?.retryResume ?? false) || flags.retryResume === true, + }; + queued.set(threadId, next); + return pending === undefined ? worker.enqueue(threadId) : Effect.void; + }); + + const start: GoalWaitReactorShape["start"] = Effect.fn("start")(function* () { + const events = yield* orchestrationEngine.subscribeDomainEvents; + yield* Effect.forkScoped( + Stream.runForEach(events, (event) => + userActedOnGoal(event) + ? enqueue(event.aggregateId as ThreadId, { userActed: true }) + : changesWait(event) + ? enqueue(event.aggregateId as ThreadId) + : Effect.void, + ), + ); + // A scheduled-task card shown or answered changes no thread event. + if (Option.isSome(scheduledTasks)) { + let previous: ReadonlySet = yield* scheduleWaiting; + yield* Effect.forkScoped( + Stream.runForEach(scheduledTasks.value.changes.pipe(Stream.ignoreCause), () => + Effect.gen(function* () { + const current = yield* scheduleWaiting; + const changed = [...current, ...previous].filter( + (threadId) => current.has(threadId) !== previous.has(threadId), + ); + previous = current; + yield* Effect.forEach(changed, (threadId) => enqueue(threadId), { discard: true }); + }), + ), + ); + } + // Cards answered or threads finished while the server was down, and a + // resume a restart cut off before the provider confirmed it. + const snapshot = yield* projectionSnapshotQuery + .getShellSnapshot() + .pipe(Effect.orElseSucceed(() => ({ threads: [] as const }))); + yield* Effect.forEach( + snapshot.threads.filter((thread) => thread.goal !== null), + (thread) => enqueue(thread.id, { retryResume: true }), + { discard: true }, + ); + }); + + return { start, drain: worker.drain } satisfies GoalWaitReactorShape; +}); + +export const GoalWaitReactorLive = Layer.effect(GoalWaitReactor, make); diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts index 3497d8247..5e0eb496e 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test"; import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; import { ChildThreadReactor } from "../Services/ChildThreadReactor.ts"; +import { GoalWaitReactor } from "../Services/GoalWaitReactor.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; @@ -24,7 +25,7 @@ describe("OrchestrationReactor", () => { runtime = null; }); - it("starts provider ingestion, provider command, child thread, checkpoint, thread deletion, and diff-stat baseline reactors", async () => { + it("starts provider ingestion, provider command, child thread, goal wait, checkpoint, thread deletion, and diff-stat baseline reactors", async () => { const started: string[] = []; runtime = ManagedRuntime.make( @@ -58,6 +59,15 @@ describe("OrchestrationReactor", () => { drain: Effect.void, }), ), + Layer.provideMerge( + Layer.succeed(GoalWaitReactor, { + start: () => { + started.push("goal-wait-reactor"); + return Effect.void; + }, + drain: Effect.void, + }), + ), Layer.provideMerge( Layer.succeed(CheckpointReactor, { start: () => { @@ -96,6 +106,7 @@ describe("OrchestrationReactor", () => { "provider-runtime-ingestion", "provider-command-reactor", "child-thread-reactor", + "goal-wait-reactor", "checkpoint-reactor", "thread-deletion-reactor", "thread-diffstat-baseline-reactor", diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts index beba90519..5a0e8f3b9 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts @@ -7,6 +7,7 @@ import { } from "../Services/OrchestrationReactor.ts"; import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; import { ChildThreadReactor } from "../Services/ChildThreadReactor.ts"; +import { GoalWaitReactor } from "../Services/GoalWaitReactor.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; @@ -16,6 +17,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () { const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService; const providerCommandReactor = yield* ProviderCommandReactor; const childThreadReactor = yield* ChildThreadReactor; + const goalWaitReactor = yield* GoalWaitReactor; const checkpointReactor = yield* CheckpointReactor; const threadDeletionReactor = yield* ThreadDeletionReactor; const threadDiffStatBaselineReactor = yield* ThreadDiffStatBaselineReactor; @@ -25,6 +27,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () { yield* providerCommandReactor.start(); // After the sessions the previous process left are settled. yield* childThreadReactor.start(); + yield* goalWaitReactor.start(); yield* checkpointReactor.start(); yield* threadDeletionReactor.start(); yield* threadDiffStatBaselineReactor.start(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index b6b2ac2bc..09cbf3d83 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -4154,6 +4154,20 @@ const make = Effect.gen(function* () { if (!thread) { return; } + // A pause or resume Threadlines made for a wait goes out only while the + // goal still carries it: the user took the goal over, or the provider + // ended or blocked it, since it was decided (docs/design/goal-wait-pause.md). + if (event.payload.origin === "automatic") { + const goal = thread.goal; + const stillOurs = + event.payload.status === "paused" + ? // Paused already: a resume of ours may still be on its way. + goal?.waitPause === "paused" && (goal.status === "active" || goal.status === "paused") + : goal?.waitPause === "resuming" && goal.status === "paused"; + if (!stillOurs) { + return; + } + } // Goals live provider-side, so the thread needs a live session before the // goal RPC. Cold threads get their session started (or resumed) here. In a // room the goal belongs to the agent holding the session slot. The @@ -4226,6 +4240,8 @@ const make = Effect.gen(function* () { threadId: goalHolderSessionKey, modelSelection: goalModelSelection, ...(context !== undefined ? { context } : {}), + // A pause or resume for a wait (thread.goal.wait.sync) is ours, not the user's. + ...(event.payload.origin !== undefined ? { origin: event.payload.origin } : {}), ...(event.payload.objective !== undefined ? { objective: event.payload.objective } : resumed !== null diff --git a/apps/server/src/orchestration/Services/GoalWaitReactor.ts b/apps/server/src/orchestration/Services/GoalWaitReactor.ts new file mode 100644 index 000000000..a4aed168b --- /dev/null +++ b/apps/server/src/orchestration/Services/GoalWaitReactor.ts @@ -0,0 +1,30 @@ +/** + * GoalWaitReactor - pauses a thread's goal while the thread waits, and + * resumes it when the wait ends (docs/design/goal-wait-pause.md). + * + * Watches the events that change what a thread with a goal waits on (its + * cards, the threads it started, its session, its goal) and the scheduler's + * waiting cards, and sends `thread.goal.wait.sync` for each thread whose goal + * should change. The decider holds the rule; this only asks it at the right + * moments, and only for goals whose provider can pause one. + * + * @module GoalWaitReactor + */ +import * as Context from "effect/Context"; +import type * as Effect from "effect/Effect"; +import type * as Scope from "effect/Scope"; + +export interface GoalWaitReactorShape { + /** + * Start watching, and bring every goal in line once (a restart may have + * left a card answered while the server was down). + */ + readonly start: () => Effect.Effect; + + /** Resolves once every thread queued so far has been looked at. For tests. */ + readonly drain: Effect.Effect; +} + +export class GoalWaitReactor extends Context.Service()( + "threadlines/orchestration/Services/GoalWaitReactor", +) {} diff --git a/apps/server/src/orchestration/decider.goalWait.test.ts b/apps/server/src/orchestration/decider.goalWait.test.ts new file mode 100644 index 000000000..d1dd18c56 --- /dev/null +++ b/apps/server/src/orchestration/decider.goalWait.test.ts @@ -0,0 +1,388 @@ +import { + ChildRequestBatchId, + ChildRequestId, + CommandId, + CommandRequestId, + DEFAULT_PROVIDER_INTERACTION_MODE, + MessageId, + type OrchestrationCommand, + type OrchestrationEvent, + type OrchestrationReadModel, + type OrchestrationThread, + type OrchestrationThreadGoal, + ProjectId, + ProviderInstanceId, + ThreadId, + TurnId, +} from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import { describe, expect, it } from "vite-plus/test"; + +import { decideOrchestrationCommand } from "./decider.ts"; +import { projectEvent } from "./projector.ts"; + +const now = "2026-11-18T10:00:00.000Z"; +const at = (seconds: number) => new Date(Date.parse(now) + seconds * 1000).toISOString(); +const projectId = ProjectId.make("project-1"); +const THREAD = ThreadId.make("goal-thread"); + +type Planned = Omit; + +async function run(current: OrchestrationReadModel, command: OrchestrationCommand) { + const decided = await Effect.runPromise( + decideOrchestrationCommand({ command, readModel: current }), + ); + const events = (Array.isArray(decided) ? decided : [decided]) as ReadonlyArray; + let next = current; + let sequence = current.snapshotSequence; + for (const event of events) { + sequence += 1; + next = await Effect.runPromise( + projectEvent(next, { ...event, sequence } as OrchestrationEvent), + ); + } + return { events, model: { ...next, snapshotSequence: sequence } }; +} + +const emptyModel: OrchestrationReadModel = { + snapshotSequence: 0, + updatedAt: now, + projects: [ + { + id: projectId, + kind: "workspace", + title: "threadlines", + workspaceRoot: "/repo", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [], +}; + +const goal = (status: OrchestrationThreadGoal["status"]): OrchestrationThreadGoal => ({ + threadId: THREAD, + objective: "count.txt holds 1 to 8", + status, + tokenBudget: null, + tokensUsed: 100, + timeUsedSeconds: 10, + createdAt: now, + updatedAt: now, +}); + +/** What the provider says the goal is now (runtime ingestion). */ +const reported = (status: OrchestrationThreadGoal["status"]): OrchestrationCommand => ({ + type: "thread.goal.state.set", + commandId: CommandId.make(`reported-${status}-${Math.random()}`), + threadId: THREAD, + goal: goal(status), + createdAt: at(1), +}); + +const sync = ( + scheduleAnswerWaiting = false, + flags: { readonly userActed?: boolean; readonly retryResume?: boolean } = {}, +): OrchestrationCommand => ({ + type: "thread.goal.wait.sync", + commandId: CommandId.make(`sync-${Math.random()}`), + threadId: THREAD, + scheduleAnswerWaiting, + ...flags, + createdAt: at(2), +}); + +const patchThread = ( + model: OrchestrationReadModel, + patch: (thread: OrchestrationThread) => Partial, +): OrchestrationReadModel => ({ + ...model, + threads: model.threads.map((thread) => + thread.id === THREAD ? { ...thread, ...patch(thread) } : thread, + ), +}); + +const commandCard = { + requestId: CommandRequestId.make("card-1"), + turnId: TurnId.make("turn-1"), + participantId: null, + command: "pnpm install", + reason: "Needs your network", + dialect: "posix" as const, + dismissedAt: null, + createdAt: now, + updatedAt: now, +}; + +const startedThread = (status: "running" | "awaiting_user") => ({ + requestId: ChildRequestId.make(`request-${status}`), + batchId: ChildRequestBatchId.make("batch-1"), + kind: "start" as const, + from: { participantId: null }, + callerTurnId: TurnId.make("turn-1"), + deliveryEpoch: 0, + status, + childThreadId: ThreadId.make(`child-${status}`), + childMessageId: MessageId.make(`child-message-${status}`), + createdAt: now, +}); + +/** A Codex thread whose goal the provider reports active. */ +async function threadWithActiveGoal() { + const created = await run(emptyModel, { + type: "thread.create", + commandId: CommandId.make("create"), + threadId: THREAD, + projectId, + title: "Count", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.2-sol" }, + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + createdAt: now, + }); + return (await run(created.model, reported("active"))).model; +} + +const goalOf = (model: OrchestrationReadModel) => + model.threads.find((thread) => thread.id === THREAD)?.goal ?? null; +const goalRequest = (events: ReadonlyArray) => + events.find((event) => event.type === "thread.goal-set-requested")?.payload; + +/** The thread with the one command card waiting, then answered (skipped). */ +const withCard = (model: OrchestrationReadModel) => + patchThread(model, () => ({ commandRequests: [commandCard] })); +const cardAnswered = (model: OrchestrationReadModel) => + patchThread(model, () => ({ commandRequests: [{ ...commandCard, dismissedAt: at(3) }] })); + +/** Paused for the card, and the provider has confirmed it. */ +async function pausedForCard() { + const paused = await run(withCard(await threadWithActiveGoal()), sync()); + return (await run(paused.model, reported("paused"))).model; +} + +const userGoal = (status: "active" | "paused"): OrchestrationCommand => ({ + type: "thread.goal.set", + commandId: CommandId.make(`user-${status}-${Math.random()}`), + threadId: THREAD, + status, + createdAt: at(3), +}); + +describe("decider goal wait pause", () => { + it("pauses an active goal while a card waits, and resumes it once the card is answered", async () => { + const paused = await run(withCard(await threadWithActiveGoal()), sync()); + expect(goalRequest(paused.events)).toMatchObject({ status: "paused", origin: "automatic" }); + expect(goalOf(paused.model)).toMatchObject({ status: "active", waitPause: "paused" }); + // Asked again before the provider confirms: nothing more. + expect((await run(paused.model, sync())).events).toEqual([]); + + const confirmed = await run(paused.model, reported("paused")); + expect(goalOf(confirmed.model)).toMatchObject({ status: "paused", waitPause: "paused" }); + + const resumed = await run(cardAnswered(confirmed.model), sync()); + expect(goalRequest(resumed.events)).toMatchObject({ status: "active", origin: "automatic" }); + // Marked until the provider says it is active again. + expect(goalOf(resumed.model)?.waitPause).toBe("resuming"); + const active = await run(resumed.model, reported("active")); + expect(goalOf(active.model)?.waitPause).toBeUndefined(); + }); + + it("keeps a resume the user made during the wait, and never pauses it again for that wait", async () => { + const userResumed = await run(await pausedForCard(), userGoal("active")); + expect(goalRequest(userResumed.events)).not.toHaveProperty("origin"); + const active = (await run(userResumed.model, reported("active"))).model; + expect(goalOf(active)?.waitPause).toBe("user"); + // The card still waits: their resume stands. + expect((await run(active, sync())).events).toEqual([]); + // Once it's answered, the mark goes and nothing is sent. + const over = await run(cardAnswered(active), sync()); + expect(goalRequest(over.events)).toBeUndefined(); + expect(goalOf(over.model)?.waitPause).toBeUndefined(); + }); + + it("keeps a pause the user made, even one that landed before ours", async () => { + // Paused by the user while the card already waited, before any sync. + const userPaused = await run(withCard(await threadWithActiveGoal()), userGoal("paused")); + expect(goalOf(userPaused.model)?.waitPause).toBe("user"); + // Our sync, while the provider still reports it active: no pause of ours. + expect((await run(userPaused.model, sync())).events).toEqual([]); + const confirmed = (await run(userPaused.model, reported("paused"))).model; + // Answered: it stays paused. + expect(goalRequest((await run(cardAnswered(confirmed), sync())).events)).toBeUndefined(); + }); + + it("never resumes a goal the user cleared or stopped during the wait", async () => { + const confirmed = await pausedForCard(); + const cleared = await run(confirmed, { + type: "thread.goal.clear", + commandId: CommandId.make("user-clear"), + threadId: THREAD, + createdAt: at(3), + }); + expect(goalRequest((await run(cardAnswered(cleared.model), sync())).events)).toBeUndefined(); + + const stopped = await run(confirmed, { + type: "thread.session.stop", + commandId: CommandId.make("user-stop"), + threadId: THREAD, + createdAt: at(3), + }); + expect(goalOf(stopped.model)?.waitPause).toBe("user"); + expect(goalRequest((await run(cardAnswered(stopped.model), sync())).events)).toBeUndefined(); + }); + + it("leaves a goal that completed alone", async () => { + const paused = await run(withCard(await threadWithActiveGoal()), sync()); + const completed = await run(paused.model, reported("complete")); + expect(goalOf(completed.model)?.waitPause).toBeUndefined(); + expect((await run(cardAnswered(completed.model), sync())).events).toEqual([]); + }); + + it("stays paused while threads it started still owe reports, and until the report's turn runs", async () => { + const base = await threadWithActiveGoal(); + const waitingOnBoth = patchThread(base, (thread) => ({ + childRequests: { ...thread.childRequests, open: [startedThread("awaiting_user")] }, + commandRequests: [commandCard], + })); + const paused = (await run((await run(waitingOnBoth, sync())).model, reported("paused"))).model; + + // The card is answered and the threads start: still waiting on their reports. + const started = patchThread(paused, (thread) => ({ + childRequests: { ...thread.childRequests, open: [startedThread("running")] }, + commandRequests: [], + })); + expect((await run(started, sync())).events).toEqual([]); + + // The last report arrives: its request settles and the report waits in + // the queue to be sent, a turn about to start. The resume waits for it. + const reportQueued = patchThread(started, (thread) => ({ + childRequests: { ...thread.childRequests, open: [] }, + queuedFollowUps: [ + { + messageId: MessageId.make("report"), + text: "ok", + attachments: [], + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(4), + }, + ], + })); + expect((await run(reportQueued, sync())).events).toEqual([]); + + // Sent: the session is starting its turn. + const reportStarting = patchThread(reportQueued, () => ({ + queuedFollowUps: [], + session: { + threadId: THREAD, + status: "starting", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: at(4), + }, + })); + expect((await run(reportStarting, sync())).events).toEqual([]); + + // Running now: the goal carries on after that turn. + const reportRunning = patchThread(reportStarting, (thread) => ({ + session: { ...thread.session!, status: "running", activeTurnId: TurnId.make("report") }, + })); + expect(goalRequest((await run(reportRunning, sync())).events)).toMatchObject({ + status: "active", + origin: "automatic", + }); + }); + + it("waits for a command's output to go back, not just for the command to finish", async () => { + const run1 = { + runId: "run-1", + terminalId: "terminal-1", + mode: "run", + dialect: "posix", + command: "pnpm install", + source: { kind: "request", requestId: commandCard.requestId }, + turnId: TurnId.make("turn-1"), + participantId: null, + cwd: "/repo", + autoSend: true, + status: "finished", + startedAt: at(2), + finishedAt: at(3), + exitCode: 0, + error: null, + hasOutput: true, + heldReason: null, + outputSentAt: null, + outputMessageId: null, + createdAt: at(2), + updatedAt: at(3), + } as unknown as NonNullable[number]; + const finished = patchThread(await pausedForCard(), () => ({ commandRuns: [run1] })); + expect((await run(finished, sync())).events).toEqual([]); + const sent = patchThread(finished, () => ({ + commandRuns: [{ ...run1, outputSentAt: at(4) }], + session: { + threadId: THREAD, + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: TurnId.make("output"), + lastError: null, + updatedAt: at(4), + }, + })); + expect(goalRequest((await run(sent, sync())).events)).toMatchObject({ status: "active" }); + }); + + it("pauses for a scheduled-task card, which the scheduler holds", async () => { + const paused = await run(await threadWithActiveGoal(), sync(true)); + expect(goalRequest(paused.events)).toMatchObject({ status: "paused" }); + }); + + it("resumes after a restart, and sends an unconfirmed resume again only then", async () => { + // The mark is part of the goal the projection keeps, so it is there + // after a restart: only the answer is new. + const answered = cardAnswered(await pausedForCard()); + const resumed = await run(answered, sync()); + expect(goalRequest(resumed.events)).toMatchObject({ status: "active" }); + // Not confirmed yet: an ordinary look sends nothing more. + expect((await run(resumed.model, sync())).events).toEqual([]); + // The server restarted before the provider got it: it goes again. + expect( + goalRequest((await run(resumed.model, sync(false, { retryResume: true }))).events), + ).toMatchObject({ status: "active" }); + }); + + it("pauses again, sent, when a new wait starts before a resume was confirmed", async () => { + const resumed = (await run(cardAnswered(await pausedForCard()), sync())).model; + // The card came back (an undo) while the resume was on its way. + const again = await run(withCard(resumed), sync()); + expect(goalRequest(again.events)).toMatchObject({ status: "paused", origin: "automatic" }); + expect(goalOf(again.model)?.waitPause).toBe("paused"); + // The resume lands first, then the pause: it stays ours, and paused. + const active = (await run(again.model, reported("active"))).model; + expect(goalOf(active)?.waitPause).toBe("paused"); + }); + + it("keeps the user's pause when the only wait is a scheduled-task card", async () => { + // The decider can't see the scheduler's card when the user pauses; the + // reactor says the user acted. + const userPaused = await run(await threadWithActiveGoal(), userGoal("paused")); + expect(goalOf(userPaused.model)?.waitPause).toBeUndefined(); + const taken = await run(userPaused.model, sync(true, { userActed: true })); + expect(goalRequest(taken.events)).toBeUndefined(); + expect(goalOf(taken.model)?.waitPause).toBe("user"); + // Our own look while the provider still reports it active: no pause of ours. + expect((await run(taken.model, sync(true))).events).toEqual([]); + // The card answered: nothing resumes it. + const confirmed = (await run(taken.model, reported("paused"))).model; + expect(goalRequest((await run(confirmed, sync(false))).events)).toBeUndefined(); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index e35929211..87322acc1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -145,6 +145,13 @@ import { } from "./threadMoveDecisions.ts"; import { carriedBackgroundTasks } from "./sessionBackgroundTasks.ts"; import { questionsClosedByUserMessage, unansweredResponseRefusal } from "./userInput.ts"; +import { + carriedGoalWaitMark, + goalWaitOf, + goalWaitStep, + type GoalWaitMark, + turnAboutToStart, +} from "@threadlines/shared/goalWaitPause"; import { isContinueTrigger, RESTART_CONTINUE_MESSAGE, @@ -436,6 +443,56 @@ function passCeilingCancelEvents( ]; } +/** The goal with `mark` (or none), as `thread.goal-state-set`. */ +function goalWithWaitMark( + thread: OrchestrationThread, + mark: GoalWaitMark | null, + command: Pick & { + readonly threadId: ThreadId; + readonly createdAt: string; + }, +): PlannedOrchestrationEvent[] { + const goal = thread.goal ?? null; + if (goal === null || (goal.waitPause ?? null) === mark) return []; + const { waitPause: _mark, ...unmarked } = goal; + return [ + { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: {}, + }), + type: "thread.goal-state-set", + payload: { + threadId: command.threadId, + goal: mark === null ? unmarked : { ...unmarked, waitPause: mark }, + updatedAt: command.createdAt, + }, + }, + ]; +} + +/** + * The user paused, resumed, edited, cleared or stopped the goal: if it is + * paused for a wait, or the thread waits now, it is the user's for this wait, + * and nothing automatic undoes their choice (docs/design/goal-wait-pause.md). + * A scheduled-task card isn't on the thread; a goal waiting only on one and + * not yet paused is the one case this can't see. + */ +function goalTakenByUser( + thread: OrchestrationThread, + command: Pick & { + readonly threadId: ThreadId; + readonly createdAt: string; + }, +): PlannedOrchestrationEvent[] { + if ((thread.goal ?? null) === null) return []; + const waits = thread.goal?.waitPause !== undefined || goalWaitOf(thread, false) !== null; + return waits ? goalWithWaitMark(thread, "user", command) : []; +} + /** * Marks an outside agent's message that never reached the agent `notSent` * (docs/design/outside-agents.md): the event every client already reads as @@ -4621,6 +4678,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...decideAgentChainStop(thread, base, command.createdAt), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), + // Stop is the user's say: a goal paused for a wait stays as Stop + // leaves it, never resumed when the waits Stop ends are over. + ...goalTakenByUser(thread, command), ]; const stopsTurnId = command.turnId ?? turnBeingStopped(thread); const interruptEvent: PlannedOrchestrationEvent = { @@ -4967,6 +5027,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...decideAgentChainStop(thread, base, command.createdAt), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), + // Stop is the user's say: a goal paused for a wait stays as Stop + // leaves it, never resumed when the waits Stop ends are over. + ...goalTakenByUser(thread, command), ]; const stopsTurnId = turnBeingStopped(thread); const stopEvent: PlannedOrchestrationEvent = { @@ -5507,53 +5570,107 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // Resume on a moved thread whose agent hasn't been given the // conversation yet: no provider call, the goal waits for the message // that gives it (docs/design/fleet.md, Part 3e, (a)). + // The user's own pause, resume or edit stands: a goal Threadlines paused + // for a wait, or one whose thread waits now, is theirs for this wait. + const unmarked = goalTakenByUser(goalThread, command); const movedResume = decideMovedGoalResume( goalThread, command, childEventBase(command, command.createdAt), ); if (movedResume !== null) { - return yield* planChildThreadDecision(command.type, movedResume); + const moved = yield* planChildThreadDecision(command.type, movedResume); + return [...unmarked, ...(Array.isArray(moved) ? moved : [moved])]; } - return { - ...withEventBase({ - aggregateKind: "thread", - aggregateId: command.threadId, - occurredAt: command.createdAt, - commandId: command.commandId, - metadata: {}, - }), - type: "thread.goal-set-requested", - payload: { - threadId: command.threadId, - ...(command.objective !== undefined ? { objective: command.objective } : {}), - ...(command.status !== undefined ? { status: command.status } : {}), - ...(command.tokenBudget !== undefined ? { tokenBudget: command.tokenBudget } : {}), - createdAt: command.createdAt, + return [ + ...unmarked, + { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: {}, + }), + type: "thread.goal-set-requested", + payload: { + threadId: command.threadId, + ...(command.objective !== undefined ? { objective: command.objective } : {}), + ...(command.status !== undefined ? { status: command.status } : {}), + ...(command.tokenBudget !== undefined ? { tokenBudget: command.tokenBudget } : {}), + createdAt: command.createdAt, + }, }, - }; + ]; } case "thread.goal.clear": { - yield* requireThread({ + const clearedThread = yield* requireThread({ readModel, command, threadId: command.threadId, }); - return { - ...withEventBase({ - aggregateKind: "thread", - aggregateId: command.threadId, - occurredAt: command.createdAt, - commandId: command.commandId, - metadata: {}, - }), - type: "thread.goal-clear-requested", - payload: { - threadId: command.threadId, - createdAt: command.createdAt, + return [ + // Nothing resumes a goal the user cleared, whatever the provider says first. + ...goalTakenByUser(clearedThread, command), + { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: {}, + }), + type: "thread.goal-clear-requested", + payload: { + threadId: command.threadId, + createdAt: command.createdAt, + }, }, - }; + ]; + } + + // The goal pauses while the thread waits on a card or on threads it + // started, and resumes when that wait ends (docs/design/goal-wait-pause.md). + case "thread.goal.wait.sync": { + const thread = yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const step = goalWaitStep({ + goal: thread.goal, + waiting: goalWaitOf(thread, command.scheduleAnswerWaiting) !== null, + turnStarting: turnAboutToStart(thread), + userActed: command.userActed, + retryResume: command.retryResume, + }); + if (step === null) { + return []; + } + return [ + ...goalWithWaitMark(thread, step.mark, command), + ...(step.send === null + ? [] + : [ + { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + metadata: {}, + }), + type: "thread.goal-set-requested" as const, + payload: { + threadId: command.threadId, + status: step.send, + origin: "automatic" as const, + createdAt: command.createdAt, + }, + }, + ]), + ]; } case "thread.check-backs.set": { @@ -5619,11 +5736,22 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" } case "thread.goal.state.set": { - yield* requireThread({ + const goalThread = yield* requireThread({ readModel, command, threadId: command.threadId, }); + // A goal's wait mark lives through the provider's reports while it + // means something (carriedGoalWaitMark); the provider's own copy of the + // goal never carries one. + const { waitPause: _reported, ...reported } = command.goal ?? {}; + const carried = carriedGoalWaitMark(goalThread.goal, command.goal); + const goal = + command.goal === null + ? null + : carried === undefined + ? (reported as typeof command.goal) + : { ...command.goal, waitPause: carried }; return { ...withEventBase({ aggregateKind: "thread", @@ -5635,7 +5763,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" type: "thread.goal-state-set", payload: { threadId: command.threadId, - goal: command.goal, + goal, updatedAt: command.createdAt, }, }; diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index a09e9a141..cd58c1ee0 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -1969,6 +1969,33 @@ routing.layer("ProviderServiceLive routing", (it) => { }), ); + it.effect( + "sends a goal pause Threadlines made for a wait as automatic, and a user's as theirs", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const threadId = asThreadId("thread-goal-wait-pause"); + + yield* provider.startSession(threadId, { + provider: CODEX_DRIVER, + providerInstanceId: codexInstanceId, + threadId, + cwd: "/tmp/project-goal-wait", + runtimeMode: "full-access", + }); + yield* provider.setThreadGoal({ threadId, objective: "Count to eight" }); + routing.codex.setThreadGoal.mockClear(); + + yield* provider.setThreadGoal({ threadId, status: "paused", origin: "automatic" }); + yield* provider.setThreadGoal({ threadId, status: "active" }); + + assert.deepEqual(routing.codex.setThreadGoal.mock.calls, [ + [{ threadId, status: "paused", origin: "automatic" }], + [{ threadId, status: "active", origin: "user" }], + ]); + }), + ); + it.effect("does not recover a stopped session just to pause its goal", () => Effect.gen(function* () { const provider = yield* ProviderService; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 0cc8f4e49..bd3eff178 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -125,6 +125,7 @@ const ProviderSetThreadGoalServiceInput = Schema.Struct({ tokenBudget: Schema.optional(Schema.NullOr(NonNegativeInt)), modelSelection: Schema.optional(ModelSelection), context: Schema.optional(Schema.String), + origin: Schema.optional(Schema.Literals(["user", "automatic"])), }); const ProviderClearThreadGoalServiceInput = Schema.Struct({ threadId: ThreadId, @@ -2360,7 +2361,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( } const goal = yield* routed.adapter.setThreadGoal({ threadId: routed.threadId, - origin: "user", + origin: input.origin ?? "user", ...(input.objective !== undefined ? { objective: input.objective } : {}), ...(input.status !== undefined ? { status: input.status } : {}), ...(input.tokenBudget !== undefined ? { tokenBudget: input.tokenBudget } : {}), diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 7253d7eaf..47e07b99d 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -273,6 +273,8 @@ export interface ProviderServiceShape { /** What the agent reads ahead of the goal's work (a lead chat's role). * See `ProviderSetThreadGoalInput.context`. */ readonly context?: string; + /** Who asked; the user when absent. See `ProviderSetThreadGoalInput.origin`. */ + readonly origin?: "user" | "automatic"; }) => Effect.Effect; /** diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 083cbed54..6c1abd177 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -89,6 +89,7 @@ import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRun import { RealtimeVoiceDevicesLive } from "./orchestration/Layers/RealtimeVoiceDevices.ts"; import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts"; import { ChildThreadReactorLive } from "./orchestration/Layers/ChildThreadReactor.ts"; +import { GoalWaitReactorLive } from "./orchestration/Layers/GoalWaitReactor.ts"; import { ThreadContextSeedBuilderLive } from "./provider/contextSeed/ThreadContextSeedBuilder.ts"; import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts"; import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts"; @@ -374,8 +375,12 @@ const ReactorLayerLive = Layer.empty.pipe( Layer.provideMerge(OrchestrationReactorLive), Layer.provideMerge(ProviderRuntimeIngestionLive), Layer.provideMerge(ProviderCommandReactorLive), - // Both reactors above take these (optionally), so they come after them. - Layer.provideMerge(Layer.mergeAll(RemoteRequestTurnEndsLive, RemoteRequestGateLive)), + // Both reactors above take the remote request layers (optionally), so they + // come after them. The goal wait reactor (started by the orchestration + // reactor) reads the scheduler's waiting cards, so it comes before it. + Layer.provideMerge( + Layer.mergeAll(GoalWaitReactorLive, RemoteRequestTurnEndsLive, RemoteRequestGateLive), + ), // Ingestion reads who spoke; the WebSocket route notes it. Layer.provideMerge(RealtimeVoiceDevicesLive), Layer.provideMerge(ScheduledTasksLayerLive), diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 24ad32698..ff2a98577 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -253,12 +253,14 @@ import { } from "../../lib/providerUsage"; import { formatProviderSkillDisplayName } from "../../providerSkillPresentation"; import { resolveFileAttachmentType } from "@threadlines/shared/fileAttachments"; +import { goalWaitPauseLabel } from "@threadlines/shared/goalWaitPause"; +import { scopeThreadRef } from "@threadlines/client-runtime"; import { searchProviderSkills } from "../../providerSkillSearch"; import { resolveComposerSkillReferences } from "../../providerSkillReferences"; import { useIsPhoneViewport } from "../../hooks/useMediaQuery"; import { ComposerDictationControl } from "./ComposerDictationControl"; import { useDictation } from "../../dictation/useDictation"; -import { useStore } from "../../store"; +import { selectSidebarThreadSummaryByRef, useStore } from "../../store"; import { readLeadProjectName } from "../../leadChat"; const ATTACHMENT_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; @@ -922,6 +924,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const workflowKeywordActive = selectedProvider === CLAUDE_AGENT_PROVIDER && containsWorkflowKeyword(prompt); const threadGoal = optimisticGoal ?? activeThread?.goal ?? null; + // A goal Threadlines paused while the thread waits says what for, in the + // words the sidebar's facts give (a card, or threads at work). + const goalWaitLabel = useStore((store) => + (threadGoal?.waitPause === "paused" || threadGoal?.waitPause === "resuming") && + threadGoal.status === "paused" && + activeThread + ? goalWaitPauseLabel( + selectSidebarThreadSummaryByRef( + store, + scopeThreadRef(activeThread.environmentId, activeThread.id), + ) ?? {}, + ) + : null, + ); const goalSupported = goalControls != null && activeThreadId !== null && @@ -3851,6 +3867,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
): OrchestrationThreadGoal => ({ @@ -23,6 +25,7 @@ const renderBar = (input: { readonly driver: string; readonly goal: OrchestrationThreadGoal | null; readonly editorOpen?: boolean; + readonly waitLabel?: string | null; }) => { const controls = threadGoalControls(ProviderDriverKind.make(input.driver)); if (controls === null) throw new Error(`${input.driver} has no goals`); @@ -30,6 +33,7 @@ const renderBar = (input: { render( { expect(onSetGoal).toHaveBeenCalledWith({ objective: "Make the build pass" }); }); + it("says why Threadlines paused a goal while its thread waits, and still offers Resume", async () => { + renderBar({ + driver: "codex", + goal: goal({ status: "paused", waitPause: "paused" }), + waitLabel: goalWaitPauseLabel({ pendingChildApproval: true, awaitedChildThreadCount: 0 }), + }); + await expect.element(page.getByText("Paused until you answer")).toBeVisible(); + await expect.element(page.getByRole("button", { name: "Resume goal" })).toBeVisible(); + // After Start, the threads it started are what it waits on. + expect(goalWaitPauseLabel({ awaitedChildThreadCount: 1 })).toBe( + "Paused while its threads work", + ); + }); + it("keeps Codex's tokens, budget and pause", async () => { renderBar({ driver: "codex", goal: goal({ tokenBudget: 50_000 }) }); await expect.element(page.getByText("12k / 50k")).toBeVisible(); diff --git a/apps/web/src/components/chat/ComposerGoalBar.tsx b/apps/web/src/components/chat/ComposerGoalBar.tsx index 5a5f344ff..491d52413 100644 --- a/apps/web/src/components/chat/ComposerGoalBar.tsx +++ b/apps/web/src/components/chat/ComposerGoalBar.tsx @@ -58,6 +58,8 @@ export function formatGoalChecks(checks: number): string { interface ComposerGoalBarProps { readonly goal: OrchestrationThreadGoal | null; + /** Why Threadlines paused the goal while the thread waits; null when it didn't. */ + readonly waitLabel?: string | null; readonly controls: ThreadGoalControls; readonly editorOpen: boolean; readonly isDispatching: boolean; @@ -124,6 +126,7 @@ function parseTokenBudgetDraft(draft: string): number | null | undefined { */ export function ComposerGoalBar({ goal, + waitLabel = null, controls, editorOpen, isDispatching, @@ -187,6 +190,11 @@ export function ComposerGoalBar({ > {goal.objective} + {waitLabel !== null ? ( + + {waitLabel} + + ) : null} {controls.progress === "checks" ? ( formatGoalChecks(goal.checks ?? 0) diff --git a/docs/design/goal-wait-pause.md b/docs/design/goal-wait-pause.md new file mode 100644 index 000000000..148d829aa --- /dev/null +++ b/docs/design/goal-wait-pause.md @@ -0,0 +1,94 @@ +# A goal pauses while its thread waits + +A goal keeps an agent working across turns. When the agent asks for something +through a card and gets control back at once, or starts threads and waits for +their reports, the goal would keep running turns that can only say "still +pending". On Codex that was three turns before Codex marked the goal blocked, +and more while started threads worked. So Threadlines pauses the goal while +the thread waits, and resumes it when the wait ends. + +## What counts as waiting + +`goalWaitOf` in `packages/shared/src/goalWaitPause.ts`, from the same facts the +sidebar reads: + +- **A card only the user can answer:** threads waiting for approval to start, + a settings change, an invite, a command card not yet run or skipped (or run, + with its output still to go back: a run's finish is recorded a moment before + its output is sent), a scheduled-task card (the scheduler holds those: + `ScheduledTasks.waitingThreadIds`). +- **Threads it started that still owe their reports** (`awaitedChildRequestCount`). + +A permission prompt or a question is not here: the turn that asked is still +running, and nothing loops. + +## The mark + +The goal carries `waitPause` (an optional field, not a new `ThreadGoalStatus` +value, which clients decode as a closed set): + +- `paused`: Threadlines paused it for the wait. The provider may not have + confirmed yet, so the mark stays while the goal reads active or paused. +- `resuming`: the wait ended and the resume went out. It stays until the + provider reports the goal active, so a restart in between sends it again. +- `user`: the user paused, resumed, edited, cleared or stopped the goal during + the wait (or while it was paused for one). Nothing automatic happens until + that wait is over; then the mark goes and the goal stays as the user left it. + The decider marks it when it sees the user's command; a wait on a + scheduled-task card is the scheduler's, not the thread's, so the reactor + also reports each user action (`userActed` on the sync). + +A provider report keeps the mark only while it means something +(`carriedGoalWaitMark`); a goal that completed, blocked or hit a limit loses +`paused`, and a completed or cleared one loses any mark. + +## The rule + +`goalWaitStep`, applied by the decider on `thread.goal.wait.sync` (server only): + +- Waiting, the goal active and unmarked: pause it (`paused`), and send + `thread/goal/set` paused with `origin: "automatic"`, which Codex keeps out of + the model's history. +- The wait is over and the goal is paused with `paused`: resume it + (`resuming`, `thread/goal/set` active, automatic). A resume not yet confirmed + is sent again only on the reactor's pass at startup (`retryResume`), never on + every look. Not while a turn is + about to start (the session is starting one, or a message waits in the + queue): resumed while idle, Codex starts a goal turn at once, and it would + race the turn that ended the wait. A report from a thread it started is + queued in the same decision that settles its request, so the resume lands + once the report's own turn runs, and the goal carries on inside it. +- The wait is over and the mark is `user`: drop it, send nothing. +- Waiting again before a resume was confirmed: back to `paused`, and the pause + is sent, so a resume still on its way doesn't win. + +The provider reactor sends an automatic pause or resume only while the goal +still carries that intent when it gets to it (`paused` for a pause, `resuming` +on a paused goal for a resume): a goal the user took over, or that the +provider ended or blocked in between, is left alone. + +## Who asks + +`GoalWaitReactor` watches the events that change a wait or the goal (cards and +their runs, started threads, the queue, the session, the goal, reverts, agents +leaving) and the scheduler's waiting cards, and sends the sync for a thread +whose goal should change, saying when the user acted on the goal or pressed +Stop. At start it looks at every thread with a goal once, which also resends a +resume a restart cut off. It skips a pause or resume for +a provider that can't pause a goal. + +## Per provider + +- **Codex:** paused and resumed as above. Codex finishes a turn already running + when the pause lands and starts nothing after it. +- **Claude:** not supported. Its goal is `/goal` with Claude Code's own Stop + hook, which keeps one turn going until its evaluator is satisfied. There is + no pause (`threadGoalPause: "unsupported"`), and clearing and setting it again + would lose its checks and change what the user sees. +- **OpenCode, Muse Code, Pi, the ACP agents:** no goals. + +## On screen + +The goal bar shows "Paused until you answer", or "Paused while its threads +work" once the card is answered and threads are running, beside the objective. +Resume and clear stay available. diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 629742824..168c1de34 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -2152,6 +2152,14 @@ export const OrchestrationThreadGoal = Schema.Struct({ checks: Schema.optional(NonNegativeInt), /** Claude: the evaluator's latest reason (not met yet, or why it is done). */ lastCheck: Schema.optional(TrimmedNonEmptyString), + /** + * Threadlines pauses a goal while the thread waits on a card or on threads + * it started, and resumes it when that wait ends (docs/design/goal-wait-pause.md). + * `paused`: paused for the wait. `resuming`: the resume went out, not yet + * confirmed. `user`: the user acted on it during the wait, so nothing + * automatic happens until the wait is over. + */ + waitPause: Schema.optional(Schema.Literals(["paused", "resuming", "user"])), }); export type OrchestrationThreadGoal = typeof OrchestrationThreadGoal.Type; @@ -4377,6 +4385,25 @@ const ThreadCheckBacksSetCommand = Schema.Struct({ createdAt: IsoDateTime, }); +/** + * Server-internal: bring the thread's goal in line with what the thread waits + * on (docs/design/goal-wait-pause.md). The decider pauses an active goal while + * the thread waits, and resumes one it paused when the wait is over; anything + * else is a no-op. `scheduleAnswerWaiting`: a card asks the user about its + * agent's scheduled-task change, which the scheduler holds, not the thread. + */ +const ThreadGoalWaitSyncCommand = Schema.Struct({ + type: Schema.Literal("thread.goal.wait.sync"), + commandId: CommandId, + threadId: ThreadId, + scheduleAnswerWaiting: Schema.Boolean, + /** The user acted on the goal (pause, resume, edit, clear, Stop) since the last look. */ + userActed: Schema.optional(Schema.Boolean), + /** Send a resume not yet confirmed again (after a restart). */ + retryResume: Schema.optional(Schema.Boolean), + createdAt: IsoDateTime, +}); + /** Provider-internal: record provider-reported goal state (null when the * provider cleared it). Emitted by runtime ingestion off `goal.updated` / * `goal.cleared` events. */ @@ -5872,6 +5899,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadGoalSetCommand, ThreadGoalClearCommand, ThreadGoalStateSetCommand, + ThreadGoalWaitSyncCommand, ThreadMessageUserRecordCommand, ThreadMessageAssistantDeltaCommand, ThreadMessageAssistantCompleteCommand, @@ -6854,6 +6882,8 @@ export const ThreadGoalSetRequestedPayload = Schema.Struct({ objective: Schema.optional(TrimmedNonEmptyString), status: Schema.optional(ThreadGoalStatus), tokenBudget: Schema.optional(Schema.NullOr(NonNegativeInt)), + /** Threadlines paused or resumed it for a wait, not the user (`thread.goal.wait.sync`). */ + origin: Schema.optional(Schema.Literal("automatic")), createdAt: IsoDateTime, }); diff --git a/packages/shared/package.json b/packages/shared/package.json index b843a0dea..5d45f5a4e 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -431,6 +431,10 @@ "types": "./src/childThreads.ts", "import": "./src/childThreads.ts" }, + "./goalWaitPause": { + "types": "./src/goalWaitPause.ts", + "import": "./src/goalWaitPause.ts" + }, "./projectLead": { "types": "./src/projectLead.ts", "import": "./src/projectLead.ts" diff --git a/packages/shared/src/goalWaitPause.ts b/packages/shared/src/goalWaitPause.ts new file mode 100644 index 000000000..da4aa9318 --- /dev/null +++ b/packages/shared/src/goalWaitPause.ts @@ -0,0 +1,187 @@ +/** + * A goal pauses while its thread waits on something that will wake the agent + * by itself, and carries on when the wait ends (docs/design/goal-wait-pause.md). + * + * An agent working toward a goal often asks for something through a card and + * gets control back at once: threads to start, a scheduled task, a settings + * change, an invite, a command for the user to run. Or it starts threads and + * waits for their reports. The goal would otherwise keep running turns that + * can only say "still pending". The server pauses it then, and keeps a mark + * on the goal (`waitPause`) so that only its own pause is ever undone: + * + * - `paused`: paused for the wait (the provider may not have confirmed yet). + * - `resuming`: the wait ended and the resume went out; the mark goes when the + * provider reports the goal active, so a restart in between sends it again. + * - `user`: the user paused, resumed, edited, cleared or stopped it during the + * wait. Nothing automatic happens until that wait is over; then it goes. + */ +import type { OrchestrationThread, OrchestrationThreadGoal } from "@threadlines/contracts"; + +import { awaitedChildRequestCount, hasPendingChildApproval } from "./childThreads.ts"; +import { commandRunAwaitsAutoSend, isCommandRunSettled } from "./commandRuns.ts"; +import { awaitingInvite } from "./roomAgentRequests.ts"; +import { hasPendingSettingsChange } from "./settingsChangeState.ts"; + +/** What the thread waits on: the user's answer on a card, or threads it started. */ +export type GoalWait = "user" | "threads"; + +/** The mark a goal carries for a wait (OrchestrationThreadGoal.waitPause). */ +export type GoalWaitMark = NonNullable; + +type GoalWaitFacts = Pick< + OrchestrationThread, + "childRequests" | "settingsRequests" | "agentRequests" | "commandRequests" | "commandRuns" +>; + +/** + * A run whose output goes back to the agent by itself and hasn't yet: still + * running, or finished with its output on the way (the finish is recorded a + * moment before the output is sent). Held output waits for the user to send + * it, which no card asks for. + */ +const outputStillComing = (run: NonNullable[number]): boolean => + commandRunAwaitsAutoSend(run) && + run.heldReason === null && + (!isCommandRunSettled(run.status) || run.status === "finished"); + +/** + * A command card the user hasn't run or skipped, or one they ran whose output + * hasn't gone back yet: its output wakes the agent that asked. + */ +function hasWaitingCommandCard(thread: GoalWaitFacts): boolean { + const allRuns = thread.commandRuns ?? []; + return (thread.commandRequests ?? []).some((request) => { + if (request.dismissedAt !== null) return false; + const runs = allRuns.filter( + (run) => run.source.kind === "request" && run.source.requestId === request.requestId, + ); + return runs.length === 0 || runs.some(outputStillComing); + }); +} + +/** + * What the thread waits on that will wake its agent by itself, if anything. + * A card only the user can answer comes first; then threads it started that + * still owe their reports. `scheduleAnswerWaiting`: a card asks the user about + * its agent's scheduled-task change (the scheduler holds those, not the thread). + * A permission prompt or a question is not here: the turn that asked is still + * running, and nothing loops while it waits. + */ +export function goalWaitOf(thread: GoalWaitFacts, scheduleAnswerWaiting: boolean): GoalWait | null { + if ( + scheduleAnswerWaiting || + hasPendingChildApproval(thread.childRequests) || + hasPendingSettingsChange(thread.settingsRequests) || + awaitingInvite(thread.agentRequests) !== undefined || + hasWaitingCommandCard(thread) + ) { + return "user"; + } + return awaitedChildRequestCount(thread.childRequests) > 0 ? "threads" : null; +} + +/** + * Whether a turn is about to start: the session is starting one, or a message + * waits in the queue to go next (a report from a thread it started is queued + * in the same decision that settles its request, then sent). + */ +export function turnAboutToStart( + thread: Pick, +): boolean { + return thread.session?.status === "starting" || (thread.queuedFollowUps ?? []).length > 0; +} + +/** + * What to do with the thread's goal now: the mark it should carry, and what + * to send the provider, if anything. Null: leave it as it is. + * + * - The user acted on the goal (`userActed`: a pause, resume, edit, clear or + * Stop) while the thread waits or while it carries our mark: it is theirs + * for this wait. + * - Waiting, an active goal with no mark: pause it. + * - The wait is over and we paused it: resume it, marked `resuming` until the + * provider confirms. A resume not yet confirmed is sent again only when + * asked (`retryResume`: after a restart), never on every look. Not while a + * turn is about to start: resumed while idle, the provider starts a goal + * turn of its own, and it would race the turn that ended the wait (a report, + * a command's output). Resumed while that turn runs, the goal carries on + * after it. + * - The wait is over and the user acted during it: forget the mark. + * - Waiting again before a resume was confirmed: pause it again, sent, so a + * resume still on its way doesn't win. + */ +export function goalWaitStep(input: { + readonly goal: Pick | null; + readonly waiting: boolean; + readonly turnStarting: boolean; + readonly userActed?: boolean | undefined; + readonly retryResume?: boolean | undefined; +}): { readonly mark: GoalWaitMark | null; readonly send: "paused" | "active" | null } | null { + const { goal } = input; + if (goal === null) return null; + const mark = goal.waitPause; + if (input.userActed === true && mark !== "user" && (input.waiting || mark !== undefined)) { + return { mark: "user", send: null }; + } + if (input.waiting) { + if (mark === undefined) { + return goal.status === "active" ? { mark: "paused", send: "paused" } : null; + } + return mark === "resuming" ? { mark: "paused", send: "paused" } : null; + } + if (mark === "user") return { mark: null, send: null }; + if (mark === "paused" || mark === "resuming") { + if (goal.status === "paused") { + if (input.turnStarting || (mark === "resuming" && input.retryResume !== true)) return null; + return { mark: "resuming", send: "active" }; + } + // Active with `paused`: our pause is on its way; with `resuming`: our + // resume, confirmed in the next report. Anything else is the provider's + // own ending, not ours to undo. + return goal.status === "active" ? null : { mark: null, send: null }; + } + return null; +} + +/** + * The mark a goal the provider reported keeps: ours while the goal is still + * active (a pause on its way) or paused; `resuming` until the provider says it + * is active again; the user's until the goal is gone or complete. + */ +export function carriedGoalWaitMark( + previous: Pick | null, + next: Pick | null, +): GoalWaitMark | undefined { + const mark = previous?.waitPause; + if (mark === undefined || next === null || next.status === "complete") return undefined; + switch (mark) { + case "paused": + return next.status === "active" || next.status === "paused" ? "paused" : undefined; + case "resuming": + return next.status === "paused" ? "resuming" : undefined; + case "user": + return "user"; + } +} + +/** + * The goal bar's words for a goal this paused, read from the facts the + * sidebar reads, so the two never disagree: a card first, else the threads + * at work. + */ +export function goalWaitPauseLabel(thread: { + readonly pendingChildApproval?: boolean | undefined; + readonly pendingSettingsChange?: boolean | undefined; + readonly pendingScheduleApproval?: boolean | undefined; + readonly hasPendingUserInput?: boolean | undefined; + readonly awaitedChildThreadCount?: number | undefined; +}): string { + const cardWaits = + thread.pendingChildApproval === true || + thread.pendingSettingsChange === true || + thread.pendingScheduleApproval === true || + thread.hasPendingUserInput === true; + return !cardWaits && (thread.awaitedChildThreadCount ?? 0) > 0 + ? "Paused while its threads work" + : "Paused until you answer"; +}