Skip to content

fix(conversations): Stop child agents when a person stops the parent - #2832

Merged
dcramer merged 15 commits into
mainfrom
fix/stop-child-agents-on-parent-stop
Nov 7, 2026
Merged

dcramer merged 15 commits into
mainfrom
fix/stop-child-agents-on-parent-stop

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Prep for #2792.

#2792 decides that a stop on the parent stops every child agent. Before this PR, only the Slack stop keyword did that, through stopConversationSession. Every other way a person stops a Conversation called only stopConversationTurn, so child agents kept running and could still report to the parent. The review on this PR also asks for one universal stop: it ends the session of the stopped Conversation and every descendant, and while they are stopped, watch events are saved to the transcript but start no Turn.

One stop function

Every person stop now calls stopConversation in chat/conversations/stop.ts:

  1. stopChildAgentsBelow: stop every child agent below the Conversation and mark them stopped.
  2. markConversationsStopped([id]): mark the stopped Conversation itself.
  3. stopConversationTurn: stop its Turn.

The callers:

  • Dashboard Stop: stopConversationTurnForViewer in api/conversations/stop.ts. The MCP stopConversation tool uses it too. Its description now names the child agents and the saved watch events.
  • ACP session/cancel: api/acp/conversations.ts.
  • Slack: the stop keyword and the native stop button (agent_session_stopped) share one handler, handleSlackStop in ingress/slack-webhook.ts. See "Slack stop" below. stopConversationSession is deleted.

The child agents and sessions stop first, so a failure leaves the Turn running and the stop can be retried. This also runs when no Turn is running (no_work), because a child agent can outlive the parent Turn.

A stop never goes up the tree. All paths accept a child agent Conversation id, because access is checked through its root. stopChildAgentsBelow does not change the stopped Conversation's own agent invocations, so a stopped child's worker still reports agent_invocation.stopped to its parent. The parent stays as it is.

Slack stop

Slack is no longer a special case. The stop keyword is a plain stop, the same as the button:

  • handleSlackStop calls core stopConversation, then does only Slack UI work: it clears the processing status in a finally (so it also runs when the stop fails; the error still propagates), clears pending reactions, and posts one ack, Stopped..
  • The keyword message is saved as a skipped Message (thread_opt_out:<reason>) and never enters the mailbox. The ack always posts for the keyword. For the button it posts only when work was stopped.
  • The keyword no longer unsubscribes the thread. chat/slack/thread-stop.ts is deleted: the Slack stop timestamp, isSlackMessageStopped and the resubscribe hook (subscribeThread) are gone. stopped_at orders input, so the next @jr mention ends the stop.
  • The model router's thread opt-out (providers/slack/runtime.ts) stays as it is. It means "leave this thread", not a stop, and still cancels Watches.

Root cascade

A run sees its stop only at its next stop signal check. run in chat/app/conversation-work.ts, which every root Turn goes through (Slack, web, ACP, dispatch), now records whether the run read its stop signal. When that signal was aborted, it calls stopChildAgentsOf for the root, the same late cascade a child agent's worker runs. So a child agent that a root spawns or re-tasks after the stop, but before its run sees the stop, ends stopped. This closes the spawn race that the previous body listed as a known gap.

stopped status

The API Conversation status has a new value, stopped. It is reported when stopped_at is set and no work is running or pending. A Turn that runs on a stopped Conversation (an agent message or a system Event) shows as active while it runs and as stopped after. execution_status, the work state, recordExecution, the aggregates and the partial index do not change. The dashboard shows a stopped marker in lists and "Stopped" in the sidebar, and the MCP views report the same status.

A stopped Conversation

A stopped Conversation is one with stopped_at set. There is no new column, no migration and no Watch change: Watch records stay exactly as on main. execution_status is not used, because the worker owns it.

  • While a Conversation is stopped, every Watch Event that reaches it is saved as one skipped Message (skippedReason: "stopped conversation"), the same way Slack messages that Junior does not reply to are stored. The next Turn sees it in history. No Turn starts. This also covers a Watch that the running Turn created before it saw the stop.
  • A Conversation that is not stopped gets Events exactly as on main.
  • Agent results and agent messages to a stopped Conversation are dropped, as before.
  • A person's stop keeps the Watches. An agent's stopAgent also sets stopped_at, and still cancels the Watches of the child tree, as on main.

The worker check is skipInputAfterConversationStop in chat/conversations/session-stop.ts (it replaces skipInputBeforeConversationStop). It runs first for root and child work:

  • Input from a person (web or slack; ACP uses web input) always runs. When it was received after stopped_at, it clears stopped_at for that Conversation and for every child agent below it whose stop is no later (resumeStoppedConversationTree). So the queued person input that a stop drops does not undo that stop, and input to a parent does not undo a later stop of only one child agent.
  • A batch of only Events on a stopped Conversation: Watch Events are saved. Events with no Watch (such as a review item change) run when they were received after the stop and are dropped otherwise. In a mixed batch, the check waits out the debounce window, saves the Watch Events, and runs the rest.
  • Any other input runs as before.

The saved Message is appended directly as one idempotent message event (key message:<id>). It does not load the message history.

Decisions:

  • A person's stop marks the stopped Conversation and all its descendants.
  • A person's input that runs on a stopped Conversation (web, ACP, Slack) ends the stop of that Conversation and its descendants.
  • New work from a parent (a messageAgent message, or a new invocation of a named child) ends the stop of that child and its descendants. The hook is enqueueAgentInvocation, for invocations that carry a parentToolCallId. A child's own Events and results do not.
  • A Watch Event on a child whose stop ended starts a new agent invocation, even when its latest invocation is stopped.
  • The late cascade (stopChildAgentsOf) runs when a root's or child's run sees its stop, which can be late. If the stop already ended, it does nothing. Otherwise it stops only the child agents that the Conversation spawned or gave new work to after its stop (agent invocation created after stopped_at), even when they already finished, and everything below them. It keeps their Watches. A child agent that the stop already reached keeps its stop time, so a person's input to the root still ends it.
  • A child agent that the late cascade stops has a later stopped_at than its root, so a person's input to the root does not end its stop. Only new work from its parent does.

stopped_at readers checked: the stopped-child display (isChildAgentSessionStopped) falls back to the invocation status once it is cleared, stopChildAgent (wasStopped), the late cascade, and the worker check.

Already reviewed, kept

Results sent to the stopped Conversation:

  • pending results (not yet in its mailbox) become skipped.
  • appended results that still wait in its mailbox become skipped. The root worker drops skipped results (withAgentInvocationResultActors, shared isSkippedAgentResult with the child worker), so they start no new parent Turn.
  • A result that the parent already read stays appended, so listChildAgents and searchAgents still show its lastResult.

The dashboard response does not change: it still returns the Turn status and the viewer's queued web text.

Known gaps

  • A Slack stop has no watermark now. A late or redelivered stop keyword stops the Conversation again, with stopped_at set to that time.
  • With passive routing off, a plain thread message does not wake a worker, so only a mention ends a Slack stop.
  • Person input that steers a Turn that is still running does not go through the worker check, so it does not end a stop. The next person input that starts a Turn does.
  • An Event that waited in the mailbox when stopAgent ran is now saved to the transcript. Main dropped it. It still starts no Turn.
  • Descendants still stop through stopConversationWork, not the sign-in pause path. Child agents cannot pause for sign-in today: getAuthPausedConversationTurnId skips dispatch Turns (Add subagent context, lifecycle controls, and execution limits #881). Thread Turns in Add Threads: child conversations people can talk to #2792 PR 3 need that path.
  • The three "is it stopped" checks stay separate because they answer different questions. The PR thread has the details.

Tests

  • tests/integration/api/conversations/stop.test.ts:
    • Dashboard stop with a running child agent: the child stops, and the viewer's queued text still comes back.
    • Dashboard stop after the parent Turn ended (no_work): the running child stops, the parent is stopped, and a result that the parent already read keeps appended and its lastResult.
    • ACP cancel stops the child and the parent.
    • Dashboard stop of a child agent Conversation: the parent gets the agent_invocation.stopped report, the child and the agent below it are stopped, and the parent is not.
    • A child result that waits in the parent mailbox when a person stops the parent starts no parent Turn.
    • A child agent that a directly stopped child agent spawned before its run saw the stop, and that already finished, is still stopped by the late cascade.
    • A child agent's late cascade after a root stop does not move its grandchild's stop. After a person's input to the root ends the stop, a late cascade does not stop the grandchild again.
    • A child agent that a stopped root spawns after the stop, while its run is in a long tool call, ends stopped when the run sees the stop.
  • tests/integration/slack/conversation-turn-steering-behavior.test.ts: the native stop button and the stop keyword each stop a running child agent and the root, clear the status and post Stopped.. The thread stays subscribed.
  • tests/integration/slack/webhook-persistence-contract.test.ts: a stop keyword keeps the thread subscribed and enqueues no mailbox work.
  • tests/integration/durable-queue.test.ts: a stop keyword stops a paused Turn, and a later mention ends the stop and gets a reply.
  • tests/integration/heartbeat-timers.test.ts:
    • After a person stops a root, a timer that already fired, a later timer and a timer set after the stop are saved to the transcript with no Turn, and the root reports stopped. A person's message ends the stop (active, then completed), and the next timer starts a Turn.
    • A stop that drops a queued person message keeps the root stopped: the old timer, and an Event of a watch re-created after the stop, are saved with no Turn.
    • A person's stop of a root saves its child's timers to the child's transcript. A person's message to the root ends the child's stop, and the next child timer starts the child. A later stop of only the child stays in effect when a person writes to the root. A messageAgent message from the parent then ends that stop, and the next timer starts a Turn.
  • tests/integration/agent-invocation-concurrency.test.ts: stopAgent cancels the child's watches, so its timers never fire. A timer that already fired is saved to the child's transcript with no Turn.
  • tests/integration/agent-invocation-stop.test.ts: a person's stop of a running child reports to the parent and stops the child's own child agents.

via @dcramer.

--

View Session [Sentry]

@vercel

vercel Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 7, 2026 4:15am UTC

Request Review

@sentry-junior

sentry-junior Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Why the three "is it stopped" checks stay separate. Each one reads a different record and answers a different question, so a single helper would change behavior.

  1. skipInputBeforeConversationStop (chat/conversations/session-stop.ts), per input batch, on any Conversation: it drops a batch only when the whole batch is watch events, agent results, or agent messages, and every message has receivedAtMs <= stoppedAt. Input from a person or a parent always runs. Input that arrives after the stop runs.
  2. startAgentInvocationsForChildInput (chat/agent-invocations/result.ts), per child Conversation: it reads the latest agent invocation (status === "stopped", or terminal with parentMailboxStatus === "skipped") and ignores stoppedAt and timestamps. A stopped child takes no results or watch events, even ones that arrive after the stop, until the parent gives it new work. Rule 1 lets that later input through.
  3. isChildAgentSessionStopped (chat/agent-invocations/list.ts), for display and for stopChildAgent's wasStopped: it is true when stoppedAt >= latest.createdAtMs. This means the session stopped after the latest invocation started, so no new work has started since. When it is false, the listing falls back to the invocation status (skipped shows as stopped, replaced shows as pending).

The new rule in #2792 for Thread restarts ("stoppedAt set and no person messaged it later") mixes rules 1 and 2. It compares stoppedAt with later person input, but it decides for the whole child the way rule 2 does. It would most likely replace rule 2 for Threads only.

@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 6, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 113aab2, including the Slack native stop commit. The touched tests, agent-invocation-stop, acp-http-recovery, pnpm typecheck, and file-length:check all pass. I found two bugs that should be fixed before merge. I confirmed both with scratch integration tests on the fixtures this PR adds.

1. Stopping a child conversation now hides the stop from its parent (regression). The dashboard, MCP stopConversation, and ACP cancel accept a child conversation id, because access resolves through the root. stopChildAgentsOf(id) passes id itself into stopAgentInvocationTree. The first UPDATE then matches the child's own open invocation. If a person stops a running child from the dashboard, the invocation becomes stopped / "Stopped by the parent conversation" / parentMailboxStatus: skipped. On main it stayed open: the child worker then recorded "Agent invocation was stopped" and reported it to the parent (work.ts finishStopped). Now the parent never learns that its child was stopped, and the error text is wrong. The existing caller in finishStopped is safe only because it marks its own invocation terminal first. That is the precondition in the JSDoc ("whose own stop is already recorded"), and these new callers break it. Fix: cascade only for root conversations here, or exclude the target's own invocations from the tree update.

2. A child result that is already in the parent mailbox still starts a new parent Turn after Stop. Repro: parent Turn running → child completes and enqueueAgentInvocationResult appends its result → dashboard Stop → worker runs completeConversationStop. The invocation row is now skipped, and listChildAgents reports the child as stopped. But stopConversationWork drops only web/slack messages, so the [agent result] event stays in pendingMessages. The root path (conversation-work.ts → resolveMailboxTurnWork → withAgentInvocationResultActors) has no skipped check, so the parent restarts right after the person's Stop. The session stop avoids this through stoppedAt (skipInputBeforeConversationStop). A Turn stop does not set stoppedAt. The child worker already drops results whose source is skipped (result.ts ~L426–433). The root path needs the same filter (ack and complete when every input is filtered out). This applies to the dashboard, ACP, and Slack native stop paths alike. It is the PR's stated guarantee ("could still report to the parent") and the #2792 rule, so it needs a test.

Should fix: the order of the two calls hurts error handling. The cascade runs after stopConversationTurn has already written the stop marker. If stopChildAgentsOf throws, the dashboard returns 500 "Unable to stop the active turn." But the parent Turn did stop, and the worker still drops the queued human messages. So the viewer's queued web text, which the response exists to give back, is lost. On the Slack native path, a throw also skips the processing status clear that the doc comment says must always run. Running stopChildAgentsOf before stopConversationTurn fixes both. A failure then leaves the parent untouched, and the 500 is honest and safe to retry. It also closes the window where an unfinished child completes between the two calls, because stopped invocations cannot complete. (Results already appended still need the fix in #2.)

Smaller notes

  • The MCP stopConversation description and the no_work field doc ("when nothing was running") now hide the cascade. no_work can now come back after child agents were stopped. Cascading through MCP is fine, but the model-facing contract should say it.
  • The PR body still says "The Slack native stop button still stops only the parent Turn."
  • Remaining race: the parent sees the stop only on its next stop-signal poll. A spawnAgent that executes in that window creates a child after the cascade, and nothing stops that child. You could cascade in the root worker after it observes the stop, as the child worker does in finishStopped. That would cover this race and all three entry points. Not blocking for this PR.
  • Explicit dependencies look fine. The dashboard handler takes the default state, the same as its getConversationStore() and stopConversationTurn calls. ACP and Slack pass their state.
  • Calling createAcpConversations().cancel directly is enough coverage. The changed code is in cancel, and acp-http-recovery.test.ts already covers the route → cancel wiring.

queue: services.queue,
});
// A child agent can outlive the parent Turn, so stop it even with no Turn.
await stopChildAgentsOf(conversationId);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If conversationId is a child agent conversation (participants of the root can stop it here and through MCP), this marks that child's own open invocation stopped/skipped with "Stopped by the parent conversation". Its parent then never gets the stop report it got on main. I reproduced it: on main the invocation stays pending until the child worker records and reports the stop. Please cascade only when the conversation has no parentConversationId, or exclude the target's own invocations.

Also consider calling this before stopConversationTurn. As written, a throw here returns 500 after the parent stop is already recorded, and the viewer's queued text is dropped without being returned.

state: args.state,
});
// A child agent can outlive the parent Turn, so stop it even with no Turn.
await stopChildAgentsOf(conversationId, args.state);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this throws, the Slack processing status clear below never runs. The doc comment says that clear must always happen. Running the cascade before stopConversationTurn, or the status clear before the cascade, avoids a stuck status.

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

5 screenshot changes — 5 changed · 0 added · 0 removed

Review screenshots in Frameshift

Conversation Captured Memories Popover · Desktop
Conversation Captured Memories Popover · Desktop
Changed
Conversation Captured Memories Popover · Mobile
Conversation Captured Memories Popover · Mobile
Changed
Conversation Details Watched Linked Work · Desktop
Conversation Details Watched Linked Work · Desktop
Changed
Conversation Long Transcript Touch · Mobile
Conversation Long Transcript Touch · Mobile
Changed
Settings Mcp · Desktop
Settings Mcp · Desktop
Changed

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@github-actions github-actions Bot added risk: high PR risk score: high and removed risk: medium PR risk score: medium labels Nov 6, 2026

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 4691d72. These pass against Postgres: stop.test.ts, agent-invocation-stop, -spawn, -nested, acp-http-recovery, conversation-turn-steering-behavior, pnpm typecheck, and file-length:check.

The earlier findings are fixed:

  • Stopping a child by id now keeps the child's own invocation open. The child worker records "Agent invocation was stopped" and reports it to the parent, and the new test proves it.
  • The root path now drops skipped results.
  • The cascade runs first on all three paths. If it fails, the Turn keeps running and the stop can be retried.
  • The MCP contract now states the cascade.

stopChildAgentsBelow and stopChildAgentsOf differ only by includeRoot. That split is fine: they record two different preconditions.

Dropping skipped results on the root path looks safe. Only the tree stop writes skipped. A re-tasked child gets a new invocation id, so its result is never skipped by an earlier stop. A mixed batch still acks the dropped message through context.attempt.ack().

Must fix: a person's Stop now marks child results the parent already read as skipped. The tree stop marks every pending or appended result sent to the target as skipped. On a root parent, appended is the last status a result ever gets: reading it does not change the row. So the update also hits results the parent read in earlier Turns, not only results that still wait in the mailbox. I reproduced this with a scratch integration test:

  1. A child completes, and the root Turn reads its result.
  2. The Turn ends.
  3. The person sends a dashboard Stop and gets no_work.
  4. listChildAgents changes from [completed, lastResult: completed] to [stopped, lastResult: none], and the row becomes skipped.

listChildAgents feeds api/conversations/child-agents.ts (the dashboard) and the searchAgents tool, so the parent model sees finished work as stopped. On main, only the Slack stop keyword did this. This PR adds it to the dashboard, MCP, ACP session/cancel, and the native stop button, and these are routine actions. A suggested fix: skip appended results only when their result message still waits in the target's mailbox. You can read the waiting result messages from the work state before the tree stop and pass their invocation ids in. Please add a "child result already read" case to the no_work test.

Small notes

  • Deferring the spawn race is acceptable. The PR body names it, the window is only until the next stop-signal poll, and the fix would need a new hook from the Slack provider. Please add a short code comment or an issue link so the gap is visible in code, not only in the PR body.
  • Slack native stop: if stopChildAgentsBelow throws, the processing status clear still does not run. Retrying is safe now, so this is minor.

// Stop the child agents first, so a failure leaves the Turn running and
// the stop can be retried. A child agent can outlive the parent Turn, so
// this runs even with no Turn.
await stopChildAgentsBelow(conversationId);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also flips child results that the root already read to skipped. On a root parent, appended does not change after the result is read, and the tree stop skips every pending or appended result sent to the target. In my repro, a no_work Stop after a child completed and its result was read turned listChildAgents from completed to stopped and dropped lastResult. Please skip only results whose message still waits in the mailbox.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 0dc6172. Nothing here blocks merge. These pass against Postgres: stop.test.ts, agent-invocation-stop, -spawn, -nested, acp-http-recovery, and conversation-turn-steering-behavior (28 tests). pnpm typecheck and file-length:check also pass.

skipUnreadResults order: the race claim holds. A result is enqueued in two steps: first it is appended to the mailbox, then the row moves from pending to appended, and that update applies only while the row is pending. The interleavings:

  • The row was appended before the tree stop. Its message is already in the mailbox, or the parent already acked it. So the read after the tree stop either finds it and skips it, or correctly keeps it.
  • The row was still pending when the tree stop ran. The tree stop marks it skipped, and the later appended update matches nothing. An enqueue or repair that runs late with a stale pending object still appends the message, but the root path drops it because isSkippedAgentResult sees skipped.
  • No child that existed at stop time can produce a new pending row, because the tree stop stopped every open invocation in the same locked transaction.

messages holds only unacked mailbox messages, so a result the parent already read is never skipped.

The only way left for a result to reach appended after this read: the parent run keeps running until its next stop-signal check and gives a child new work. That is the spawn race the JSDoc names.

Display: there is one more difference besides "direct child shows stopped with lastResult: completed". For a child agent inside the stopped tree, results it already read from its children still become skipped, because the first branch still skips pending/appended for stoppedChildIds. I reproduced this: a grandchild whose result its parent (the child) read goes from [completed, completed] to [stopped, none] in listChildAgents(child). This matches the Slack stop keyword on main, and I don't think it blocks this PR. It is a second case for #2792 PR 7 to cover.

Nits

  • The known-gap JSDoc says "a child agent that it spawns". messageAgent, which gives a stopped child new work, takes the same window. Consider "spawns or gives work to".
  • Slack native stop: the try/finally is right. If the status clear in finally throws, it hides the original error. This is unlikely and acceptable.

@dcramer dcramer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stop should generally be universal, and do the following:

  1. stop all sessions in the tree (direct+children, it should not go upwards)

  2. change active watch notifications to passive: they should get written to the transcript but not initiate a turn

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 3786daf. These pass against Postgres: stop.test.ts, agent-invocation-stop, -concurrency, -nested, heartbeat-timers, acp-http-recovery, and the Slack stop and steering tests (67 tests). pnpm typecheck, pnpm lint, and file-length:check also pass, and db:generate reports no schema drift.

The shape is right. One core stopConversation handles every person stop path, and the parent is never touched (the test asserts that the parent has no stoppedAt). The Slack keyword keeps its opt-out, and the model-router opt-out still cancels. I found two must-fix problems.

1. A stop that drops queued person input reactivates the Watches at once. skipInputAfterConversationStop reactivates on any web or Slack message in the attempt. That includes the messages that the stop itself cancels. The worker builds attemptMessages from the mailbox before completeConversationStop removes the stopped input, and run() reaches the reactivation before the Turn sees the stop. I reproduced it with a scratch integration test:

  1. A timer Watch exists, and a person web message waits in the mailbox.
  2. stopConversation returns requested.
  3. drain() runs: 0 agent runs, 0 pending messages, but watches_passive_at is already null.
  4. The timer fires and starts a Turn (1 run, 0 passive Messages).

So a person who presses Stop while their own message is queued gets no passive Watches. Fix: reactivate only on person input with receivedAtMs > watchesPassiveAt, because input received before the stop is input that the stop cancels. Please add this case to the heartbeat-timers scenario.

2. Passive Watches below the stopped Conversation can never become active, but the docs say they do.

  • using-junior.md says the Watches "of its child agents" become passive and that a later @jr mention "makes those watches active again".
  • reactivateWatches clears only context.conversationId, so the descendants keep watchesPassiveAt forever.
  • Clearing it would not help: the child worker acks and drops every Event for a child whose latest invocation is stopped (startAgentInvocationsForChildInput).
  • Decision (1) makes this worse for stopAgent and the worker cascade. A parent can give a stopped child new work through messageAgent (see agent-invocation-stop.test.ts, "lets a message start new work"). Parent input does not reactivate, and listWatches still lists the old Watches (the concurrency test asserts this). So the re-tasked child believes its Watches are live, while their Events go only to its transcript. On main, stopAgent cancelled them, so the child saw no Watches and could create new ones.

My suggestion: make only the Watches of the Conversation that the person stopped passive, and keep cancelling Watches for every descendant, both on a person's stop and on stopAgent or the cascade. If David wants the whole tree passive, then a person's input must reactivate the tree, a parent re-task must reactivate the child, and the docs need to match. Either way, the docs and the code must agree.

Migration order. This PR adds 0083_conversation_watches_passive, and #2834 adds 0083_conversation_kind on main. #2841 is stacked on #2834 with 0084_thread_archived_at. Whichever lands second must rebase, delete its own migration SQL, snapshot, and journal entry, and run db:generate again, so the prevId chain stays valid. If this PR lands first, #2834 becomes 0084 and #2841 becomes 0085. If #2834 and #2841 land first, this one becomes 0085. A rename alone is not enough, because each snapshot links to the one before it.

The passive check is correct. Both watch.createdAtMs and watchesPassiveAt use app Date.now(). The <= comparison and "a missing record counts as passive" are both fine, because a missing record means the Watch was cancelled or expired. I checked the Event producers:

  • Watches and timers carry subscriptionId.
  • Agent results, top-level agent messages, and system review-item changes do not, so they take the stoppedAt branch.
  • Dispatch and scheduler input is plugin or scheduler, and event automations run in their own Conversations.

So no other source reactivates, and no other source is silenced by mistake. A Watch that a later agent-result Turn creates stays active. That is reasonable, because a later Turn created it on purpose.

Rolling deploy is acceptable. The column is additive and nullable, and junior upgrade migrates before deploy. During the rollout, an old pod's worker still runs Events after stoppedAt. That is a short window.

Nits

  • Name one more known gap: a Watch created by the running Turn between markConversationsStopped and its stop-signal check stays active. This is the same class as the spawn race.
  • A Watch that is created again with the same key keeps its old createdAtMs, so after a stop it stays passive.
  • savePassiveWatchEvents loads the full message history for each batch. A noisy passive Watch, such as a busy channel over its TTL, grows the transcript with a load for each Event, and the next person Turn then reads all of it. Consider a cap, or one rolling Message per Watch, as a follow-up.

)
) {
// Parent agent input does not reactivate Watches: only a person does.
if (messages.some(isPersonInput)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also matches the person messages that the stop itself cancels: they are still in attemptMessages when run() starts, because completeConversationStop removes them only after the run. I reproduced it: Stop with a queued web message → watches_passive_at is null after drain() → the timer from before the stop starts a Turn. Please check only person input with receivedAtMs > watchesPassiveAt.

- **Verbosity:** `@jr tl;dr` or `@jr more detail on the error handling`

When Junior acknowledges a stop, it leaves the thread and cancels active resource watches for that conversation. A later `@jr` mention invites Junior back, but you must ask it to create those watches again.
When Junior acknowledges a stop, it leaves the thread and stops its child agents. Its resource watches, and those of its child agents, become passive: Junior saves their events to the conversation but does not act on them. A later `@jr` mention invites Junior back and makes those watches active again.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code does not do this for child agents. reactivateWatches clears only the Conversation that got the person's input, and a stopped child drops every Event anyway. Either cancel descendant Watches and drop "and those of its child agents", or reactivate the tree.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@sentry-junior sentry-junior Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 3513fce. These pass against Postgres: stop.test.ts, agent-invocation-stop, -concurrency, -nested, -message, -work, heartbeat-timers, event-wake-delay, acp-http-recovery, and Slack steering (54 tests). pnpm typecheck, pnpm lint, and file-length:check also pass.

Both earlier must-fixes are resolved. reactivateWatchTree's lt(watchesPassiveAt, beforeMs) keeps any stop newer than the input in effect, and it also keeps input that the stop cancels from reactivating. parentToolCallId is set only by spawn.ts and createAgentInvocationForMessage. createAgentInvocationFromLatest (Event and result work) leaves it unset. The heartbeat append recovery does carry it, but beforeMs = invocation.createdAtMs makes a replay of an invocation from before the stop a no-op. The passive append uses the same message:<id> key as appendConversationMessages, so a redelivered batch is deduped. If a later Turn saves that Message, it goes through the normal path and emits message_updated.

Must-fix: a child's late cascade marks its descendants again, using the mode that the child has at that later time. stopChildAgentsOf(C) calls markConversationsStopped on every Conversation below C, not only on the ones whose work it stopped. The person's tree stop already marked them. C runs this only when its own run sees the stop, which can be much later if C is in a long tool call. If the person sends input to the root in that window, reactivateWatchTree clears C's watchesPassiveAt. The cascade then reads undefined and cancels the grandchild's Watches.

I reproduced this with a scratch integration test (since deleted):

  1. Root R, running child C, and grandchild G with a timer Watch.
  2. stopConversation(R): G is passive.
  3. reactivateWatchTree(R, now): R, C, and G are active.
  4. C's run is released and aborts. G's stoppedAt moves later, and G's timer Watch is now cancelled.

The variant without a reactivation has the same root cause. The cascade sets a newer watchesPassiveAt on G, so person input received between the stop and the cascade no longer reactivates G (watchesPassiveAt < beforeMs fails). Fix: let the cascade mark only the Conversations whose invocations it stopped itself (from tree.stopped), so it still covers the spawn race. Or skip Conversations whose stoppedAt is at or after C's own stoppedAt. Please add this ordering to stop.test.ts.

Nits

  • isFromLiveWatches checks "not cancelled", not "not passive". This is safe only because skipInputAfterConversationStop runs first and saves batches that contain only passive Events. A mixed batch (a passive Event plus an Event received after the stop) returns undefined there, so the passive Event goes into a new invocation. This is rare, because an active Watch on a stopped child that was not reactivated only comes from the known gap. Still, the JSDoc claim "these come from Watches that a person made active again" does not hold for mixed batches. Two options: give isPassiveWatch the same check, or say so in the comment. A related case: a passive Event batched with an Event that has no subscriptionId (a system review-item change) on a stopped child is acked by isFromLiveWatches → false, so the passive Event is never saved.
  • A messageAgent call from a parent Turn that has not yet seen the stop now also reactivates the child's Watches. This is the same class as the spawn race, so add it to the gap that is already named.
  • stopChildAgentsOf reads the mode with readConversationStop before stopAgentInvocationTree takes the tree lock. A concurrent stopAgent (cancel) and a person stop on the same child can interleave, with the last writer winning. This is acceptable, but the fix above makes it moot for descendants that are already stopped.

state,
{
state,
watches: stop?.watchesPassiveAtMs === undefined ? "cancel" : "passive",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This marks every Conversation below this child again, using this child's mode at cascade time. If a person's input reactivates the tree before this run sees the stop, the mode becomes cancel and the grandchild's Watches are cancelled. I reproduced it: stop the root → reactivateWatchTree(root) → release the child run → the grandchild's timer is cancelled. Otherwise it gives the grandchildren a newer watchesPassiveAt, so input received in between does not reactivate them. Mark only the Conversations whose work this call stopped (tree.stopped).

? metadata.event.subscriptionId
: undefined;
const watch = watchId ? await getWatch({ id: watchId, state }) : undefined;
if (!watch || watch.status === "cancelled") {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Live" here means "not cancelled", not "not passive". A mixed batch (a passive Event plus an Event received after the stop) gets past skipInputAfterConversationStop, so the passive Event starts work. This is rare (it needs the Watch-during-stop gap), but either check passivity here too or narrow the JSDoc.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

sentry-junior Bot and others added 10 commits November 7, 2026 03:06
Prettier output only. lint-staged reformats this file on any change, so
keep the reformat out of the next commit.

Co-Authored-By: David Cramer <[email protected]>
A stopped Conversation (stopped_at set) whose work is idle or failed now
reports status "stopped" in the dashboard and MCP Conversation views
instead of "completed". A Turn that runs while it is stopped still shows
as "active". execution_status and the work state stay as they are. The
dashboard shows a stopped marker in lists and "Stopped" in the sidebar.

Co-Authored-By: David Cramer <[email protected]>
…stops

The stop keyword and Slack's stop button now share one handler that calls
core stopConversation. The keyword no longer leaves the thread, so the
thread stop watermark and resubscribe hook are gone; stopped_at orders
input, and the next mention ends the stop.

When a root's run sees its stop late, core now stops the child agents it
spawned or re-tasked after the stop, as a child agent's worker does.

Co-Authored-By: David Cramer <[email protected]>
stopChildAgentsOf stopped the tree with includeRoot, so it skipped every
appended result sent to the Conversation, including results it already
read, and listChildAgents lost their lastResult. It now leaves the
Conversation's own work alone and skips only the results that still wait
in its mailbox, as a person's stop does.

The dashboard treats a stopped Conversation as idle for unread tracking.

Co-Authored-By: David Cramer <[email protected]>
Slack sends one mention as both message and app_mention, and it retries
events. Each delivery stopped the Conversation again and posted another
ack, and a late retry could stop a newer Turn. Saving the stop message
now claims the stop on its Message id, so a second delivery does nothing.

A late cascade now stamps child agents with the stop it cascades, so
input that ends that stop ends theirs too. A stopped Conversation no
longer counts as failed in aggregates.

Co-Authored-By: David Cramer <[email protected]>
A Slack stop now builds the same inbound message as any other Slack
message and claims its inboundMessageId in the work state, next to the
mailbox append. A second delivery of the same message is a duplicate for
the stop and for the mailbox, so it stops nothing and posts no ack. Core
stopConversation takes the stop message and claims it before it stops
anything. The skipped stop Message uses the plain idempotent append.

Co-Authored-By: David Cramer <[email protected]>
A failed stop kept its message claim, so Slack's retry of the same stop
was a duplicate and stopped nothing. stopConversation now releases the
claim and rethrows, so the webhook answers 503 and the retry stops the
work. A failed ack after a stop keeps the claim: the work is stopped.

Co-Authored-By: David Cramer <[email protected]>
A stop released its message claim on any failure, also when its metadata
write or wake failed after the stop request was saved. Slack's retry was
then a new stop and could stop newer work. Release the claim only when
the stop fails before its request is saved.

Co-Authored-By: David Cramer <[email protected]>
…p button

A Slack retry of a failed stop wrote a new Date.now() stop time, so a
mention sent after the stop was dropped. A stop with a message or button
press now uses its Slack send time. Only person input sent at or before
it is dropped, and the stopped_at write never moves a stop back.

The native stop button claims its event_ts like the keyword, so a retry
of the press stops nothing more. Slack stop handling moves to
ingress/slack-stop.ts, with one shared skipped-Message save.

Co-Authored-By: David Cramer <[email protected]>
The claim ran before the try, so a failed metadata write after the claim
landed kept the claim, and every Slack retry was a duplicate. Claim inside
the try so that failure releases it too.

Pin that a stop ends only for person input sent after it, by send time, and
note the known gap: input sent before the stop but received after it runs and
leaves the Conversation stopped.

Co-Authored-By: David Cramer <[email protected]>
@blacksmith-sh

This comment has been minimized.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

After a run sees its stop, it throws only when saving the cancelled Turn
fails. With retries left, recordConversationRetry keeps the runId, so the
retried run sees the stop and cascades. On the final attempt the cascade was
lost, so child agents tasked after the stop kept running. Run the cascade on
that path too, and log a failed cascade so the run's own error wins.

This case has no test seam: the cancelled-Turn save uses only global stores,
and injecting one would add test-only surface.
Claiming inside the try released on any claim error, including errors before
the duplicate check, such as a lock timeout or a failed read. Then a
redelivery of a stop that already worked dropped the first delivery's claim,
and Slack's next retry stopped again.

The store now releases a claim only when its own metadata write fails, and
stopConversation claims before its try again. Also name the cascade log event
with the .failed convention, and count stopped Conversations as unread in the
dashboard mock, as the API does.

Co-Authored-By: David Cramer <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 4819757. Configure here.

A claim can land and still throw, from an index write after the record or
from the lock release. Then nothing released it, and every Slack retry was a
duplicate, so the stop was lost.

claimInboundMessage now releases its claim on any failure after its
duplicate check passed. A failure before that check still keeps a claim that
an earlier delivery saved. releaseInboundMessage now logs its own failure,
so its three callers no longer repeat that catch.
@dcramer
dcramer merged commit 72edb9c into main Nov 7, 2026
45 checks passed
@dcramer
dcramer deleted the fix/stop-child-agents-on-parent-stop branch November 7, 2026 04:32
sentry-junior Bot added a commit that referenced this pull request Nov 8, 2026
A tree stop marks each child stopped and stops its work. A Thread's
person Turn that waits for sign-in has no worker, so the stop never
reached it, and a later sign-in callback could resume it. The tree stop
now cancels that Turn with the same cleanup as a stopped resume.
abandonTurnRecord takes onlyIfAuthPaused, so a Turn that a worker
already resumed keeps its worker.

A person's input already ends a stopped Thread's stop through #2832, so
no Thread restart rule is needed.

Co-Authored-By: David Cramer <[email protected]>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — 5b237150 Deployed Nov 7, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant