Skip to content

feat(runner): reliable multi-gate approvals: truthful results, persisted answers, per-card dispatch#5382

Merged
mmabrouk merged 15 commits into
feat/sessions-storage-reworkfrom
plan/concurrent-approvals
Jul 21, 2026
Merged

feat(runner): reliable multi-gate approvals: truthful results, persisted answers, per-card dispatch#5382
mmabrouk merged 15 commits into
feat/sessions-storage-reworkfrom
plan/concurrent-approvals

Conversation

@mmabrouk

@mmabrouk mmabrouk commented Jul 18, 2026

Copy link
Copy Markdown
Member

The symptom

During live QA, a user asked the agent to run two permission-gated shell commands in one turn (append a line to two files). The user approved the first command, and the playground reported it as "not executed" even though it had run. After the user approved the second command the whole conversation went silent and never replied, the already-approved first card flipped back to "waiting for approval", and a later question was answered with a stale "Done" instead of being read. Both files were in fact written exactly once, each only after its approval. What broke was the reporting, the rebuilt state, and the delivery of the final approval to the runner.

The runner is the Node/TypeScript sidecar under services/runner/ that drives a coding-agent harness (Pi or Claude) inside a sandbox. A gate is a human-approval request the harness raises before a policy-gated tool runs. When a gate has no answer the runner ends the turn and parks the live harness session in a keep-alive pool; when the answer arrives it checks the session back out and continues in place (a warm resume).

What this PR changes

Truthful results when a turn pauses. Before: the post-pause cleanup swept every open tool call and stamped a "not executed, retry the same call" sentinel onto calls that had actually been approved and were mid-execution, so their real result was dropped and a side-effecting command was invited to run twice. After: an approved, executing call is excluded from the sweep and keeps its real executor result; a call that never started is recorded as deferred, never as a fake success.

Persisted approval answers. Before: the session record stored every approval request but no answer, so any state rebuild (a reload) resurrected answered gates as pending. That is why the first card flipped back to "waiting". After: resolving a gate emits a durable interaction_response record and writes the allow/deny verdict into the interaction row's resolution field. Rebuilt conversations overlay answers onto requests and render answered cards as answered.

Per-card dispatch with partial answer sets. Before: the frontend sent approvals only once every visible card looked settled, a condition that could never hold after a rebuild, so the final answer sat unsent in browser memory and the conversation died. After: one click sends one answer. The runner accepts a resume that answers a subset of the parked gates, answers those, streams their results, and re-parks on the rest.

The Pi-batching park rule. Pi does not execute a parallel tool call the moment its own approval resolves; it waits until every sibling call in the batch has been answered, then runs them together. Before: the runner held the resume turn open waiting for the approved call's result, which under Pi could never arrive while a sibling gate was still pending, so the turn hung for the full five-minute per-call limit and the watchdog killed the stream. After: under Pi, when a fresh gate is still parked, the runner skips that bounded wait and parks immediately, carrying the approved call ids so the final resume replaces the interim placeholder with the real result. Claude keeps the bounded wait, where the approved call does finish inside the same turn.

Cross-turn rebuild correctness. Before: on reload, hydration treated the runner's park placeholders as final tool results, so a re-raised gate was sealed shut and the card could never be answered again. After: a later approval request reopens a placeholder-only result but never a real one, and answers are resolved across turn boundaries through a transcript-wide index, so a rebuilt conversation is answerable and matches the live one.

What this PR deliberately does not do

  • Real turn cancellation (abandoning parked work when new user text arrives, the Zed-style cancel-then-restart) goes to a follow-up with Arda after the sessions PRs merge. It depends on the session-streams control plane those PRs introduce and is partly a product decision.
  • Audit-hardening of record ids (scoping stable record ids by turn so contradictory results append instead of overwriting) is queued separately. The answer persistence here already fixes the user-facing rebuild problem.
  • Two approval cards genuinely on screen at once. Both live harnesses raise gates serially today, so the user sees one card per cycle. True simultaneous gates depend on upstream adapter changes, tracked in issue [bug] ACP permission gates are raised serially, so parallel gated tool calls are approved one at a time #5391.

Merge order

This branch is stacked on the sessions rebase: PR #5375 (backend) and PR #5376 (runner) carry the shared session_turns counter fix and its 409 mapping, and merge first. This PR's base is sessions-rebase/runner; merge it after those two.

How this was verified

  • Unit suites pass: the runner tests (1,238), the playground package tests, and the API tests including real-Postgres round-trips of the new resolution verdict.
  • An adversarial review pass over the whole train produced seven findings (four blockers). All seven are fixed, each with a regression test encoding its failure scenario, including the incident replayed end to end at the engine seam (two parallel gated calls, one gate surfacing mid-resume, a cancellation-closure frame).
  • Four live QA cycles on the EE dev stack drove the real product endpoint and asserted on the SSE frame stream and the runner log, never on model prose. Two regressions surfaced during verification and were fixed with live-observed root causes: the Pi-batching deadlock above, and two frontend defects (the dispatch guard misreading a freshly clicked second card, and hydration sealing a re-raised gate). Cycle 4 is fully green on the incident's exact shape: both files appended exactly once, no card flips to waiting, the follow-up question is answered directly. A 32-second MP4 of the passing run is saved on the dev box (debug/qa-concurrent-approvals/qa-concurrent-approvals-pass.mp4) and is pending a manual browser upload to this thread.

@vercel

vercel Bot commented Jul 18, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
agenta-documentation Ready Ready Preview, Comment Jul 21, 2026 3:37pm

Request Review

@mmabrouk

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0ce95503-7a06-4928-b18f-49acfc1b59aa

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR spans three main slices: (1) runner-side concurrent human-approval support, removing the single-gate latch and enabling multiple parked approval gates with plural resume decisions; (2) a backend sessions API rewrite introducing session_turns, stream headers, mounts agent_id, and span/record identity columns, replacing session_states; and (3) a repository-wide HarnessTypeHarnessKind rename, plus deployment config for a runner kill token.

Changes

Concurrent approvals

Layer / File(s) Summary
Design and incident docs
docs/design/agent-workflows/projects/concurrent-approvals/*, docs/design/agent-workflows/projects/approvals-incident-fixes/*, docs/design/agent-workflows/scratch/*
Documents concurrent approval behavior, incident root causes, and remediation plans.
Plural approval pause contracts
services/runner/src/permission-plan.ts, services/runner/src/protocol.ts, services/runner/src/engines/sandbox_agent/{acp-interactions.ts,client-tools.ts,environment-setup.ts,pause.ts,runtime-contracts.ts}
Removes the approval latch and introduces per-tool-call parked approvals and non-parkable pause tracking.
Multi-gate runner parking and resume
services/runner/src/engines/sandbox_agent/{run-turn.ts,runtime-policy.ts,environment.ts,sandbox-reconnect.ts,session-continuity-durable.ts}, services/runner/src/{server.ts,responder.ts,version.ts}, services/runner/src/sessions/{alive.ts,interactions.ts,persist.ts}, services/runner/src/tracing/otel.ts
Parks multiple gates, builds per-gate resume decisions, and falls back cold for incomplete/mixed pauses.
Runner multi-gate validation
services/runner/tests/**
Updates harnesses and assertions for separate approval cards, plural parked state, and per-gate resumes.
SDK and frontend approval framing
sdks/python/oss/tests/pytest/unit/agents/**, web/packages/agenta-playground/tests/unit/agentApprovalResume.test.ts, web/oss/src/components/AgentChatSlice/*
Verifies one approval frame/tool-result per gate and hydration of interaction_response.

Sessions API rewrite

Layer / File(s) Summary
Database migrations
api/oss/databases/postgres/migrations/**
Adds session_turns, stream header columns, mounts.agent_id, span/record identity columns; drops session_states.
Core domain and DAOs
api/oss/src/core/{sessions,mounts,tracing,shared}/**, api/oss/src/dbs/postgres/{sessions,mounts,tracing}/**
Implements turns/streams/interactions/mounts services and DAOs, plus span identity promotion.
FastAPI surface
api/oss/src/apis/fastapi/{sessions,mounts,otlp,tracing}/**, api/entrypoints/routers.py, api/oss/src/utils/env.py
Exposes new turns/streams/mounts endpoints and runner kill config.
Python client regeneration
clients/python/agenta_client/**
Regenerates types/clients for turns, stream headers, and mounts agent_id.
SDK identity tracing
sdks/python/agenta/sdk/{engines/tracing,middlewares,models}/*
Adds agent_id span attribute and normalizer wiring.
Backend tests
api/oss/tests/pytest/**
Covers session lifecycle, turns DAO, mounts backfill, and tracing identity.

HarnessType→HarnessKind rename

Layer / File(s) Summary
SDK harness enum rename
sdks/python/agenta/sdk/agents/**
Renames the harness enum and all dependent signatures.
Rename in tests
sdks/python/oss/tests/**, services/oss/tests/pytest/unit/agent/conftest.py
Updates test fixtures to use HarnessKind.

Runner config

Layer / File(s) Summary
Deployment config and docs
hosting/docker-compose/**, hosting/kubernetes/helm/templates/api-deployment.yaml, docs/docs/self-host/reference/01-configuration.mdx
Adds AGENTA_RUNNER_INTERNAL_URL/AGENTA_RUNNER_TOKEN for the API-to-runner kill hop.

Estimated code review effort: 5 (Critical) | ~150 minutes

Possibly related issues

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The diff includes a separate agent_id/tracing/mounts feature set that is unrelated to multi-file approval handling. Split the agent_id/tracing/mounts work into a separate PR and keep this one scoped to approval concurrency.
Docstring Coverage ⚠️ Warning Docstring coverage is 31.75% which is insufficient. The required threshold is 60.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes implement the runner-side multi-approval handling requested by #5373, including separate cards and per-gate resume decisions.
Title check ✅ Passed The title is concise and accurately summarizes the main runner-side multi-gate approval changes.
Description check ✅ Passed The description is detailed and clearly aligned with the approval, persistence, and dispatch changes in the diff.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch plan/concurrent-approvals

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@mmabrouk mmabrouk left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Plan review: approved with decisions on the four open questions, binding for the implementation.

  1. Yes, remove the client-tool side of the latch and delete PendingApprovalLatch entirely, on the condition the implementer greps for every consumer first and the test suite pins that no other behavior leaned on it. Dead coordination primitives left in place get resurrected by accident.

  2. The watchdog watches the whole set. A turn with parked gates is pending until every gate is resolved; watching only the first gate recreates the width-one assumption we are removing.

  3. Proceed as planned on the Claude concurrency unknown. Steps 1 and 2 fix #5373 regardless of whether the Claude adapter holds gates concurrently. The step-3 live warm-path test is the arbiter: if Claude serializes its permission requests, document that as the harness's own behavior, keep the plural machinery (Pi and future harnesses benefit), and do not build workarounds.

  4. Yes, the live rendering check must explicitly cover two cards plus the #5078 dedup interaction, including the deny-one-approve-one combination now that #5381 gives denials their own frame.

The #5373 confirmation is the important find here: the implementation PR should carry 'Closes #5373'. Sequencing stays as agreed: client-tools-on-Daytona implements first, this second; step 3 (warm resume) lands after the sessions work settles to avoid churning against #5376. Implementation may start once CodeRabbit's pass is in and Mahmoud has had his look.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
docs/design/agent-workflows/projects/concurrent-approvals/PLAN.md (2)

205-216: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the two-card rendering test mandatory and deterministic.

The core contract requires independently answerable cards keyed by distinct toolCallIds, but the component test is marked “if feasible” and the remaining coverage is manual. Add a required test asserting distinct card identity and independent approve/deny behavior.


369-383: 🩺 Stability & Availability | 🔵 Trivial

Add an independent warm-path rollout gate.

The plan calls the multi-gate warm path the least-proven behavior, but its rollback mechanism is a code revert. Gate the warm multi-answer behavior separately, retain the cold fallback, and add metrics for fallback, partial response, rejection, and duplicate-answer cases.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f9d25fd2-3e3c-4b18-a4c6-97821edb46d8

📥 Commits

Reviewing files that changed from the base of the PR and between 3b0c0cb and 6474509.

📒 Files selected for processing (2)
  • docs/design/agent-workflows/projects/concurrent-approvals/PLAN.md
  • docs/design/agent-workflows/projects/concurrent-approvals/README.md

Comment on lines +364 to +367
Order to prefer: deny-frame (#5381) and sessions (#5375/#5376) land, then concurrent-approvals
steps 1 to 2, then step 3 on top of the sessions machinery. If steps 1 to 2 are ready before
sessions lands, they can go first since they do not touch the keep-alive files, and step 3
follows.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the inconsistent sessions PR reference.

The preceding section identifies the sessions work as PR #5376, but this sequence refers to #5375/#5376. Keep the PR number and branch reference consistent to avoid stacking the implementation on the wrong base.

Proposed wording
- Order to prefer: deny-frame (`#5381`) and sessions (`#5375/`#5376) land, then concurrent-approvals
+ Order to prefer: deny-frame (`#5381`) and sessions (`#5376`) land, then concurrent-approvals
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Order to prefer: deny-frame (#5381) and sessions (#5375/#5376) land, then concurrent-approvals
steps 1 to 2, then step 3 on top of the sessions machinery. If steps 1 to 2 are ready before
sessions lands, they can go first since they do not touch the keep-alive files, and step 3
follows.
Order to prefer: deny-frame (`#5381`) and sessions (`#5376`) land, then concurrent-approvals
steps 1 to 2, then step 3 on top of the sessions machinery. If steps 1 to 2 are ready before
sessions lands, they can go first since they do not touch the keep-alive files, and step 3
follows.

Comment on lines +48 to +52
Related prior work this plan builds on: [../hitl-fix/](../hitl-fix/) (the original
approve/deny round-trip fix) and [../cold-replay-stopgaps/](../cold-replay-stopgaps/) (the
text-replay hardening). The ground-truth code trace this plan is built on lives at
[../../scratch/research-client-tools-and-concurrent-hitl.md](../../scratch/research-client-tools-and-concurrent-hitl.md),
Question 2.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Complete the trailing research reference.

The README ends with a dangling Question 2. fragment. Fold it into the preceding sentence so readers know exactly which section to open.

Proposed wording
- The ground-truth code trace this plan is built on lives at
- [../../scratch/research-client-tools-and-concurrent-hitl.md](../../scratch/research-client-tools-and-concurrent-hitl.md),
- Question 2.
+ The ground-truth code trace this plan is built on lives at
+ [../../scratch/research-client-tools-and-concurrent-hitl.md](../../scratch/research-client-tools-and-concurrent-hitl.md),
+ specifically Question 2.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Related prior work this plan builds on: [../hitl-fix/](../hitl-fix/) (the original
approve/deny round-trip fix) and [../cold-replay-stopgaps/](../cold-replay-stopgaps/) (the
text-replay hardening). The ground-truth code trace this plan is built on lives at
[../../scratch/research-client-tools-and-concurrent-hitl.md](../../scratch/research-client-tools-and-concurrent-hitl.md),
Question 2.
Related prior work this plan builds on: [../hitl-fix/](../hitl-fix/) (the original
approve/deny round-trip fix) and [../cold-replay-stopgaps/](../cold-replay-stopgaps/) (the
text-replay hardening). The ground-truth code trace this plan is built on lives at
[../../scratch/research-client-tools-and-concurrent-hitl.md](../../scratch/research-client-tools-and-concurrent-hitl.md),
specifically Question 2.

@mmabrouk
mmabrouk force-pushed the plan/concurrent-approvals branch from 6474509 to 0071f90 Compare July 18, 2026 22:37
@mmabrouk mmabrouk changed the title docs(plan): multiple simultaneous approval requests in one turn feat(runner): allow multiple simultaneous approval requests in one turn Jul 18, 2026
@mmabrouk
mmabrouk changed the base branch from main to feat/deny-frame-egress July 18, 2026 22:38

@mmabrouk mmabrouk left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reviewer guide: the four riskiest hunks are flagged inline. The cold-path fix (latch removal + plural record) resolves #5373 on its own; the warm-resume machinery is the least-proven part and is what to scrutinize hardest. Live warm-path QA is the arbiter (evidence in a PR comment).

// Do NOT force-settle open tool calls here, at first pause. With concurrent approvals a
// second gated call may still be in flight (its permission request lands a tick after the
// first gate pauses the turn), and settling it here would orphan a call that is about to
// emit its own approval card. The orphan settle is deferred to the post-drain sweep below

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Scrutinize: the eager first-pause settle was removed. This is the subtle consequence of deleting the latch. With gates arriving as separate ACP messages, force-settling open siblings at the first pause used to close a second gate before its own permission request landed — the latch masked this by only ever pausing one gate. Orphan settling now happens once, in the post-drain sweep below (after waitForEventDrain lets every pending gate mark its call paused). Check: does every path that used to rely on the eager settle still settle genuine orphans? The post-drain sweep at ~line 500 and the in-handleUpdate re-sweep are the two remaining settle sites; confirm a late-announced non-gated sibling still settles (pinned by the orchestration test).

env.parkedApprovals.set(info.toolCallId, record);
// The first recorded gate is the per-turn representative for logging and the
// per-turn-uniform validation reads (gate type, history, credentials).
env.parkedApproval ??= record;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Scrutinize: the plural park record. Every parkable gate is now recorded, keyed by its own toolCallId (was: only the first, guarded by approvalGateCount === 1). approvalGateCount still counts every gate, so parkedApprovals.size !== approvalGateCount means a gate lacked a resumable id — the dispatch treats that whole turn as unresumable and stays cold. Check the key choice: a gate with an empty toolCallId is counted but not recorded, which is what makes that inequality detectable.

title: decision.toolName,
kind: decision.toolName,
rawInput: decision.args,
});

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Scrutinize: the warm resume settles each gate by its own tool-call id. One respondPermission per parked gate; all decisions share the one held prompt promise (one prompt per turn). This assumes the harness holds several pending permission requests concurrently and answers each independently — the open question for the Claude ACP adapter (#5373 strongly implies yes; the live warm-path test is the arbiter). Known gap called out for review: the loop is not atomic — if gate 1's respondPermission succeeds and gate 2's throws, gate 1 may already be executing. Today that surfaces as a turn error the dispatch handles; a first-reply-succeeds / second-reply-fails test and an explicit no-cold-retry-after-partial-success contract are follow-ups.

// ANY parked prompt means the harness or sandbox died mid-park and the dead session must be
// evicted. Every parked gate shares the one turn prompt promise, so the catches are on the
// same promise; the eviction is identity-checked and idempotent, so repeated catches are safe.
for (const parked of env.parkedApprovals.values()) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Scrutinize: watchdog set semantics. The parked-prompt eviction now watches the WHOLE parked set, not just the first gate — a turn is pending until every gate resolves, and a rejection of any parked prompt evicts the dead session. Every parked gate shares the one turn prompt promise, so these catches attach to the same promise; the eviction is identity-checked and idempotent, so repeated catches are safe (no double-evict).

mismatch = "no-matching-approval";
break;
}
resumeDecisions.push({

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Scrutinize: the all-or-cold resume rule. A multi-gate turn resumes live ONLY when the request answers EVERY parked gate; a partial answer degrades to cold (which re-raises and multiplexes the subset). The frontend's all-settled rule guarantees a resume /run is only sent once all cards are answered, so a partial set here means an edited/stale request. Paired fix: inBandAnswerTokens now spares stale-sweep tokens only when the same all-answered condition holds, so a partial answer never strands an interaction row as pending on the cold fallback.

// the sweep runs; this narrow suppression only masks the cancel artifact.) Residual: a genuine
// mid-pause tool error also arrives as `failed` and reads as paused here — acceptable, since the
// paused result invites a retry and the runner has no adapter provenance to tell the two apart.
if (kind === "tool_call_update" && pause.active && frame?.status === "failed") {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Scrutinize: narrowed pause suppression (Codex fix). Only a failed update for a non-gated open call during a pause is suppressed (a managed-cancel artifact → the post-drain sweep settles it as paused). A completed update is NOT suppressed, so an auto-allowed sibling that legitimately finishes on the kept-alive warm session shows its real result. Residual, stated in the comment: a genuine mid-pause tool error also arrives as failed and reads as paused — accepted, since the runner has no adapter provenance to distinguish cancel from error and the paused result invites a retry.

@mmabrouk

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@mmabrouk

Copy link
Copy Markdown
Member Author

Live QA — wire-level walkthrough (fallback: browser recording unavailable)

Why a walkthrough and not an MP4: the Claude-in-Chrome extension (a remote macOS browser) was not connected to this automation session, so I could not drive the playground UI to capture a screen recording. Per the plan's QA fallback (the same one the sibling client-tools-on-Daytona PR used), this is the annotated frame-by-frame wire walkthrough instead. The runner change is exercised end-to-end below at the wire level, which is the layer this change actually touches — the frontend and SDK are unchanged in behavior and already handled the plural case.

Deployment: the EE dev runner container was rebuilt/restarted onto this branch's code (tsx src/server.ts, healthy, listening on :8765). The runner is the only component with behavior changes; the SDK and frontend carry test-only changes.

Scenario: an agent calls two gated tools in one turn ("read file A and file B", read gated with an ask rule)

The walkthrough traces the exact frame stream. Each step cites the runner-unit test that asserts that frame on the real event stream (these tests drive runSandboxAgent / the keep-alive dispatch and assert on the emitted events and respondPermission calls — the same wire the product endpoint streams).

Cold path (steps 1–2 of the plan — fixes #5373 on its own):

  1. The model emits two read tool calls in one assistant turn. The harness raises two ACP permission gates.
  2. The runner emits two interaction_request (kind: user_approval) frames — one per gate, each keyed by its own toolCallId (tool-a, tool-b). Neither gate is force-settled as TOOL_NOT_EXECUTED_PAUSED; both stay open. The turn ends once.
    • Asserted by sandbox-agent-orchestration.test.ts"emits a card for EACH of two racing ask gates and force-settles neither (cold-path plural approvals)": interactions.length === 2, ids ["tool-a","tool-b"], tool_result list empty.
    • Before this change: only tool-a's card emitted; tool-b was force-settled TOOL_NOT_EXECUTED_PAUSED and re-asked on a later turn — the [bug] HITL breaks on multi-file approval flow #5373 symptom.
  3. The frontend shows both cards and (its already-shipped all-settled rule) waits until both are answered before it resumes. The human answers both; the next /run replays both {approved} tool_result blocks and both tools run — no extra re-ask turn.
    • The plural decision store (extractApprovalDecisionsMap<key, list>) and the frontend all-settled gate are pinned by the SDK ingress test and agentApprovalResume.test.ts (two pending cards → no resume until both settle).

Warm path (step 3 — keep-alive, the deny-one-approve-one headline):

  1. Same two gates, keep-alive on. The dispatch parks the turn in awaiting_approval (it no longer refuses a multi-gate turn): every pending gate is a resumable approval gate, so parkedApprovals holds {tc-1, tc-2}, the session is kept alive, and both gated calls stay open.
    • Asserted by session-keepalive-approval.test.ts"two parallel gates each emit a card and BOTH park (neither is force-settled)": parkedApprovals.size === 2, keys ["tc-1","tc-2"], run.settled === [], session not destroyed.
  2. The human denies one card and approves the other in the same turn. The resume /run carries two approval-responded parts. The dispatch builds one decision per parked gate and resumes live, calling respondPermission once per gate by its own tool-call id: tc-1 → reject, tc-2 → once. The denied tool reports a decline (its own tool-output-denied frame, from the deny-frame lane this stacks on); the approved tool runs. One resume settles both — no extra turns.
    • Asserted by session-keepalive-approval.test.ts"resumes a two-gate turn with deny-one-approve-one, each gate answered on its own id": resumes === ["tc-1:reject","tc-2:once"].
  3. Partial answer (answer one card, leave the other pending): the run stays paused. The dispatch's all-or-cold rule refuses a partial live resume and degrades to cold; the frontend's all-settled rule never sends a resume until both are answered anyway.
    • Asserted by "keeps a partly-answered two-gate turn paused (only one card answered -> cold)": resumes.length === 0, re-acquired cold.

#5078 dedup interaction (checked)

The #5078 "approved tools appear multiple times" dedup lives on the frontend (PR #5058) and keys on tool identity (type + input) for the approval-card superseding, plus a separate toolCallId-keyed seen-set for file-activity. Two distinct concurrent cards (different tool, or same tool with different input — the real concurrent case) have different identities and different tool-call ids, so neither dedup ever collapses them. The correctness-critical "don't resume until every card is answered" gate does no dedup at all. Confirmed read-only during the frontend test work.

Open item (the plan's stated ship-gate for step 3)

Whether the Claude ACP adapter raises several permission requests concurrently in one turn (vs serializing them) — plan open question 3 — is the one thing only a live Claude run confirms, and it is the stated gate for trusting the warm multi-gate path. The runner is proven to handle the plural case; the cold-path fix resolves #5373 regardless of the answer. The reviewer-guiding inline comments flag exactly the warm-path hunks to scrutinize.

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
services/runner/tests/unit/client-tools.test.ts (1)

38-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Exercise onNonParkablePause in this seam.

Capture the callback count and assert that pending verdicts increment it, while deny/fulfilled verdicts do not. Otherwise the mixed-gate cold-fallback signal is only tested through a fake counter.

As per coding guidelines, “Unit-test pure engine-internal logic directly, including tools/*.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 343276b4-34ab-43c5-b903-89570cf88361

📥 Commits

Reviewing files that changed from the base of the PR and between 6474509 and 0071f90.

📒 Files selected for processing (19)
  • docs/design/agent-workflows/projects/concurrent-approvals/PLAN.md
  • docs/design/agent-workflows/projects/concurrent-approvals/README.md
  • sdks/python/oss/tests/pytest/unit/agents/adapters/test_vercel_stream_park.py
  • sdks/python/oss/tests/pytest/unit/agents/test_ui_messages.py
  • services/runner/src/engines/sandbox_agent/acp-interactions.ts
  • services/runner/src/engines/sandbox_agent/client-tools.ts
  • services/runner/src/engines/sandbox_agent/environment-setup.ts
  • services/runner/src/engines/sandbox_agent/run-turn.ts
  • services/runner/src/engines/sandbox_agent/runtime-contracts.ts
  • services/runner/src/engines/sandbox_agent/runtime-policy.ts
  • services/runner/src/permission-plan.ts
  • services/runner/src/server.ts
  • services/runner/tests/unit/client-tools.test.ts
  • services/runner/tests/unit/permission-plan.test.ts
  • services/runner/tests/unit/sandbox-agent-acp-interactions.test.ts
  • services/runner/tests/unit/sandbox-agent-orchestration.test.ts
  • services/runner/tests/unit/session-keepalive-approval.test.ts
  • services/runner/tests/unit/session-keepalive-dispatch.test.ts
  • web/packages/agenta-playground/tests/unit/agentApprovalResume.test.ts
💤 Files with no reviewable changes (2)
  • services/runner/src/permission-plan.ts
  • services/runner/tests/unit/permission-plan.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/design/agent-workflows/projects/concurrent-approvals/README.md

| File | Change |
| --- | --- |
| `services/runner/tests/unit/...` (new or extended) | Two-gates-one-turn on the cold path and the warm path; force-settle no longer fires for a second gate; multi-answer warm resume. |
| `web/packages/agenta-playground/src/state/execution/agentApprovalResume.test.ts` | Two pending cards: no resume until both settled. |

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the frontend test path.

The plan names web/packages/agenta-playground/src/state/execution/agentApprovalResume.test.ts, but the supplied stack context places this unit test at web/packages/agenta-playground/tests/unit/agentApprovalResume.test.ts. Update the plan to prevent placing Vitest tests under src/.

As per coding guidelines, unit tests for @agenta/* packages belong under tests/unit/.

Source: Coding guidelines

Comment on lines +424 to +426
- **Plans #5373** ("HITL breaks on multi-file approval flow"). This is exactly the multi-gate
breakage: several gated tool calls in one turn, capped to one card, re-asked across turns. The
implementation pull request that follows this plan will close it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Call #5373 an issue, not a plan.

This document consistently describes #5373 as a GitHub issue, so “Plans #5373” is misleading and may send readers to the wrong tracker.

🧰 Tools
🪛 LanguageTool

[style] ~424-~424: Consider an alternative for the overused word “exactly”.
Context: ... on multi-file approval flow"). This is exactly the multi-gate breakage: several gate...

(EXACTLY_PRECISELY)

// the sweep runs; this narrow suppression only masks the cancel artifact.) Residual: a genuine
// mid-pause tool error also arrives as `failed` and reads as paused here — acceptable, since the
// paused result invites a retry and the runner has no adapter provenance to tell the two apart.
if (kind === "tool_call_update" && pause.active && frame?.status === "failed") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
file="$(fd -a '^runtime-policy\.ts$' services/runner/src | head -n 1)"
sed -n '31,60p' "$file"

Repository: Agenta-AI/agenta

Length of output: 1937


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== services/runner tsconfig files =="
fd -a 'tsconfig.*\.json$' services/runner -t f

echo
echo "== runtime-policy.ts excerpt =="
file="$(fd -a '^runtime-policy\.ts$' services/runner/src | head -n 1)"
sed -n '1,120p' "$file"

echo
echo "== search for status on the asserted frame/update shape =="
rg -n "sessionUpdate\?: unknown; toolCallId\?: unknown|frame\.status|status\?: unknown|tool_call_update" services/runner/src/engines/sandbox_agent -S

Repository: Agenta-AI/agenta

Length of output: 6119


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="services/runner/src/engines/sandbox_agent/run-turn.ts"
sed -n '180,220p' "$file"

Repository: Agenta-AI/agenta

Length of output: 2154


Include status in the frame cast. frame.status is read below, but the asserted shape only declares sessionUpdate and toolCallId, which breaks strict TypeScript. The nearby run-turn.ts handler already treats status as part of the same update shape.

Proposed fix
   const frame = update as
-    | { sessionUpdate?: unknown; toolCallId?: unknown }
+    | { sessionUpdate?: unknown; toolCallId?: unknown; status?: unknown }
     | undefined;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (kind === "tool_call_update" && pause.active && frame?.status === "failed") {
const frame = update as
| { sessionUpdate?: unknown; toolCallId?: unknown; status?: unknown }
| undefined;

Source: Coding guidelines

@mmabrouk mmabrouk left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

My commit-level review of the feature commit (0071f90), after the plan review and Codex's pass. Verdict: architecture approved; final sign-off waits only on the live two-card run now in progress, which is also the plan's stated arbiter for the warm path.

What I verified in the diff:

  • The latch is genuinely gone, class and all, not bypassed: permission-plan.ts simply no longer exports it, and the emit path has no width-one guard left. The repo-wide grep confirms no surviving code consumer.
  • The parkability rule is the right conservative shape. A turn parks only when every pending gate is a parkable ACP permission gate with a resumable id; any mix with client-tool pauses or unresumable gates degrades to the cold path, which is the only path that can multiplex such a set. The three distinct no-park log lines (non-parkable, mixed, unresumable) will make production diagnosis trivial.
  • The whole-set watchdog and the per-gate resume are correct where it counts: every parked prompt is watched with an identity-checked, idempotent eviction; the resume builds one decision per tool-call id and refuses to resume live unless the request answers every parked gate, matching the frontend's all-settled predicate exactly, with partial answers degrading to cold rather than half-resuming.
  • The sibling-settle fix is a real pre-existing bug caught by this work: deferring orphan settling to the post-drain sweep, with suppression narrowed to managed-cancel failures only, removes the force-settle of a gate whose request had not yet arrived.

Noted as agreed follow-ups, not blockers: the singular parkedApproval kept as the logging representative (drop it in the warm-path hardening pass), partial-respondPermission-failure atomicity with its two failure-order tests, and the pause-registry refactor replacing the summary counters — all Codex items already documented inline.

Merge order stands: #5381 first (this PR uses its denied-frame marker), then this, and at merge time reconcile client-tools.ts and environment-setup.ts against #5383, which shares those two files.

@mmabrouk

Copy link
Copy Markdown
Member Author

Live QA: concurrent approvals (wire-level, fallback walkthrough)

Wire-level verification of this PR against the EE dev stack, driving the real product endpoint (POST /services/agent/v0/invoke) the playground drives, asserting on the SSE frame stream and the runner log, never on model prose. Cell: Claude harness, local sandbox, sonnet, vault Anthropic key (an ephemeral account minted through the admin endpoint, key stored in its vault). Tools gated with permission.default = "ask". Runner verified fresh: the running container serves this branch (bind mount), parkedApprovals is present and PendingApprovalLatch is gone.

This is the wire-walkthrough fallback, not a video. Two reasons the video was not possible, stated plainly:

  1. The headline "two approval cards in one turn" does not occur on the live Claude harness, so there is no two-card UI to film. See the Q3 finding below.
  2. The playground on this box is plain HTTP from a remote browser, which trips the known crypto.randomUUID secure-context crash, so the UI does not load there anyway.

Open question Q3 is settled: Claude raises the gates SERIALLY, not concurrently

This is the ship-gate the plan left open for step 3, and the live answer is serial. When the agent emits two parallel gated tool calls in one turn (parallel file reads, the exact #5373 shape, and separately two mutating bash calls), the runner sees exactly one permission request. Evidence, deterministic across three independent sessions and two tool types:

  • The runner logs [HITL] ACP gate ... at the entry of the permission handler, once per request_permission the harness sends. Every turn logged exactly one, even when two parallel tool-input-available frames for two distinct toolCallIds streamed on the wire. Because that log sits before any pause or latch logic, its count is the number of permission requests Claude actually sent. One per turn means Claude sent one per turn. This rules out a runner race (the runner was never asked to raise a second card).
  • The durable persist stream shows the same shape every time: tool_call -> interaction_request (one) -> done, and the sibling parallel call resolves as a settled tool_result / tool-output-error, never a second interaction_request.

Turn 1 wire frames for "read /etc/hostname and /etc/os-release in parallel" (permission.default = ask):

tool-input-available   toolu_013f…  (Read /etc/hostname, partial input x3)
tool-approval-request  toolu_013f…  approvalId=7defd9b6      <- the ONE card
tool-input-available   toolu_01FU…  (Read /etc/os-release)   <- second read's input arrives AFTER the card
tool-output-error      toolu_01FU…                           <- second read SETTLED, not carded
finish                 finishReason=other                    <- turn parks on the one gate

The Claude ACP adapter (claude-agent-acp 0.58.1) blocks on each request_permission and does not issue the next one until the current is answered. Parking the first gate ends the prompt turn, so the second call is settled rather than surfaced. This matches Claude Code's own UX, where parallel gated calls are approved one at a time.

Per-scenario result

Scenario Result Note
1. Cold two-gate park Not reproducible on Claude Turn 1 shows one tool-approval-request, not two; the sibling is settled (tool-output-error), finish=other. The "two cards in one turn" premise does not hold for the live Claude harness.
2. Resume deny-one-approve-one Not exercisable on Claude Only one gate exists per turn, so there is no second decision to carry in the same resume.
3. Warm two-gate + Q3 Warm path healthy; two gates never park Q3 = serial (evidence above). The warm resume machinery itself works (see scenario 4).
4. Regression guard (single gate) PASS Single approve -> tool-output-available, finish=stop. Single deny -> tool-output-denied (the #5381 deny frame), finish=stop. Both park cleanly (finish=other) and settle on the warm live path: the log shows resume answered gate reply=once tool=Terminal and reply=reject tool=Terminal, the new plural iterate loop calling respondPermission per gate with a one-element decision list.

What this means for the PR

The runner change is sound and does not regress the common path. The latch removal, the plural parkedApprovals map, the deferred force-settle sweep, and the plural warm resume are all correctly built, and the runner unit tests exercise the N=2 case against a fake harness that raises two concurrent gates.

The gap is the PR's before/after claim. "After: two gated reads in one turn -> two approval cards, each answerable independently, and one resume runs both" does not reproduce on the live Claude harness in this stack, because Claude never delivers two concurrent permission requests. The user still sees one card at a time. This is exactly what the plan flagged as the risk under Q3 ("If the Claude ACP adapter turns out to serialize gates rather than hold them concurrently, step 3's benefit shrinks"), and the live run confirms that branch.

Suggestions: temper the headline before/after to reflect serial Claude gating, and confirm the concurrent path against a harness that genuinely raises concurrent gates before trusting the two-card benefit. Pi builtin gating raises a separate gate per tool call and is the natural candidate to check (in these runs Pi auto-allowed, so it was not gated). The single-gate approve and deny paths, and the warm resume, are green and safe to ship.

Evidence (JSON frame captures, driver, runner log correlation) under debug/qa-concurrent-approvals/.

@mmabrouk

Copy link
Copy Markdown
Member Author

Live QA follow-up: the serial-chain value, and the concurrent path on Pi

A second live pass on the EE dev stack, driving the real product endpoint (POST /services/agent/v0/invoke, the one the playground drives) and asserting on the SSE frame stream plus the runner log, never on model prose. This pass answers the two questions the first pass left open: (1) what the user actually gets on the warm keep-alive path when a turn has two gated calls, and (2) whether any harness raises genuinely concurrent gates. Driver and JSON captures under debug/qa-concurrent-approvals/ (multi_gate.py --scn chain, chain_bash.json, chain_pi.json, park_pi.json).

1. Warm serial chain on Claude — verified, and it is replay-free

Cell: Claude, local sandbox, sonnet, vault Anthropic key, permission.default = ask, keep-alive on. Prompt: run two mutating bash commands in parallel in one turn (a reliable two-parallel-gated-call shape). The run drives to completion, approving the one card that appears each turn.

Turn Wire frames Model reasoning? Outcome
1 (cold invoke) input(A)approval-request(A)input(B)output-error(B)finish=other yes (initial turn) one card (A); sibling B force-settled; park warm on A
2 (warm resume, approve A) input(A)output-available(A)input(B)approval-request(B)finish=other no A executes, then card B arrives in the same live resume; park warm on B
3 (warm resume, approve B) input(B)output-available(B)finish=stop no B executes; reply carries both GATE-A-… and GATE-B-…

Three things prove this is the live harness continuing the original prompt, not a cold model replay between gates:

  • No model reasoning on the resume turns (reasoning-* frames absent in turns 2 and 3). The model does not re-plan; the adapter unblocks and continues.
  • B keeps its original toolCallId (toolu_015kaJ…) across all three turns. A cold replay re-mints tool-call ids; this does not.
  • Runner log, same session, no cold miss between the gates:
    [keepalive] resume … gates=1 approve=1 reject=0 tool=Terminal
    [keepalive] resume answered gate reply=once tool=Terminal      <- gate A answered on the LIVE session
    [HITL] ACP gate id=62414742… toolCallId=toolu_015kaJ… (GATE-B) <- gate B raised on the SAME session
    [keepalive] park … state=awaiting_approval (re-park)           <- re-parks on B; no `miss …; cold` in between
    

So on the warm path the user answers card 1, the approved tool runs, and card 2 arrives immediately on the same keep-alive session with no model round-trip between them. This is the honest "serial-chain" win. Note it is one card at a time (see §2), and this warm single-gate-per-turn park/resume behavior predates this PR — because the adapters serialize (each turn holds one gate), this PR's plural generalization is not what produces the chain here.

2. The genuinely-concurrent case: Pi also serializes

Cell: Pi (pi_core), local sandbox, gpt-5.6-luna, vault key, permission.default = ask. Same two-parallel-gated-bash prompt. The model issues both tool calls in one turn (both tool-input-available frames stream), but the runner raises exactly one gate:

input-available  call_j3Av…   (GATE-A)
input-available  call_LhV5…   (GATE-B)
input-available  call_j3Av…
tool-approval-request  call_j3Av…  approvalId=06ca0a9f     <- the ONE card
tool-output-error      call_LhV5…                          <- sibling force-settled, not carded
finish  finishReason=other

Runner log for this session: exactly one [HITL] pi-gate … toolName=Bash line (for call_j3Av…); none for call_LhV5…. Pi's builtin-gate path raises one permission request for the two parallel calls, same as Claude. Driving the Pi chain to completion gives the same one-card-per-turn serial chain as Claude, finishing with both gate files' contents in the reply.

So neither live harness (Claude claude-agent-acp 0.58.1, nor Pi) produces two approval cards in one turn. The plural machinery in this PR — the parkedApprovals map holding two, the deny-one-approve-one in a single resume — is correct and unit-tested against a fake concurrent harness, but it is not reachable on any harness available in this stack. The adapter-level serialization is filed as #5391.

Bottom line

  • The runner change is sound and does not regress the common path; single-gate approve and deny are green (prior pass), and the warm serial chain completes cleanly on both harnesses.
  • The headline "two approval cards in one turn" does not reproduce on Claude or Pi. Both serialize.
  • On the warm path, a two-gate turn resolves as a replay-free serial chain (evidence above), but that warm behavior is not introduced by this PR and the user still answers one card per turn.
  • The concurrent-card benefit this PR builds is latent until a harness raises concurrent gates ([bug] ACP permission gates are raised serially, so parallel gated tool calls are approved one at a time #5391).

@mmabrouk
mmabrouk marked this pull request as ready for review July 19, 2026 09:49
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 19, 2026
@mmabrouk mmabrouk added the needs-review Agent updated; awaiting Mahmoud's review label Jul 19, 2026
@dosubot dosubot Bot added the enhancement New feature or request label Jul 19, 2026
@mmabrouk
mmabrouk changed the base branch from feat/deny-frame-egress to release/v0.105.6 July 19, 2026 09:50
@github-actions

github-actions Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Railway Preview Environment

Status Destroyed (PR closed)

Updated at 2026-07-21T16:15:55.756Z

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 19, 2026
@mmabrouk

Copy link
Copy Markdown
Member Author

The full incident root cause, the Zed ACP comparison, and the five-step execution plan now live in this PR under docs/design/agent-workflows/projects/approvals-incident-fixes/ (start with README.md for reading order). Implementation is starting per that plan; each step lands as its own commit here.

@mmabrouk
mmabrouk changed the base branch from sessions-rebase/runner to feat/sessions-storage-rework July 21, 2026 12:48
@mmabrouk
mmabrouk force-pushed the plan/concurrent-approvals branch from 3f71d40 to a1468ec Compare July 21, 2026 14:29
@mmabrouk
mmabrouk force-pushed the feat/sessions-storage-rework branch from 1367100 to fab413d Compare July 21, 2026 14:31
@mmabrouk
mmabrouk force-pushed the plan/concurrent-approvals branch from a1468ec to 689168a Compare July 21, 2026 14:31
mmabrouk added 14 commits July 21, 2026 17:04
Plan-only workspace for removing the one-approval-per-turn latch so each gated
tool call in a turn emits its own approval card, pluralizing the parked-approval
record and the warm/keep-alive resume path, and verifying the already-plural
frontend and SDK behavior with tests.

Plans #5373, assesses #5078 and #5097.

Claude-Session: https://claude.ai/code/session_01DnWRxU3dCJ11hgDidm26vW
Remove the one-approval-per-turn latch (PendingApprovalLatch) so each gated tool
call in a turn emits its own approval card; pluralize the parked-approval record
(a Map keyed by tool-call id) and the warm keep-alive resume input (a list of
decisions), settling each parked gate by its own tool-call id on a live resume;
defer orphan-sibling settling to the post-drain sweep so a concurrent gate is not
force-settled before its own permission request arrives. Add runner unit tests
(two cards emit, neither force-settled; multi-gate warm park + resume;
deny-one-approve-one; mixed/unresumable sets stay cold), SDK vercel adapter plural
egress/ingress tests, and a playground all-settled resume test.

Closes #5373.

Claude-Session: https://claude.ai/code/session_01DnWRxU3dCJ11hgDidm26vW
Complete the plural approval path in run-turn: record every parkable gate into
env.parkedApprovals (keyed by tool-call id), iterate opts.resume.decisions to
answer each parked gate by its own permissionId on the live session, defer the
orphan-sibling settle to the post-drain sweep (so a concurrent gate is not
force-settled before its own permission request arrives), and wire the
non-parkable-pause signal. Update the acp-interactions unit test to assert both
concurrent gates emit their own card.

Part of the concurrent-approvals change (#5373); sits on the deny-frame egress
lane whose markToolCallDenied the live-resume deny path reuses.

Claude-Session: https://claude.ai/code/session_01DnWRxU3dCJ11hgDidm26vW
@mmabrouk
mmabrouk force-pushed the plan/concurrent-approvals branch from 689168a to ca104f0 Compare July 21, 2026 15:14
@mmabrouk

Copy link
Copy Markdown
Member Author

The interactions guard is relaxed per ruling: every approval gate now leaves a durable interaction row even when the run carries no workflow reference (attribution optional; such rows group under the session). In-band answering resolves reference-less rows, and the respond path was verified safe without references. The runner-side guard removal hunks ride the base PR #5436 (hunk attribution); the interactions client, tests, and the handoff rulings update land here.

@mmabrouk

mmabrouk commented Jul 21, 2026

Copy link
Copy Markdown
Member Author

Live verification caught an integration gap the unit tests missed: the turns-ledger append and interaction rows read the request's execution id, but no caller sets it; the runner resolved the real id for locks and records without writing it back. The dispatch now threads the resolved id onto the request (minting one when absent), pinned by a dispatch-seam test. Runner suite 1244 green.

@mmabrouk

Copy link
Copy Markdown
Member Author

Live verification — reference-less approval rows + concurrent-approval regression

EE dev stack, agent Local Claude (Pi harness · anthropic/claude-sonnet-4-5 · local sandbox · Bash gated ask). Fresh session ids.

Suite baselines: runner pnpm test 1244 passed / typecheck clean; API sessions pytest 156 passed.


D — reference-less approval row (session qa-D-1784648322)

Driven directly through /services/agent/v0/invoke with no runContext.workflow — so the raised gate has no workflow reference. A session_interactions row is created anyway.

Before answering (kind=user_approval, status=pending, no workflow attribution):

id      | 019f8554-6bdc-75f2-931b-7d90f10c3f0c
kind    | user_approval
status  | pending
token   | 212450d0-03dc-4eb8-8d26-a818a43160f0
turn_id | 6eb9c674-fd02-421c-a64e-2ad4f9460052
data    | {"request": {"tool": "Bash", "args": {"command": "echo WROTE-2a3971 > /tmp/qa-2a3971.txt && cat /tmp/qa-2a3971.txt"}}}
flags   | {"delivered_in_band": true, "delivered_webhook": false}

After answering (approve) — same row, resolved with the verdict:

id      | 019f8554-6bdc-75f2-931b-7d90f10c3f0c
kind    | user_approval
status  | resolved
data    | {"request": {...}, "resolution": {"verdict": "approved", "tool_call_id": "toolu_01K11gpwhx6KCeqVGZ7QA5Su"}}

The gate leaves a durable inbox/audit row and resolves with the verdict, with no workflow reference required. PASS.


F — concurrent-approval regression spot-check (browser, fresh session)

Re-ran the headline incident scenario end to end in the playground: "Append the line QA-F-verify-2026 to agent-files/README.md and to agent-files/NOTES.md, as two separate Bash commands issued in parallel in the same turn."

  1. Model issued two bash calls. Pi serializes gates, so card 1 (README.md) showed Awaiting approval while the sibling showed "waiting on another approval"not a phantom (no output) success for an unrun command. (screenshot F-02)
  2. Approved card 1 → it executed ("bash approved, result unknown", 129 ms) and stayed approved; card 2 (NOTES.md) then surfaced on the warm resume with card 1 unaffected. (screenshot F-03)
  3. Approved card 2 → turn completed with "Done! I've appended QA-F-verify-2026 to both README.md and NOTES.md". (screenshot F-04)
  4. Both files written exactly once — grep on the local sandbox mount:
/tmp/agenta/mounts/019e8df5-.../.../agent-files/README.md:1
/tmp/agenta/mounts/019e8df5-.../.../agent-files/NOTES.md:1
  1. Reloaded the page: the turn hydrated from its records as answered/executed with the final answer present, and no answered card was resurrected as a pending approval (no active Approve/Deny controls). (screenshot F-05)

The regression spot-check passes after today's changes — both parallel gated writes approve cleanly, each side effect happens exactly once, and a reload keeps the cards answered.

@mmabrouk
mmabrouk merged commit 188025a into feat/sessions-storage-rework Jul 21, 2026
52 of 56 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request needs-review Agent updated; awaiting Mahmoud's review size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] HITL breaks on multi-file approval flow

1 participant