Skip to content

fix(acp-server): forward autonomous turns and hold queued prompts - #5271

Open
nitishagar wants to merge 1 commit into
MoonshotAI:mainfrom
nitishagar:fix/5095-acp-self-started-turns
Open

nitishagar wants to merge 1 commit into
MoonshotAI:mainfrom
nitishagar:fix/5095-acp-self-started-turns

Conversation

@nitishagar

Copy link
Copy Markdown

Requirement or Bug

Resolve #5095. ACP hosts never see turns the agent starts on its own from background-task notifications, and prompts sent while such a turn runs are answered immediately with an empty end_turn while the text runs later invisibly (or appears lost). After this PR, hosts receive updates for every turn the agent runs, and prompts arriving during an autonomous turn wait for their own turn instead of settling empty.

Bug Reproduction Steps

See linked issue. Automated coverage is in packages/acp-server/test/autonomous-turn.test.ts (both cases fail on main, pass with this fix).

Root Cause

Fundamental fix, both mechanisms in AcpSession (packages/acp-server/src/session.ts):

  1. Every turn-event handler dropped events unless driverFor(turnId) matched the single ACP-owned driver. Engine-driven turns (background-task notifications, goals, cron) have no driver, so no session/update was ever emitted for them.
  2. agent.prompt() returns undefined when the loop is busy (the prompt is admitted to the queue). driveLaunch treated undefined as completion and resolved { stopReason: 'end_turn' } at once. The queued prompt later ran with its driver already settled, so its output was dropped by mechanism 1 and the host never saw an answer.

Code Changes

Core idea: give every ACP prompt a promptId, correlate turn.started / prompt.completed / prompt.aborted with the waiting driver so queued prompts settle only after their own work, and forward events for turns no driver owns.

  • driveTurn assigns a fresh id and passes it to agent.prompt; the engine honors attributes.promptId as the prompt id.
  • New turn.started subscription claims the driver turn when the promptId matches, sharing one claimDriverTurn helper with the launch-result path (sets the turn id, runs a deferred cancel, flushes matching buffered events).
  • A launch that returns undefined with a promptId now marks the driver queued and flushes the early buffer (every buffered event is foreign: ours has not started) instead of settling empty.
  • New shouldForwardTurnEvent guard: content events are forwarded unless a driver owns a different turn, so autonomous-turn output reaches the host whether or not a prompt is waiting.
  • turn.ended with no matching driver now emits a usage_update.
  • prompt.completed / prompt.aborted settle a still-waiting driver by promptId, covering prompts that never start their own turn (gate-blocked, steered, aborted). Ordering is safe because the engine dispatches turn.ended before prompt completion, so the normal path still settles on turn.ended with full error detail.
  • Skill activations carry no promptId and keep the previous behavior.

Key decisions:

Decision Choice Not chosen Reason
Queued prompt handling Hold until its own turn runs Reject while busy The issue lists holding first; it matches the single-flight ACP contract, and further concurrent prompts still get turn.agent_busy
Correlation key Engine promptId Claim the next turn.started Exact even with several queued prompts and across process restarts of unrelated turns
Autonomous-turn visibility Forward all updates Notify-only that a turn runs The issue's stronger option; hosts already tolerate updates outside prompted turns

Reading guide: packages/acp-server/src/session.ts holds the whole fix; packages/acp-server/test/autonomous-turn.test.ts holds the two real-engine regressions; the two .changeset/ files are the library and CLI entries.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
session/update for engine-driven turns over ACP Nothing emitted Assistant, thinking, tool-call and usage updates emitted ACP clients (Zed and others via kimi acp) that assume updates only follow their own prompts; ACP frames no turn ownership, so extra updates are additive None; purely additive
session/prompt sent while an autonomous turn runs Immediate empty end_turn; the text runs later with no visible output Stays pending; resolves when its own turn completes, with visible output Nobody sane: the old response carried no output and the work was invisible None; this was data loss
Second prompt while a queued prompt is still waiting Each prompt settled immediately on its own Rejected with turn.agent_busy, like any in-flight turn Same clients as above Retry after the turn ends
usage_update after autonomous turns Never emitted Emitted Usage-tracking clients get accurate context meters None; additive

Affected modules and coverage:

  • packages/acp-server/src/session.ts: new test/autonomous-turn.test.ts (engine-driven output forwarded with no prompt in flight; queued prompt waits for its own turn; both fail before, pass after). Existing e2e-turn, lifecycle, kap-parity and the rest of the acp-server suite pass: 163/165, where the 2 failures are a pre-existing session/delete assertion that also fails on pristine main and a load-induced convert timeout that passes in isolation (8/8).
Verification commands and results
  • pnpm exec vitest run --reporter=agent test/autonomous-turn.test.ts → 2 passed (with fix); 2 failed (fix stashed)
  • pnpm exec vitest run --reporter=agent test/ (acp-server) → 163 passed, 2 failed as described above
  • pnpm exec tsc -p packages/acp-server/tsconfig.json --noEmit → clean
  • pnpm --filter @moonshot-ai/acp-server run build → clean
  • pnpm lint components: check-comments, import-boundaries, guards, test-doubles, quarantine, instructions all pass; type-aware oxlint passes on the changed files (0 warnings, 0 errors). The repo-wide type-aware oxlint backend was killed by the sandbox (SIGTERM) in this environment, so CI is the final word there.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Assign a promptId to every ACP prompt and correlate turn.started, prompt.completed and prompt.aborted with the waiting driver, so prompts queued behind engine-driven turns settle only after their own work. Forward turn events for turns no driver owns and emit a usage update when they end, instead of dropping them.

Fixes MoonshotAI#5095
@changeset-bot

changeset-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 328934d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/kimi-code Patch
@moonshot-ai/acp-server Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T07:52:01.708553Z 328934d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 328934ddfd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (driver === undefined || driver.settled) return;
if (driver.promptId === undefined || event.promptId !== driver.promptId) return;
this.settleDriver(driver, () => {
driver.resolve({ stopReason: turnEndReasonToStopReason(event.reason ?? 'completed') });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor cancellation before settling a blocked queued prompt

When an ACP host sends session/cancel while this prompt is queued behind an autonomous turn, AcpSession.cancel() sets driver.cancelRequested; if the queued prompt is then blocked before its own turn.started, the engine emits prompt.completed(reason: 'blocked') rather than prompt.aborted, and this handler maps it to refusal without checking the flag. The canceled session/prompt therefore reports a refusal instead of cancelled; honor cancelRequested before mapping the completion reason.

AGENTS.md reference: AGENTS.md:L205-L205

Useful? React with 👍 / 👎.

@RealKai42

Copy link
Copy Markdown
Collaborator

Thanks for this. Since #5447 and #5586 landed, turns that the engine starts on its own are already forwarded to ACP editors, so that half of this PR now overlaps with main. Could you rebase it to keep only the part that queues editor prompts while such a turn is running, instead of rejecting them as busy? If we don't hear back within a week, we'll close this and pick up the queueing part in a separate PR.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ACP: turns self-started by background-task notifications emit no session/update; prompts arriving during them are answered with empty end_turn and lost

2 participants