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(turns): a Harness input queues behind a person's Turn instead of steering it (#2741)

Call White163dcfec52e2
diff --git a/core/internal_server.py b/core/internal_server.py
index ebffd6cf0..6812ca9b1 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -32,6 +32,7 @@ import os
import re
import socket
import time
+from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable, Optional, TYPE_CHECKING
@@ -264,7 +265,9 @@ def create_app(
The explicit source intent decides whether this content queues or steers.
Content-bearing P1 targets this Delivery; content-free P1 promotion is
- exposed separately through ``SessionTurnManager.send_now``.
+ exposed separately through ``SessionTurnManager.send_now``. ``send_now``
+ is P1 that also steers a Turn a person's input is part of, which a
+ default P1 Harness input queues behind (``DeliveryRequest.send_now``).
The submission remains a Delivery until exact native acceptance materializes
the harness Message.
"""
@@ -302,7 +305,7 @@ def create_app(
scope_id: str | None = None
delivery_owner_transferred = False
target_was_busy = False
- legacy_send_now = str(delivery_intent or "").strip().lower() == "send_now"
+ send_now = str(delivery_intent or "").strip().lower() == "send_now"
delivery_intent = normalize_delivery_intent(delivery_intent)
effective_delivery_intent = delivery_intent
execution_id = str(
@@ -380,7 +383,7 @@ def create_app(
delivery_status="canceled",
)
if (
- legacy_send_now
+ send_now
and existing_state == "queued"
and existing.get("priority") == "p3"
and message_deliveries.delivery_has_history_event(
@@ -437,7 +440,10 @@ def create_app(
raise ValueError("Session is archived")
if existing is not None:
delivery_id = str(existing["id"])
- delivery_request = manager._request_from_delivery(existing)
+ delivery_request = replace(
+ manager._request_from_delivery(existing),
+ send_now=send_now,
+ )
scope_id = delivery_request.scope_id
from core.message_priority import delivery_intent_for_priority
@@ -555,6 +561,7 @@ def create_app(
SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)
},
native_message_id=native_message_id or None,
+ send_now=send_now,
)
if context.platform_specific is None:
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 3b54a2c03..021dee122 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -145,7 +145,9 @@ _TaskStoreResult = TypeVar("_TaskStoreResult")
AGENT_RUN_DELIVERY_STEER = "steer"
AGENT_RUN_DELIVERY_QUEUE = "queue"
-LEGACY_AGENT_RUN_DELIVERY_SEND_NOW = "send_now"
+# Stored as given: P1 like the default, and explicit, so it also steers a Turn a
+# person's input is part of, which a default P1 Run queues behind.
+AGENT_RUN_DELIVERY_SEND_NOW = "send_now"
AGENT_RUN_DELIVERY_INTENTS = frozenset(
{
AGENT_RUN_DELIVERY_STEER,
@@ -2807,6 +2809,8 @@ class TaskExecutionStore:
# real message; a blank one is a bug in the caller.
raise ValueError("agent run requires a non-empty message")
normalized_delivery_intent = normalize_agent_run_delivery_intent(delivery_intent)
+ if str(delivery_intent or "").strip().lower() == AGENT_RUN_DELIVERY_SEND_NOW:
+ normalized_delivery_intent = AGENT_RUN_DELIVERY_SEND_NOW
run_metadata = dict(metadata or {})
run_metadata[AGENT_RUN_DELIVERY_INTENT_METADATA_KEY] = normalized_delivery_intent
request = TaskExecutionRequest(
@@ -9461,7 +9465,7 @@ class ScheduledTaskService:
failure_code=FAILURE_CODE_SESSION_TURN_GATE_UNAVAILABLE,
)
if session_id and gate is not None:
- if raw_delivery_intent == LEGACY_AGENT_RUN_DELIVERY_SEND_NOW:
+ if raw_delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW:
state = await gate.submit_scheduled(
session_id,
context,
diff --git a/core/session_turns.py b/core/session_turns.py
index 54e79ac87..f9ea68361 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -479,6 +479,28 @@ def _segment_dispatch_text(segment: list[dict[str, Any]]) -> str:
return ("\n\n---\n\n" if scheduled else "\n").join(texts)
+def _yields_to_human_turn(
+ conn: Connection,
+ request: "DeliveryRequest",
+ delivery: dict[str, Any],
+ turn_id: str,
+) -> bool:
+ """Whether this P1 input queues behind the active Turn instead of steering it.
+
+ A Watch, Hook, Webhook, or Agent Run delivers a scheduled Harness input: an
+ automatic signal, not a person speaking. Steered into a Turn that serves a
+ person, it would continue that Turn past the person's answer, which would
+ then no longer be the Turn's result. So it waits for that Turn to end and
+ runs as its own Turn. A person's input (IM, a Show annotation) and an
+ explicit send-now keep steering.
+ """
+ if request.send_now:
+ return False
+ if delivery_store.scheduled_delivery_provenance(delivery_store.delivery_payload(delivery)) is None:
+ return False
+ return delivery_store.turn_has_human_input(conn, turn_id)
+
+
def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:
"""The ONE active-turn token rule (FSM Phase 2 — collapses the three previously
duplicated guards: ``_stream_chunk`` completion, ``_is_active_turn``, and
@@ -593,6 +615,10 @@ class DeliveryRequest:
# 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
+ # A producer's explicit send-now (``vibe agent run --send-now``). Without it,
+ # a scheduled Harness P1 input never steers a Turn a person's input is part
+ # of; it queues behind that Turn (``_yields_to_human_turn``).
+ send_now: bool = False
@dataclass(frozen=True)
@@ -3119,7 +3145,23 @@ class SessionTurnManager:
and identity is not None
and identity[0] == observed_id
)
- if same_active:
+ if current is not None and _yields_to_human_turn(conn, request, delivery, str(current["id"])):
+ queued = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "queue",
+ "reason": "behind_human_turn",
+ "turn_id": str(current["id"]),
+ },
+ )
+ if queued is None:
+ raise RuntimeError("P1 queue claim behind a human Turn lost after writer reservation")
+ delivery = queued
+ elif same_active:
attempt_id = delivery_store.new_attempt_id()
native_id = str(identity[1])
turn_id = observed_id
diff --git a/docs/CLI.md b/docs/CLI.md
index d330f5a14..b4aed5db7 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -487,11 +487,14 @@ vibe agent run --close-after --no-callback --agent release-reviewer --message 'R
With an existing `--session-id`, the default admission is P1: Avibe steers the
new Run into an active native Turn, starts it immediately when idle, or moves the
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` and explicitly selects
-the normal content-bearing P1 behavior: the new message steers an active native
-Turn, starts immediately when idle, and falls back to P3 after a definitive
+receipt. It does not interrupt the active Turn. When a person's message is part
+of the active Turn, the Run is not steered into it: it waits in the P3 queue and
+runs as its own Turn after that Turn ends, so the person's answer stays that
+Turn's result. Watch, Hook, Webhook, and callback deliveries follow the same rule.
+
+`--send-now` is valid only with an existing `--session-id` and explicitly steers
+the new message into the active native Turn, including one a person's message is
+part of. It starts immediately when idle and falls back to P3 after a definitive
refusal. It never promotes an older queued message. `vibe session send-now` is
the content-free P1 operation: it promotes the exact existing FIFO head without
adding a message. A stale head is refused rather than replaced by the next queued
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 37b0594d9..ca00149c5 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -388,9 +388,14 @@ vibe agent run --no-callback --create-session --scope-id slack::channel::C999 --
vibe agent run --close-after --no-callback --agent release-reviewer --message 'Run a disposable batch review.'
```
-`--send-now` 只能和现有 `--session-id` 一起使用,它显式选择普通的带内容 P1
-语义:新消息会 steering 进活动 native Turn,Session 空闲时立即启动;只有明确
-拒绝后才回退到 P3。它不会提升更早的排队消息。`vibe session send-now` 是无内容
+对于现有 `--session-id`,默认投递是 P1:新 Run 会 steering 进活动 native Turn,
+Session 空闲时立即启动。如果活动 Turn 中包含用户本人发送的消息,Run 不会 steering
+进去,而是进入 P3 队列,在该 Turn 结束后作为独立 Turn 执行,这样用户得到的答复仍是
+该 Turn 的结果。Watch、Hook、Webhook 和回调投递遵循同一规则。
+
+`--send-now` 只能和现有 `--session-id` 一起使用,它显式把新消息 steering 进活动
+native Turn,包括包含用户消息的 Turn;Session 空闲时立即启动;只有明确拒绝后才
+回退到 P3。它不会提升更早的排队消息。`vibe session send-now` 是无内容
P1 操作,只提升现有的精确 FIFO 队头,不新增消息。过期队头会被拒绝,而不会改为
提升下一条;两个命令都不会调用 Stop。
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index ab80f1e72..364cfd356 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -969,9 +969,11 @@ record. It cannot target an existing `--session-id`.
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. For an existing Session, `--send-now` explicitly selects the same
-content-bearing P1 behavior; it targets the new message and never promotes older
+definitive refusal/not-active receipt. When a person's message is part of the
+active Turn, the Run queues behind it as P3 and runs as its own Turn instead.
+`--queue` selects P3 without attempting a steer. For an existing Session,
+`--send-now` steers the new message into the active Turn, including one a
+person's message is part of; it targets the new message and never promotes older
queued work. `vibe session send-now` is the content-free P1 operation that
promotes the exact existing FIFO head without adding a message.
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index 09e1dbc4c..497353141 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -899,9 +899,10 @@ runtime,同时保留 Session、transcript 和 Run 记录;不能和现有的
`--session-id` 一起使用。
对于现有 `--session-id`,默认投递是 P1:新消息会 steering 进活动 native Turn,
-Session 空闲时立即启动;明确拒绝后,同一个 Delivery 才回退到 P3。`--queue` 会
-直接选择 P3。`--send-now` 显式选择相同的带内容 P1 语义,只针对这条新消息,
-不会提升更早的排队工作。`vibe session send-now` 是无内容 P1 操作,只提升现有的
+Session 空闲时立即启动;明确拒绝后,同一个 Delivery 才回退到 P3。如果活动 Turn
+中包含用户本人发送的消息,Run 会以 P3 排在该 Turn 之后,作为独立 Turn 执行。
+`--queue` 会直接选择 P3。`--send-now` 显式把这条新消息 steering 进活动 Turn,
+包括包含用户消息的 Turn,不会提升更早的排队工作。`vibe session send-now` 是无内容 P1 操作,只提升现有的
精确 FIFO 队头,不新增消息。命令响应包含 `delivery_intent`,Controller 消费请求后,
`vibe runs show <run-id>` 会显示持久化的 `metadata.delivery_outcome`。
diff --git a/docs/plans/agent-message-priority.md b/docs/plans/agent-message-priority.md
index f61e7f86f..065bfffc3 100644
--- a/docs/plans/agent-message-priority.md
+++ b/docs/plans/agent-message-priority.md
@@ -108,14 +108,25 @@ 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. `--send-now` explicitly selects the same content-bearing P1 behavior and never promotes older queued work. |
-| Watch, Hook, Webhook | P1 | Continues the target Session without interrupting it. |
+| Existing-Session Agent Run | P1 | Same as ordinary IM, except behind a Turn a person's input is part of (below). `--queue` selects P3. `--send-now` steers even that Turn and never promotes older queued work. |
+| Watch, Hook, Webhook | P1 | Continues the target Session without interrupting it; behind a person's Turn it queues (below). |
| Show annotation | P1 | Delivers the annotation to the current Turn when possible. |
-| Session callback | P1 | Delivers each completed child Run independently. |
+| Session callback | P1 | Delivers each completed child Run independently; behind a person's Turn it queues (below). |
| Scheduled Task | P3 | Never interrupts or steers the work a user is already doing. |
| Stop | Empty P0 | Stops the exact live Turn. Definitive terminal settlement immediately starts the oldest claimable P3 segment. |
| Send Now existing head | Empty P1 | Promotes only the exact observed FIFO head. |
+A scheduled Harness input (one a Watch, Hook, Webhook, or Agent Run delivers,
+callbacks included) is an automatic signal, not a person speaking. When a
+person's input is part of the active Turn (the input it started with, one
+steered into it, or one still being steered into it), P1 admission writes that
+Harness input as P3 instead of steering it, under the same writer lock that
+observes the Turn. It waits in the FIFO and runs as its own Turn after that Turn
+ends, however it ends. Steered in, it would continue the Turn past the person's
+answer, which would then be narration rather than the Turn's result. A person's
+input (IM, a Show annotation), an explicit `--send-now`, and content-free Send
+Now keep steering; a Turn no person's input is part of is still steered.
+
Attachments remain part of the same Delivery and follow the same P1 admission
as text. Send Now can steer pure-image and mixed text/file messages into the
active Turn without stopping it. Definitive refusal preserves the queue; an
diff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.md
index dc04e7a5b..ade7742b5 100644
--- a/skills/use-avibe-harness/SKILL.md
+++ b/skills/use-avibe-harness/SKILL.md
@@ -67,7 +67,7 @@ Any run that creates a new Session (a blank new Session from `--agent`, `--creat
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 its message into an active native Turn, starts that message 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. `vibe agent run --session-id <id> --send-now --message ...` explicitly selects that same content-bearing P1 behavior; it does not promote an older queued message. Use `vibe session send-now <id>` only when no new Message should be added: this content-free P1 promotes the exact existing FIFO head. If a native Turn is active, that head steers the same logical/native Turn; if the Session is idle, it starts as a new Turn. Both commands 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.
+That existing-Session send is a P1 delivery by default: it steers its message into an active native Turn, starts that message immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. When a person's message is part of the active Turn, it is not steered: it waits in the P3 queue and runs as its own Turn after that Turn ends, as Watch and callback deliveries do. 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. `vibe agent run --session-id <id> --send-now --message ...` steers that message into the active Turn even when a person's message is part of it; it does not promote an older queued message. Use `vibe session send-now <id>` only when no new Message should be added: this content-free P1 promotes the exact existing FIFO head. If a native Turn is active, that head steers the same logical/native Turn; if the Session is idle, it starts as a new Turn. Both commands 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/storage/message_deliveries.py b/storage/message_deliveries.py
index 05072a5af..94ce755c5 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -2563,6 +2563,15 @@ def pending_steer_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | N
)
+def turn_has_human_input(conn: Connection, turn_id: str) -> bool:
+ """Whether a person's input is part of this Turn: one it started with, one
+ steered into it, or one still being steered into it."""
+ return any(
+ execution_delivery_payload(conn, row).get("source") == "user"
+ for row in deliveries_for_turn(conn, turn_id)
+ )
+
+
def turn_has_delivery_owner(conn: Connection, turn_id: str) -> bool:
turn = get_turn(conn, turn_id)
return bool(turn and get_delivery(conn, str(turn["initial_delivery_id"])))
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index a339521e7..be4f4c08d 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -379,5 +379,20 @@ scenarios:
kind: recovery
layer: contract
test: tests/test_backend_failure_retry.py::test_restart_notice_names_the_watch_running_the_command_and_offers_no_retry
+ - id: MESSAGE-DELIVERY-323
+ name: A scheduled Harness P1 input queues behind a Turn a person's input is part of and runs as its own Turn
+ status: covered
+ kind: concurrency
+ layer: contract
+ test:
+ - tests/test_session_delivery_fsm.py::test_a_harness_p1_input_steers_only_a_turn_no_persons_input_is_part_of
+ - tests/test_session_delivery_fsm.py::test_harness_inputs_behind_a_persons_turn_each_run_as_their_own_turn_in_queue_order
+ - tests/test_internal_server.py::test_an_agent_run_report_queues_behind_a_persons_turn_and_runs_as_the_next_turn
+ - id: MESSAGE-DELIVERY-324
+ name: A Harness report during a person's Vibey Turn leaves the answer its result and runs as the next Turn
+ status: covered
+ kind: regression
+ layer: scenario
+ test: tests/test_vibey_agent.py::test_a_harness_input_during_a_persons_turn_leaves_the_answer_its_result_and_runs_next
next_priority:
- - MESSAGE-DELIVERY-323
+ - MESSAGE-DELIVERY-325
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index ff451afcc..67a0c3a99 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -535,12 +535,14 @@ def test_agent_run_send_now_is_explicit_p1_on_an_existing_session(
assert result == 0
payload = json.loads(capsys.readouterr().out)
- assert payload["delivery_intent"] == "steer"
- assert payload["run"]["delivery_intent"] == "steer"
+ # Stored as given, not folded into the default: an explicit send-now also
+ # steers a Turn a person's input is part of, which a default Run queues behind.
+ assert payload["delivery_intent"] == "send_now"
+ assert payload["run"]["delivery_intent"] == "send_now"
stored = request_store.get_run(payload["run_id"])
assert stored is not None
assert stored["session_id"] == session_id
- assert stored["metadata"]["delivery_intent"] == "steer"
+ assert stored["metadata"]["delivery_intent"] == "send_now"
def test_agent_run_send_now_rejects_a_new_session(capsys) -> None:
@@ -713,10 +715,10 @@ def test_agent_run_send_now_accepts_an_im_backed_session(
assert result == 0
payload = json.loads(capsys.readouterr().out)
assert payload["session_id"] == session["id"]
- assert payload["delivery_intent"] == "steer"
+ assert payload["delivery_intent"] == "send_now"
stored = request_store.get_run(payload["run_id"])
assert stored is not None
- assert stored["metadata"]["delivery_intent"] == "steer"
+ 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 611f8a087..1dea9bf4b 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -4122,6 +4122,150 @@ def test_agent_run_send_now_steers_its_content_without_promoting_fifo(monkeypatc
}
+def test_an_agent_run_report_queues_behind_a_persons_turn_and_runs_as_the_next_turn(monkeypatch, tmp_path):
+ """Scenario: MESSAGE-DELIVERY-323.
+
+ The default (not send-now) Agent Run a lane reports with, through the real
+ producer: it never steers the person's Turn, and starts its own Turn after it.
+ """
+ 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_report",
+ 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"]
+ question = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="2547是做什么的来着?",
+ )
+
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="PR #2688 merged externally.",
+ agent_name="worker",
+ source_kind="agent",
+ source_actor="ses_lane",
+ )
+ assert request_store.claim(request.id) is not None
+ answering, answered, report_started = asyncio.Event(), asyncio.Event(), asyncio.Event()
+ seen: list[tuple[str, str]] = []
+
+ async def _dispatch(
+ ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None, **_kwargs
+ ):
+ seen.append((text, source))
+ _bind_test_native_start(engine, ctx)
+ if text == "2547是做什么的来着?":
+ answering.set()
+ await answered.wait()
+ else:
+ report_started.set()
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
+
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ 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:
+ response = await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "2547是做什么的来着?",
+ "user_message_id": question["id"],
+ },
+ )
+ assert response.status_code == 202
+ await asyncio.wait_for(answering.wait(), timeout=3)
+ 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",
+ "source_kind": "agent",
+ "source_actor": "ses_lane",
+ "suppress_delivery": True,
+ },
+ )
+ result = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ )
+ with engine.connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == [
+ "PR #2688 merged externally."
+ ]
+ answered.set()
+ await asyncio.wait_for(report_started.wait(), timeout=3)
+ return result
+
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="queued",
+ delivery_owner_transferred=True,
+ )
+ controller.session_turns._steer.assert_not_awaited()
+ controller.command_handler.handle_stop.assert_not_awaited()
+ assert seen == [
+ ("2547是做什么的来着?", SOURCE_HUMAN),
+ ("PR #2688 merged externally.", SOURCE_SCHEDULED),
+ ]
+ with engine.connect() as conn:
+ report = message_deliveries.get_delivery_by_native_identity(
+ conn,
+ platform="avibe",
+ native_message_id=f"agent_run:{request.id}",
+ scope_id=scope_id,
+ session_id=session_id,
+ )
+ first = message_deliveries.get_delivery(conn, question["id"])
+ assert report is not None and first is not None
+ assert (report["turn_role"], report["turn_position"]) == ("initial", 0)
+ assert report["turn_id"] != first["turn_id"]
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["metadata"]["delivery_outcome"] == {
+ "intent": "steer",
+ "status": "queued",
+ "target_was_busy": True,
+ }
+
+
def test_agent_run_send_now_steers_a_turn_started_during_admission(monkeypatch, tmp_path):
"""A stale idle snapshot cannot downgrade explicit P1 into P3 queueing."""
from core.scheduled_tasks import TaskExecutionStore
@@ -4731,7 +4875,7 @@ def test_agent_run_send_now_restart_preserves_refused_queue_behind_durable_owner
]
stored = request_store.get_run(request.id)
assert stored is not None
- assert stored["metadata"]["delivery_intent"] == "steer"
+ assert stored["metadata"]["delivery_intent"] == "send_now"
assert stored["metadata"]["delivery_outcome"]["status"] == "queued"
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 31b20585d..a55647812 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -9397,9 +9397,9 @@ def test_busy_avibe_agent_run_send_now_keeps_transferred_owner_running(monkeypat
assert run.get("started_at") is not None
assert run.get("completed_at") is None
assert "workbench_queue_holds_run" not in (run.get("metadata") or {})
- assert run["metadata"]["delivery_intent"] == "steer"
+ assert run["metadata"]["delivery_intent"] == "send_now"
assert submitted == [
- (session_id, "run behind active workbench turn", request.id, "steer")
+ (session_id, "run behind active workbench turn", request.id, "send_now")
]
assert handler_calls == []
@@ -9538,7 +9538,7 @@ def test_send_now_runtime_uses_shared_delivery_for_im_session(monkeypatch, tmp_p
assert stored["error"] is None
assert direct_calls == []
submit_scheduled.assert_awaited_once()
- assert submit_scheduled.await_args.kwargs == {}
+ 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_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 4868f4019..4778d2b25 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -291,10 +291,11 @@ async def _activate(
*,
text: str = "primary",
priority: str = "p3",
+ **fields,
) -> tuple[str, MessageContext]:
context = _context()
admitted = await manager.deliver(
- DeliveryRequest(session_id="ses_fsm", priority=priority, content=text),
+ DeliveryRequest(session_id="ses_fsm", priority=priority, content=text, **fields),
context=context,
)
assert admitted.turn_id
@@ -314,6 +315,21 @@ async def _activate(
return turn_id, context
+def _harness_fields(trigger_kind: str, **platform_specific) -> dict:
+ """A scheduled Harness input's request fields, as the internal server builds them."""
+ return {
+ "source": "harness",
+ "author": "harness",
+ "message_type": "harness",
+ "author_name": trigger_kind,
+ "metadata": {
+ SCHEDULED_PROVENANCE_KEY: {
+ "platform_specific": {"task_trigger_kind": trigger_kind, **platform_specific}
+ }
+ },
+ }
+
+
def _rows(engine) -> list[dict]:
with engine.connect() as conn:
return [
@@ -823,6 +839,198 @@ def test_fifo_scheduled_segment_does_not_merge_different_source_sessions(manager
assert _row(engine, str(queued[1].delivery_id))["turn_id"] is None
+def _bind_native_start(manager: SessionTurnManager, turn_id: str) -> None:
+ """The backend's native start for a claimed Turn, as ``_activate`` binds it."""
+ context = _context()
+ context.platform_specific["turn_token"] = turn_id
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ manager._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ manager.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{turn_id}",
+ runtime_turn_id=f"runtime-{turn_id}",
+ )
+
+
+_P1_INPUTS = {
+ "watch": _harness_fields("watch", task_definition_id="watch-pr"),
+ "hook": _harness_fields("hook", task_definition_id="hook-ci"),
+ "agent_run": _harness_fields("agent_run", source_kind="agent", source_actor="lane"),
+ "agent_run_send_now": {
+ **_harness_fields("agent_run", source_kind="agent", source_actor="lane"),
+ "send_now": True,
+ },
+ "person": {},
+ # A person's Show annotation is a Harness row without scheduled provenance.
+ "show_annotation": {
+ "source": "harness",
+ "author": "harness",
+ "message_type": "annotation",
+ "author_name": "show_annotation",
+ "metadata": {"source": "show_page"},
+ },
+}
+
+
+ ("turn", "incoming", "admitted"),
+ [
+ ("person", "watch", "queued"),
+ ("person", "hook", "queued"),
+ ("person", "agent_run", "queued"),
+ ("person_starting", "agent_run", "queued"),
+ ("harness_with_person_steer", "watch", "queued"),
+ ("person", "agent_run_send_now", "accepted"),
+ ("person", "person", "accepted"),
+ ("person", "show_annotation", "accepted"),
+ ("harness", "agent_run", "accepted"),
+ ("harness_starting", "agent_run", "pending_steer"),
+ ("idle", "agent_run", "claimed"),
+ ],
+)
+def test_a_harness_p1_input_steers_only_a_turn_no_persons_input_is_part_of(
+ managers, turn, incoming, admitted
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-323."""
+ manager, _other, engine, _engine_b, starts = managers
+ accepted = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ turn_id: str | None = None
+ if turn in {"person", "harness", "harness_with_person_steer"}:
+ fields = {} if turn == "person" else _harness_fields("watch", task_definition_id="watch-ci")
+ turn_id, _ = asyncio.run(_activate(manager, text="the Turn's input", **fields))
+ elif turn in {"person_starting", "harness_starting"}:
+ fields = {} if turn == "person_starting" else _harness_fields("watch", task_definition_id="watch-ci")
+ started = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="the Turn's input", **fields),
+ context=_context(),
+ )
+ )
+ turn_id = started.turn_id
+ if turn == "harness_with_person_steer":
+ manager._steer = accepted
+ steered = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="a person steers"),
+ context=_context(),
+ )
+ )
+ assert steered.state == "accepted" and _row(engine, steered.delivery_id)["turn_id"] == turn_id
+ accepted = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ manager._steer = accepted
+
+ result = asyncio.run(
+ manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="PR #2688 merged", **_P1_INPUTS[incoming]),
+ context=_context(),
+ )
+ )
+
+ assert result.state == admitted
+ assert accepted.await_count == (1 if admitted == "accepted" else 0)
+ row = _row(engine, result.delivery_id)
+ if admitted == "queued":
+ # It waits in the FIFO for the Turn to end, and never touched that Turn.
+ assert (row["priority"], row["turn_id"], row["current_target_turn_id"]) == ("p3", None, None)
+ last_event = json.loads(row["delivery_history_json"])["events"][-1]
+ assert {key: value for key, value in last_event.items() if key != "at"} == {
+ "kind": "queue",
+ "reason": "behind_human_turn",
+ "turn_id": turn_id,
+ }
+ with engine.connect() as conn:
+ assert delivery_store.active_turn(conn, "ses_fsm")["id"] == turn_id
+ elif admitted == "claimed":
+ assert [text for _turn_id, text in starts] == ["PR #2688 merged"]
+ else:
+ assert (row["turn_id"] or row["current_target_turn_id"]) == turn_id
+
+
[email protected]("outcome", ["completed", "failed", "canceled"])
+def test_harness_inputs_behind_a_persons_turn_each_run_as_their_own_turn_in_queue_order(
+ managers, outcome
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-323.
+
+ Two callbacks and a Watch arrive while a person's Turn runs, around a
+ message the person queues. However that Turn ends, each input runs once,
+ after it, in the order it arrived, and a person's input never shares a Turn
+ with them.
+ """
+ manager, _other, engine, _engine_b, starts = managers
+ person_turn_id, _ = asyncio.run(_activate(manager, text="2547是做什么的来着?"))
+ manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
+ arrivals = [
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="the PR's checks passed", **_P1_INPUTS["watch"]),
+ DeliveryRequest(
+ session_id="ses_fsm", priority="p1", content="lane A reports",
+ **_harness_fields("agent_run", source_kind="agent", source_actor="lane-a"),
+ ),
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="and one more question"),
+ DeliveryRequest(
+ session_id="ses_fsm", priority="p1", content="lane B reports",
+ **_harness_fields("agent_run", source_kind="agent", source_actor="lane-b"),
+ ),
+ ]
+ delivered = [asyncio.run(manager.deliver(request, context=_context())) for request in arrivals]
+ assert [result.state for result in delivered] == ["queued"] * 4
+ manager._steer.assert_not_awaited()
+
+ turn_ids = [person_turn_id]
+ asyncio.run(manager.terminalize_turn(person_turn_id, outcome=outcome))
+ for _ in arrivals:
+ with engine.connect() as conn:
+ successor = delivery_store.active_turn(conn, "ses_fsm")
+ assert successor is not None and successor["id"] not in turn_ids
+ turn_ids.append(str(successor["id"]))
+ _bind_native_start(manager, turn_ids[-1])
+ assert asyncio.run(manager.terminalize_turn(turn_ids[-1]))
+ with engine.connect() as conn:
+ assert delivery_store.active_turn(conn, "ses_fsm") is None
+
+ assert [text for _turn_id, text in starts] == [
+ "2547是做什么的来着?",
+ "the PR's checks passed",
+ "lane A reports",
+ "and one more question",
+ "lane B reports",
+ ]
+ assert [turn_id for turn_id, _text in starts] == turn_ids
+ rows = [_row(engine, result.delivery_id) for result in delivered]
+ assert [(row["state"], row["turn_id"], row["turn_role"]) for row in rows] == [
+ ("accepted", turn_id, "initial") for turn_id in turn_ids[1:]
+ ]
+
+
+def test_a_turns_person_check_reads_only_that_turns_rows(managers) -> None:
+ """The check runs on every P1 admission: it must not scan a Session's history."""
+ from sqlalchemy import event
+
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, _ = asyncio.run(_activate(manager, text="active"))
+ statements: list[tuple[str, object]] = []
+
+ def capture(_conn, _cursor, statement, parameters, _context, _executemany):
+ statements.append((statement, parameters))
+
+ event.listen(engine, "before_cursor_execute", capture)
+ try:
+ with engine.connect() as conn:
+ assert delivery_store.turn_has_human_input(conn, turn_id)
+ finally:
+ event.remove(engine, "before_cursor_execute", capture)
+ db_path = engine.url.database
+ plans = []
+ with closing(sqlite3.connect(db_path)) as raw:
+ for statement, parameters in statements:
+ plans.extend(row[-1] for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters))
+ assert plans and not [plan for plan in plans if plan.startswith("SCAN")]
+
+
@pytest.mark.anyio
async def test_scheduled_submit_passes_metadata_separately_to_native_steering(managers) -> None:
manager, _other, engine, _engine_b, _starts = managers
@@ -831,7 +1039,8 @@ async def test_scheduled_submit_passes_metadata_separately_to_native_steering(ma
manager.controller.message_handler = SimpleNamespace(
prepare_input_metadata=prepare,
)
- await _activate(manager, text="active")
+ # A Harness input steers a Turn no person's input is part of.
+ await _activate(manager, text="active", **_harness_fields("watch"))
manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))
context = _context()
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 4b6dca1da..15c51235f 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -754,6 +754,112 @@ async def test_a_steer_enters_after_the_tool_batch_even_when_its_row_arrives_lat
assert late.outcome is SteerOutcome.NOT_ACTIVE
+async def test_a_harness_input_during_a_persons_turn_leaves_the_answer_its_result_and_runs_next(
+ engine, session, tmp_path, published
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-324.
+
+ A lane's report reaches a Session while it answers a person: it goes through
+ the real admission into the live run's steer path, and must not continue that
+ Turn past the person's answer, which would then be stored as narration.
+ """
+ from core.session_turns import SCHEDULED_PROVENANCE_KEY, DeliveryRequest, SessionTurnManager
+ from modules.agents.base import AGENT_RUNTIME_TURN_TOKEN
+
+ generating, answered = asyncio.Event(), asyncio.Event()
+
+ async def answer(_request, _cancel):
+ generating.set()
+ await answered.wait()
+ yield Done(assistant("#2547 让 Avibe 不启动 Claude CLI 就能发现插件里的 Skill。"))
+
+ harness = _Harness(engine, tmp_path, "avibe", [answer, [Done(assistant("已记录 #2688 的合并。"))]])
+ request = harness.request("2547是做什么的来着?")
+ person_turn = _turn(request.context)
+ request.context.platform_specific[AGENT_RUNTIME_TURN_TOKEN] = "runtime-person"
+ # The live Turn as AgentService registers it, which the real steer path finds the run through.
+ gate = SimpleNamespace(
+ backend="vibey", token="runtime-person", runtime_started=True,
+ request=request, context=request.context, agent=harness.agent,
+ )
+ started: list[tuple[str, str]] = []
+
+ async def _run(_session_id, _context, text, **kwargs):
+ started.append((str(kwargs.get("logical_turn_id") or ""), text))
+
+ manager = SessionTurnManager(
+ SimpleNamespace(
+ agent_service=SimpleNamespace(agents={"vibey": harness.agent}, _turn_gates={"runtime": gate}),
+ config=SimpleNamespace(language="en"),
+ set_agent_status=lambda *_args: None,
+ ),
+ build_context=lambda session_id: _context("avibe", session_id, turn_id="", delivery_id=""),
+ )
+ manager._engine = engine
+ manager._run = _run
+ running = asyncio.create_task(harness.agent.handle_message(request))
+ await generating.wait()
+
+ report = await manager.deliver(
+ DeliveryRequest(
+ session_id=SESSION,
+ priority="p1",
+ content="PR #2688 merged externally.",
+ source="harness",
+ author="harness",
+ message_type="harness",
+ author_name="agent_run",
+ native_message_id="agent_run:d14b57437088",
+ metadata={
+ SCHEDULED_PROVENANCE_KEY: {
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "source_kind": "agent",
+ "source_actor": "ses_lane",
+ }
+ }
+ },
+ ),
+ context=_context("avibe", SESSION, turn_id="", delivery_id=""),
+ )
+ assert report.state == "queued"
+ answered.set()
+ await running
+
+ # The person's answer is the Turn's result, the run read no other input, and nothing is narration.
+ [answer_row] = harness.rows("result")
+ assert answer_row["content_text"].startswith("#2547 让 Avibe")
+ assert "transcript_copy" not in json.loads(answer_row["metadata_json"])
+ assert harness.rows("assistant") == [] and harness.rows("harness") == []
+ assert [entry.kind for entry in await harness.context_rows()] == ["input", "response"]
+
+ # Its Turn ends, and the report starts the next Turn on its own.
+ assert await manager.terminalize_turn(person_turn)
+ [(report_turn, text)] = started
+ assert report_turn != person_turn and text == "PR #2688 merged externally."
+ report_context = _context("avibe", SESSION, turn_id=report_turn, delivery_id=report.delivery_id)
+ await harness.agent.handle_message(
+ AgentRequest(
+ context=report_context,
+ message=text,
+ user_message=text,
+ working_path=str(tmp_path),
+ base_session_id=SESSION,
+ composite_session_id=SESSION,
+ session_key=f"avibe::{SESSION}",
+ vibe_agent_model="test-model",
+ )
+ )
+ [report_row] = harness.rows("harness")
+ assert report_row["id"] == report.delivery_id and report_row["content_text"] == "PR #2688 merged externally."
+ assert [row["content_text"] for row in harness.rows("result")] == [
+ answer_row["content_text"],
+ "已记录 #2688 的合并。",
+ ]
+ assert harness.rows("assistant") == []
+ assert [entry.kind for entry in await harness.context_rows()] == ["input", "response", "input", "response"]
+
+
async def test_reconcile_reports_a_steer_attempt_only_from_evidence(engine, session, tmp_path, published) -> None:
from core.services.agent_steering import SteerReconcileRequest
from modules.im.base import FileAttachment
diff --git a/vibe/cli.py b/vibe/cli.py
index ef39ae577..a3834ffee 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -39,6 +39,7 @@ from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, display_
from core.scheduled_tasks import (
AGENT_RUN_CLOSE_AFTER_METADATA_KEY,
AGENT_RUN_DELIVERY_QUEUE,
+ AGENT_RUN_DELIVERY_SEND_NOW,
AGENT_RUN_DELIVERY_STEER,
BINDING_FOLLOWS_SESSION_METADATA_KEY,
ScheduledTaskStore,
@@ -2044,8 +2045,9 @@ def _agent_run_examples_text() -> str:
Session target:
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.
+ A Turn that a person's message is part of is not steered: the Run queues behind it and runs as its own Turn.
Add --queue to persist this Run as P3 behind the active Turn.
- --send-now explicitly selects the same P1 content delivery for an existing Session.
+ --send-now steers the active Turn even when a person's message is part of it.
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>
@@ -7013,6 +7015,8 @@ def cmd_agent_run(args):
delivery_intent = (
AGENT_RUN_DELIVERY_QUEUE
if bool(getattr(args, "queue", False))
+ else AGENT_RUN_DELIVERY_SEND_NOW
+ if bool(getattr(args, "send_now", False))
else AGENT_RUN_DELIVERY_STEER
)
if bool(getattr(args, "send_now", False)) and session_policy != "existing":
@@ -7277,7 +7281,7 @@ def cmd_agent_run(args):
"close_after": close_after,
},
}
- if bool(getattr(args, "send_now", False)) or delivery_intent != AGENT_RUN_DELIVERY_STEER:
+ if delivery_intent != AGENT_RUN_DELIVERY_STEER:
payload["delivery_intent"] = delivery_intent
payload["run"]["delivery_intent"] = delivery_intent
if fork_result:
@@ -17929,7 +17933,7 @@ def build_parser():
agent_run_delivery_group.add_argument(
"--send-now",
action="store_true",
- help="Explicitly deliver this Run as P1 to an existing Session (the default behavior)",
+ help="Steer this Run into the active Turn of an existing Session, even one serving a person's message",
)
agent_run_delivery_group.add_argument(
"--queue",