Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(agent): reconcile native steering terminal races (#1200)

Call White0380dbec1309
diff --git a/core/internal_server.py b/core/internal_server.py
index 084b236ca..87cf6f013 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -135,7 +135,9 @@ def create_app(controller: "Controller") -> FastAPI:
) -> Any:
"""Run a Harness input through the same durable owner as interactive Chat.
- The explicit source intent decides whether it queues, steers, or replaces.
+ The explicit source intent decides whether it queues or steers. Send-now
+ persists the new input at P3, then promotes the exact FIFO head through
+ empty P1; it never stops the active Turn or jumps older queued work.
The submission remains a Delivery until exact native acceptance materializes
the harness Message.
"""
@@ -239,24 +241,30 @@ def create_app(controller: "Controller") -> FastAPI:
target_was_busy=target_was_busy,
delivery_status="canceled",
)
- return TurnSubmissionResult(
- route=(
- "enqueued"
- if existing_state
- in {
- "queued",
- "interrupt_waiting",
- "waiting_terminal",
- "reconciling_steer",
- }
- else "ran"
- ),
- queue_persisted=True,
- target_was_busy=target_was_busy,
- delivery_status=existing_state,
- delivery_owner_transferred=True,
- )
- return "duplicate"
+ if not (
+ delivery_intent == "send_now"
+ and existing_state == "queued"
+ ):
+ return TurnSubmissionResult(
+ route=(
+ "enqueued"
+ if existing_state
+ in {
+ "queued",
+ "interrupt_waiting",
+ "waiting_terminal",
+ "reconciling_steer",
+ }
+ else "ran"
+ ),
+ queue_persisted=True,
+ target_was_busy=target_was_busy,
+ delivery_status=existing_state,
+ delivery_owner_transferred=True,
+ )
+ delivery_owner_transferred = True
+ if not delivery_owner_transferred:
+ return "duplicate"
if legacy_accepted:
return "duplicate"
status = conn.execute(
@@ -270,9 +278,19 @@ def create_app(controller: "Controller") -> FastAPI:
scope_id = delivery_request.scope_id
from core.message_priority import delivery_intent_for_priority
- effective_delivery_intent = delivery_intent_for_priority(
+ persisted_intent = delivery_intent_for_priority(
delivery_request.priority
)
+ effective_delivery_intent = (
+ "send_now"
+ if delivery_intent == "send_now"
+ and delivery_request.priority == "p3"
+ else persisted_intent
+ )
+ delivery_request = replace(
+ delivery_request,
+ admission_only=effective_delivery_intent == "send_now",
+ )
provenance = (delivery_request.metadata or {}).get(
SCHEDULED_PROVENANCE_KEY
)
@@ -290,7 +308,11 @@ def create_app(controller: "Controller") -> FastAPI:
delivery_id = message_deliveries.new_delivery_id()
admitted_state = "reserved"
- priority = priority_for_delivery_intent(delivery_intent)
+ priority = (
+ "p3"
+ if delivery_intent == "send_now"
+ else priority_for_delivery_intent(delivery_intent)
+ )
message_deliveries.insert_delivery(
conn,
delivery_id=delivery_id,
@@ -322,7 +344,7 @@ def create_app(controller: "Controller") -> FastAPI:
"state": admitted_state,
},
)
- if execution_id:
+ if execution_id and not delivery_owner_transferred:
if not attach_agent_run_delivery_in_connection(
conn,
execution_id,
@@ -354,7 +376,11 @@ def create_app(controller: "Controller") -> FastAPI:
delivery_request = DeliveryRequest(
session_id=session_id,
- priority=priority_for_delivery_intent(delivery_intent),
+ priority=(
+ "p3"
+ if delivery_intent == "send_now"
+ else priority_for_delivery_intent(delivery_intent)
+ ),
content=text,
delivery_id=delivery_id,
scope_id=scope_id,
@@ -369,6 +395,7 @@ def create_app(controller: "Controller") -> FastAPI:
SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)
},
native_message_id=native_message_id or None,
+ admission_only=delivery_intent == "send_now",
)
if context.platform_specific is None:
@@ -436,8 +463,30 @@ def create_app(controller: "Controller") -> FastAPI:
delivery_status=delivery_status,
delivery_owner_transferred=True,
)
- route = "enqueued" if result.state in {
+ delivery_state = str(result.state)
+ if effective_delivery_intent == "send_now":
+ with get_cached_sqlite_engine().connect() as conn:
+ admitted = message_deliveries.get_delivery(conn, delivery_id)
+ observed_head = message_deliveries.ordering_head(conn, session_id)
+ if (
+ admitted is not None
+ and admitted["state"] == "queued"
+ and observed_head is not None
+ and observed_head["state"] == "queued"
+ ):
+ await manager.send_now(
+ session_id,
+ expected_delivery_id=str(observed_head["id"]),
+ )
+ with get_cached_sqlite_engine().connect() as conn:
+ latest = message_deliveries.get_delivery(conn, delivery_id)
+ if latest is not None:
+ delivery_state = str(latest["state"])
+
+ route = "enqueued" if delivery_state in {
"queued",
+ "pending_steer",
+ "steering",
"interrupt_waiting",
"waiting_terminal",
"reconciling_steer",
@@ -447,11 +496,11 @@ def create_app(controller: "Controller") -> FastAPI:
queue_persisted=True,
target_was_busy=target_was_busy,
delivery_status=(
- result.state if effective_delivery_intent == "send_now" else None
+ delivery_state if effective_delivery_intent == "send_now" else None
),
delivery_owner_transferred=delivery_owner_transferred,
)
- _publish_scheduled_queue_growth(session_id, str(result.state))
+ _publish_scheduled_queue_growth(session_id, delivery_state)
if effective_delivery_intent == "send_now":
try:
with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
@@ -460,7 +509,7 @@ def create_app(controller: "Controller") -> FastAPI:
execution_id,
{
"intent": "send_now",
- "status": result.state,
+ "status": delivery_state,
"target_was_busy": submission.target_was_busy,
},
)
diff --git a/core/message_priority.py b/core/message_priority.py
index bd735a498..155f81e06 100644
--- a/core/message_priority.py
+++ b/core/message_priority.py
@@ -3,11 +3,11 @@ from __future__ import annotations
from typing import Literal, cast
-DeliveryIntent = Literal["send_now", "steer", "queue"]
+DeliveryIntent = Literal["replace", "steer", "queue"]
DeliveryPriority = Literal["p0", "p1", "p3"]
_PRIORITY_BY_INTENT: dict[DeliveryIntent, DeliveryPriority] = {
- "send_now": "p0",
+ "replace": "p0",
"steer": "p1",
"queue": "p3",
}
diff --git a/core/run_settlement.py b/core/run_settlement.py
index b6460d3fe..4cd36f45d 100644
--- a/core/run_settlement.py
+++ b/core/run_settlement.py
@@ -355,7 +355,7 @@ _SWEEP_TURN = (
)
_SEND_NOW = (
"tests/test_internal_server.py::"
- "test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head"
+ "test_agent_run_send_now_steers_the_fifo_head_without_stopping"
)
_SEND_NOW_RESTART = (
"tests/test_internal_server.py::"
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index f1268b7b6..e82f979b3 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -140,6 +140,8 @@ AGENT_RUN_DELIVERY_INTENTS = frozenset(
)
AGENT_RUN_DELIVERY_INTENT_METADATA_KEY = "delivery_intent"
AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY = "delivery_outcome"
+FAILURE_CODE_SEND_NOW_GATE_UNAVAILABLE = "send_now_requires_turn_gate"
+SEND_NOW_GATE_UNAVAILABLE_I18N_KEY = "harness.run.sendNowGateUnavailable"
def _publish_task_definitions_updated() -> None:
@@ -559,6 +561,7 @@ class TaskDispatchResult:
class AgentRunExecutionResult:
error: Optional[str]
complete_on_return: bool
+ failure_code: Optional[str] = None
requeue_on_return: bool = False
recover_queue_on_return: bool = False
# The run's terminal row was already written by the executor itself (through a
@@ -7732,6 +7735,7 @@ class ScheduledTaskService:
)
error = result.error
should_complete = result.complete_on_return
+ failure_code = result.failure_code
settled_out_of_band = result.settled_out_of_band
recover_queue_on_return = result.recover_queue_on_return
if result.requeue_on_return:
@@ -8485,33 +8489,11 @@ class ScheduledTaskService:
delivery_intent = normalize_agent_run_delivery_intent(
(metadata or {}).get(AGENT_RUN_DELIVERY_INTENT_METADATA_KEY)
)
- if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW and (
- target.platform != "avibe" or not session_id or gate is None
- ):
- target_label = target.platform or "unknown"
- delivery_outcome = {
- "intent": delivery_intent,
- "status": "unsupported_target",
- "target_was_busy": False,
- }
- from storage.background import (
- record_agent_run_delivery_outcome_in_connection,
- run_update_event_transaction,
- )
-
- with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
- record_agent_run_delivery_outcome_in_connection(
- conn,
- execution_id,
- delivery_outcome,
- )
+ if session_id and delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW and gate is None:
return AgentRunExecutionResult(
- error=(
- "send-now requires a live Web/Workbench Agent Session; "
- f"target platform is '{target_label}'"
- ),
+ error=self._t(SEND_NOW_GATE_UNAVAILABLE_I18N_KEY),
complete_on_return=True,
- delivery_outcome=delivery_outcome,
+ failure_code=FAILURE_CODE_SEND_NOW_GATE_UNAVAILABLE,
)
if session_id and gate is not None:
if delivery_intent != AGENT_RUN_DELIVERY_STEER:
diff --git a/core/session_turns.py b/core/session_turns.py
index e234a4977..4494af113 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -453,6 +453,10 @@ class DeliveryRequest:
admission_context: dict[str, Any] | None = None
native_message_id: str | None = None
parent_native_message_id: str | None = None
+ # A caller that will immediately promote the durable FIFO head can request
+ # P3 admission without the usual idle-session auto-start. This keeps the
+ # admission and promotion decision on one post-admission queue snapshot.
+ admission_only: bool = False
@dataclass(frozen=True)
@@ -2252,7 +2256,7 @@ class SessionTurnManager:
raise RuntimeError("P3 queue claim lost after writer reservation")
delivery = queued
active = delivery_store.active_turn(conn, request.session_id)
- while active is None and not backend_draining:
+ while active is None and not backend_draining and not request.admission_only:
queued_payloads = delivery_store.claimable_fifo_prefix(
conn, request.session_id
)
@@ -5861,7 +5865,7 @@ class SessionTurnManager:
text: str,
*,
source: str = SOURCE_HUMAN,
- delivery_intent: Literal["queue", "send_now", "steer"] = "queue",
+ delivery_intent: Literal["queue", "replace", "steer"] = "queue",
) -> TurnSubmissionResult:
"""Admit one caller through the durable Delivery owner."""
from core.message_priority import priority_for_delivery_intent
@@ -5872,7 +5876,7 @@ class SessionTurnManager:
await self._run(None, context, text, source=source)
return TurnSubmissionResult(
route="ran",
- delivery_status="ran" if delivery_intent == "send_now" else None,
+ delivery_status="ran" if delivery_intent == "replace" else None,
)
spec = dict(getattr(context, "platform_specific", None) or {})
@@ -5933,7 +5937,7 @@ class SessionTurnManager:
route="enqueued" if enqueued else "ran",
queue_persisted=True,
target_was_busy=busy,
- delivery_status=result.state if delivery_intent == "send_now" else None,
+ delivery_status=result.state if delivery_intent == "replace" else None,
)
async def _run(
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 05d99a67e..029022ac8 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -283,7 +283,7 @@ Useful Harness queries include schema discovery, current session lookup, existin
| Continue a pointed Session | `vibe agent run --session-id ...` |
| Inspect queued Workbench Session input | `vibe session queue list <session-id>` |
| Remove one queued Workbench Session input | `vibe session queue remove <session-id> <message-id>` |
-| Dispatch an existing queued Workbench Session head now | `vibe session send-now <session-id>` |
+| Promote an existing queued Session head now | `vibe session send-now <session-id>` |
| Branch from current Session context | `vibe agent run --fork-self ...` |
| State/history inspection | `vibe data query`, `vibe runs list --current-session`, `vibe runs show` |
| Recurring specialist workflow | `vibe agent create/update` plus tasks, watches, or runs |
@@ -298,7 +298,7 @@ Use `vibe agent run --fork-self --message ...` when work should branch from this
When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings; those properties belong to the Session itself. Use a new Session or a fork when those properties need to differ.
-That existing-Session send is a P1 delivery by default: it steers into an active native Turn, starts immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. Use `--queue` when the new Run should enter that P3 queue without steering. When coordinating another Workbench Session, decide whether its current work should finish, accept a steer, or be replaced based on the dependency, urgency, and cost of discarding in-flight work; an explicit user request is one signal, not a prerequisite. Use `vibe agent run --session-id <id> --send-now --message ...` when the new instruction itself must preempt: `--send-now --message` is a content-P0 admission. With an active turn it claims the shared interrupt control and persists its successor before Stop; when idle it starts that new instruction immediately even if older backlog is held, without releasing or promoting that backlog. Use `vibe session send-now <id>` for an empty-P1 promotion: it adds no Message; it releases the hold and promotes the exact oldest queued P3 head. If a Turn is active, empty P1 steers that exact head into the active logical/native Turn; if the Session is idle, it starts that head as a new Turn. Both forms require a Web/Workbench Session. Only content P0 interrupts through the shared Stop path; if that interruption is refused, the active Turn and durable queue remain intact.
+That existing-Session send is a P1 delivery by default: it steers into an active native Turn, starts immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. Use `--queue` when the new Run should enter that P3 queue without steering. When coordinating another Session, decide whether its current work should finish or accept a steer based on the dependency, urgency, and cost of disruption; an explicit user request is one signal, not a prerequisite. Use `vibe agent run --session-id <id> --send-now --message ...` to persist the new Run at P3 and then promote the exact FIFO head through P1. If older work is queued, that older head is promoted first; the new message never leapfrogs it. Use `vibe session send-now <id>` for the same exact-head P1 promotion without adding a Message. If a native Turn is active, the promoted head steers that same logical/native Turn; if the Session is idle, it starts as a new Turn. Both forms work for Workbench and IM Sessions. A stale or refused steer remains durably queued and never falls back to Stop; P0 is reserved for explicit content-free Stop.
Coordinating Agents can inspect the same durable Workbench queue the user sees with `vibe session queue list <id>`. If one queued instruction has become obsolete, contradictory, or duplicated, remove that exact row with `vibe session queue remove <id> <message-id>`. Always list first and use the returned stable message id; never guess an id or delete a different row to simulate reordering.
diff --git a/docs/CLI.md b/docs/CLI.md
index 9a6a7bb1c..e389eb117 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -289,7 +289,7 @@ task definition. Use `--sync` only when the terminal should wait for completion.
vibe agent run --no-callback --agent release-reviewer --message 'Review the latest deployment result.'
vibe agent run --sync --agent release-reviewer --message 'Review the latest deployment result and print it here.'
vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
-vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Stop and apply this correction first.'
+vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Apply this correction in the current turn.'
vibe agent run --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'
vibe agent run --no-callback --create-session --scope-id slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
@@ -300,12 +300,12 @@ new Run into an active native Turn, starts it immediately when idle, or moves th
same Delivery to the durable P3 queue after a definitive refusal/not-active
receipt. It does not interrupt the active Turn.
-`--send-now` is valid only with an existing `--session-id`. It admits the new
-Run as content P0: with an active Turn, Avibe persists the replacement successor
-before calling Stop; when idle, it starts the new Run immediately. This is
-different from `vibe session send-now`, which adds no message and promotes only
-the exact current P3 queue head, steering it when active or starting it when
-idle. A stale head is refused rather than replaced by the next queued item.
+`--send-now` is valid only with an existing `--session-id`. Avibe persists the
+new Run at P3 first, then promotes the exact FIFO head through P1. With an active
+Turn that head steers the same native Turn; when idle it starts normally. Older
+queued work remains ahead of the new Run. `vibe session send-now` uses the same
+exact-head promotion without adding a message. A stale head is refused rather
+than replaced by the next queued item, and neither form calls Stop.
Use `--fork-session <session-id>` when a new Agent Session should branch from
an existing Session's native backend context instead of starting blank. The new
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index b4c317929..6927652ad 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -266,20 +266,17 @@ Session,且在目标 Session 已存在时仍然会被拒绝。
vibe agent run --no-callback --agent release-reviewer --message 'Review the latest deployment result.'
vibe agent run --sync --agent release-reviewer --message 'Review the latest deployment result and print it here.'
vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
-vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Stop and apply this correction first.'
+vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Apply this correction in the current turn.'
vibe agent run --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'
vibe agent run --no-callback --create-session --scope-id slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
```
-`--send-now` 只能和现有 `--session-id` 一起使用。Avibe 会先把 Agent Run
-持久化到该 Session 的队列,再执行与 Workbench“立即发送”相同的操作:通过共享
-Stop 路径打断活动 Turn,并把 FIFO 队头作为新 Turn 发送。它不会把输入注入同一个
-backend native Turn,也不会让新消息越过更早的排队工作。如果打断被拒绝,当前 Turn
-继续运行,Agent Run 保持排队。命令接受结果会显示 `delivery_intent`;Controller
-消费后,可通过 `vibe runs show <run-id>` 查看持久化的
-`metadata.delivery_outcome`(`interrupted`、`flushed`、`deferred` 或
-`stop_failed`)。
+`--send-now` 只能和现有 `--session-id` 一起使用。Avibe 会先把新的 Agent Run
+以 P3 持久化,再通过 P1 提升精确的 FIFO 队头。活动 Turn 存在时,队头会 steering
+进同一个 backend native Turn;Session 空闲时则正常启动。新消息不会越过更早的
+排队工作。`vibe session send-now` 执行相同的精确队头提升,但不会新增消息。
+两种形式都不会调用 Stop;过期或被拒绝的 steering 会保持持久化排队。
当一个新 Agent Session 需要从现有 Session 的 native backend 上下文分叉,而不是空白开始时,
使用 `--fork-session <session-id>`。新 Session 会保持源 Session 的 backend。
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 2c7415ce6..a3b8d5fed 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -903,10 +903,9 @@ result later. Use `--sync` only when the terminal should wait for completion.
With an existing `--session-id`, the default is P1: steer the new Run into an
active native Turn, start it when idle, or move the same Delivery to P3 after a
definitive refusal/not-active receipt. `--queue` selects P3 without attempting a
-steer. `--send-now` instead admits the new Run as content P0 and persists its
-replacement successor before stopping an active Turn. `vibe session send-now`
-adds no message; it promotes only the exact current P3 queue head, steering it
-when active or starting it when idle.
+steer. `--send-now` persists the new Run at P3, then promotes the exact FIFO head
+through P1, so it neither stops the active Turn nor jumps older work. `vibe
+session send-now` performs that exact-head promotion without adding a message.
`--fork-session <session_id>` creates a new Agent Session by forking the source
Session's native backend context. It is for alternate investigations or
diff --git a/docs/plans/agent-message-priority.md b/docs/plans/agent-message-priority.md
index 2e4d86108..af8762133 100644
--- a/docs/plans/agent-message-priority.md
+++ b/docs/plans/agent-message-priority.md
@@ -8,10 +8,8 @@ P2 and P4 remain reserved for a separate Mailbox design.
## Priority Semantics
-- **P0 interrupt** is an explicit action, never a default for ordinary input.
- Without content it stops the active Turn. With content, the delivery owner
- first persists the replacement Delivery and waiting successor Turn, then
- stops the active Turn and starts the successor.
+- **P0 Stop** is an explicit content-free action. It stops the exact active
+ Turn; no message-producing surface may use P0 to replace that Turn.
- **P1 steer** delivers content into the expected currently active Turn without
stopping it. A content-free P1 request atomically promotes the current
P3 queue head. A definitive steering failure may transfer the same Delivery to
@@ -93,7 +91,7 @@ instead of claiming equivalent durability.
| --- | --- | --- |
| Web composer | P3 | Starts when idle; otherwise joins the FIFO backlog. |
| Ordinary IM message | P1 | Steers the active Turn or starts when idle; a definitive refusal falls back to P3. |
-| Existing-Session Agent Run | P1 | Same as ordinary IM. `--queue` selects P3 and `--send-now` selects content P0 for Workbench Sessions. |
+| Existing-Session Agent Run | P1 | Same as ordinary IM. `--queue` selects P3. `--send-now` first persists the new Run at P3, then promotes the exact FIFO head through P1; it never stops the active Turn or jumps older work. |
| Watch, Hook, Webhook | P1 | Continues the target Session without interrupting it. |
| Show annotation | P1 | Delivers the annotation to the current Turn when possible. |
| Session callback | P1 | Delivers each completed child Run independently. |
diff --git a/docs/plans/avibe-turn-lifecycle-fsm.md b/docs/plans/avibe-turn-lifecycle-fsm.md
index 8d9262fd7..1739c0701 100644
--- a/docs/plans/avibe-turn-lifecycle-fsm.md
+++ b/docs/plans/avibe-turn-lifecycle-fsm.md
@@ -3,6 +3,10 @@
Status: **design / pre-implementation**. Branch `refactor/avibe-turn-state-machine` (off master @ e324cc0, which includes #367 `2c88c7b`).
Author: refactor follow-up to PR #367. Tracks task #85; folds in #84 + Codex #3336001455.
+> Historical design record. The current message-priority and Send now contract is
+> defined in `docs/plans/agent-message-priority.md`; where this document describes
+> Send now as Stop/cancel, the current contract supersedes it.
+
> Read this top-to-bottom before touching code. Part 1 is the EXHAUSTIVE current
> behavior (so nothing is lost). Part 2 is the target. Part 3 is the migration.
> Part 4 is the edge-case catalog = the regression suite. Part 5 = open decisions.
diff --git a/docs/plans/session-delivery-foundation.md b/docs/plans/session-delivery-foundation.md
index 5b442636c..4f57f1830 100644
--- a/docs/plans/session-delivery-foundation.md
+++ b/docs/plans/session-delivery-foundation.md
@@ -127,10 +127,11 @@ live Session/Run bindings and cannot mutate an unaccepted Delivery snapshot.
- existing-Session Agent Run and Watch input is P1 by default; it steers the
active Turn, starts itself when idle, and falls back to P3 only after a
definitive refusal or not-active receipt;
-- explicit send-now/content replacement is P0;
-- empty send-now promotes the exact current P3 head segment;
-- only empty P0/Stop establishes the durable backlog hold;
-- content P0 preserves the existing hold and its replacement Turn bypasses it.
+- Agent Run send-now persists its new input at P3, then promotes the exact
+ current P3 head segment through empty P1, so older work cannot be bypassed;
+- Session send-now performs the same exact-head P1 promotion without adding
+ content;
+- P0 is reserved for explicit content-free Stop.
On startup, OpenCode first restores the exact logical/runtime/native identity
map. Restored polling then waits until durable Delivery/Turn reconciliation has
diff --git a/docs/plans/workbench-message-queue.md b/docs/plans/workbench-message-queue.md
index d447e55d5..09b511eac 100644
--- a/docs/plans/workbench-message-queue.md
+++ b/docs/plans/workbench-message-queue.md
@@ -3,6 +3,10 @@
Status: proposal (awaiting confirmation). Branch: `fix/workbench-chat-page`.
Supersedes the "refuse the 2nd concurrent message" behavior.
+> Historical proposal. The current message-priority and Send now contract is
+> defined in `docs/plans/agent-message-priority.md`; where this document describes
+> Send now as Stop/cancel, the current contract supersedes it.
+
## Background — what PR #359 already gives us
PR #359 (`per-session inbox + unified typed message persistence + realtime
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index f21091d19..bc3f433d4 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -85,6 +85,7 @@ class ClaudeAgent(BaseAgent):
self._steering_locks: dict[str, asyncio.Lock] = {}
self._steering_generations: dict[str, int] = {}
self._steering_terminal_barriers: dict[str, list[str]] = {}
+ self._steering_response_generations: dict[str, int] = {}
self._ambiguous_primary_results: dict[str, object] = {}
self._ambiguous_input_shutdowns: set[str] = set()
self._ambiguous_interrupts: set[str] = set()
@@ -763,6 +764,9 @@ class ClaudeAgent(BaseAgent):
barriers = getattr(self, "_steering_terminal_barriers", None)
if barriers is not None:
barriers.pop(composite_key, None)
+ response_generations = getattr(self, "_steering_response_generations", None)
+ if response_generations is not None:
+ response_generations.pop(composite_key, None)
ambiguous_results = getattr(self, "_ambiguous_primary_results", None)
if ambiguous_results is not None:
ambiguous_results.pop(composite_key, None)
@@ -809,10 +813,28 @@ class ClaudeAgent(BaseAgent):
composite_key: str,
expected_steering_generation: int,
) -> bool:
- """Consume one pre-steer terminal frame, including SDK-buffered frames."""
+ """Consume a terminal frame that predates a native steer.
+
+ Claude's receiver can deliver a ResultMessage after the steering write,
+ even when the corresponding AssistantMessage was already emitted. That
+ result belongs to the steered continuation and must settle the Turn. Only
+ suppress the accepted barrier when no post-steer assistant response was
+ observed; this preserves the guard for a buffered pre-steer ResultMessage
+ without dropping the real steered answer.
+ """
generation_changed = expected_steering_generation != self._steering_generation(
composite_key
)
+ barrier = self._next_terminal_barrier(composite_key)
+ response_generation = (
+ getattr(self, "_steering_response_generations", {}) or {}
+ ).get(composite_key)
+ if (
+ barrier == "accepted"
+ and response_generation == self._steering_generation(composite_key)
+ ):
+ self._consume_terminal_barrier(composite_key)
+ return generation_changed
buffered_terminal = self._consume_terminal_barrier(composite_key) is not None
return generation_changed or buffered_terminal
@@ -1155,8 +1177,14 @@ class ClaudeAgent(BaseAgent):
message_stream = client.receive_messages().__aiter__()
while True:
settling_ambiguous_primary = False
+ terminal_steering_generation = None
try:
message = await anext(message_stream)
+ # Capture ownership at the receive boundary. The receiver may
+ # yield while it captures session metadata or opens an
+ # agent-initiated turn; sampling generation later can relabel a
+ # buffered pre-steer frame as the steered continuation.
+ terminal_steering_generation = self._steering_generation(composite_key)
except StopAsyncIteration:
message = self._ambiguous_primary_results.pop(composite_key, None)
if message is None:
@@ -1216,11 +1244,8 @@ class ClaudeAgent(BaseAgent):
continue
message_type = self._detect_message_type(message)
- terminal_steering_generation = (
- self._steering_generation(composite_key)
- if message_type in {"assistant", "result", "system"}
- else None
- )
+ if message_type not in {"assistant", "result", "system"}:
+ terminal_steering_generation = None
formatter = self._get_formatter(context)
is_model_refusal_fallback = self._is_model_refusal_fallback_message(message)
model_refusal_fallback_notice = (
@@ -1308,6 +1333,10 @@ class ClaudeAgent(BaseAgent):
if assistant_text:
self._detached_assistant_text[composite_key] = assistant_text
continue
+ if assistant_text and terminal_steering_generation:
+ self._steering_response_generations[composite_key] = (
+ terminal_steering_generation
+ )
async with self._steering_lock(composite_key):
if composite_key in self._steering_closing_keys():
logger.info(
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 37af8b396..456502df7 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -68,6 +68,10 @@ _STATUS_RECONCILIATION_FAILURE_LIMIT = 3
# OpenCode returns 204 after forking prompt work, before that worker necessarily
# registers the session as busy.
_ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS = 5.0
+# A prompt accepted at the end of the previous native turn can race its final
+# status transition. Let that transition settle before trusting the write as a
+# same-turn steer.
+_STEER_POST_WRITE_STATUS_SETTLE_SECONDS = 0.1
_RESTORED_IM_REGISTRATION_RETRY_DELAY_SECONDS = 0.25
_RESTORED_IM_PLATFORMS = {"slack", "discord", "telegram", "lark", "wechat"}
@@ -1425,6 +1429,42 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
+ _ASYNC_PROMPT_START_CONFIRMATION_TIMEOUT_SECONDS
)
state.awaiting_active_status_observed = False
+ await asyncio.sleep(_STEER_POST_WRITE_STATUS_SETTLE_SECONDS)
+ try:
+ status_after_write = await server.get_session_status(
+ native_session_id,
+ directory,
+ )
+ except (asyncio.TimeoutError, TimeoutError, aiohttp.ClientConnectionError) as exc:
+ # The native write may have been accepted, so leave the
+ # reconciliation evidence armed for the poll owner.
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="post_write_status_unknown",
+ backend=self.name,
+ diagnostic=str(exc),
+ )
+ except Exception as exc: # noqa: BLE001 - write already happened
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="post_write_status_unknown",
+ backend=self.name,
+ diagnostic=str(exc),
+ )
+ if (
+ status_after_write is None
+ or status_after_write.get("type") not in {"busy", "retry"}
+ ):
+ # The prompt write is durable, but OpenCode can take longer
+ # than this first status sample to register the continuation as
+ # busy. Keep the five-second reconciliation evidence armed so
+ # the poll owner can observe either start confirmation or the
+ # exact native attempt before any retry is admitted.
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="native_turn_start_pending",
+ backend=self.name,
+ )
except OpenCodePromptRejectedError as exc:
outcome = SteerOutcome.NOT_ACTIVE if exc.status == 404 else SteerOutcome.REFUSED
reason = "native_session_missing" if exc.status == 404 else "backend_refused"
diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.md
index 0ae95db46..ec9a92223 100644
--- a/skills/use-avibe/SKILL.md
+++ b/skills/use-avibe/SKILL.md
@@ -789,8 +789,8 @@ Preferred CLI shape:
- delegate to a visible sibling Session in the same scope from an Avibe Agent shell: `vibe agent run --agent '<agent-name>' --same-scope --message '...'`
- wait for an Agent result in the terminal: `vibe agent run --sync --agent '<agent-name>' --message '...'`
- continue a specific existing Session: `vibe agent run --session-id '<session-id>' --message '...'`
-- persist a new message and interrupt a busy existing Session to dispatch its FIFO queue head: `vibe agent run --session-id '<session-id>' --send-now --message '...'`
-- interrupt a busy existing Session and dispatch an already-queued head without adding a message: `vibe session send-now '<session-id>'`
+- persist a new message and steer the exact FIFO head into the active Turn: `vibe agent run --session-id '<session-id>' --send-now --message '...'`
+- steer an already-queued exact head without adding a message: `vibe session send-now '<session-id>'`
- inspect another Session's durable FIFO queue: `vibe session queue list '<session-id>'`
- remove one exact queued message after inspecting its stable ID: `vibe session queue remove '<session-id>' '<message-id>'`
- fork this Session for an alternate path: `vibe agent run --fork-self --message '...'`
@@ -813,9 +813,9 @@ Targeting and callbacks:
- Use `--session-id <id>` only when the command should operate on a different existing Agent Session.
- When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings.
- When coordinating another Workbench Session, decide whether its current turn should finish or be preempted from the work dependency, urgency, and cost of discarding in-flight work. An explicit user request is one signal, not a prerequisite.
-- Add `--send-now` when a newly persisted Agent Run should also trigger the Workbench Session-level Stop plus FIFO-head flush used by the Web UI. If older work is already queued, that older head runs first; the new message never leapfrogs it.
-- Use `vibe session send-now <session-id>` when a Workbench Session already has queued work and no new message should be added. This dispatches the existing FIFO head.
-- Both send-now forms require a Web/Workbench Session and start a new turn rather than promising backend-native same-turn steering. A refused interrupt leaves the active turn and durable queue intact.
+- Add `--send-now` when a newly persisted Agent Run should also promote the exact FIFO head through same-turn steering. If older work is already queued, that older head is promoted first; the new message never leapfrogs it.
+- Use `vibe session send-now <session-id>` when a Session already has queued work and no new message should be added. This promotes the existing FIFO head.
+- Both send-now forms use the shared steering path for Workbench and IM Sessions. A refused or stale steer leaves the input durably queued and never falls back to Stop.
- Use `vibe session queue list <session-id>` before changing another Workbench Session's queue. If an instruction is obsolete, contradictory, or duplicated, remove that exact stable row with `vibe session queue remove <session-id> <message-id>`. Never guess a message ID or delete another row to simulate reordering.
- When `vibe agent run` creates a new Session, the default placement is private/background. Add `--same-scope` for a visible sibling Session in the same Workbench project or IM scope, or `--scope-id <scopes.id>` for a specific existing scope.
- When a task, watch, or new Agent run creates a Session and `--cwd` is omitted, Avibe uses the command's current working directory. Forks keep the source Session cwd by default.
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index efc504ec0..670984753 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -773,8 +773,8 @@ Preferred CLI shape:
- delegate to a visible sibling Session in the same scope from an Avibe Agent shell: `vibe agent run --agent '<agent-name>' --same-scope --message '...'`
- wait for an Agent result in the terminal: `vibe agent run --sync --agent '<agent-name>' --message '...'`
- continue a specific existing Session: `vibe agent run --session-id '<session-id>' --message '...'`
-- persist a new message and interrupt a busy existing Session to dispatch its FIFO queue head: `vibe agent run --session-id '<session-id>' --send-now --message '...'`
-- interrupt a busy existing Session and dispatch an already-queued head without adding a message: `vibe session send-now '<session-id>'`
+- persist a new message and steer the exact FIFO head into the active Turn: `vibe agent run --session-id '<session-id>' --send-now --message '...'`
+- steer an already-queued exact head without adding a message: `vibe session send-now '<session-id>'`
- inspect another Session's durable FIFO queue: `vibe session queue list '<session-id>'`
- remove one exact queued message after inspecting its stable ID: `vibe session queue remove '<session-id>' '<message-id>'`
- fork this Session for an alternate path: `vibe agent run --fork-self --message '...'`
@@ -797,9 +797,9 @@ Targeting and callbacks:
- Use `--session-id <id>` only when the command should operate on a different existing Agent Session.
- When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings.
- When coordinating another Workbench Session, decide whether its current turn should finish or be preempted from the work dependency, urgency, and cost of discarding in-flight work. An explicit user request is one signal, not a prerequisite.
-- Add `--send-now` when a newly persisted Agent Run should also trigger the Workbench Session-level Stop plus FIFO-head flush used by the Web UI. If older work is already queued, that older head runs first; the new message never leapfrogs it.
-- Use `vibe session send-now <session-id>` when a Workbench Session already has queued work and no new message should be added. This dispatches the existing FIFO head.
-- Both send-now forms require a Web/Workbench Session and start a new turn rather than promising backend-native same-turn steering. A refused interrupt leaves the active turn and durable queue intact.
+- Add `--send-now` when a newly persisted Agent Run should also promote the exact FIFO head through same-turn steering. If older work is already queued, that older head is promoted first; the new message never leapfrogs it.
+- Use `vibe session send-now <session-id>` when a Session already has queued work and no new message should be added. This promotes the existing FIFO head.
+- Both send-now forms use the shared steering path for Workbench and IM Sessions. A refused or stale steer leaves the input durably queued and never falls back to Stop.
- Use `vibe session queue list <session-id>` before changing another Workbench Session's queue. If an instruction is obsolete, contradictory, or duplicated, remove that exact stable row with `vibe session queue remove <session-id> <message-id>`. Never guess a message ID or delete another row to simulate reordering.
- When `vibe agent run` creates a new Session, the default placement is private/background. Add `--same-scope` for a visible sibling Session in the same Workbench project or IM scope, or `--scope-id <scopes.id>` for a specific existing scope.
- When a task, watch, or new Agent run creates a Session and `--cwd` is omitted, Avibe uses the command's current working directory. Forks keep the source Session cwd by default.
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 13c8891a3..c3f689506 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -3835,20 +3835,16 @@ scenarios:
# work into one tail-boundary rewind while the durable store retains the inventory.
test: tests/test_runtime_work_supervisor.py::test_hfr_288_expired_backoff_preserves_forward_scan_before_retry
- id: HFR-430
- name: an Agent Run can apply the Workbench send-now transition to a busy Session
+ name: an Agent Run send-now steers the exact FIFO head without stopping
status: covered
kind: recovery
layer: contract
backend: shared
- # Agent-to-Agent delivery previously had only the queue path even though
- # Workbench already owned the cross-backend interrupt-and-flush transition.
- # The delivery intent is durable on the Agent Run. The shared turn owner first
- # persists the harness-attributed queue row, then marks the active turn for
- # flush-on-cancel and interrupts it through the ordinary Stop handler. The old
- # turn settles exactly once and the FIFO head starts as a new scheduled turn.
- # A refused Stop leaves both owners intact, and an idle backlog starts directly
- # without a post-submit call racing and interrupting the newly started head.
- test: tests/test_internal_server.py::test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head
+ # The delivery intent is durable on the Agent Run. The shared owner first
+ # persists the harness-attributed row at P3, then promotes the exact FIFO head
+ # through empty P1. An active native Turn is steered without Stop, older queued
+ # work cannot be bypassed, and a refused or stale steer stays durably queued.
+ test: tests/test_internal_server.py::test_agent_run_send_now_steers_the_fifo_head_without_stopping
- id: HFR-431
name: a terminal Turn racing a successful Stop receipt remains a successful cancel
status: covered
@@ -3873,6 +3869,27 @@ scenarios:
# and lets a different OpenCode Agent waiting on that shared provider continue.
# The timeout never enters the empty successful-result fallback.
test: tests/test_agent_service.py::test_hfr_432_opencode_timeout_releases_fifo_and_shared_runtime
+ - id: HFR-434
+ name: an OpenCode steer at the native terminal boundary stays reconcilable
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: opencode
+ # prompt_async returns 204 after persisting the user message, while its worker
+ # may still be registering the continuation as busy. A transient idle sample
+ # keeps the exact attempt in reconciliation so it cannot be replayed; later
+ # native evidence either accepts the attempt or closes it terminally.
+ test: tests/test_agent_steering.py::test_opencode_keeps_reconciliation_armed_after_post_write_idle
+ - id: HFR-435
+ name: a Claude steered Assistant response owns the following terminal result
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: claude
+ # The accepted steering barrier suppresses only a buffered pre-steer result.
+ # Once the receiver has emitted Assistant text in the current generation,
+ # its ResultMessage is the real continuation and must settle the pending Turn.
+ test: tests/test_claude_agent_sessions.py::test_steered_assistant_and_result_settle_the_pending_turn
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index d1616c476..6cc17b99b 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -621,6 +621,37 @@ async def test_opencode_steers_existing_runner_without_abort_or_new_turn() -> No
await _cancel_tasks(gate_task)
+async def test_opencode_keeps_reconciliation_armed_after_post_write_idle() -> None:
+ """HFR-434: a transient post-write idle stays reconcilable, not refused."""
+ primary = _primary_request(backend="opencode")
+ gate_task = await _held_task()
+ server = _OpenCodeServer(
+ status_responses=[{"type": "busy"}, {"type": "idle"}],
+ )
+ agent = _opencode_agent(primary, gate_task, server)
+ controller = _controller_with_active_gate(agent, primary, gate_task)
+ state = agent._steering_states[primary.base_session_id]
+ try:
+ identity = active_steer_identity(controller, "opencode", "avibe-session")
+ assert identity is not None
+
+ receipt = await steer_active_turn(
+ controller,
+ "opencode",
+ _steer_request(identity[1]),
+ )
+
+ assert receipt.outcome is SteerOutcome.UNKNOWN
+ assert receipt.reason == "native_turn_start_pending"
+ assert state.awaiting_user_text == STEER_TEXT
+ assert state.awaiting_after_message_ids == {"primary-user"}
+ assert state.awaiting_start_confirmation_deadline is not None
+ assert server.abort_calls == []
+ finally:
+ await _cancel_tasks(gate_task)
+
+
@pytest.mark.anyio
async def test_opencode_reconciles_exact_native_attempt_without_resteering() -> None:
primary = _primary_request(backend="opencode")
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 5a720a81a..7dc521e68 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -881,6 +881,187 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])
self.assertTrue(controller.session_manager.session.session_active[composite_key])
+ def test_steered_result_after_assistant_response_is_not_suppressed(self):
+ controller = _StubController()
+ agent = ClaudeAgent(controller)
+ composite_key = "session-1:/tmp/work"
+ agent._steering_generations[composite_key] = 1
+ agent._steering_terminal_barriers[composite_key] = ["accepted"]
+ agent._steering_response_generations[composite_key] = 1
+
+ self.assertFalse(agent._terminal_claim_superseded(composite_key, 1))
+ self.assertIsNone(agent._next_terminal_barrier(composite_key))
+
+ def test_buffered_result_without_steered_assistant_is_suppressed(self):
+ controller = _StubController()
+ agent = ClaudeAgent(controller)
+ composite_key = "session-1:/tmp/work"
+ agent._steering_generations[composite_key] = 1
+ agent._steering_terminal_barriers[composite_key] = ["accepted"]
+
+ self.assertTrue(agent._terminal_claim_superseded(composite_key, 1))
+ self.assertIsNone(agent._next_terminal_barrier(composite_key))
+
+ async def test_steered_assistant_and_result_settle_the_pending_turn(self):
+ """HFR-435: the steered Assistant owns its following terminal result."""
+ controller = _StubController()
+ controller._get_session_key = lambda _context: "session-1"
+ controller.emit_agent_message = AsyncMock()
+ controller.session_handler.mark_session_idle = lambda _key: None
+ controller.session_handler.handle_session_error = AsyncMock()
+ agent = ClaudeAgent(controller)
+ agent.emit_result_message = AsyncMock()
+ agent._get_formatter = lambda _context: SimpleNamespace(
+ format_assistant_message=lambda parts: "\n\n".join(parts),
+ )
+ composite_key = "session-1:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform_specific={"turn_token": "T1"},
+ )
+ pending_request = SimpleNamespace(
+ context=context,
+ started_at=None,
+ ack_reaction_message_id=None,
+ ack_reaction_emoji=None,
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ agent._steering_generations[composite_key] = 1
+ agent._steering_terminal_barriers[composite_key] = ["accepted"]
+
+ text_block = TextBlock("steered final answer")
+ assistant_message = type(
+ "AssistantMessage",
+ (),
+ {"content": [text_block]},
+ )()
+ result_message = type(
+ "ResultMessage",
+ (),
+ {
+ "subtype": "success",
+ "result": "steered final answer",
+ "duration_ms": 1,
+ },
+ )()
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield assistant_message
+ yield result_message
+
+ return _iterate()
+
+ await agent._receive_messages(
+ _Client(),
+ "session-1",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ agent.emit_result_message.assert_awaited_once_with(
+ context,
+ "steered final answer",
+ subtype="success",
+ duration_ms=1,
+ parse_mode="markdown",
+ request=pending_request,
+ )
+ self.assertNotIn(composite_key, agent._pending_requests)
+
+ async def test_buffered_pre_steer_assistant_keeps_primary_result_ownership(self):
+ controller = _StubController()
+ controller._get_session_key = lambda _context: "session-1"
+ controller.emit_agent_message = AsyncMock()
+ controller.session_handler.mark_session_idle = lambda _key: None
+ controller.session_handler.handle_session_error = AsyncMock()
+ agent = ClaudeAgent(controller)
+ agent.emit_result_message = AsyncMock()
+ agent._get_formatter = lambda _context: SimpleNamespace(
+ format_assistant_message=lambda parts: "\n\n".join(parts),
+ )
+ composite_key = "session-buffered:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform_specific={"turn_token": "T1"},
+ )
+ pending_request = SimpleNamespace(
+ context=context,
+ started_at=None,
+ ack_reaction_message_id=None,
+ ack_reaction_emoji=None,
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ assistant_received = asyncio.Event()
+ release_assistant = asyncio.Event()
+ terminal_processed = asyncio.Event()
+ end_stream = asyncio.Event()
+
+ original_begin = agent._maybe_begin_agent_initiated_turn
+
+ async def _hold_assistant(*args, **kwargs):
+ assistant_received.set()
+ await release_assistant.wait()
+ return await original_begin(*args, **kwargs)
+
+ agent._maybe_begin_agent_initiated_turn = _hold_assistant
+ terminal_claim = agent._terminal_claim_superseded
+
+ def _observe_terminal_claim(*args):
+ superseded = terminal_claim(*args)
+ if asyncio.current_task() is receiver_task:
+ terminal_processed.set()
+ return superseded
+
+ agent._terminal_claim_superseded = _observe_terminal_claim
+ assistant_message = type(
+ "AssistantMessage",
+ (),
+ {"content": [TextBlock("buffered primary answer")]},
+ )()
+ result_message = type(
+ "ResultMessage",
+ (),
+ {
+ "subtype": "success",
+ "result": "buffered primary answer",
+ "duration_ms": 1,
+ },
+ )()
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield assistant_message
+ yield result_message
+ await end_stream.wait()
+
+ return _iterate()
+
+ receiver_task = asyncio.create_task(
+ agent._receive_messages(
+ _Client(),
+ "session-buffered",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ )
+ await assistant_received.wait()
+ agent._advance_steering_generation(composite_key)
+ release_assistant.set()
+ await asyncio.wait_for(terminal_processed.wait(), timeout=1)
+
+ self.assertEqual(agent._pending_requests[composite_key], [pending_request])
+ agent.emit_result_message.assert_not_awaited()
+
+ receiver_task.cancel()
+ await asyncio.gather(receiver_task, return_exceptions=True)
+
async def test_toolcall_emit_adopts_current_pending_turn_token(self):
controller = _StubController()
controller._get_session_key = lambda _context: "session-1"
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index 88ee918d0..3a5815d41 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -594,7 +594,7 @@ def test_agent_run_queue_persists_explicit_p3_intent(
assert stored["metadata"]["delivery_intent"] == "queue"
-def test_agent_run_send_now_rejects_an_im_backed_session(
+def test_agent_run_send_now_accepts_an_im_backed_session(
tmp_path: Path,
capsys,
) -> None:
@@ -653,7 +653,7 @@ def test_agent_run_send_now_rejects_an_im_backed_session(
"--send-now",
"--no-callback",
"--message",
- "interrupt this",
+ "steer this",
]
)
@@ -664,14 +664,13 @@ def test_agent_run_send_now_rejects_an_im_backed_session(
):
result = cli.cmd_agent_run(args)
- assert result == 1
- payload = json.loads(capsys.readouterr().err)
- assert payload["code"] == "send_now_unsupported_target"
- assert payload["details"] == {
- "session_id": session["id"],
- "platform": "slack",
- }
- assert request_store.list_runs() == []
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["session_id"] == session["id"]
+ assert payload["delivery_intent"] == "send_now"
+ stored = request_store.get_run(payload["run_id"])
+ assert stored is not None
+ assert stored["metadata"]["delivery_intent"] == "send_now"
def test_agent_run_async_self_target_defaults_to_no_callback(
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 44db9913e..4bda73785 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -34,6 +34,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core import internal_server, session_turns
from core.message_context import build_context_turn_sink_key
from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT
+from core.services.agent_steering import SteerOutcome, result as steer_result
from core.services.dispatch import (
SOURCE_HUMAN,
SOURCE_SCHEDULED,
@@ -3078,13 +3079,8 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
assert ("queue.updated", {"session_id": session_id}) in published
-def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch, tmp_path):
- """HFR-430 — Agent-to-Agent send-now reuses the Workbench turn transition.
-
- The Agent Run row and queued message must exist before Stop is attempted. The
- active turn is then canceled once, and the durable successor claim starts
- the durable Agent Run as a new scheduled turn.
- """
+def test_agent_run_send_now_steers_the_fifo_head_without_stopping(monkeypatch, tmp_path):
+ """HFR-430: send-now persists first, then steers the exact FIFO head."""
from core.scheduled_tasks import TaskExecutionStore
from core.services import sessions as sessions_service
from storage.db import create_sqlite_engine
@@ -3125,8 +3121,6 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
)
assert request_store.claim(request.id) is not None
original_started = asyncio.Event()
- replacement_started = asyncio.Event()
- original_cancelled = asyncio.Event()
seen: list[tuple[str, str]] = []
async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
@@ -3134,12 +3128,7 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
if text == "original work":
_bind_test_native_start(engine, ctx)
original_started.set()
- try:
- await asyncio.sleep(60)
- except asyncio.CancelledError:
- original_cancelled.set()
- raise
- replacement_started.set()
+ await asyncio.sleep(60)
return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
@@ -3147,14 +3136,9 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
controller = _build_controller_double()
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
-
- async def _stop_original(_context):
- active = app.state.in_flight_dispatches.get(session_id)
- assert active is not None
- active.task.cancel()
- return True
-
- controller.command_handler.handle_stop.side_effect = _stop_original
+ controller.session_turns._steer = AsyncMock(
+ return_value=steer_result(SteerOutcome.ACCEPTED)
+ )
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
@@ -3185,39 +3169,156 @@ def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch
request.message or "",
delivery_intent="send_now",
)
- await asyncio.wait_for(original_cancelled.wait(), timeout=3)
- await asyncio.wait_for(replacement_started.wait(), timeout=3)
- for _ in range(200):
- if session_id not in app.state.in_flight_dispatches:
- break
- await asyncio.sleep(0.01)
+ active = app.state.in_flight_dispatches[session_id]
+ assert not active.task.done()
+ active.task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await active.task
return result
result = asyncio.run(_go())
assert result == session_turns.TurnSubmissionResult(
- route="enqueued",
+ route="ran",
queue_persisted=True,
target_was_busy=True,
- delivery_status="waiting_terminal",
+ delivery_status="accepted",
delivery_owner_transferred=True,
)
- controller.command_handler.handle_stop.assert_awaited_once()
- assert seen == [
- ("original work", SOURCE_HUMAN),
- ("apply the correction", SOURCE_SCHEDULED),
- ]
+ controller.command_handler.handle_stop.assert_not_awaited()
+ controller.session_turns._steer.assert_awaited_once()
+ assert seen == [("original work", SOURCE_HUMAN)]
with engine.connect() as conn:
assert message_deliveries.list_queued(conn, session_id) == []
stored = request_store.get_run(request.id)
assert stored is not None
assert stored["metadata"]["delivery_outcome"] == {
"intent": "send_now",
- "status": "waiting_terminal",
+ "status": "accepted",
"target_was_busy": True,
}
+def test_agent_run_send_now_promotes_a_turn_started_during_admission(monkeypatch, tmp_path):
+ """A stale idle snapshot cannot downgrade explicit send-now into P3 queueing."""
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_agent_send_now_admission_race",
+ now="2026-07-30T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session_id = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )["id"]
+
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="apply the late correction",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(request.id) is not None
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ controller.session_turns._steer = AsyncMock(
+ return_value=steer_result(SteerOutcome.ACCEPTED)
+ )
+ original_deliver = controller.session_turns.deliver
+ inserted_racer = False
+
+ async def _deliver_with_race(delivery_request, *, context=None):
+ nonlocal inserted_racer
+ if delivery_request.admission_only and not inserted_racer:
+ inserted_racer = True
+ with engine.begin() as conn:
+ owner = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="racing owner",
+ )
+ turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ initial_delivery_id=owner["id"],
+ state="starting",
+ backend="claude",
+ )
+ claimed = message_deliveries.open_start_attempt(
+ conn,
+ owner["id"],
+ expected_version=1,
+ turn_id=turn_id,
+ attempt_id=message_deliveries.new_attempt_id(),
+ )
+ assert claimed is not None
+ bound = message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(
+ message_deliveries.get_turn(conn, turn_id)["version"]
+ ),
+ runtime_key=f"runtime:{session_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ )
+ assert bound is not None
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
+ return await original_deliver(delivery_request, context=context)
+
+ controller.session_turns.deliver = _deliver_with_race
+ context = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{request.id}",
+ platform_specific={
+ "task_execution_id": request.id,
+ "task_trigger_kind": "agent_run",
+ },
+ )
+
+ async def _exercise():
+ return await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+
+ result = asyncio.run(_exercise())
+
+ assert result.target_was_busy is False
+ assert result.delivery_status == "accepted"
+ controller.session_turns._steer.assert_awaited_once()
+ controller.command_handler.handle_stop.assert_not_awaited()
+ with engine.connect() as conn:
+ assert message_deliveries.list_queued(conn, session_id) == []
+
+
def test_agent_run_send_now_refusal_keeps_the_turn_and_queue(monkeypatch, tmp_path):
"""A refused interrupt is truthful and leaves both durable owners untouched."""
from core.scheduled_tasks import TaskExecutionStore
@@ -3303,11 +3404,75 @@ def test_agent_run_send_now_refusal_keeps_the_turn_and_queue(monkeypatch, tmp_pa
}
-def test_concurrent_agent_run_send_now_callers_share_one_interrupt_and_drain_fifo(
+def test_agent_run_send_now_retry_promotes_its_persisted_queue_head(monkeypatch, tmp_path):
+ """A retry reuses the owned P3 Delivery instead of losing send-now intent."""
+ from core.scheduled_tasks import TaskExecutionStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, _owner_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_agent_send_now_retry",
+ )
+ session_id = session["id"]
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="retry this correction",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(request.id) is not None
+ controller = _build_controller_double()
+ internal_server.create_app(controller)
+ controller.session_turns._steer = AsyncMock(
+ side_effect=(
+ steer_result(SteerOutcome.REFUSED, reason="temporarily_unavailable"),
+ steer_result(SteerOutcome.ACCEPTED),
+ )
+ )
+ context = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{request.id}",
+ platform_specific={
+ "task_execution_id": request.id,
+ "task_trigger_kind": "agent_run",
+ },
+ )
+
+ async def _go():
+ first = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ second = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ return first, second
+
+ first, second = asyncio.run(_go())
+
+ assert first.delivery_status == "queued"
+ assert second.delivery_status == "accepted"
+ assert controller.session_turns._steer.await_count == 2
+ with engine.connect() as conn:
+ assert message_deliveries.list_queued(conn, session_id) == []
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["metadata"]["delivery_outcome"]["status"] == "accepted"
+
+
+def test_concurrent_agent_run_send_now_callers_steer_in_fifo_order(
monkeypatch,
tmp_path,
):
- """Two admitted Runs share one Stop, then drain the joined FIFO in order."""
+ """Concurrent send-now callers preserve FIFO and never invoke Stop."""
from core.scheduled_tasks import TaskExecutionStore
from core.services import sessions as sessions_service
from storage import messages_service
@@ -3354,9 +3519,6 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt_and_drain_fif
assert request_store.claim(request.id) is not None
original_started = asyncio.Event()
- original_cancelled = asyncio.Event()
- stop_entered = asyncio.Event()
- release_stop = asyncio.Event()
seen: list[str] = []
async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
@@ -3364,28 +3526,18 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt_and_drain_fif
_bind_test_native_start(engine, ctx)
if text == "original work":
original_started.set()
- try:
- await asyncio.sleep(60)
- except asyncio.CancelledError:
- original_cancelled.set()
- raise
+ await asyncio.sleep(60)
return TurnDispatchOutcome(
error=None,
settled_by=SETTLED_BY_TERMINAL_RESULT,
)
- async def _stop(_context):
- stop_entered.set()
- await release_stop.wait()
- active = app.state.in_flight_dispatches.get(session_id)
- assert active is not None
- active.task.cancel()
- return True
-
monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
controller = _build_controller_double()
- controller.command_handler.handle_stop = AsyncMock(side_effect=_stop)
app = internal_server.create_app(controller)
+ controller.session_turns._steer = AsyncMock(
+ return_value=steer_result(SteerOutcome.ACCEPTED)
+ )
transport = httpx.ASGITransport(app=app)
def _context(request):
@@ -3426,41 +3578,32 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt_and_drain_fif
)
for request in requests
]
- await asyncio.wait_for(stop_entered.wait(), timeout=3)
- for _ in range(100):
- with engine.connect() as conn:
- queued = message_deliveries.list_queued(conn, session_id)
- owner = message_deliveries.active_turn(conn, session_id)
- if len(queued) == 1 and owner and owner["control_successor_turn_id"]:
- break
- await asyncio.sleep(0.01)
- assert controller.command_handler.handle_stop.await_count == 1
- release_stop.set()
results = await asyncio.gather(*submissions)
- await asyncio.wait_for(original_cancelled.wait(), timeout=3)
- for _ in range(300):
- if len(seen) == 3 and session_id not in app.state.in_flight_dispatches:
- break
- await asyncio.sleep(0.01)
+ active = app.state.in_flight_dispatches[session_id]
+ assert not active.task.done()
+ active.task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await active.task
return results
results = asyncio.run(_go())
- assert controller.command_handler.handle_stop.await_count == 1
+ controller.command_handler.handle_stop.assert_not_awaited()
+ assert controller.session_turns._steer.await_count == 2
assert [result.delivery_status for result in results] == [
- "waiting_terminal",
- "queued",
+ "accepted",
+ "accepted",
]
- assert all(result.route == "enqueued" for result in results)
+ assert all(result.route == "ran" for result in results)
assert all(result.queue_persisted is True for result in results)
assert all(result.target_was_busy is True for result in results)
assert all(result.delivery_owner_transferred is True for result in results)
- assert seen == ["original work", "first correction", "second correction"]
+ assert seen == ["original work"]
with engine.connect() as conn:
assert message_deliveries.list_queued(conn, session_id) == []
for request, expected_status in zip(
requests,
- ("waiting_terminal", "queued"),
+ ("accepted", "accepted"),
strict=True,
):
stored = request_store.get_run(request.id)
@@ -3652,7 +3795,7 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatc
delivery_intent="send_now",
)
for _ in range(300):
- if len(seen) == 1 and session_id not in app.state.in_flight_dispatches:
+ if len(seen) == 1:
break
await asyncio.sleep(0.01)
return result
@@ -3660,16 +3803,16 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatc
result = asyncio.run(_go())
assert result == session_turns.TurnSubmissionResult(
- route="ran",
+ route="enqueued",
queue_persisted=True,
target_was_busy=False,
- delivery_status="claimed",
+ delivery_status="queued",
delivery_owner_transferred=True,
)
- assert seen == ["new urgent input"]
+ assert seen == ["older queued input"]
with engine.connect() as conn:
assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
- "older queued input"
+ "new urgent input"
]
controller.command_handler.handle_stop.assert_not_awaited()
diff --git a/tests/test_message_priority_cutover.py b/tests/test_message_priority_cutover.py
index da8b5ecb8..5479e755f 100644
--- a/tests/test_message_priority_cutover.py
+++ b/tests/test_message_priority_cutover.py
@@ -31,7 +31,7 @@ def test_source_policy_has_one_explicit_delivery_intent(
@pytest.mark.parametrize(
("intent", "expected_priority"),
[
- ("send_now", "p0"),
+ ("replace", "p0"),
("steer", "p1"),
("queue", "p3"),
],
@@ -47,7 +47,7 @@ def test_delivery_intent_maps_to_exact_priority(
@pytest.mark.parametrize(
("priority", "expected_intent"),
- [("p0", "send_now"), ("p1", "steer"), ("p3", "queue")],
+ [("p0", "replace"), ("p1", "steer"), ("p3", "queue")],
)
def test_delivery_priority_maps_to_exact_intent(
priority: str,
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 4d3ec9545..4e92349c8 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -1355,7 +1355,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
prompt,
)
self.assertIn(
- "| Dispatch an existing queued Workbench Session head now | `vibe session send-now <session-id>` |",
+ "| Promote an existing queued Session head now | `vibe session send-now <session-id>` |",
prompt,
)
self.assertIn("| Branch from current Session context | `vibe agent run --fork-self ...` |", prompt)
@@ -1387,7 +1387,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
prompt,
)
self.assertIn(
- "Both forms require a Web/Workbench Session",
+ "Both forms work for Workbench and IM Sessions",
prompt,
)
self.assertIn(
@@ -1411,32 +1411,32 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
prompt,
)
self.assertIn(
- "`--send-now --message` is a content-P0 admission",
+ "persist the new Run at P3 and then promote the exact FIFO head through P1",
prompt,
)
self.assertIn(
- "starts that new instruction immediately even if older backlog is held",
+ "the new message never leapfrogs it",
prompt,
)
self.assertIn(
- "adds no Message; it releases the hold and promotes the exact oldest queued P3 head",
+ "the same exact-head P1 promotion without adding a Message",
prompt,
)
self.assertIn(
- "steers that exact head into the active logical/native Turn",
+ "the promoted head steers that same logical/native Turn",
prompt,
)
self.assertIn(
- "if the Session is idle, it starts that head as a new Turn",
+ "if the Session is idle, it starts as a new Turn",
prompt,
)
self.assertNotIn(
"Both forms require a Web/Workbench Session, interrupt through the shared Stop path",
prompt,
)
- self.assertNotIn("the new message does not leapfrog it", prompt)
+ self.assertNotIn("content-P0 admission", prompt)
self.assertIn(
- "if that interruption is refused, the active Turn and durable queue remain intact",
+ "never falls back to Stop",
prompt,
)
self.assertNotIn("Add `--same-scope` to require the caller/source scope", prompt)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 31aa58800..b4f930235 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -72,6 +72,8 @@ from core.scheduled_tasks import (
TaskDispatchResult,
TaskExecutionRequest,
TaskExecutionStore,
+ FAILURE_CODE_SEND_NOW_GATE_UNAVAILABLE,
+ SEND_NOW_GATE_UNAVAILABLE_I18N_KEY,
_TASK_RESULT_NOT_RECORDED_I18N_KEY,
_agent_run_message_for_request,
build_session_key_for_context,
@@ -8645,6 +8647,42 @@ def test_avibe_agent_run_routes_through_gate_without_completing_early(monkeypatc
assert handler_calls == []
+def test_avibe_agent_run_send_now_refuses_without_turn_gate(monkeypatch, tmp_path) -> None:
+ """A send-now Agent Run fails typed instead of bypassing durable admission."""
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="must stay durable",
+ agent_name="codex",
+ delivery_intent="send_now",
+ )
+ direct_calls: list[str] = []
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ direct_calls.append(message)
+ return None
+
+ controller = _avibe_controller_double(
+ gate=None,
+ handle_scheduled_message=_handle_scheduled_message,
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ _run_single_request(service, request.id)
+
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "failed"
+ assert stored["error"] == i18n_t(SEND_NOW_GATE_UNAVAILABLE_I18N_KEY, "en")
+ assert stored["metadata"]["failure_code"] == FAILURE_CODE_SEND_NOW_GATE_UNAVAILABLE
+ assert direct_calls == []
+
+
def test_explicit_queue_delivery_intent_remains_queued() -> None:
assert normalize_agent_run_delivery_intent("queue") == "queue"
@@ -8673,10 +8711,10 @@ def test_busy_avibe_agent_run_send_now_keeps_transferred_owner_running(monkeypat
)
)
return TurnSubmissionResult(
- route="enqueued",
+ route="ran",
queue_persisted=True,
target_was_busy=True,
- delivery_status="interrupted",
+ delivery_status="accepted",
delivery_owner_transferred=True,
)
@@ -8714,43 +8752,26 @@ def test_busy_avibe_agent_run_send_now_keeps_transferred_owner_running(monkeypat
assert handler_calls == []
-def test_idle_send_now_flush_failure_invokes_queue_recovery(monkeypatch, tmp_path) -> None:
+def test_send_now_refusal_keeps_transferred_delivery_running(monkeypatch, tmp_path) -> None:
from core.session_turns import TurnSubmissionResult
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
session_id=session_id,
- message="recover the held queue",
+ message="keep this queued after refusal",
agent_name="codex",
delivery_intent="send_now",
)
- recovered: list[str] = []
-
async def _submit_scheduled(_sid, _ctx, _text, *, delivery_intent="queue"):
- request_store.requeue(
- request.id,
- metadata={
- "workbench_queue_holds_run": True,
- "delivery_outcome": {
- "intent": "send_now",
- "status": "flush_failed",
- "target_was_busy": False,
- },
- },
- )
return TurnSubmissionResult(
route="enqueued",
queue_persisted=True,
- target_was_busy=False,
- delivery_status="flush_failed",
+ target_was_busy=True,
+ delivery_status="queued",
delivery_owner_transferred=True,
)
- async def _recover_queue(sid):
- recovered.append(sid)
- return []
-
async def _handle_scheduled_message(context, message, parsed_session_key=None):
raise AssertionError("send-now must not use direct IM dispatch")
@@ -8759,9 +8780,6 @@ def test_idle_send_now_flush_failure_invokes_queue_recovery(monkeypatch, tmp_pat
gate=gate,
handle_scheduled_message=_handle_scheduled_message,
)
- controller.session_turns = SimpleNamespace(
- recover_persisted_agent_run_queue=_recover_queue,
- )
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
@@ -8772,13 +8790,11 @@ def test_idle_send_now_flush_failure_invokes_queue_recovery(monkeypatch, tmp_pat
stored = request_store.get_run(request.id)
assert stored is not None
- assert stored["status"] == "queued"
- assert stored["metadata"]["workbench_queue_holds_run"] is True
- assert stored["metadata"]["delivery_outcome"]["status"] == "flush_failed"
- assert recovered == [session_id]
+ assert stored["status"] == "running"
+ assert "workbench_queue_holds_run" not in stored["metadata"]
-def test_send_now_runtime_rejects_non_workbench_session(monkeypatch, tmp_path) -> None:
+def test_send_now_runtime_uses_shared_delivery_for_im_session(monkeypatch, tmp_path) -> None:
from core.services import sessions as sessions_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -8824,7 +8840,7 @@ def test_send_now_runtime_rejects_non_workbench_session(monkeypatch, tmp_path) -
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
session_id=session_id,
- message="do not silently downgrade",
+ message="steer through the shared owner",
agent_name="worker",
delivery_intent="send_now",
)
@@ -8833,6 +8849,17 @@ def test_send_now_runtime_rejects_non_workbench_session(monkeypatch, tmp_path) -
async def _handle_scheduled_message(context, message, parsed_session_key=None):
direct_calls.append(message)
+ from core.session_turns import TurnSubmissionResult
+
+ submit_scheduled = AsyncMock(
+ return_value=TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="queued",
+ delivery_owner_transferred=True,
+ )
+ )
controller = SimpleNamespace(
platform_settings_managers={"slack": object()},
im_clients={"slack": SimpleNamespace()},
@@ -8840,7 +8867,7 @@ def test_send_now_runtime_rejects_non_workbench_session(monkeypatch, tmp_path) -
should_use_thread_for_reply=lambda: True,
should_use_thread_for_dm_session=lambda: False,
),
- session_turn_gate=SimpleNamespace(submit_scheduled=AsyncMock(), in_flight={}),
+ session_turn_gate=SimpleNamespace(submit_scheduled=submit_scheduled, in_flight={}),
message_handler=SimpleNamespace(
handle_scheduled_message=_handle_scheduled_message,
),
@@ -8855,15 +8882,11 @@ def test_send_now_runtime_rejects_non_workbench_session(monkeypatch, tmp_path) -
stored = request_store.get_run(request.id)
assert stored is not None
- assert stored["status"] == "failed"
- assert "Web/Workbench Agent Session" in stored["error"]
- assert stored["metadata"]["delivery_outcome"] == {
- "intent": "send_now",
- "status": "unsupported_target",
- "target_was_busy": False,
- }
+ assert stored["status"] == "running"
+ assert stored["error"] is None
assert direct_calls == []
- controller.session_turn_gate.submit_scheduled.assert_not_awaited()
+ submit_scheduled.assert_awaited_once()
+ assert submit_scheduled.await_args.kwargs == {"delivery_intent": "send_now"}
def test_busy_avibe_agent_run_requeue_preserves_session_fork_metadata(monkeypatch, tmp_path) -> None:
diff --git a/tests/test_session_cli.py b/tests/test_session_cli.py
index 2fd336369..5edb340fe 100644
--- a/tests/test_session_cli.py
+++ b/tests/test_session_cli.py
@@ -245,7 +245,7 @@ def test_send_now_dispatches_an_existing_queue_without_adding_a_message(
}
-def test_send_now_surfaces_a_typed_interrupt_refusal(monkeypatch, tmp_path, capsys):
+def test_send_now_surfaces_a_typed_steer_refusal(monkeypatch, tmp_path, capsys):
from vibe import internal_client
engine = _setup(monkeypatch, tmp_path)
@@ -257,8 +257,8 @@ def test_send_now_surfaces_a_typed_interrupt_refusal(monkeypatch, tmp_path, caps
"body": {
"ok": False,
"session_id": session_id,
- "code": "stop_failed",
- "detail": "backend refused Stop",
+ "code": "send_now_refused",
+ "detail": "backend refused steering",
},
}
@@ -271,8 +271,8 @@ def test_send_now_surfaces_a_typed_interrupt_refusal(monkeypatch, tmp_path, caps
)
assert code == 1
- assert payload["code"] == "stop_failed"
- assert payload["error"] == "backend refused Stop"
+ assert payload["code"] == "send_now_refused"
+ assert payload["error"] == "backend refused steering"
assert payload["details"]["session_id"] == "sesaaa"
assert payload["details"]["controller_status_code"] == 409
@@ -344,7 +344,7 @@ def test_send_now_requires_an_explicit_target(capsys):
assert payload["help_command"] == "vibe session send-now --help"
-def test_send_now_and_queue_controls_reject_an_im_backed_session(
+def test_send_now_accepts_im_while_queue_management_remains_workbench_only(
monkeypatch,
tmp_path,
capsys,
@@ -354,8 +354,15 @@ def test_send_now_and_queue_controls_reject_an_im_backed_session(
engine = _setup(monkeypatch, tmp_path)
_seed(engine, "sesim", platform="slack", native="C123")
- async def _send_now(_session_id):
- raise AssertionError("IM-backed Session must not reach the Workbench controller")
+ async def _send_now(session_id):
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "status": "accepted",
+ },
+ }
monkeypatch.setattr(internal_client, "send_now", _send_now)
@@ -375,8 +382,8 @@ def test_send_now_and_queue_controls_reject_an_im_backed_session(
capsys,
)
- assert send_code == 1
- assert send_payload["code"] == "send_now_unsupported_target"
+ assert send_code == 0
+ assert send_payload["status"] == "accepted"
assert list_code == 1
assert list_payload["code"] == "session_queue_unsupported_target"
assert remove_code == 1
diff --git a/vibe/cli.py b/vibe/cli.py
index 46e12ff16..fbf7f7859 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -1228,7 +1228,7 @@ def _agent_run_examples_text() -> str:
Use --session-id to continue an existing Agent Session.
The default is P1: steer an active native Turn, start when idle, or fall back to the durable P3 queue.
Add --queue to persist this Run as P3 behind the active Turn.
- Add --send-now to admit this new Run as content P0 and replace the active Turn.
+ Add --send-now to persist the new Run and steer the exact FIFO head into the active Turn.
To promote the exact existing P3 queue head without a new message, use: vibe session send-now <session-id>
Inspect queued work with: vibe session queue list <session-id>
Remove one exact queued row with: vibe session queue remove <session-id> <message-id>
@@ -1256,7 +1256,7 @@ def _agent_run_examples_text() -> str:
Avibe Agent shell examples:
vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'
vibe agent run --agent release-reviewer --visible --message 'Review this project in a visible sibling Session.'
- vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Stop and apply this correction first.'
+ vibe agent run --session-id sesk8m4q2p7x --send-now --message 'Apply this correction in the current turn.'
vibe session queue list sesk8m4q2p7x
vibe session queue remove sesk8m4q2p7x msg_queued123
vibe session send-now sesk8m4q2p7x
@@ -5715,23 +5715,6 @@ def cmd_agent_run(args):
session_metadata = _session_creation_metadata_from_caller(caller_context)
if session_policy in {"existing", "fork"} and session_id:
target = resolve_session_id_target(session_id)
- if (
- delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW
- and target.session_key.platform != "avibe"
- ):
- raise TaskCliError(
- "--send-now requires a Web/Workbench Agent Session",
- code="send_now_unsupported_target",
- hint=(
- "Omit --send-now to steer the active IM Turn or start a new "
- "Turn when idle."
- ),
- help_command="vibe agent run --help",
- details={
- "session_id": session_id,
- "platform": target.session_key.platform,
- },
- )
session_key = target.session_key.to_key()
agent = _resolve_agent_for_target(
agent_name=agent_name or None,
@@ -6330,7 +6313,7 @@ def cmd_session_get(args):
def cmd_session_send_now(args):
- """Apply Workbench's Session-level Send now transition without adding work."""
+ """Promote a Session's exact FIFO head without adding work."""
from core.services import sessions as sessions_service
from vibe import internal_client
@@ -6340,17 +6323,6 @@ def cmd_session_send_now(args):
engine = _open_session_engine()
with engine.connect() as conn:
sessions_service.get_active_session(conn, session_id)
- target = resolve_session_id_target(session_id)
- if target.session_key.platform != "avibe":
- raise TaskCliError(
- "send-now requires a Web/Workbench Agent Session",
- code="send_now_unsupported_target",
- hint="This Session uses an IM scope, whose active turn is not owned by Workbench.",
- details={
- "session_id": session_id,
- "platform": target.session_key.platform,
- },
- )
controller_result = asyncio.run(internal_client.send_now(session_id))
except LookupError:
_print_task_error(
@@ -13942,7 +13914,7 @@ def build_parser():
agent_run_delivery_group.add_argument(
"--send-now",
action="store_true",
- help="Replace the active Turn with this new Run; start it immediately when idle",
+ help="Persist this Run, then steer the exact FIFO head without stopping the active Turn",
)
agent_run_delivery_group.add_argument(
"--queue",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 3babc27bb..3a80ab3a2 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -85,6 +85,7 @@
"canceled": "The run was canceled before producing a result.",
"failed": "The run failed before producing a result."
},
+ "sendNowGateUnavailable": "This send-now run could not be admitted because the Session turn gate is unavailable. Retry after the service finishes starting.",
"bindingUnresolvedRetry": "Pinned agent session {session} cannot accept a turn ({attempt}/{threshold}). This definition will be paused after {threshold} consecutive unresolvable-target failures. Re-point it with: vibe task update {id} --session-id <id>.",
"bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}."
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 3ca5a8609..4b99bc998 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -85,6 +85,7 @@
"canceled": "本次 run 在产出结果前被取消,因此没有结果。",
"failed": "本次 run 在产出结果前失败,因此没有结果。"
},
+ "sendNowGateUnavailable": "本次 send-now run 无法接入:Session turn gate 当前不可用。请等待服务启动完成后重试。",
"bindingUnresolvedRetry": "绑定的 Agent 会话 {session} 无法接收请求({attempt}/{threshold})。连续 {threshold} 次出现目标会话不可用后,该定义将自动暂停。请用以下命令重新绑定:vibe task update {id} --session-id <id>。",
"bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。"
},