From dd1f3bee1b8c89e28f2639d951fb3503200f3959 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:19:09 -0500 Subject: [PATCH 1/4] feat: a goal pauses while its thread waits on you or on threads it started A Codex goal whose agent asked for something through a card (threads to start, a scheduled task, a settings change, an invite, a command to run) kept running turns that could only say "still pending", and again while the threads it started worked. Threadlines now pauses the goal while the thread waits and resumes it when the wait ends. - goalWaitOf/goalWaitStep (shared) say what the thread waits on and what the goal should do; the decider applies them on the server-only thread.goal.wait.sync, sent by the new GoalWaitReactor. - The pause is marked on the goal (pausedForWait, optional) and sent to Codex with origin automatic. The user's own pause, resume, edit or clear drops the mark; a goal that completes or hits a limit loses it. - A resume waits while a turn is about to start, so a report never gets a second goal turn beside it. - The goal bar says "Paused until you answer" or "Paused while its threads work". Claude's goals have no pause and are left alone. --- .../OrchestrationEngineHarness.integration.ts | 7 + apps/server/src/guide/topics.ts | 2 + .../orchestration/Layers/GoalWaitReactor.ts | 160 ++++++++++ .../Layers/OrchestrationReactor.test.ts | 13 +- .../Layers/OrchestrationReactor.ts | 3 + .../Layers/ProviderCommandReactor.ts | 2 + .../orchestration/Services/GoalWaitReactor.ts | 30 ++ .../orchestration/decider.goalWait.test.ts | 285 ++++++++++++++++++ apps/server/src/orchestration/decider.ts | 156 ++++++++-- .../provider/Layers/ProviderService.test.ts | 27 ++ .../src/provider/Layers/ProviderService.ts | 3 +- .../src/provider/Services/ProviderService.ts | 2 + apps/server/src/server.ts | 9 +- apps/web/src/components/chat/ChatComposer.tsx | 17 +- .../chat/ComposerGoalBar.browser.tsx | 18 ++ .../src/components/chat/ComposerGoalBar.tsx | 8 + docs/design/goal-wait-pause.md | 66 ++++ packages/contracts/src/orchestration.ts | 24 ++ packages/shared/package.json | 4 + packages/shared/src/goalWaitPause.ts | 126 ++++++++ 20 files changed, 929 insertions(+), 33 deletions(-) create mode 100644 apps/server/src/orchestration/Layers/GoalWaitReactor.ts create mode 100644 apps/server/src/orchestration/Services/GoalWaitReactor.ts create mode 100644 apps/server/src/orchestration/decider.goalWait.test.ts create mode 100644 docs/design/goal-wait-pause.md create mode 100644 packages/shared/src/goalWaitPause.ts 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 821d2291e..c9c3b3060 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..d00de101f --- /dev/null +++ b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts @@ -0,0 +1,160 @@ +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 } 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 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.session-set", + "thread.goal-state-set", +] as const; + +const changesWait = (event: OrchestrationEvent): boolean => + event.aggregateKind === "thread" && + WAIT_EVENT_PREFIXES.some((prefix) => event.type.startsWith(prefix)); + +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) { + 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: thread.session?.status === "starting", + }); + if (step === null || !(yield* canPauseGoal(thread))) return; + yield* orchestrationEngine + .dispatch({ + type: "thread.goal.wait.sync", + commandId: CommandId.make(`goal-wait-sync:${threadId}:${randomUUID()}`), + threadId, + scheduleAnswerWaiting, + 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: it is read as it stands then. + const queued = new Set(); + const worker = yield* makeDrainableWorker((threadId: ThreadId) => + Effect.sync(() => queued.delete(threadId)).pipe(Effect.andThen(syncThread(threadId))), + ); + const enqueue = (threadId: ThreadId) => + Effect.suspend(() => { + if (queued.has(threadId)) return Effect.void; + queued.add(threadId); + return worker.enqueue(threadId); + }); + + const start: GoalWaitReactorShape["start"] = Effect.fn("start")(function* () { + const events = yield* orchestrationEngine.subscribeDomainEvents; + yield* Effect.forkScoped( + Stream.runForEach(events, (event) => + 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, enqueue, { discard: true }); + }), + ), + ); + } + // Cards answered or threads finished while the server was down. + 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), + { 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 755146296..73aa7ecda 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -4212,6 +4212,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..a12b5e09e --- /dev/null +++ b/apps/server/src/orchestration/decider.goalWait.test.ts @@ -0,0 +1,285 @@ +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): OrchestrationCommand => ({ + type: "thread.goal.wait.sync", + commandId: CommandId.make(`sync-${Math.random()}`), + threadId: THREAD, + scheduleAnswerWaiting, + 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; + +describe("decider goal wait pause", () => { + it("pauses an active goal while a card waits, and resumes it once the card is answered", async () => { + const waiting = patchThread(await threadWithActiveGoal(), () => ({ + commandRequests: [commandCard], + })); + const paused = await run(waiting, sync()); + expect(goalRequest(paused.events)).toMatchObject({ status: "paused", origin: "automatic" }); + expect(goalOf(paused.model)).toMatchObject({ status: "active", pausedForWait: true }); + // Asked again before the provider confirms: nothing more. + expect((await run(paused.model, sync())).events).toEqual([]); + + // The provider confirms; the mark stays through its report. + const confirmed = await run(paused.model, reported("paused")); + expect(goalOf(confirmed.model)).toMatchObject({ status: "paused", pausedForWait: true }); + + const answered = patchThread(confirmed.model, () => ({ + commandRequests: [{ ...commandCard, dismissedAt: at(3) }], + })); + const resumed = await run(answered, sync()); + expect(goalRequest(resumed.events)).toMatchObject({ status: "active", origin: "automatic" }); + expect(goalOf(resumed.model)?.pausedForWait).toBeUndefined(); + }); + + it("leaves the goal to the user once they paused, resumed or cleared it themselves", async () => { + const paused = await run( + patchThread(await threadWithActiveGoal(), () => ({ commandRequests: [commandCard] })), + sync(), + ); + const confirmed = (await run(paused.model, reported("paused"))).model; + const answered = (thread: OrchestrationReadModel) => + patchThread(thread, () => ({ commandRequests: [] })); + + // The user resumed while the card waited: their goal now, never paused again by the answer. + const userResumed = await run(confirmed, { + type: "thread.goal.set", + commandId: CommandId.make("user-resume"), + threadId: THREAD, + status: "active", + createdAt: at(3), + }); + expect(goalOf(userResumed.model)?.pausedForWait).toBeUndefined(); + expect(goalRequest(userResumed.events)).not.toHaveProperty("origin"); + + // The user paused it themselves, then answered: it stays paused. + const userPaused = await run(confirmed, { + type: "thread.goal.set", + commandId: CommandId.make("user-pause"), + threadId: THREAD, + status: "paused", + createdAt: at(3), + }); + expect((await run(answered(userPaused.model), sync())).events).toEqual([]); + + // Cleared: nothing resumes, whatever the provider reports first. + const cleared = await run(confirmed, { + type: "thread.goal.clear", + commandId: CommandId.make("user-clear"), + threadId: THREAD, + createdAt: at(3), + }); + expect(goalOf(cleared.model)?.pausedForWait).toBeUndefined(); + expect((await run(answered(cleared.model), sync())).events).toEqual([]); + }); + + it("leaves a goal that completed alone", async () => { + const paused = await run( + patchThread(await threadWithActiveGoal(), () => ({ commandRequests: [commandCard] })), + sync(), + ); + const completed = await run(paused.model, reported("complete")); + expect(goalOf(completed.model)?.pausedForWait).toBeUndefined(); + const answered = patchThread(completed.model, () => ({ commandRequests: [] })); + expect((await run(answered, sync())).events).toEqual([]); + }); + + it("stays paused while threads it started still owe reports, and until the last wait ends", async () => { + const base = await threadWithActiveGoal(); + const waitingOnBoth = patchThread(base, (thread) => ({ + childRequests: { ...thread.childRequests, open: [startedThread("awaiting_user")] }, + commandRequests: [commandCard], + })); + const paused = (await run(await (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 as a turn about to start: the resume waits for it. + const reportStarting = patchThread(started, (thread) => ({ + childRequests: { ...thread.childRequests, open: [] }, + 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("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 a goal it paused when the wait ended while the server was down", async () => { + // The mark is part of the goal the projection keeps, so it is there + // after a restart: only the answer is new. + const paused = await run( + patchThread(await threadWithActiveGoal(), () => ({ commandRequests: [commandCard] })), + sync(), + ); + const restarted = patchThread((await run(paused.model, reported("paused"))).model, () => ({ + commandRequests: [], + })); + expect(goalRequest((await run(restarted, sync())).events)).toMatchObject({ status: "active" }); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index ebe941540..08924e7dc 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -145,6 +145,7 @@ import { } from "./threadMoveDecisions.ts"; import { carriedBackgroundTasks } from "./sessionBackgroundTasks.ts"; import { questionsClosedByUserMessage, unansweredResponseRefusal } from "./userInput.ts"; +import { goalWaitOf, goalWaitStep, keepsGoalWaitMark } from "@threadlines/shared/goalWaitPause"; import { isContinueTrigger, RESTART_CONTINUE_MESSAGE, @@ -436,6 +437,35 @@ function passCeilingCancelEvents( ]; } +/** + * The goal without the mark of a pause Threadlines made for a wait, as one + * event, when it has one: the user acted on the goal themselves. + */ +function withoutGoalWaitMark( + thread: OrchestrationThread, + command: Pick & { + readonly threadId: ThreadId; + readonly createdAt: string; + }, +): PlannedOrchestrationEvent[] { + const goal = thread.goal; + if (goal?.pausedForWait !== true) return []; + const { pausedForWait: _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: unmarked, updatedAt: command.createdAt }, + }, + ]; +} + type DecideOrchestrationCommandResult = | PlannedOrchestrationEvent | ReadonlyArray; @@ -5424,53 +5454,113 @@ 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 pause Threadlines made + // for a wait is theirs now, never undone when the wait ends. + const unmarked = withoutGoalWaitMark(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({ + return [ + // Nothing resumes a goal the user cleared, whatever the provider says first. + ...withoutGoalWaitMark(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 goal = thread.goal; + const step = goalWaitStep({ + goal, + waiting: goalWaitOf(thread, command.scheduleAnswerWaiting) !== null, + turnStarting: thread.session?.status === "starting", + }); + if (step === null || goal === null) { + return []; + } + const base = () => + 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, + }); + const { pausedForWait: _mark, ...unmarkedGoal } = goal; + return [ + { + ...base(), + type: "thread.goal-state-set", + payload: { + threadId: command.threadId, + goal: step === "pause" ? { ...goal, pausedForWait: true as const } : unmarkedGoal, + updatedAt: command.createdAt, + }, }, - }; + { + ...base(), + type: "thread.goal-set-requested", + payload: { + threadId: command.threadId, + status: step === "pause" ? ("paused" as const) : ("active" as const), + origin: "automatic" as const, + createdAt: command.createdAt, + }, + }, + ]; } case "thread.check-backs.set": { @@ -5536,11 +5626,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" } case "thread.goal.state.set": { - yield* requireThread({ + const goalThread = yield* requireThread({ readModel, command, threadId: command.threadId, }); + // A pause Threadlines made for a wait stays marked through the + // provider's reports while the goal is active or paused; a goal that + // ended or hit a limit is the provider's, and loses it. + const { pausedForWait: _reported, ...reported } = command.goal ?? {}; + const goal = + command.goal === null + ? null + : keepsGoalWaitMark(goalThread.goal, command.goal) + ? { ...command.goal, pausedForWait: true as const } + : (reported as typeof command.goal); return { ...withEventBase({ aggregateKind: "thread", @@ -5552,7 +5652,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 3366df202..b9a216a29 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -1910,6 +1910,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 b2a7405f0..b34d54c09 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, @@ -2347,7 +2348,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..840416939 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,18 @@ 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?.pausedForWait === true && threadGoal.status === "paused" && activeThread + ? goalWaitPauseLabel( + selectSidebarThreadSummaryByRef( + store, + scopeThreadRef(activeThread.environmentId, activeThread.id), + ) ?? {}, + ) + : null, + ); const goalSupported = goalControls != null && activeThreadId !== null && @@ -3851,6 +3865,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", pausedForWait: true }), + 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..f6809a6a5 --- /dev/null +++ b/docs/design/goal-wait-pause.md @@ -0,0 +1,66 @@ +# 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 on its way), 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 rule + +`goalWaitStep`, applied by the decider on `thread.goal.wait.sync` (server only): + +- Waiting and the goal is active and not already paused by us: pause it. The + goal gets `pausedForWait: true` (an optional field, not a new + `ThreadGoalStatus` value, which clients decode as a closed set) and the + provider gets `thread/goal/set` paused with `origin: "automatic"`, which Codex + keeps out of the model's history. +- Not waiting, the goal is paused and marked: resume it, and drop the mark. + Not while a turn is about to start (session `starting`): resumed while idle, + Codex starts a goal turn at once, 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, so a report never gets a second turn beside it. +- The user's own pause, resume, edit or clear drops the mark first, so their + choice stands. A provider report keeps the mark only while the goal is active + or paused; a goal that completed, blocked or hit a limit loses it. + +The mark lives in the goal the projections keep, so a restart with a card still +waiting leaves the goal paused, and answering the card afterwards resumes it. + +## Who asks + +`GoalWaitReactor` watches the events that change a wait or the goal (cards, +started threads, the session, the goal) and the scheduler's waiting cards, and +sends the sync for a thread whose goal should change. At start it looks at +every thread with a goal once. It skips goals whose provider can't pause one. + +## 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 0f3acb095..1d18e22aa 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -2126,6 +2126,12 @@ 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 paused it 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). + * The user's own pause, resume or clear, and a goal that ends, take it away. + */ + pausedForWait: Schema.optional(Schema.Literal(true)), }); export type OrchestrationThreadGoal = typeof OrchestrationThreadGoal.Type; @@ -4327,6 +4333,21 @@ 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, + 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. */ @@ -5784,6 +5805,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadGoalSetCommand, ThreadGoalClearCommand, ThreadGoalStateSetCommand, + ThreadGoalWaitSyncCommand, ThreadMessageUserRecordCommand, ThreadMessageAssistantDeltaCommand, ThreadMessageAssistantCompleteCommand, @@ -6747,6 +6769,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..2feee68c1 --- /dev/null +++ b/packages/shared/src/goalWaitPause.ts @@ -0,0 +1,126 @@ +/** + * 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, marking the goal + * `pausedForWait` so that only its own pause is ever undone; the user's own + * pause, resume or clear, and a goal that ends, take the mark away. + */ +import type { OrchestrationThread, OrchestrationThreadGoal } from "@threadlines/contracts"; + +import { awaitedChildRequestCount, hasPendingChildApproval } from "./childThreads.ts"; +import { 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"; + +type GoalWaitFacts = Pick< + OrchestrationThread, + "childRequests" | "settingsRequests" | "agentRequests" | "commandRequests" | "commandRuns" +>; + +/** + * 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((run) => run.autoSend && !isCommandRunSettled(run.status)) + ); + }); +} + +/** + * 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; +} + +/** + * What to do with the thread's goal now: pause an active goal while it waits, + * resume one this paused once the wait is over, or nothing. A resume waits + * while a turn is about to start (`turnStarting`): resumed while idle, the + * provider starts a goal turn of its own, and it would race the turn that + * ended the wait (a report, the output of a command). Resumed while that turn + * runs, the goal carries on after it. + */ +export function goalWaitStep(input: { + readonly goal: Pick | null; + readonly waiting: boolean; + readonly turnStarting: boolean; +}): "pause" | "resume" | null { + const { goal } = input; + if (goal === null) return null; + if (input.waiting) { + return goal.status === "active" && goal.pausedForWait !== true ? "pause" : null; + } + return goal.pausedForWait === true && goal.status === "paused" && !input.turnStarting + ? "resume" + : null; +} + +/** + * Whether the mark carries over to a goal the provider reported: only while + * the goal is still active (our pause on its way) or paused. A goal that + * completed, blocked or hit a limit is the provider's to report, not ours to + * resume. + */ +export function keepsGoalWaitMark( + previous: Pick | null, + next: Pick | null, +): boolean { + return ( + previous?.pausedForWait === true && + next !== null && + (next.status === "active" || next.status === "paused") + ); +} + +/** + * 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"; +} From 6775c96672c21c5ffcfca80cf07f23ecca30d42f Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:30:19 -0500 Subject: [PATCH 2/4] fix: a goal paused for a wait resumes only once the report's turn is under way A report from a thread the agent started settles its request and waits in the queue in one decision, then goes out a moment later. Resuming the goal in that gap let Codex start a goal turn first, with the report steered into it. A message waiting in the queue now counts as a turn about to start, so the resume lands after the report's own turn starts and the goal carries on inside it (seen live: one turn, resume 44 ms after it started). --- .../orchestration/Layers/GoalWaitReactor.ts | 8 ++++--- .../orchestration/decider.goalWait.test.ts | 21 +++++++++++++++++-- apps/server/src/orchestration/decider.ts | 9 ++++++-- packages/shared/src/goalWaitPause.ts | 15 +++++++++++-- 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts index d00de101f..f5bbb54f5 100644 --- a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts +++ b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts @@ -7,7 +7,7 @@ import { type ThreadId, } from "@threadlines/contracts"; import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; -import { goalWaitOf, goalWaitStep } from "@threadlines/shared/goalWaitPause"; +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"; @@ -27,7 +27,8 @@ 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 session (a turn about to start or running) and its goal. + * 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 = [ @@ -39,6 +40,7 @@ const WAIT_EVENT_PREFIXES = [ "thread.agent-request", "thread.command-request", "thread.command-run-", + "thread.follow-up-", "thread.session-set", "thread.goal-state-set", ] as const; @@ -89,7 +91,7 @@ export const make = Effect.gen(function* () { const step = goalWaitStep({ goal: thread.goal, waiting: goalWaitOf(thread, scheduleAnswerWaiting) !== null, - turnStarting: thread.session?.status === "starting", + turnStarting: turnAboutToStart(thread), }); if (step === null || !(yield* canPauseGoal(thread))) return; yield* orchestrationEngine diff --git a/apps/server/src/orchestration/decider.goalWait.test.ts b/apps/server/src/orchestration/decider.goalWait.test.ts index a12b5e09e..c3d027fac 100644 --- a/apps/server/src/orchestration/decider.goalWait.test.ts +++ b/apps/server/src/orchestration/decider.goalWait.test.ts @@ -240,9 +240,26 @@ describe("decider goal wait pause", () => { })); expect((await run(started, sync())).events).toEqual([]); - // The last report arrives as a turn about to start: the resume waits for it. - const reportStarting = patchThread(started, (thread) => ({ + // 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", diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 08924e7dc..f67ada48c 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -145,7 +145,12 @@ import { } from "./threadMoveDecisions.ts"; import { carriedBackgroundTasks } from "./sessionBackgroundTasks.ts"; import { questionsClosedByUserMessage, unansweredResponseRefusal } from "./userInput.ts"; -import { goalWaitOf, goalWaitStep, keepsGoalWaitMark } from "@threadlines/shared/goalWaitPause"; +import { + goalWaitOf, + goalWaitStep, + keepsGoalWaitMark, + turnAboutToStart, +} from "@threadlines/shared/goalWaitPause"; import { isContinueTrigger, RESTART_CONTINUE_MESSAGE, @@ -5526,7 +5531,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" const step = goalWaitStep({ goal, waiting: goalWaitOf(thread, command.scheduleAnswerWaiting) !== null, - turnStarting: thread.session?.status === "starting", + turnStarting: turnAboutToStart(thread), }); if (step === null || goal === null) { return []; diff --git a/packages/shared/src/goalWaitPause.ts b/packages/shared/src/goalWaitPause.ts index 2feee68c1..23eef05e9 100644 --- a/packages/shared/src/goalWaitPause.ts +++ b/packages/shared/src/goalWaitPause.ts @@ -63,11 +63,22 @@ export function goalWaitOf(thread: GoalWaitFacts, scheduleAnswerWaiting: boolean 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: pause an active goal while it waits, * resume one this paused once the wait is over, or nothing. A resume waits - * while a turn is about to start (`turnStarting`): resumed while idle, the - * provider starts a goal turn of its own, and it would race the turn that + * while a turn is about to start (`turnAboutToStart`): resumed while idle, + * the provider starts a goal turn of its own, and it would race the turn that * ended the wait (a report, the output of a command). Resumed while that turn * runs, the goal carries on after it. */ From aecbf9a60fee62ee1cfd109d5c8db7da922878aa Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:11:03 -0500 Subject: [PATCH 3/4] fix: review fixes for the goal wait pause - The mark has three states: paused (ours), resuming (sent, until the provider reports the goal active, so a restart in between resends it), and user (the user acted during the wait). A resume the user made while a card still waited was paused again as soon as Codex confirmed it; the user mark keeps their choice until that wait is over, including a pause that landed before ours. - Stop marks the goal the user's, so the waits Stop ends never resume it. - A command's output on its way still counts as a wait: the run's finish is recorded a moment before the output goes back. - The reactor also watches reverts and agents leaving. --- .../orchestration/Layers/GoalWaitReactor.ts | 8 +- .../orchestration/decider.goalWait.test.ts | 176 ++++++++++++------ apps/server/src/orchestration/decider.ts | 125 +++++++------ apps/web/src/components/chat/ChatComposer.tsx | 4 +- .../chat/ComposerGoalBar.browser.tsx | 2 +- docs/design/goal-wait-pause.md | 63 ++++--- packages/contracts/src/orchestration.ts | 10 +- packages/shared/src/goalWaitPause.ts | 103 +++++++--- 8 files changed, 318 insertions(+), 173 deletions(-) diff --git a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts index f5bbb54f5..285412db3 100644 --- a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts +++ b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts @@ -42,6 +42,10 @@ const WAIT_EVENT_PREFIXES = [ "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; @@ -93,7 +97,9 @@ export const make = Effect.gen(function* () { waiting: goalWaitOf(thread, scheduleAnswerWaiting) !== null, turnStarting: turnAboutToStart(thread), }); - if (step === null || !(yield* canPauseGoal(thread))) return; + // 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", diff --git a/apps/server/src/orchestration/decider.goalWait.test.ts b/apps/server/src/orchestration/decider.goalWait.test.ts index c3d027fac..3c2930610 100644 --- a/apps/server/src/orchestration/decider.goalWait.test.ts +++ b/apps/server/src/orchestration/decider.goalWait.test.ts @@ -149,89 +149,103 @@ const goalOf = (model: OrchestrationReadModel) => 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 waiting = patchThread(await threadWithActiveGoal(), () => ({ - commandRequests: [commandCard], - })); - const paused = await run(waiting, sync()); + const paused = await run(withCard(await threadWithActiveGoal()), sync()); expect(goalRequest(paused.events)).toMatchObject({ status: "paused", origin: "automatic" }); - expect(goalOf(paused.model)).toMatchObject({ status: "active", pausedForWait: true }); + 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([]); - // The provider confirms; the mark stays through its report. const confirmed = await run(paused.model, reported("paused")); - expect(goalOf(confirmed.model)).toMatchObject({ status: "paused", pausedForWait: true }); + expect(goalOf(confirmed.model)).toMatchObject({ status: "paused", waitPause: "paused" }); - const answered = patchThread(confirmed.model, () => ({ - commandRequests: [{ ...commandCard, dismissedAt: at(3) }], - })); - const resumed = await run(answered, sync()); + const resumed = await run(cardAnswered(confirmed.model), sync()); expect(goalRequest(resumed.events)).toMatchObject({ status: "active", origin: "automatic" }); - expect(goalOf(resumed.model)?.pausedForWait).toBeUndefined(); + // 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("leaves the goal to the user once they paused, resumed or cleared it themselves", async () => { - const paused = await run( - patchThread(await threadWithActiveGoal(), () => ({ commandRequests: [commandCard] })), - sync(), - ); - const confirmed = (await run(paused.model, reported("paused"))).model; - const answered = (thread: OrchestrationReadModel) => - patchThread(thread, () => ({ commandRequests: [] })); - - // The user resumed while the card waited: their goal now, never paused again by the answer. - const userResumed = await run(confirmed, { - type: "thread.goal.set", - commandId: CommandId.make("user-resume"), - threadId: THREAD, - status: "active", - createdAt: at(3), - }); - expect(goalOf(userResumed.model)?.pausedForWait).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(); + }); - // The user paused it themselves, then answered: it stays paused. - const userPaused = await run(confirmed, { - type: "thread.goal.set", - commandId: CommandId.make("user-pause"), - threadId: THREAD, - status: "paused", - createdAt: at(3), - }); - expect((await run(answered(userPaused.model), sync())).events).toEqual([]); + 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(); + }); - // Cleared: nothing resumes, whatever the provider reports first. + 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(goalOf(cleared.model)?.pausedForWait).toBeUndefined(); - expect((await run(answered(cleared.model), sync())).events).toEqual([]); + 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( - patchThread(await threadWithActiveGoal(), () => ({ commandRequests: [commandCard] })), - sync(), - ); + const paused = await run(withCard(await threadWithActiveGoal()), sync()); const completed = await run(paused.model, reported("complete")); - expect(goalOf(completed.model)?.pausedForWait).toBeUndefined(); - const answered = patchThread(completed.model, () => ({ commandRequests: [] })); - expect((await run(answered, sync())).events).toEqual([]); + 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 last wait ends", async () => { + 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 (await run(waitingOnBoth, sync())).model, reported("paused"))) - .model; + 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) => ({ @@ -282,21 +296,61 @@ describe("decider goal wait pause", () => { }); }); + 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 a goal it paused when the wait ended while the server was down", async () => { + it("resumes after a restart, whether the wait ended or the resume went unconfirmed", async () => { // The mark is part of the goal the projection keeps, so it is there // after a restart: only the answer is new. - const paused = await run( - patchThread(await threadWithActiveGoal(), () => ({ commandRequests: [commandCard] })), - sync(), - ); - const restarted = patchThread((await run(paused.model, reported("paused"))).model, () => ({ - commandRequests: [], - })); - expect(goalRequest((await run(restarted, sync())).events)).toMatchObject({ status: "active" }); + const answered = cardAnswered(await pausedForCard()); + const resumed = await run(answered, sync()); + expect(goalRequest(resumed.events)).toMatchObject({ status: "active" }); + // The server stopped before the provider got the resume: it goes again. + expect(goalRequest((await run(resumed.model, sync())).events)).toMatchObject({ + status: "active", + }); }); }); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 479b86dab..b2808e2b5 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -146,9 +146,10 @@ import { import { carriedBackgroundTasks } from "./sessionBackgroundTasks.ts"; import { questionsClosedByUserMessage, unansweredResponseRefusal } from "./userInput.ts"; import { + carriedGoalWaitMark, goalWaitOf, goalWaitStep, - keepsGoalWaitMark, + type GoalWaitMark, turnAboutToStart, } from "@threadlines/shared/goalWaitPause"; import { @@ -442,20 +443,18 @@ function passCeilingCancelEvents( ]; } -/** - * The goal without the mark of a pause Threadlines made for a wait, as one - * event, when it has one: the user acted on the goal themselves. - */ -function withoutGoalWaitMark( +/** 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; - if (goal?.pausedForWait !== true) return []; - const { pausedForWait: _mark, ...unmarked } = goal; + const goal = thread.goal ?? null; + if (goal === null || (goal.waitPause ?? null) === mark) return []; + const { waitPause: _mark, ...unmarked } = goal; return [ { ...withEventBase({ @@ -466,11 +465,34 @@ function withoutGoalWaitMark( metadata: {}, }), type: "thread.goal-state-set", - payload: { threadId: command.threadId, goal: unmarked, updatedAt: command.createdAt }, + 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 @@ -4656,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 = { @@ -5002,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 = { @@ -5542,9 +5570,9 @@ 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 pause Threadlines made - // for a wait is theirs now, never undone when the wait ends. - const unmarked = withoutGoalWaitMark(goalThread, command); + // 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, @@ -5584,7 +5612,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }); return [ // Nothing resumes a goal the user cleared, whatever the provider says first. - ...withoutGoalWaitMark(clearedThread, command), + ...goalTakenByUser(clearedThread, command), { ...withEventBase({ aggregateKind: "thread", @@ -5610,44 +5638,36 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); - const goal = thread.goal; const step = goalWaitStep({ - goal, + goal: thread.goal, waiting: goalWaitOf(thread, command.scheduleAnswerWaiting) !== null, turnStarting: turnAboutToStart(thread), }); - if (step === null || goal === null) { + if (step === null) { return []; } - const base = () => - withEventBase({ - aggregateKind: "thread", - aggregateId: command.threadId, - occurredAt: command.createdAt, - commandId: command.commandId, - metadata: {}, - }); - const { pausedForWait: _mark, ...unmarkedGoal } = goal; return [ - { - ...base(), - type: "thread.goal-state-set", - payload: { - threadId: command.threadId, - goal: step === "pause" ? { ...goal, pausedForWait: true as const } : unmarkedGoal, - updatedAt: command.createdAt, - }, - }, - { - ...base(), - type: "thread.goal-set-requested", - payload: { - threadId: command.threadId, - status: step === "pause" ? ("paused" as const) : ("active" as const), - origin: "automatic" as const, - createdAt: command.createdAt, - }, - }, + ...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, + }, + }, + ]), ]; } @@ -5719,16 +5739,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); - // A pause Threadlines made for a wait stays marked through the - // provider's reports while the goal is active or paused; a goal that - // ended or hit a limit is the provider's, and loses it. - const { pausedForWait: _reported, ...reported } = command.goal ?? {}; + // 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 - : keepsGoalWaitMark(goalThread.goal, command.goal) - ? { ...command.goal, pausedForWait: true as const } - : (reported as typeof command.goal); + : carried === undefined + ? (reported as typeof command.goal) + : { ...command.goal, waitPause: carried }; return { ...withEventBase({ aggregateKind: "thread", diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 840416939..ff2a98577 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -927,7 +927,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // 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?.pausedForWait === true && threadGoal.status === "paused" && activeThread + (threadGoal?.waitPause === "paused" || threadGoal?.waitPause === "resuming") && + threadGoal.status === "paused" && + activeThread ? goalWaitPauseLabel( selectSidebarThreadSummaryByRef( store, diff --git a/apps/web/src/components/chat/ComposerGoalBar.browser.tsx b/apps/web/src/components/chat/ComposerGoalBar.browser.tsx index adba2c0c3..eac62876a 100644 --- a/apps/web/src/components/chat/ComposerGoalBar.browser.tsx +++ b/apps/web/src/components/chat/ComposerGoalBar.browser.tsx @@ -71,7 +71,7 @@ describe("ComposerGoalBar", () => { it("says why Threadlines paused a goal while its thread waits, and still offers Resume", async () => { renderBar({ driver: "codex", - goal: goal({ status: "paused", pausedForWait: true }), + goal: goal({ status: "paused", waitPause: "paused" }), waitLabel: goalWaitPauseLabel({ pendingChildApproval: true, awaitedChildThreadCount: 0 }), }); await expect.element(page.getByText("Paused until you answer")).toBeVisible(); diff --git a/docs/design/goal-wait-pause.md b/docs/design/goal-wait-pause.md index f6809a6a5..ae85ca47f 100644 --- a/docs/design/goal-wait-pause.md +++ b/docs/design/goal-wait-pause.md @@ -14,40 +14,59 @@ 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 on its way), a scheduled-task card (the scheduler holds - those: `ScheduledTasks.waitingThreadIds`). + 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. + A goal whose only wait is a scheduled-task card, and that wasn't paused yet, + is the one case the user's action can't be told apart (the decider can't see + the scheduler's cards). + +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 and the goal is active and not already paused by us: pause it. The - goal gets `pausedForWait: true` (an optional field, not a new - `ThreadGoalStatus` value, which clients decode as a closed set) and the - provider gets `thread/goal/set` paused with `origin: "automatic"`, which Codex - keeps out of the model's history. -- Not waiting, the goal is paused and marked: resume it, and drop the mark. - Not while a turn is about to start (session `starting`): resumed while idle, - Codex starts a goal turn at once, 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, so a report never gets a second turn beside it. -- The user's own pause, resume, edit or clear drops the mark first, so their - choice stands. A provider report keeps the mark only while the goal is active - or paused; a goal that completed, blocked or hit a limit loses it. - -The mark lives in the goal the projections keep, so a restart with a card still -waiting leaves the goal paused, and answering the card afterwards resumes it. +- 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` or `resuming`: resume + it (`resuming`, `thread/goal/set` active, automatic). 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`. ## Who asks -`GoalWaitReactor` watches the events that change a wait or the goal (cards, -started threads, the session, the goal) and the scheduler's waiting cards, and -sends the sync for a thread whose goal should change. At start it looks at -every thread with a goal once. It skips goals whose provider can't pause one. +`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. 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 diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 6a61163f8..04bd623c2 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -2153,11 +2153,13 @@ export const OrchestrationThreadGoal = Schema.Struct({ /** Claude: the evaluator's latest reason (not met yet, or why it is done). */ lastCheck: Schema.optional(TrimmedNonEmptyString), /** - * Threadlines paused it 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). - * The user's own pause, resume or clear, and a goal that ends, take it away. + * 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. */ - pausedForWait: Schema.optional(Schema.Literal(true)), + waitPause: Schema.optional(Schema.Literals(["paused", "resuming", "user"])), }); export type OrchestrationThreadGoal = typeof OrchestrationThreadGoal.Type; diff --git a/packages/shared/src/goalWaitPause.ts b/packages/shared/src/goalWaitPause.ts index 23eef05e9..d88d0b64b 100644 --- a/packages/shared/src/goalWaitPause.ts +++ b/packages/shared/src/goalWaitPause.ts @@ -6,25 +6,44 @@ * 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, marking the goal - * `pausedForWait` so that only its own pause is ever undone; the user's own - * pause, resume or clear, and a goal that ends, take the mark away. + * 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 { isCommandRunSettled } from "./commandRuns.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. @@ -36,9 +55,7 @@ function hasWaitingCommandCard(thread: GoalWaitFacts): boolean { const runs = allRuns.filter( (run) => run.source.kind === "request" && run.source.requestId === request.requestId, ); - return ( - runs.length === 0 || runs.some((run) => run.autoSend && !isCommandRunSettled(run.status)) - ); + return runs.length === 0 || runs.some(outputStillComing); }); } @@ -75,43 +92,67 @@ export function turnAboutToStart( } /** - * What to do with the thread's goal now: pause an active goal while it waits, - * resume one this paused once the wait is over, or nothing. A resume waits - * while a turn is about to start (`turnAboutToStart`): resumed while idle, - * the provider starts a goal turn of its own, and it would race the turn that - * ended the wait (a report, the output of a command). Resumed while that turn - * runs, the goal carries on after it. + * 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. + * + * - 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 (and again after a restart that came in between). 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 the resume was confirmed: paused again, for this wait. */ export function goalWaitStep(input: { - readonly goal: Pick | null; + readonly goal: Pick | null; readonly waiting: boolean; readonly turnStarting: boolean; -}): "pause" | "resume" | null { +}): { readonly mark: GoalWaitMark | null; readonly send: "paused" | "active" | null } | null { const { goal } = input; if (goal === null) return null; + const mark = goal.waitPause; if (input.waiting) { - return goal.status === "active" && goal.pausedForWait !== true ? "pause" : null; + if (mark === undefined) { + return goal.status === "active" ? { mark: "paused", send: "paused" } : null; + } + if (mark === "resuming") { + return { mark: "paused", send: goal.status === "paused" ? null : "paused" }; + } + return null; + } + if (mark === "user") return { mark: null, send: null }; + if (mark === "paused" || mark === "resuming") { + if (goal.status === "paused") { + return input.turnStarting ? null : { mark: "resuming", send: "active" }; + } + // Active and `paused`: our pause is on its way. Anything else is the + // provider's own ending, not ours to undo. + return goal.status === "active" ? null : { mark: null, send: null }; } - return goal.pausedForWait === true && goal.status === "paused" && !input.turnStarting - ? "resume" - : null; + return null; } /** - * Whether the mark carries over to a goal the provider reported: only while - * the goal is still active (our pause on its way) or paused. A goal that - * completed, blocked or hit a limit is the provider's to report, not ours to - * resume. + * 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 keepsGoalWaitMark( - previous: Pick | null, +export function carriedGoalWaitMark( + previous: Pick | null, next: Pick | null, -): boolean { - return ( - previous?.pausedForWait === true && - next !== null && - (next.status === "active" || next.status === "paused") - ); +): 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"; + } } /** From 78f7a3f6a6069b77adfb93d7908b419b9ad2ecb1 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:29:20 -0500 Subject: [PATCH 4/4] fix: second review fixes for the goal wait pause - The reactor reports each user goal action and Stop (userActed), so a pause the user made where the only wait is a scheduled-task card, which the decider can't see, is theirs for that wait. - A resume not yet confirmed is sent again only on the reactor's startup pass (retryResume), never on every look. - A new wait before a resume was confirmed sends the pause, so the 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: a goal the user took over, or that the provider ended or blocked since, is left alone. --- .../orchestration/Layers/GoalWaitReactor.ts | 62 +++++++++++++++---- .../Layers/ProviderCommandReactor.ts | 14 +++++ .../orchestration/decider.goalWait.test.ts | 44 +++++++++++-- apps/server/src/orchestration/decider.ts | 2 + docs/design/goal-wait-pause.md | 25 +++++--- packages/contracts/src/orchestration.ts | 4 ++ packages/shared/src/goalWaitPause.ts | 35 +++++++---- 7 files changed, 147 insertions(+), 39 deletions(-) diff --git a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts index 285412db3..bb03a8d6b 100644 --- a/apps/server/src/orchestration/Layers/GoalWaitReactor.ts +++ b/apps/server/src/orchestration/Layers/GoalWaitReactor.ts @@ -53,6 +53,23 @@ 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; @@ -83,7 +100,10 @@ export const make = Effect.gen(function* () { ); }; - const syncThread = Effect.fn("GoalWaitReactor.syncThread")(function* (threadId: ThreadId) { + 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), @@ -96,6 +116,8 @@ export const make = Effect.gen(function* () { 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. @@ -106,6 +128,8 @@ export const make = Effect.gen(function* () { commandId: CommandId.make(`goal-wait-sync:${threadId}:${randomUUID()}`), threadId, scheduleAnswerWaiting, + ...(flags.userActed ? { userActed: true } : {}), + ...(flags.retryResume ? { retryResume: true } : {}), createdAt: yield* nowIso, }) .pipe( @@ -116,23 +140,36 @@ export const make = Effect.gen(function* () { ); }); - // A thread already queued is looked at once: it is read as it stands then. - const queued = new Set(); + // 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.sync(() => queued.delete(threadId)).pipe(Effect.andThen(syncThread(threadId))), + Effect.suspend(() => { + const flags = queued.get(threadId) ?? { userActed: false, retryResume: false }; + queued.delete(threadId); + return syncThread(threadId, flags); + }), ); - const enqueue = (threadId: ThreadId) => + const enqueue = (threadId: ThreadId, flags: Partial = {}) => Effect.suspend(() => { - if (queued.has(threadId)) return Effect.void; - queued.add(threadId); - return worker.enqueue(threadId); + 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) => - changesWait(event) ? enqueue(event.aggregateId as ThreadId) : Effect.void, + 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. @@ -146,18 +183,19 @@ export const make = Effect.gen(function* () { (threadId) => current.has(threadId) !== previous.has(threadId), ); previous = current; - yield* Effect.forEach(changed, enqueue, { discard: true }); + yield* Effect.forEach(changed, (threadId) => enqueue(threadId), { discard: true }); }), ), ); } - // Cards answered or threads finished while the server was down. + // 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), + (thread) => enqueue(thread.id, { retryResume: true }), { discard: true }, ); }); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 9eff58c5d..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 diff --git a/apps/server/src/orchestration/decider.goalWait.test.ts b/apps/server/src/orchestration/decider.goalWait.test.ts index 3c2930610..d1dd18c56 100644 --- a/apps/server/src/orchestration/decider.goalWait.test.ts +++ b/apps/server/src/orchestration/decider.goalWait.test.ts @@ -83,11 +83,15 @@ const reported = (status: OrchestrationThreadGoal["status"]): OrchestrationComma createdAt: at(1), }); -const sync = (scheduleAnswerWaiting = false): OrchestrationCommand => ({ +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), }); @@ -342,15 +346,43 @@ describe("decider goal wait pause", () => { expect(goalRequest(paused.events)).toMatchObject({ status: "paused" }); }); - it("resumes after a restart, whether the wait ended or the resume went unconfirmed", async () => { + 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" }); - // The server stopped before the provider got the resume: it goes again. - expect(goalRequest((await run(resumed.model, sync())).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 b2808e2b5..87322acc1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -5642,6 +5642,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" goal: thread.goal, waiting: goalWaitOf(thread, command.scheduleAnswerWaiting) !== null, turnStarting: turnAboutToStart(thread), + userActed: command.userActed, + retryResume: command.retryResume, }); if (step === null) { return []; diff --git a/docs/design/goal-wait-pause.md b/docs/design/goal-wait-pause.md index ae85ca47f..148d829aa 100644 --- a/docs/design/goal-wait-pause.md +++ b/docs/design/goal-wait-pause.md @@ -34,9 +34,9 @@ value, which clients decode as a closed set): - `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. - A goal whose only wait is a scheduled-task card, and that wasn't paused yet, - is the one case the user's action can't be told apart (the decider can't see - the scheduler's cards). + 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 @@ -49,23 +49,32 @@ A provider report keeps the mark only while it means something - 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` or `resuming`: resume - it (`resuming`, `thread/goal/set` active, automatic). Not while a turn is +- 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`. +- 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. 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 +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 diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 04bd623c2..168c1de34 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -4397,6 +4397,10 @@ const ThreadGoalWaitSyncCommand = Schema.Struct({ 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, }); diff --git a/packages/shared/src/goalWaitPause.ts b/packages/shared/src/goalWaitPause.ts index d88d0b64b..da4aa9318 100644 --- a/packages/shared/src/goalWaitPause.ts +++ b/packages/shared/src/goalWaitPause.ts @@ -95,40 +95,49 @@ export function turnAboutToStart( * 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 (and again after a restart that came in between). 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. + * 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 the resume was confirmed: paused again, for this wait. + * - 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; } - if (mark === "resuming") { - return { mark: "paused", send: goal.status === "paused" ? null : "paused" }; - } - return 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") { - return input.turnStarting ? null : { mark: "resuming", send: "active" }; + if (input.turnStarting || (mark === "resuming" && input.retryResume !== true)) return null; + return { mark: "resuming", send: "active" }; } - // Active and `paused`: our pause is on its way. Anything else is the - // provider's own ending, not ours to undo. + // 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;