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.

feat(harness): send queued Agent Runs now (#1098)

Call White45a792b83903
diff --git a/core/inbox_events.py b/core/inbox_events.py
index c8128063a..fc21bcd0a 100644
--- a/core/inbox_events.py
+++ b/core/inbox_events.py
@@ -21,6 +21,7 @@ logger = logging.getLogger(__name__)
RUNS_UPDATED_EVENT = "runs.updated"
VAULTS_UPDATED_EVENT = "vaults.updated"
+QUEUE_UPDATED_EVENT = "queue.updated"
WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT = "workbench.events.bridge.status"
_CONTROLLER_PROCESS = False
diff --git a/core/internal_server.py b/core/internal_server.py
index 92c4c2aca..67f2ca5f6 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -31,6 +31,7 @@ import json
import logging
import os
import socket
+from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, TYPE_CHECKING
@@ -114,7 +115,13 @@ def create_app(controller: "Controller") -> FastAPI:
in_flight = manager.in_flight
app.state.in_flight_dispatches = in_flight
- async def _submit_scheduled_turn(session_id: str, context: MessageContext, text: str) -> str:
+ async def _submit_scheduled_turn(
+ session_id: str,
+ context: MessageContext,
+ text: str,
+ *,
+ delivery_intent: str = "queue",
+ ) -> Any:
"""Run a scheduled / watch turn through the SAME unified ``manager.submit``
the interactive Chat path uses, so a scheduled run can never preempt an
active Chat turn and gets the full turn lifecycle (in_flight + turn.start /
@@ -143,10 +150,23 @@ def create_app(controller: "Controller") -> FastAPI:
):
return "duplicate"
+ queue_owner_transferred = False
+ queue_transfer_cancelled = False
+
+ class _QueueTransferCancelled(RuntimeError):
+ pass
+
def _enqueue() -> bool:
+ nonlocal queue_owner_transferred, queue_transfer_cancelled
+
from core.message_mirror import _scope_id_for_session
from core.session_turns import SCHEDULED_PROVENANCE_KEY, capture_scheduled_provenance
from storage import messages_service
+ from storage.background import (
+ agent_run_cancellation_won_in_connection,
+ hold_running_agent_run_for_workbench_in_connection,
+ run_update_event_transaction,
+ )
# Persist the scheduled run's delivery / attribution provenance on the
# queued row's metadata so flush_queue re-runs it as SOURCE_SCHEDULED with
@@ -154,7 +174,7 @@ def create_app(controller: "Controller") -> FastAPI:
# attribution instead of degrading to a plain user turn (#84). The key's
# PRESENCE also marks this row as a scheduled segment for the flush.
engine = get_cached_sqlite_engine()
- with engine.begin() as conn:
+ with run_update_event_transaction(engine) as conn:
scope_id = _scope_id_for_session(conn, session_id)
try:
with conn.begin_nested():
@@ -170,8 +190,43 @@ def create_app(controller: "Controller") -> FastAPI:
metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},
native_message_id=native_message_id or None,
)
+ if delivery_intent == "send_now":
+ execution_id = str(
+ (context.platform_specific or {}).get(
+ "task_execution_id"
+ )
+ or ""
+ ).strip()
+ if not hold_running_agent_run_for_workbench_in_connection(
+ conn,
+ execution_id,
+ delivery_outcome={
+ "intent": "send_now",
+ "status": "admitted",
+ "target_was_busy": bool(
+ manager.in_flight.get(session_id)
+ ),
+ },
+ ):
+ if agent_run_cancellation_won_in_connection(
+ conn,
+ execution_id,
+ ):
+ raise _QueueTransferCancelled
+ raise RuntimeError(
+ "send-now Agent Run queue ownership transfer was refused"
+ )
+ queue_owner_transferred = True
+ except _QueueTransferCancelled:
+ queue_transfer_cancelled = True
+ return False
except IntegrityError:
logger.info("scheduled turn duplicate native id already queued: %s", native_message_id)
+ if delivery_intent == "send_now":
+ # A send-now attempt may not treat somebody else's
+ # duplicate row as its own admission; that would
+ # interrupt without transferring this Run.
+ return False
return bool(
native_message_id
and messages_service.native_message_exists(
@@ -188,10 +243,45 @@ def create_app(controller: "Controller") -> FastAPI:
text,
source=SOURCE_SCHEDULED,
enqueue=_enqueue,
+ delivery_intent=delivery_intent,
)
if submission.route == "enqueued" and submission.queue_persisted is not True:
- raise RuntimeError("scheduled turn queue row was not persisted")
- return submission.route
+ if queue_transfer_cancelled:
+ submission = replace(submission, delivery_status="canceled")
+ else:
+ raise RuntimeError("scheduled turn queue row was not persisted")
+ if delivery_intent == "send_now":
+ from storage.background import (
+ record_agent_run_delivery_outcome_in_connection,
+ run_update_event_transaction,
+ )
+
+ execution_id = str(
+ (context.platform_specific or {}).get("task_execution_id") or ""
+ ).strip()
+ outcome = {
+ "intent": "send_now",
+ "status": submission.delivery_status or submission.route,
+ "target_was_busy": submission.target_was_busy,
+ }
+ with run_update_event_transaction(get_cached_sqlite_engine()) as conn:
+ if not record_agent_run_delivery_outcome_in_connection(
+ conn,
+ execution_id,
+ outcome,
+ ):
+ raise RuntimeError(
+ "send-now Agent Run delivery outcome could not be recorded"
+ )
+ submission = replace(
+ submission,
+ queue_owner_transferred=queue_owner_transferred,
+ )
+ # Existing scheduled/task/watch callers consume only the route string.
+ # A direct Agent Run with send-now also needs the turn owner's exact
+ # interrupt outcome, so return the structured result only for that
+ # explicit contract and keep every legacy caller byte-compatible.
+ return submission if delivery_intent == "send_now" else submission.route
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
@@ -638,14 +728,23 @@ def create_app(controller: "Controller") -> FastAPI:
but they can reach this permission-restricted Unix socket and reuse the
same Controller -> UI-server -> browser SSE path.
"""
- from core.inbox_events import RUNS_UPDATED_EVENT, VAULTS_UPDATED_EVENT, bus
+ from core.inbox_events import (
+ QUEUE_UPDATED_EVENT,
+ RUNS_UPDATED_EVENT,
+ VAULTS_UPDATED_EVENT,
+ bus,
+ )
payload = await _safe_json(request)
if not isinstance(payload, dict):
return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_payload"})
event_type = str(payload.get("type") or "").strip()
data = payload.get("data")
- if event_type not in {RUNS_UPDATED_EVENT, VAULTS_UPDATED_EVENT}:
+ if event_type not in {
+ QUEUE_UPDATED_EVENT,
+ RUNS_UPDATED_EVENT,
+ VAULTS_UPDATED_EVENT,
+ }:
return JSONResponse(status_code=400, content={"ok": False, "error": "unsupported_event_type"})
if not isinstance(data, dict):
return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_event_data"})
@@ -687,10 +786,13 @@ def create_app(controller: "Controller") -> FastAPI:
@app.post("/internal/send-now/{session_id}")
async def _send_now(session_id: str) -> Any:
"""HTTP adapter: delegate "立即发送" (run the send-while-busy queue now) to
- the turn owner (FSM, Phase 1b); ``stop_failed`` -> 409."""
+ the turn owner (FSM, Phase 1b); typed failures remain HTTP failures."""
result = await manager.send_now(session_id)
- if result.get("code") == "stop_failed":
+ code = result.get("code")
+ if code == "stop_failed":
return JSONResponse(status_code=409, content=result)
+ if code == "flush_failed":
+ return JSONResponse(status_code=503, content=result)
return result
# Expose the per-session turn gate to in-process callers (the scheduler)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index f7ac29f26..3e9670dbf 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -65,6 +65,14 @@ from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
+AGENT_RUN_DELIVERY_QUEUE = "queue"
+AGENT_RUN_DELIVERY_SEND_NOW = "send_now"
+AGENT_RUN_DELIVERY_INTENTS = frozenset(
+ {AGENT_RUN_DELIVERY_QUEUE, AGENT_RUN_DELIVERY_SEND_NOW}
+)
+AGENT_RUN_DELIVERY_INTENT_METADATA_KEY = "delivery_intent"
+AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY = "delivery_outcome"
+
class _ScopeAgentTarget(NamedTuple):
agent_name: Optional[str]
@@ -83,6 +91,15 @@ def _json_loads(value: str | None, default: Any) -> Any:
return default
+def normalize_agent_run_delivery_intent(value: Any) -> str:
+ """Return the durable Agent Run delivery intent or reject an unknown value."""
+
+ normalized = str(value or AGENT_RUN_DELIVERY_QUEUE).strip().lower()
+ if normalized not in AGENT_RUN_DELIVERY_INTENTS:
+ raise ValueError(f"unsupported Agent Run delivery intent: {normalized}")
+ return normalized
+
+
def _path_signature(path: Path) -> Optional[tuple[int, int, int]]:
try:
stat = path.stat()
@@ -242,11 +259,13 @@ class AgentRunExecutionResult:
error: Optional[str]
complete_on_return: bool
requeue_on_return: bool = False
+ recover_queue_on_return: bool = False
coalesced_completion_ids: tuple[str, ...] = ()
# The run's terminal row was already written by the executor itself (through a
# guarded writer), so the caller must skip ``complete()`` but still run the
# post-completion side effects: callback delivery and session-queue recovery.
settled_out_of_band: bool = False
+ delivery_outcome: Optional[dict[str, Any]] = None
#: Durable definition-metadata key recording the last binding recovery, so a
@@ -1438,6 +1457,7 @@ class TaskExecutionStore:
parent_run_id: Optional[str] = None,
callback_session_id: Optional[str] = None,
callback_active: bool = True,
+ delivery_intent: str = AGENT_RUN_DELIVERY_QUEUE,
metadata: Optional[dict[str, Any]] = None,
) -> TaskExecutionRequest:
if not (message or "").strip():
@@ -1446,6 +1466,9 @@ class TaskExecutionStore:
# by a terminal result. Every caller (CLI, callback, delivery) has a
# 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)
+ run_metadata = dict(metadata or {})
+ run_metadata[AGENT_RUN_DELIVERY_INTENT_METADATA_KEY] = normalized_delivery_intent
return self.enqueue(
TaskExecutionRequest(
id=uuid4().hex[:12],
@@ -1467,7 +1490,7 @@ class TaskExecutionStore:
model=model,
reasoning_effort=reasoning_effort,
session_policy=session_policy,
- metadata=dict(metadata or {}),
+ metadata=run_metadata,
)
)
@@ -3139,6 +3162,7 @@ class ScheduledTaskService:
error: Optional[str] = None
should_complete = True
settled_out_of_band = False
+ recover_queue_on_return = False
coalesced_completion_ids: list[str] = _live_coalesced_agent_run_ids(request) or []
task_id = request.task_id
session_key = request.session_key
@@ -3213,8 +3237,16 @@ class ScheduledTaskService:
error = result.error
should_complete = result.complete_on_return
settled_out_of_band = result.settled_out_of_band
+ recover_queue_on_return = result.recover_queue_on_return
if result.requeue_on_return:
- self.request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
+ requeue_metadata: dict[str, Any] = {
+ "workbench_queue_holds_run": True,
+ }
+ if result.delivery_outcome is not None:
+ requeue_metadata[
+ AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY
+ ] = result.delivery_outcome
+ self.request_store.requeue(request.id, metadata=requeue_metadata)
coalesced_completion_ids = list(result.coalesced_completion_ids)
else:
raise ValueError(f"unknown task request type: {request.request_type}")
@@ -3247,24 +3279,31 @@ class ScheduledTaskService:
)
if should_complete or settled_out_of_band:
# An out-of-band settlement still made this run terminal, so it owes
- # the same follow-through as ``complete()``: deliver the callback and
- # let the next queued turn for this session start.
+ # the same callback follow-through as ``complete()``.
await self._drain_callbacks()
- if request.request_type == "agent_run" and session_id:
- manager = getattr(self.controller, "session_turns", None)
- recover_queue = getattr(
- manager,
- "recover_persisted_agent_run_queue",
- None,
- )
- if callable(recover_queue):
- try:
- await recover_queue(session_id)
- except Exception:
- logger.exception(
- "Failed to recover persisted Agent Run queue for session=%s",
- session_id,
- )
+ if (
+ request.request_type == "agent_run"
+ and session_id
+ and (
+ should_complete
+ or settled_out_of_band
+ or recover_queue_on_return
+ )
+ ):
+ manager = getattr(self.controller, "session_turns", None)
+ recover_queue = getattr(
+ manager,
+ "recover_persisted_agent_run_queue",
+ None,
+ )
+ if callable(recover_queue):
+ try:
+ await recover_queue(session_id)
+ except Exception:
+ logger.exception(
+ "Failed to recover persisted Agent Run queue for session=%s",
+ session_id,
+ )
async def _execute_task(
self,
@@ -3398,6 +3437,7 @@ class ScheduledTaskService:
``docs/plans/agent-run-zombie-settlement.md``.
"""
from core.services.dispatch import SOURCE_SCHEDULED, dispatch_turn_with_outcome
+ from core.session_turns import TurnSubmissionResult
target_info = resolve_session_id_target(session_id) if session_id else None
target = target_info.session_key if target_info else parse_session_key(session_key or "")
@@ -3418,6 +3458,37 @@ class ScheduledTaskService:
)
gate = getattr(self.controller, "session_turn_gate", None)
+ 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,
+ )
+ return AgentRunExecutionResult(
+ error=(
+ "send-now requires a live Web/Workbench Agent Session; "
+ f"target platform is '{target_label}'"
+ ),
+ complete_on_return=True,
+ delivery_outcome=delivery_outcome,
+ )
if target.platform == "avibe" and session_id and gate is not None:
stale_queue_rows = _retire_stale_agent_run_queue_rows(
session_id=session_id,
@@ -3437,10 +3508,56 @@ class ScheduledTaskService:
bus.publish("queue.updated", {"session_id": session_id})
except Exception:
logger.debug("agent_run recovery: queue.updated publish failed", exc_info=True)
- state = await gate.submit_scheduled(session_id, context, message)
- if state == "enqueued":
- return AgentRunExecutionResult(error=None, complete_on_return=False, requeue_on_return=True)
- if state == "duplicate":
+ if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW:
+ state = await gate.submit_scheduled(
+ session_id,
+ context,
+ message,
+ delivery_intent=delivery_intent,
+ )
+ else:
+ state = await gate.submit_scheduled(session_id, context, message)
+ route = state.route if isinstance(state, TurnSubmissionResult) else state
+ delivery_outcome = None
+ if isinstance(state, TurnSubmissionResult):
+ delivery_outcome = {
+ "intent": delivery_intent,
+ "status": state.delivery_status or state.route,
+ "target_was_busy": state.target_was_busy,
+ }
+ if (
+ delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW
+ and isinstance(state, TurnSubmissionResult)
+ and state.delivery_status == "canceled"
+ ):
+ self.request_store.settle_without_result(
+ execution_id,
+ terminal_status="canceled",
+ metadata={
+ AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY: delivery_outcome,
+ },
+ )
+ return AgentRunExecutionResult(
+ error=None,
+ complete_on_return=False,
+ settled_out_of_band=True,
+ delivery_outcome=delivery_outcome,
+ )
+ if route == "enqueued":
+ return AgentRunExecutionResult(
+ error=None,
+ complete_on_return=False,
+ requeue_on_return=not (
+ isinstance(state, TurnSubmissionResult)
+ and state.queue_owner_transferred
+ ),
+ recover_queue_on_return=bool(
+ isinstance(state, TurnSubmissionResult)
+ and state.delivery_status == "flush_failed"
+ ),
+ delivery_outcome=delivery_outcome,
+ )
+ if route == "duplicate":
live_ids = _live_coalesced_agent_run_ids(
TaskExecutionRequest(
id=execution_id,
@@ -3453,7 +3570,11 @@ class ScheduledTaskService:
complete_on_return=True,
coalesced_completion_ids=tuple(live_ids or [execution_id]),
)
- return AgentRunExecutionResult(error=None, complete_on_return=False)
+ return AgentRunExecutionResult(
+ error=None,
+ complete_on_return=False,
+ delivery_outcome=delivery_outcome,
+ )
async def _noop_chunk(_envelope: dict) -> None:
return None
diff --git a/core/session_turns.py b/core/session_turns.py
index f80ad3628..7539c2bea 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -726,14 +726,21 @@ class Turn:
#: Stop (Codex P1). It rides on the Turn for the same reason the flush intents
#: do: it retires when the turn is popped, with no parallel set to leak.
cancel_settled_by: Optional[str] = None
+ #: One shared backend Stop attempt for concurrent send-now callers. Each
+ #: caller already owns its own durable queue row; they must not interrupt the
+ #: same active turn more than once.
+ send_now_task: Optional[asyncio.Task[dict[str, Any]]] = None
@dataclass(frozen=True)
class TurnSubmissionResult:
- """Routing decision plus the enqueue callback's durable-write result."""
+ """Routing decision plus the durable queue / delivery-intent outcome."""
route: Literal["ran", "enqueued"]
queue_persisted: bool | None = None
+ target_was_busy: bool = False
+ delivery_status: str | None = None
+ queue_owner_transferred: bool = False
class SessionTurnManager:
@@ -970,6 +977,7 @@ class SessionTurnManager:
*,
source: str = SOURCE_HUMAN,
enqueue: Optional[Callable[[], bool]] = None,
+ delivery_intent: Literal["queue", "send_now"] = "queue",
) -> TurnSubmissionResult:
"""Unified turn entry for BOTH Chat and the scheduler: idle → run now; busy
(or a pre-existing send-while-busy queue) → enqueue and run later.
@@ -986,17 +994,31 @@ class SessionTurnManager:
session archival; callers must use ``queue_persisted`` (and any domain-owned
post-submit observation) rather than infer durability from ``route``.
"""
+ if delivery_intent not in {"queue", "send_now"}:
+ raise ValueError(f"unsupported delivery intent: {delivery_intent}")
if not (isinstance(session_id, str) and session_id):
# No session key (CLI-style) — just run; nothing to queue against.
await self._run(None, context, text, source=source)
- return TurnSubmissionResult(route="ran")
+ return TurnSubmissionResult(
+ route="ran",
+ delivery_status="ran" if delivery_intent == "send_now" else None,
+ )
backend = self._context_backend(context)
entry = self.in_flight.get(session_id)
busy = entry is not None and not entry.task.done()
# Enqueue when a turn is running OR a prior Stop left queued rows behind — the
# new message must run AFTER them, not jump ahead (Codex P2).
- if backend in self._draining_backends:
+ if delivery_intent == "send_now":
+ # Send-now always enters through the durable queue, even if the
+ # Session became idle before admission. Busy and idle delivery then
+ # share the same FIFO, provenance, and restart contract.
+ should_enqueue = True
+ if backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ session_id
+ )
+ elif backend in self._draining_backends:
should_enqueue = True
self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
elif busy:
@@ -1006,6 +1028,20 @@ class SessionTurnManager:
should_enqueue = bool(messages_service.list_queued(conn, session_id))
if should_enqueue:
queue_persisted = bool(enqueue()) if enqueue is not None else False
+ delivery_status = None
+ if queue_persisted and delivery_intent == "send_now":
+ if backend in self._draining_backends and not busy:
+ # The row is durable, but a backend cutover deliberately owns
+ # when the next turn may start. Report the deferral instead of
+ # mislabelling the still-present queue as empty.
+ delivery_status = "deferred"
+ else:
+ delivery_result = await self.send_now(session_id)
+ delivery_status = str(
+ delivery_result.get("status")
+ or delivery_result.get("code")
+ or "failed"
+ )
if queue_persisted and (busy or backend in self._draining_backends):
# The row joins the active turn's queue and stays until it drains —
# surface the queue growth NOW so the UI reflects it immediately
@@ -1014,7 +1050,11 @@ class SessionTurnManager:
from core.inbox_events import bus
bus.publish("queue.updated", {"session_id": session_id})
- elif not busy and backend not in self._draining_backends:
+ elif (
+ delivery_intent != "send_now"
+ and not busy
+ and backend not in self._draining_backends
+ ):
# Idle + pre-existing queue → no running turn to flush behind, so
# drain the durable queue now, in order. If this callback lost an
# archival race, only pre-existing rows remain. flush_queue publishes
@@ -1023,9 +1063,15 @@ class SessionTurnManager:
return TurnSubmissionResult(
route="enqueued",
queue_persisted=queue_persisted,
+ target_was_busy=busy,
+ delivery_status=delivery_status,
)
await self._run(session_id, context, text, source=source)
- return TurnSubmissionResult(route="ran")
+ return TurnSubmissionResult(
+ route="ran",
+ target_was_busy=busy,
+ delivery_status="ran" if delivery_intent == "send_now" else None,
+ )
async def _run(
self,
@@ -1794,14 +1840,53 @@ class SessionTurnManager:
turn.task.cancel()
return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
+ @staticmethod
+ def _clear_send_now_task(
+ turn: Turn,
+ task: asyncio.Task[dict[str, Any]],
+ ) -> None:
+ if turn.send_now_task is task:
+ turn.send_now_task = None
+
+ async def _interrupt_for_send_now(self, session_id: str, turn: Turn) -> dict:
+ """Own one backend Stop attempt shared by concurrent send-now callers."""
+
+ turn.flush_on_cancel = True
+ if turn.context.platform_specific is None:
+ turn.context.platform_specific = {}
+ turn.context.platform_specific["suppress_stop_no_active_notice"] = True
+ stopped = False
+ try:
+ stopped = bool(
+ await self.controller.command_handler.handle_stop(turn.context)
+ )
+ except Exception:
+ logger.exception(
+ "internal send-now: backend stop failed for session=%s",
+ session_id,
+ )
+ if not stopped:
+ turn.flush_on_cancel = False
+ return {
+ "ok": False,
+ "code": "stop_failed",
+ "session_id": session_id,
+ }
+ turn.task.cancel()
+ return {
+ "ok": True,
+ "session_id": session_id,
+ "status": "interrupted",
+ }
+
async def send_now(self, session_id: str) -> dict:
"""Run the session's send-while-busy queue immediately ("立即发送").
If a turn is running (and something is queued), interrupt it (the user chose
to cut in) and opt into ``flush_on_cancel`` so the queue runs as that turn
unwinds. If nothing is running, flush directly as a fresh turn. No-op when
- the queue is empty. Returns a result dict (``code='stop_failed'`` → 409 for
- the HTTP adapter).
+ the queue is empty. A refused Stop or idle flush returns a typed failure for
+ the HTTP/CLI caller while leaving the durable queue retryable.
"""
turn = self.in_flight.get(session_id)
if turn is not None and not turn.task.done():
@@ -1812,27 +1897,58 @@ class SessionTurnManager:
has_queue = bool(messages_service.list_queued(conn, session_id))
if not has_queue:
return {"ok": True, "session_id": session_id, "status": "empty"}
- # Record the flush intent BEFORE awaiting the interrupt (same race as
- # cancel, opposite intent: send-now WANTS the queue to run). Drop it on a
- # refused stop and leave the turn + queue untouched (Codex P2).
- turn.flush_on_cancel = True
- if turn.context.platform_specific is None:
- turn.context.platform_specific = {}
- turn.context.platform_specific["suppress_stop_no_active_notice"] = True
- stopped = False
+ # Concurrent send-now callers share one Stop attempt and therefore one
+ # truthful result. Shield the transition because caller cancellation
+ # cannot undo an already-admitted durable queue row.
+ send_now_task = turn.send_now_task
+ if send_now_task is None:
+ send_now_task = asyncio.create_task(
+ self._interrupt_for_send_now(session_id, turn),
+ name=f"send-now:{session_id}",
+ )
+ turn.send_now_task = send_now_task
try:
- stopped = bool(await self.controller.command_handler.handle_stop(turn.context))
- except Exception:
- logger.exception("internal send-now: backend stop failed for session=%s", session_id)
- if not stopped:
- turn.flush_on_cancel = False
- return {"ok": False, "code": "stop_failed", "session_id": session_id}
- turn.task.cancel()
- return {"ok": True, "session_id": session_id, "status": "interrupted"}
+ result = await asyncio.shield(send_now_task)
+ finally:
+ if (
+ send_now_task.done()
+ and not bool(send_now_task.result().get("ok"))
+ ):
+ # Existing waiters are already queued to resume. Clearing on
+ # the next loop tick lets a later explicit refusal retry make
+ # a new Stop attempt without duplicating this one. A successful
+ # Stop stays attached until the Turn is popped, so no caller
+ # can interrupt the same unwinding Turn twice.
+ asyncio.get_running_loop().call_soon(
+ self._clear_send_now_task,
+ turn,
+ send_now_task,
+ )
+ return dict(result)
# No running turn — flush the queue directly as a new turn (rebuilds routing
- # from the current session row internally). ``empty`` when nothing flushed.
+ # from the current session row internally). A false flush is only ``empty``
+ # when the queue is now actually empty; context/claim/dispatch failures keep
+ # their durable rows and must enter the caller's queue-recovery path.
flushed = await self.flush_queue(session_id)
- return {"ok": True, "session_id": session_id, "status": "flushed" if flushed else "empty"}
+ if flushed:
+ return {"ok": True, "session_id": session_id, "status": "flushed"}
+ try:
+ with self._sqlite_engine().connect() as conn:
+ queue_remains = bool(messages_service.list_queued(conn, session_id))
+ except Exception:
+ logger.exception(
+ "send-now: failed to verify queue after a refused flush for session=%s",
+ session_id,
+ )
+ queue_remains = True
+ return {
+ "session_id": session_id,
+ **(
+ {"ok": False, "code": "flush_failed"}
+ if queue_remains
+ else {"ok": True, "status": "empty"}
+ ),
+ }
# --- shared turn chokepoints (status + Show checkpoint projection) ------------
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index fb9c6cf00..836b2e063 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -280,6 +280,9 @@ Useful Harness queries include schema discovery, current session lookup, existin
| External signal trigger | `vibe watch add` |
| Independent Agent delegation | `vibe agent run --agent <agent-name>` |
| 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>` |
| 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 |
@@ -294,6 +297,10 @@ 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 queues behind an active turn by default. When coordinating another Workbench Session, decide whether its current work should finish or be preempted 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 ...` to persist a new Run and then dispatch the Session's FIFO queue head. If older work is already queued, that older head runs first and the new message does not leapfrog it. Use `vibe session send-now <id>` to dispatch an already-queued head without adding another message. Both forms require a Web/Workbench Session, interrupt through the shared Stop path, and start the queue head as a new turn; they do not steer the same native turn. If interruption is refused, the active turn and durable queue remain intact.
+
+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.
+
Use `vibe session update --visible|--hidden` (`--visibility foreground|background`) to promote or hide a persisted Session independently of its scope. Use `--scope-id <scopes.id>` to move it to another scope or `--scope-id none` to make it standalone; moving scope never changes its stored workdir.
For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--message "..."` or `--message-file <path>` as the follow-up instruction template sent with waiter output. Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement.
@@ -313,7 +320,7 @@ Rules:
- `--fork-self` creates a new Agent Session from this current Session's native backend context; use it for alternate paths that need the current context but should not mutate this Session.
- `--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context.
- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --message ...`.
-- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only when the user intends to continue that same existing Session. Async callbacks return to this conversation by default.
+- Use `vibe agent run --agent <agent-name> --session-id ... --message ...` only when the work should continue that same existing Session. Async callbacks return to this conversation by default.
- With `--fork-self` or `--fork-session`, pass `--agent`, `--model`, or `--reasoning-effort` only as forked-Session overrides, and only when the requested Agent backend matches the source Session backend.
- `--sync` changes waiting behavior, not session identity: default async runs in the background and return through callbacks; synchronous runs wait for the result and are still recorded in `vibe runs`.
- Create or update Agents only when it captures a reusable role, reduces repeated prompting, or makes a long-running Harness more reliable.
diff --git a/docs/CLI.md b/docs/CLI.md
index 5aebe80d0..dea0e1d4c 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -257,11 +257,23 @@ 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 --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` is valid only with an existing `--session-id`. Avibe first
+persists the Agent Run in that Session's queue, then applies the same operation
+as Workbench's **Send now** control: interrupt the active turn through the
+shared Stop path and dispatch the FIFO queue head as a new turn. It does not
+inject input into the same backend-native turn or move the new message ahead of
+older queued work. If interruption is refused, the active turn keeps running
+and the Agent Run remains queued. The accepted command payload names the
+`delivery_intent`; `vibe runs show <run-id>` exposes the durable
+`metadata.delivery_outcome` (`interrupted`, `flushed`, `deferred`, or
+`stop_failed`) after the controller consumes it.
+
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
Session keeps the source backend. `--agent`, `--model`, and
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 2695a4435..260a9a9b7 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -238,11 +238,21 @@ session creation 参数和 delivery 参数仍然优先。
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 --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`)。
+
当一个新 Agent Session 需要从现有 Session 的 native backend 上下文分叉,而不是空白开始时,
使用 `--fork-session <session-id>`。新 Session 会保持源 Session 的 backend。
只有 backend 不变时,才可以通过 `--agent`、`--model`、`--reasoning-effort`
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 6d0cb5eb1..ec1714722 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -726,6 +726,7 @@ Important options:
- `--name`
- `--session-id`
+- `--send-now`
- `--create-session`
- `--create-session-per-run`
- `--agent`
@@ -872,6 +873,14 @@ with `run_id` / `session_id`, and uses the callback policy to deliver the final
result later. Use `--sync` only when the terminal should wait for completion.
`--async` is still accepted for older scripts but is no longer required.
+With an existing `--session-id`, `--send-now` first persists the Agent Run and
+then reuses Workbench's Session-level interrupt-and-flush transition. It stops
+the active turn through the shared Stop path and dispatches the existing FIFO
+queue head as a new turn. It does not provide same-turn steering or queue
+reordering; a refused interrupt leaves the Run queued. The command response
+includes `delivery_intent`, and `vibe runs show <run-id>` exposes the durable
+`metadata.delivery_outcome` after the controller consumes the request.
+
`--fork-session <session_id>` creates a new Agent Session by forking the source
Session's native backend context. It is for alternate investigations or
delegated work that should keep the source context without mutating the source
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index 97c5fa982..16e3637c9 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -704,6 +704,7 @@ vibe task add (--session-id <session_id> | --create-session | --create-session-p
- `--name`
- `--session-id`
+- `--send-now`
- `--create-session`
- `--create-session-per-run`
- `--agent`
@@ -845,6 +846,13 @@ Run 默认异步:命令会队列化 run,立即返回包含 `run_id` / `sessi
payload,并按 callback 策略稍后投递最终结果。只有终端需要等待完成时才使用
`--sync`。`--async` 仍兼容旧脚本,但不再需要显式传入。
+和现有 `--session-id` 一起使用时,`--send-now` 会先持久化 Agent Run,
+然后复用 Workbench 的 Session 级打断并发送操作:通过共享 Stop 路径停止活动
+Turn,再把现有 FIFO 队头作为新 Turn 发送。它不提供同 Turn steering,也不重排
+队列;如果打断被拒绝,Run 会继续保持排队。命令响应包含
+`delivery_intent`,Controller 消费请求后,`vibe runs show <run-id>` 会显示持久化的
+`metadata.delivery_outcome`。
+
`--fork-session <session_id>` 会基于源 Session 的 native backend 上下文创建一个新的
Agent Session,适合在保留上下文的同时做分支调查或委派工作,而不修改源 Session。
fork 会保持源 Session 的 backend;只有 backend 不变时,`--agent`、`--model`
diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.md
index dc257463d..7bf450b3e 100644
--- a/skills/use-avibe/SKILL.md
+++ b/skills/use-avibe/SKILL.md
@@ -776,6 +776,10 @@ 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>'`
+- 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 '...'`
- fork another explicit Session for an alternate path: `vibe agent run --fork-session '<source-session-id>' --message '...'`
- recurring task for this conversation: `vibe task add --cron '<expr>' --message '...'`
@@ -793,6 +797,11 @@ Targeting and callbacks:
- In an Avibe-injected Agent shell, commands that operate on this conversation default to the current Agent Session. Omit the target when the work should continue here.
- 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.
+- 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.
- Async Agent runs return the final result to this conversation by default. Pass `--no-callback` only when you will inspect the run later with `vibe runs`. Pass `--callback-session-id <id>` only when the final result should return to a different Session.
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 506d88da9..6a5427451 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -776,6 +776,10 @@ 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>'`
+- 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 '...'`
- fork another explicit Session for an alternate path: `vibe agent run --fork-session '<source-session-id>' --message '...'`
- recurring task for this conversation: `vibe task add --cron '<expr>' --message '...'`
@@ -793,6 +797,11 @@ Targeting and callbacks:
- In an Avibe-injected Agent shell, commands that operate on this conversation default to the current Agent Session. Omit the target when the work should continue here.
- 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.
+- 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.
- Async Agent runs return the final result to this conversation by default. Pass `--no-callback` only when you will inspect the run later with `vibe runs`. Pass `--callback-session-id <id>` only when the final result should return to a different Session.
diff --git a/storage/background.py b/storage/background.py
index 373862ea2..add7a19b5 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -14,7 +14,11 @@ from apscheduler.triggers.date import DateTrigger
from sqlalchemy import and_, case, func, insert, or_, select, update
from config import paths
-from storage.agent_session_rows import session_openable_in_chat, unchanged_text
+from storage.agent_session_rows import (
+ reserve_write_lock,
+ session_openable_in_chat,
+ unchanged_text,
+)
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.migrations import (
background_tables_ready,
@@ -726,6 +730,45 @@ def _publish_run_rows_updated(rows: list[Any]) -> None:
logger.debug("failed to publish runs.updated for %s", run_id, exc_info=True)
+def _publish_queue_updated(session_id: str) -> None:
+ normalized_session_id = str(session_id or "").strip()
+ if not normalized_session_id:
+ return
+ try:
+ from core.inbox_events import (
+ QUEUE_UPDATED_EVENT,
+ bus,
+ is_controller_process,
+ )
+ except Exception:
+ logger.debug("failed to import queue event publisher", exc_info=True)
+ return
+ payload = {"session_id": normalized_session_id}
+ try:
+ bus.publish(QUEUE_UPDATED_EVENT, payload)
+ if bus.subscriber_count() == 0 and not is_controller_process():
+ try:
+ from vibe import internal_client
+
+ internal_client.publish_event_sync(
+ QUEUE_UPDATED_EVENT,
+ payload,
+ timeout=1.5,
+ )
+ except Exception:
+ logger.debug(
+ "failed to bridge queue.updated for %s",
+ normalized_session_id,
+ exc_info=True,
+ )
+ except Exception:
+ logger.debug(
+ "failed to publish queue.updated for %s",
+ normalized_session_id,
+ exc_info=True,
+ )
+
+
def _defer_run_rows_updated_from_connection(conn: Any, rows: list[Any]) -> None:
if not rows:
return
@@ -929,6 +972,160 @@ def claim_queued_runs_for_workbench_in_connection(
return normalized_run_ids
+def hold_running_agent_run_for_workbench_in_connection(
+ conn: Any,
+ run_id: str,
+ *,
+ delivery_outcome: Optional[dict[str, Any]] = None,
+) -> bool:
+ """Transfer a claimed Agent Run to the durable Workbench queue.
+
+ The caller persists the matching queued message in the same write
+ transaction. The queue row therefore cannot become flushable while the
+ scheduler still owns the Run as ``running``.
+ """
+
+ normalized_run_id = str(run_id or "").strip()
+ if not normalized_run_id:
+ return False
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return False
+ metadata = _json_loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict):
+ metadata = {}
+ metadata["workbench_queue_holds_run"] = True
+ if delivery_outcome is not None:
+ metadata["delivery_outcome"] = dict(delivery_outcome)
+ now = _utc_now_iso()
+ result = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .where(agent_runs.c.status.in_(_status_query_values("running")))
+ .where(agent_runs.c.cancel_requested == 0)
+ .values(
+ status="queued",
+ started_at=None,
+ updated_at=now,
+ metadata_json=_json_dumps(metadata),
+ )
+ )
+ if not result.rowcount:
+ return False
+ _defer_run_ids_updated_from_connection(conn, [normalized_run_id])
+ return True
+
+
+def agent_run_cancellation_won_in_connection(conn: Any, run_id: str) -> bool:
+ """Whether cancellation already owns a refused queue handoff."""
+
+ normalized_run_id = str(run_id or "").strip()
+ if not normalized_run_id:
+ return False
+ row = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.cancel_requested)
+ .where(agent_runs.c.id == normalized_run_id)
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return False
+ return bool(row["cancel_requested"]) or normalize_run_status(
+ row["status"]
+ ) == "canceled"
+
+
+def cancel_workbench_queued_agent_run_in_connection(
+ conn: Any,
+ run_id: str,
+ *,
+ session_id: str,
+) -> bool:
+ """Cancel a Run only while the named Workbench queue still owns it.
+
+ Queue-row deletion and this transition share the caller's transaction. A
+ concurrent claim/settlement therefore either wins before this guard (and the
+ row is not removed) or loses after both cancellation and deletion commit.
+ Missing Run rows are stale queue input and may be removed.
+ """
+
+ normalized_run_id = str(run_id or "").strip()
+ normalized_session_id = str(session_id or "").strip()
+ if not normalized_run_id or not normalized_session_id:
+ return False
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return True
+ metadata = _json_loads(row["metadata_json"], {})
+ if (
+ normalize_run_status(row["status"]) != "queued"
+ or str(row["session_id"] or "").strip() != normalized_session_id
+ or not isinstance(metadata, dict)
+ or metadata.get("workbench_queue_holds_run") is not True
+ ):
+ return False
+ now = _utc_now_iso()
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .where(agent_runs.c.session_id == normalized_session_id)
+ .where(agent_runs.c.status.in_(_status_query_values("queued")))
+ .where(agent_runs.c.metadata_json == row["metadata_json"])
+ .values(
+ status="canceled",
+ cancel_requested=1,
+ cancel_requested_at=now,
+ completed_at=now,
+ updated_at=now,
+ )
+ )
+ if not transition.rowcount:
+ return False
+ updated = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .limit(1)
+ ).mappings().one()
+ _defer_run_rows_updated_from_connection(conn, [updated])
+ return True
+
+
+def record_agent_run_delivery_outcome_in_connection(
+ conn: Any,
+ run_id: str,
+ outcome: dict[str, Any],
+) -> bool:
+ """Merge the observed delivery transition without changing Run ownership."""
+
+ normalized_run_id = str(run_id or "").strip()
+ if not normalized_run_id:
+ return False
+ result = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == normalized_run_id)
+ .where(func.json_valid(agent_runs.c.metadata_json) == 1)
+ .values(
+ updated_at=_utc_now_iso(),
+ metadata_json=func.json_set(
+ agent_runs.c.metadata_json,
+ "$.delivery_outcome",
+ func.json(_json_dumps(dict(outcome))),
+ ),
+ )
+ )
+ if not result.rowcount:
+ return False
+ _defer_run_ids_updated_from_connection(conn, [normalized_run_id])
+ return True
+
+
def _refresh_recovered_coalesced_workbench_runs_in_connection(conn: Any, *, now: str) -> None:
rows = list(
conn.execute(
@@ -1852,11 +2049,21 @@ class SQLiteBackgroundTaskStore:
def cancel_run(self, run_id: str, *, requested_at: Optional[str] = None) -> bool:
now = requested_at or _utc_now_iso()
row_to_publish = None
+ queue_session_id = ""
with self.engine.begin() as conn:
- row = conn.execute(select(agent_runs.c.status).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
+ # Cancellation and Workbench queue retirement are one ownership
+ # transition. Reserve the writer before reading so a concurrent
+ # claim cannot move the Run between the decision and its row delete.
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().first()
if not row:
return False
status = normalize_run_status(row["status"])
+ metadata = _json_loads(row["metadata_json"], {})
values: dict[str, Any] = {
"cancel_requested": 1,
"cancel_requested_at": now,
@@ -1874,7 +2081,22 @@ class SQLiteBackgroundTaskStore:
row_to_publish = dict(
conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
)
+ if (
+ status == "queued"
+ and isinstance(metadata, dict)
+ and metadata.get("workbench_queue_holds_run") is True
+ ):
+ from storage import messages_service
+
+ session_id = str(row["session_id"] or "").strip()
+ if messages_service.delete_queued_agent_run(
+ conn,
+ session_id=session_id,
+ run_id=run_id,
+ ):
+ queue_session_id = session_id
_publish_run_rows_updated([row_to_publish])
+ _publish_queue_updated(queue_session_id)
return row_to_publish is not None
def claim_pending_run(self, run_id: str, *, started_at: str) -> Optional[dict[str, Any]]:
diff --git a/storage/messages_service.py b/storage/messages_service.py
index c4d8462c9..d052bb1c3 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -28,6 +28,7 @@ from storage.models import (
scope_settings,
scopes,
)
+from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES
from vibe.message_types import types_with, types_without
@@ -83,6 +84,34 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
_AGENT_RUN_NATIVE_PREFIX = "agent_run:"
+_SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
+
+
+def _queued_agent_run_id(row: dict[str, Any]) -> str:
+ native_message_id = str(row.get("native_message_id") or "").strip()
+ if native_message_id.startswith(_AGENT_RUN_NATIVE_PREFIX):
+ return native_message_id[len(_AGENT_RUN_NATIVE_PREFIX):]
+ try:
+ metadata = json.loads(row.get("metadata_json") or "{}")
+ except (TypeError, json.JSONDecodeError):
+ return ""
+ provenance = (
+ metadata.get(_SCHEDULED_PROVENANCE_KEY)
+ if isinstance(metadata, dict)
+ else None
+ )
+ platform_specific = (
+ provenance.get("platform_specific")
+ if isinstance(provenance, dict)
+ else None
+ )
+ if (
+ not isinstance(platform_specific, dict)
+ or str(platform_specific.get("task_trigger_kind") or "").strip()
+ != "agent_run"
+ ):
+ return ""
+ return str(platform_specific.get("task_execution_id") or "").strip()
def _attach_agent_run_provenance(
@@ -754,17 +783,41 @@ def enqueue_queued(
)
-def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
- """Pending queued messages for a session, oldest first."""
- query = (
+def _queued_query(session_id: str):
+ return (
select(messages)
.where(messages.c.session_id == session_id)
.where(messages.c.type == QUEUED_TYPE)
.order_by(messages.c.created_at.asc(), messages.c.id.asc())
)
+
+
+def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
+ """Pending queued messages for a session, oldest first."""
+ query = _queued_query(session_id)
return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+def list_queued_page(
+ conn: Connection,
+ session_id: str,
+ *,
+ page_request: PageRequest,
+) -> PageResult[dict[str, Any]]:
+ """One bounded FIFO page for Agent-facing Session queue inspection."""
+
+ query = (
+ _queued_query(session_id)
+ .limit(page_request.limit + 1)
+ .offset(page_request.offset)
+ )
+ rows = [
+ _row_to_payload(dict(row))
+ for row in conn.execute(query).mappings().all()
+ ]
+ return page_result_from_limit_plus_one(rows, page_request)
+
+
def list_recoverable_pending(conn: Connection) -> list[dict[str, Any]]:
"""Every pending input reservation considered by startup cleanup.
@@ -835,6 +888,45 @@ def delete_queued(conn: Connection, ids: list[str]) -> None:
conn.execute(delete(messages).where(messages.c.id.in_(ids)))
+def delete_queued_agent_run(
+ conn: Connection,
+ *,
+ session_id: str,
+ run_id: str,
+) -> int:
+ """Retire the exact queued row owned by a canceled Workbench Agent Run."""
+
+ normalized_session_id = str(session_id or "").strip()
+ normalized_run_id = str(run_id or "").strip()
+ if not normalized_session_id or not normalized_run_id:
+ return 0
+ rows = list(
+ conn.execute(
+ select(
+ messages.c.id,
+ messages.c.native_message_id,
+ messages.c.metadata_json,
+ )
+ .where(messages.c.session_id == normalized_session_id)
+ .where(messages.c.type == QUEUED_TYPE)
+ ).mappings()
+ )
+ row_ids = [
+ str(row["id"])
+ for row in rows
+ if _queued_agent_run_id(dict(row)) == normalized_run_id
+ ]
+ if not row_ids:
+ return 0
+ result = conn.execute(
+ delete(messages)
+ .where(messages.c.id.in_(row_ids))
+ .where(messages.c.session_id == normalized_session_id)
+ .where(messages.c.type == QUEUED_TYPE)
+ )
+ return result.rowcount or 0
+
+
def clear_queued(conn: Connection, session_id: str) -> int:
"""Drop ALL send-while-busy queued rows for a session. Used by archive so no
queued prompt can later be flushed into a now-terminal session (on natural
@@ -911,14 +1003,44 @@ def pending_message_target_type(
def remove_queued(conn: Connection, session_id: str, message_id: str) -> bool:
- """Delete one queued message, scoped to its session so a stale / cross-session
- id can't drop another chat's queued row. Returns True if a row was removed."""
+ """Delete one queued message and cancel any Agent Run it durably owns.
+
+ The Session/type predicates keep stale and cross-Session ids inert. An
+ Agent-Run-backed row may be removed only while that Run is still queued and
+ explicitly held by Workbench; its cancellation and the row deletion commit
+ together in the caller's transaction.
+ """
+ row = conn.execute(
+ select(messages.c.native_message_id, messages.c.metadata_json)
+ .where(messages.c.id == message_id)
+ .where(messages.c.session_id == session_id)
+ .where(messages.c.type == QUEUED_TYPE)
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return False
+ run_id = _queued_agent_run_id(dict(row))
+ if run_id:
+ from storage.background import (
+ cancel_workbench_queued_agent_run_in_connection,
+ )
+
+ if not cancel_workbench_queued_agent_run_in_connection(
+ conn,
+ run_id,
+ session_id=session_id,
+ ):
+ return False
result = conn.execute(
delete(messages)
.where(messages.c.id == message_id)
.where(messages.c.session_id == session_id)
.where(messages.c.type == QUEUED_TYPE)
)
+ if run_id and not result.rowcount:
+ raise RuntimeError(
+ "queued Agent Run cancellation succeeded but its message deletion was refused"
+ )
return bool(result.rowcount)
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 90e242697..72cb5acd2 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -1457,6 +1457,21 @@ scenarios:
# the re-route answers SessionBackendLockedError. Same _commit_competing_bind_after
# harness and the same real _archive_write payload as HFR-252.
test: tests/test_sqlite_sessions_store.py::test_update_session_cannot_rename_a_session_archived_inside_its_window
+ - id: HFR-430
+ name: an Agent Run can apply the Workbench send-now transition to a busy Session
+ 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
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index 9a9f08214..2c0494613 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -353,6 +353,184 @@ def test_agent_run_async_defaults_callback_from_caller_env(tmp_path: Path, capsy
assert stored["metadata"]["caller_context"]["session_id"] == caller_session["id"]
+def test_agent_run_send_now_is_durable_on_an_existing_session(
+ tmp_path: Path,
+ capsys,
+) -> None:
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_send_now",
+ now="2026-07-30T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-07-30T00:00:00Z",
+ updated_at="2026-07-30T00:00:00Z",
+ )
+ )
+ session_id = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )["id"]
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--session-id",
+ session_id,
+ "--send-now",
+ "--no-callback",
+ "--message",
+ "apply this correction",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ 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"] == "send_now"
+
+
+def test_agent_run_send_now_rejects_a_new_session(capsys) -> None:
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--send-now",
+ "--no-callback",
+ "--message",
+ "apply this correction",
+ ]
+ )
+
+ result = cli.cmd_agent_run(args)
+
+ assert result == 1
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "send_now_requires_existing_session"
+ assert "--session-id" in payload["hint"]
+
+
+def test_agent_run_send_now_rejects_an_im_backed_session(
+ tmp_path: Path,
+ capsys,
+) -> None:
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state(primary_platform="slack")
+ db_path = state_home / "state" / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C_SEND_NOW",
+ now="2026-07-30T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-07-30T00:00:00Z",
+ updated_at="2026-07-30T00:00:00Z",
+ )
+ )
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--agent",
+ "worker",
+ "--session-id",
+ session["id"],
+ "--send-now",
+ "--no-callback",
+ "--message",
+ "interrupt this",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ 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() == []
+
+
def test_agent_run_async_self_target_defaults_to_no_callback(
tmp_path: Path, capsys
) -> None:
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index e29230853..9ad59d461 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -63,6 +63,7 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:
("agent", "models"),
("runs", "list"),
("session", "list"),
+ ("session", "queue", "list"),
("vault", "list"),
("vault", "find"),
("vault", "tags"),
@@ -113,6 +114,30 @@ def test_injected_vibe_commands_only_use_parser_supported_flags() -> None:
assert checked_commands >= 20
+def test_injected_session_queue_commands_name_real_subcommands() -> None:
+ context = MessageContext(
+ user_id="user",
+ channel_id="channel",
+ platform="avibe",
+ platform_specific={"agent_session_id": "ses-test"},
+ )
+ prompt = build_system_prompt_injection(context=context)
+
+ for command, expected_path in (
+ (
+ "vibe session queue list <session-id>",
+ ("session", "queue", "list"),
+ ),
+ (
+ "vibe session queue remove <session-id> <message-id>",
+ ("session", "queue", "remove"),
+ ),
+ ):
+ assert f"`{command}`" in prompt
+ _, path = _prompt_command_parser(command)
+ assert path == expected_path
+
+
def test_runs_list_cli_defaults_to_first_page(monkeypatch, tmp_path, capsys) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 96f5930c1..75971bfd1 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -303,6 +303,7 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:
assert "--fork-session FORK_SESSION" in captured.out
assert "--fork-self" in captured.out
assert "--sync" in captured.out
+ assert "--send-now" in captured.out
assert "--same-scope" in captured.out
assert "--scope-id" in captured.out
assert "--visible" in captured.out
@@ -312,6 +313,10 @@ def test_agent_run_help_includes_fork_session_guidance(capsys) -> None:
assert "--fork-self forks this current Session." in captured.out
assert "Forks keep the same backend, scope, and cwd as the source Session." in captured.out
assert "vibe agent run --fork-self --message" in captured.out
+ assert "vibe agent run --session-id sesk8m4q2p7x --send-now --message" in captured.out
+ assert "vibe session queue list sesk8m4q2p7x" in captured.out
+ assert "vibe session queue remove sesk8m4q2p7x msg_queued123" in captured.out
+ assert "vibe session send-now sesk8m4q2p7x" in captured.out
assert "Agent runs are async by default. From an Avibe Agent shell, they return their final result to this conversation by default." in captured.out
assert "vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'" in captured.out
assert (
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index c64fedff7..1fa36173f 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -16,11 +16,13 @@ We exercise three layers:
from __future__ import annotations
import asyncio
+import contextlib
import socket
import sys
import tempfile
import types
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, Mock
import httpx
@@ -251,22 +253,37 @@ async def _publish_event_round_trip():
"data": {"scope": "request", "request_id": "vreq_1", "request_status": "pending"},
},
)
+ queue_resp = await client.post(
+ "/internal/events",
+ json={
+ "type": "queue.updated",
+ "data": {"session_id": "ses_queue"},
+ },
+ )
bad_resp = await client.post("/internal/events", json={"type": "unsupported", "data": {}})
- event = await asyncio.wait_for(queue.get(), timeout=1.0)
- return resp, bad_resp, event
+ events = [
+ await asyncio.wait_for(queue.get(), timeout=1.0),
+ await asyncio.wait_for(queue.get(), timeout=1.0),
+ ]
+ return resp, queue_resp, bad_resp, events
finally:
inbox_events.bus.unsubscribe(sub_id)
def test_publish_event_endpoint_emits_allowlisted_bus_event():
- resp, bad_resp, event = asyncio.run(_publish_event_round_trip())
+ resp, queue_resp, bad_resp, events = asyncio.run(_publish_event_round_trip())
assert resp.status_code == 200
assert resp.json() == {"ok": True}
+ assert queue_resp.status_code == 200
+ assert queue_resp.json() == {"ok": True}
assert bad_resp.status_code == 400
- assert event == (
- "vaults.updated",
- {"scope": "request", "request_id": "vreq_1", "request_status": "pending"},
- )
+ assert events == [
+ (
+ "vaults.updated",
+ {"scope": "request", "request_id": "vreq_1", "request_status": "pending"},
+ ),
+ ("queue.updated", {"session_id": "ses_queue"}),
+ ]
def test_reconcile_platforms_endpoint_calls_controller(monkeypatch):
@@ -2674,6 +2691,893 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
assert transcript["messages"] == []
+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 its ``flush_on_cancel`` finally starts
+ the durable Agent Run as a new scheduled turn.
+ """
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage import messages_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",
+ 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 correction",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ 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):
+ seen.append((text, source))
+ if text == "original work":
+ original_started.set()
+ try:
+ await asyncio.sleep(60)
+ except asyncio.CancelledError:
+ original_cancelled.set()
+ raise
+ replacement_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)
+
+ 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": "original work"},
+ )
+ assert response.status_code == 202
+ await asyncio.wait_for(original_started.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",
+ "suppress_delivery": True,
+ },
+ )
+ result = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ 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)
+ return result
+
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="interrupted",
+ queue_owner_transferred=True,
+ )
+ controller.command_handler.handle_stop.assert_awaited_once()
+ assert seen == [
+ ("original work", SOURCE_HUMAN),
+ ("apply the correction", SOURCE_SCHEDULED),
+ ]
+ with engine.connect() as conn:
+ assert messages_service.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": "interrupted",
+ "target_was_busy": True,
+ }
+
+
+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
+ from core.services import sessions as sessions_service
+ from storage import messages_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_refused",
+ 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="keep this queued",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(request.id) is not None
+ controller = _build_controller_double()
+ controller.command_handler.handle_stop = AsyncMock(return_value=False)
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=MessageContext(user_id="U", channel_id=session_id, platform="avibe"),
+ )
+ 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",
+ },
+ )
+ try:
+ result = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ held = not task.done()
+ return result, held
+ finally:
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ result, held = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="stop_failed",
+ queue_owner_transferred=True,
+ )
+ assert held is True
+ with engine.connect() as conn:
+ assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ "keep this queued"
+ ]
+ 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"] == {
+ "intent": "send_now",
+ "status": "stop_failed",
+ "target_was_busy": True,
+ }
+
+
+def test_concurrent_agent_run_send_now_callers_share_one_interrupt(monkeypatch, tmp_path):
+ """Two admitted Runs share one Stop and keep FIFO order under real overlap."""
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage import messages_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_concurrent",
+ 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()
+ requests = [
+ request_store.enqueue_agent_run(
+ session_id=session_id,
+ message=message,
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ for message in ("first correction", "second correction")
+ ]
+ for request in requests:
+ 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):
+ seen.append(text)
+ if text == "original work":
+ original_started.set()
+ try:
+ await asyncio.sleep(60)
+ except asyncio.CancelledError:
+ original_cancelled.set()
+ raise
+ return TurnDispatchOutcome(
+ error=None,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+
+ async def _stop(_context):
+ stop_entered.set()
+ await release_stop.wait()
+ 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)
+ transport = httpx.ASGITransport(app=app)
+
+ def _context(request):
+ return 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():
+ 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": "original work"},
+ )
+ assert response.status_code == 202
+ await asyncio.wait_for(original_started.wait(), timeout=3)
+ submissions = [
+ asyncio.create_task(
+ controller.session_turn_gate.submit_scheduled(
+ session_id,
+ _context(request),
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ )
+ for request in requests
+ ]
+ await asyncio.wait_for(stop_entered.wait(), timeout=3)
+ for _ in range(100):
+ with engine.connect() as conn:
+ if len(messages_service.list_queued(conn, session_id)) == 2:
+ 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)
+ return results
+
+ results = asyncio.run(_go())
+
+ assert controller.command_handler.handle_stop.await_count == 1
+ assert all(
+ result
+ == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="interrupted",
+ queue_owner_transferred=True,
+ )
+ for result in results
+ )
+ assert seen == ["original work", "first correction", "second correction"]
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+ for request in requests:
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["metadata"]["delivery_outcome"] == {
+ "intent": "send_now",
+ "status": "interrupted",
+ "target_was_busy": True,
+ }
+
+
+def test_agent_run_send_now_restart_recovers_without_a_second_interrupt(
+ monkeypatch,
+ tmp_path,
+):
+ """A refused durable send-now is recovered as queued work, not replayed Stop."""
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage import messages_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_restart",
+ 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="recover after restart",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(request.id) is not None
+ first_controller = _build_controller_double()
+ first_controller.command_handler.handle_stop = AsyncMock(return_value=False)
+ first_app = internal_server.create_app(first_controller)
+ 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 _admit_then_restart():
+ task = asyncio.create_task(asyncio.sleep(60))
+ first_app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=MessageContext(
+ user_id="U",
+ channel_id=session_id,
+ platform="avibe",
+ ),
+ )
+ try:
+ result = await first_controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ finally:
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+ return result
+
+ admitted = asyncio.run(_admit_then_restart())
+ assert admitted.delivery_status == "stop_failed"
+ with engine.connect() as conn:
+ assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ "recover after restart"
+ ]
+
+ seen: list[str] = []
+
+ async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ seen.append(text)
+ return TurnDispatchOutcome(
+ error=None,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _dispatch)
+ second_controller = _build_controller_double()
+ internal_server.create_app(second_controller)
+
+ async def _recover():
+ recovered = await second_controller.session_turns.recover_persisted_agent_run_queue(
+ session_id
+ )
+ for _ in range(200):
+ if (
+ seen == ["recover after restart"]
+ and session_id not in second_controller.session_turns.in_flight
+ ):
+ break
+ await asyncio.sleep(0.01)
+ return recovered
+
+ recovered = asyncio.run(_recover())
+
+ assert recovered == [session_id]
+ assert seen == ["recover after restart"]
+ second_controller.command_handler.handle_stop.assert_not_awaited()
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["metadata"]["delivery_intent"] == "send_now"
+ assert stored["metadata"]["delivery_outcome"]["status"] == "stop_failed"
+
+
+def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatch, tmp_path):
+ """An idle backlog starts in FIFO order without a post-submit interrupt race."""
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage import messages_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_idle",
+ 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"]
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="older queued input",
+ )
+
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="new urgent input",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(request.id) is not None
+ seen: list[str] = []
+
+ async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ seen.append(text)
+ 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)
+ 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():
+ result = await controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ for _ in range(300):
+ if len(seen) == 2 and session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.01)
+ return result
+
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=False,
+ delivery_status="flushed",
+ queue_owner_transferred=True,
+ )
+ assert seen == ["older queued input", "new urgent input"]
+ controller.command_handler.handle_stop.assert_not_awaited()
+
+
+def test_agent_run_send_now_idle_flush_failure_is_recoverable(monkeypatch, tmp_path):
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage import messages_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_send_now_recovery",
+ 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="retry the idle flush",
+ 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.flush_queue = AsyncMock(return_value=False)
+ 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",
+ },
+ )
+
+ result = asyncio.run(
+ controller.session_turn_gate.submit_scheduled(
+ session_id,
+ context,
+ request.message or "",
+ delivery_intent="send_now",
+ )
+ )
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=False,
+ delivery_status="flush_failed",
+ queue_owner_transferred=True,
+ )
+ with engine.connect() as conn:
+ assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ "retry the idle flush"
+ ]
+ 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
+
+
+def test_canceling_held_agent_run_retires_queue_before_send_now(
+ monkeypatch,
+ tmp_path,
+):
+ """A canceled queue owner cannot leave stale work that triggers Stop."""
+
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage import messages_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_cancel_before_send_now",
+ 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="obsolete urgent correction",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ assert request_store.claim(request.id) is not None
+ request_store.requeue(
+ request.id,
+ metadata={"workbench_queue_holds_run": True},
+ )
+ with engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ native_message_id=f"agent_run:{request.id}",
+ text=request.message or "",
+ )
+
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+
+ async def _exercise():
+ active_task = asyncio.create_task(asyncio.sleep(60))
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=active_task,
+ context=MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ ),
+ )
+ try:
+ assert request_store.cancel_run(request.id) is True
+ return await controller.session_turns.send_now(session_id)
+ finally:
+ active_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await active_task
+
+ result = asyncio.run(_exercise())
+
+ assert result == {
+ "ok": True,
+ "session_id": session_id,
+ "status": "empty",
+ }
+ controller.command_handler.handle_stop.assert_not_awaited()
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "canceled"
+ assert stored["cancel_requested"] is True
+
+
+def test_idle_send_now_flush_failure_is_an_http_failure(
+ monkeypatch,
+ tmp_path,
+):
+ """A durable queue refusal stays retryable and never reports success."""
+
+ from core.services import sessions as sessions_service
+ from storage import messages_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_idle_flush_failed",
+ 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"]
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="retry me later",
+ )
+
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ controller.session_turns.flush_queue = AsyncMock(return_value=False)
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(f"/internal/send-now/{session_id}")
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 503
+ assert response.json() == {
+ "ok": False,
+ "code": "flush_failed",
+ "session_id": session_id,
+ }
+ with engine.connect() as conn:
+ assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ "retry me later"
+ ]
+
+
+def test_agent_run_send_now_cancel_race_never_becomes_failed(monkeypatch, tmp_path):
+ from core.scheduled_tasks import (
+ ScheduledTaskService,
+ ScheduledTaskStore,
+ TaskExecutionStore,
+ )
+ from core.services import sessions as sessions_service
+ from storage import messages_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_send_now_cancel",
+ 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="must not survive cancellation",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ controller = _build_controller_double()
+ controller.platform_settings_managers = {}
+ controller.im_clients = {"avibe": SimpleNamespace()}
+ controller.get_im_client_for_context = lambda _context: SimpleNamespace(
+ should_use_thread_for_reply=lambda: True,
+ should_use_thread_for_dm_session=lambda: False,
+ )
+ internal_server.create_app(controller)
+ submit_scheduled = controller.session_turn_gate.submit_scheduled
+
+ async def _cancel_after_claim(*args, **kwargs):
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.cancel_run(request.id) is True
+ return await submit_scheduled(*args, **kwargs)
+
+ controller.session_turn_gate.submit_scheduled = _cancel_after_claim
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ async def _exercise() -> None:
+ await service._drain_requests()
+ execution = service._inflight_executions.get(request.id)
+ assert execution is not None
+ await execution
+
+ asyncio.run(_exercise())
+
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "canceled"
+ assert stored["cancel_requested"] is True
+ assert stored["error"] is None
+ assert stored["metadata"]["delivery_outcome"]["status"] == "canceled"
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+
+
def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_path):
"""A retried harness callback already sitting in the queue is a duplicate,
not a scheduler failure."""
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index b0ee33ebe..91ac249fc 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -17,6 +17,7 @@ from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_runs, agent_sessions, messages, scopes
+from storage.pagination import PageRequest
from storage.settings_service import upsert_scope
from vibe.message_identity import HARNESS_TYPE
@@ -1138,6 +1139,161 @@ def test_remove_queued_targets_only_queued(isolated_state):
assert [q["text"] for q in messages_service.list_queued(conn, "ses_rm")] == ["b"]
+def test_remove_queued_cancels_its_held_agent_run_atomically(isolated_state):
+ from core.scheduled_tasks import TaskExecutionStore
+ from storage.background import run_update_event_transaction
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_rm_run")
+
+ store = TaskExecutionStore()
+ request = store.enqueue_agent_run(
+ session_id="ses_rm_run",
+ message="obsolete delegated work",
+ agent_name="worker",
+ )
+ assert store.claim(request.id) is not None
+ store.requeue(
+ request.id,
+ metadata={"workbench_queue_holds_run": True},
+ )
+ with engine.begin() as conn:
+ queued = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_rm_run",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text=request.message or "",
+ metadata={
+ "scheduled_provenance": {
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": request.id,
+ }
+ }
+ },
+ )
+
+ with run_update_event_transaction(engine) as conn:
+ assert (
+ messages_service.remove_queued(
+ conn,
+ "ses_rm_run",
+ queued["id"],
+ )
+ is True
+ )
+
+ stored = store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "canceled"
+ assert stored["cancel_requested"] is True
+ assert stored["completed_at"]
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, "ses_rm_run") == []
+
+
+def test_remove_queued_refuses_an_agent_run_no_longer_owned_by_queue(
+ isolated_state,
+):
+ from core.scheduled_tasks import TaskExecutionStore
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_rm_claimed")
+
+ store = TaskExecutionStore()
+ request = store.enqueue_agent_run(
+ session_id="ses_rm_claimed",
+ message="already claimed work",
+ agent_name="worker",
+ )
+ assert store.claim(request.id) is not None
+ with engine.begin() as conn:
+ queued = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_rm_claimed",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text=request.message or "",
+ native_message_id=f"agent_run:{request.id}",
+ )
+
+ with engine.begin() as conn:
+ assert (
+ messages_service.remove_queued(
+ conn,
+ "ses_rm_claimed",
+ queued["id"],
+ )
+ is False
+ )
+
+ stored = store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "running"
+ assert stored["cancel_requested"] is False
+ with engine.connect() as conn:
+ assert [row["id"] for row in messages_service.list_queued(conn, "ses_rm_claimed")] == [
+ queued["id"]
+ ]
+
+
+def test_list_queued_page_is_bounded_and_fifo(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_page")
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_page",
+ text="first",
+ )
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_page",
+ text="second",
+ )
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_page",
+ text="third",
+ )
+
+ with engine.connect() as conn:
+ page1 = messages_service.list_queued_page(
+ conn,
+ "ses_page",
+ page_request=PageRequest(page=1, limit=2),
+ )
+ page2 = messages_service.list_queued_page(
+ conn,
+ "ses_page",
+ page_request=PageRequest(page=2, limit=2),
+ )
+
+ assert [row["text"] for row in page1.items] == ["first", "second"]
+ assert page1.page == 1
+ assert page1.limit == 2
+ assert page1.has_more is True
+ assert [row["text"] for row in page2.items] == ["third"]
+ assert page2.page == 2
+ assert page2.limit == 2
+ assert page2.has_more is False
+
+
def test_draft_upsert_get_and_clear(isolated_state):
"""A session keeps exactly one draft row; setting replaces it, blank clears,
and the draft never shows in the transcript."""
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 81ac9dc14..3eea453c7 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -432,6 +432,18 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("### Choosing the right Harness shape", prompt)
self.assertIn("| Independent Agent delegation | `vibe agent run --agent <agent-name>` |", prompt)
self.assertIn("| Continue a pointed Session | `vibe agent run --session-id ...` |", prompt)
+ self.assertIn(
+ "| Inspect queued Workbench Session input | `vibe session queue list <session-id>` |",
+ prompt,
+ )
+ self.assertIn(
+ "| Remove one queued Workbench Session input | `vibe session queue remove <session-id> <message-id>` |",
+ prompt,
+ )
+ self.assertIn(
+ "| Dispatch an existing queued Workbench Session head now | `vibe session send-now <session-id>` |",
+ prompt,
+ )
self.assertIn("| Branch from current Session context | `vibe agent run --fork-self ...` |", prompt)
self.assertIn("Tasks created from an Avibe Agent shell continue this conversation by default", prompt)
self.assertIn("`vibe task add` creates a time-triggered saved Agent message", prompt)
@@ -452,6 +464,46 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn(delegate_guidance, prompt)
self.assertNotIn("Outside an Agent shell, a caller-less run", prompt)
self.assertIn("Pass `--sync` only when the current process must wait for the result", prompt)
+ self.assertIn(
+ "That existing-Session send queues behind an active turn by default",
+ prompt,
+ )
+ self.assertIn(
+ "an explicit user request is one signal, not a prerequisite",
+ prompt,
+ )
+ self.assertIn(
+ "Both forms require a Web/Workbench Session",
+ prompt,
+ )
+ self.assertIn(
+ "vibe agent run --session-id <id> --send-now --message ...",
+ prompt,
+ )
+ self.assertIn(
+ "vibe session send-now <id>",
+ prompt,
+ )
+ self.assertIn(
+ "vibe session queue list <id>",
+ prompt,
+ )
+ self.assertIn(
+ "vibe session queue remove <id> <message-id>",
+ prompt,
+ )
+ self.assertIn(
+ "Always list first and use the returned stable message id",
+ prompt,
+ )
+ self.assertIn(
+ "the new message does not leapfrog it",
+ prompt,
+ )
+ self.assertIn(
+ "If interruption is refused, the active turn and durable queue remain intact",
+ prompt,
+ )
self.assertNotIn("Add `--same-scope` to require the caller/source scope", prompt)
self.assertIn("Use `vibe agent run --fork-self --message ...` when work should branch from this current Session", prompt)
self.assertIn("Forks keep the source Session backend, scope, and cwd by default", prompt)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index b4a22a7d3..3135aeead 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -5567,20 +5567,35 @@ def test_avibe_agent_run_routes_through_gate_without_completing_early(monkeypatc
assert handler_calls == []
-def test_busy_avibe_agent_run_returns_to_queued_and_is_held_by_workbench_queue(monkeypatch, tmp_path) -> None:
+def test_busy_avibe_agent_run_send_now_records_the_turn_owner_outcome(monkeypatch, tmp_path) -> None:
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
session_id=session_id,
message="run behind active workbench turn",
agent_name="codex",
+ delivery_intent="send_now",
)
submitted: list[tuple] = []
handler_calls: list = []
- async def _submit_scheduled(sid, ctx, text):
- submitted.append((sid, text, ctx.platform_specific.get("task_execution_id")))
- return "enqueued"
+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent="queue"):
+ from core.session_turns import TurnSubmissionResult
+
+ submitted.append(
+ (
+ sid,
+ text,
+ ctx.platform_specific.get("task_execution_id"),
+ delivery_intent,
+ )
+ )
+ return TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="interrupted",
+ )
async def _handle_scheduled_message(context, message, parsed_session_key=None):
handler_calls.append(message)
@@ -5609,10 +5624,170 @@ def test_busy_avibe_agent_run_returns_to_queued_and_is_held_by_workbench_queue(m
assert run.get("started_at") is None
assert run.get("completed_at") is None
assert (run.get("metadata") or {}).get("workbench_queue_holds_run") is True
- assert submitted == [(session_id, "run behind active workbench turn", request.id)]
+ assert run["metadata"]["delivery_intent"] == "send_now"
+ assert run["metadata"]["delivery_outcome"] == {
+ "intent": "send_now",
+ "status": "interrupted",
+ "target_was_busy": True,
+ }
+ assert submitted == [
+ (session_id, "run behind active workbench turn", request.id, "send_now")
+ ]
assert handler_calls == []
+def test_idle_send_now_flush_failure_invokes_queue_recovery(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",
+ 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",
+ queue_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")
+
+ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
+ controller = _avibe_controller_double(
+ 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"),
+ 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"] == "queued"
+ assert stored["metadata"]["workbench_queue_holds_run"] is True
+ assert stored["metadata"]["delivery_outcome"]["status"] == "flush_failed"
+ assert recovered == [session_id]
+
+
+def test_send_now_runtime_rejects_non_workbench_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
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state(primary_platform="slack")
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C_SEND_NOW",
+ now="2026-07-30T00:00:00Z",
+ )
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json="{}",
+ created_at="2026-07-30T00:00:00Z",
+ updated_at="2026-07-30T00:00:00Z",
+ )
+ )
+ session_id = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )["id"]
+
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="do not silently downgrade",
+ agent_name="worker",
+ delivery_intent="send_now",
+ )
+ direct_calls: list[str] = []
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ direct_calls.append(message)
+
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": object()},
+ im_clients={"slack": SimpleNamespace()},
+ get_im_client_for_context=lambda _context: SimpleNamespace(
+ should_use_thread_for_reply=lambda: True,
+ should_use_thread_for_dm_session=lambda: False,
+ ),
+ session_turn_gate=SimpleNamespace(submit_scheduled=AsyncMock(), in_flight={}),
+ message_handler=SimpleNamespace(
+ 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 "Web/Workbench Agent Session" in stored["error"]
+ assert stored["metadata"]["delivery_outcome"] == {
+ "intent": "send_now",
+ "status": "unsupported_target",
+ "target_was_busy": False,
+ }
+ assert direct_calls == []
+ controller.session_turn_gate.submit_scheduled.assert_not_awaited()
+
+
def test_busy_avibe_agent_run_requeue_preserves_session_fork_metadata(monkeypatch, tmp_path) -> None:
session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
diff --git a/tests/test_session_cli.py b/tests/test_session_cli.py
index 5c886a919..ee84f12c4 100644
--- a/tests/test_session_cli.py
+++ b/tests/test_session_cli.py
@@ -192,6 +192,389 @@ def test_get_missing_is_not_found(monkeypatch, tmp_path, capsys):
assert payload["code"] == "session_not_found"
+# -------------------------------------------------------------------- send now
+
+
+def test_send_now_dispatches_an_existing_queue_without_adding_a_message(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ from vibe import internal_client
+
+ engine = _setup(monkeypatch, tmp_path)
+ _seed(engine, "sesaaa")
+ called: list[str] = []
+
+ async def _send_now(session_id):
+ called.append(session_id)
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "status": "flushed",
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "send_now", _send_now)
+
+ code, payload = _run(
+ cli.cmd_session_send_now,
+ ["session", "send-now", "sesaaa"],
+ capsys,
+ )
+
+ assert code == 0
+ assert called == ["sesaaa"]
+ assert payload == {
+ "schema_version": 1,
+ "ok": True,
+ "kind": "session_send_now",
+ "session_id": "sesaaa",
+ "status": "flushed",
+ "result": {
+ "ok": True,
+ "session_id": "sesaaa",
+ "status": "flushed",
+ },
+ }
+
+
+def test_send_now_surfaces_a_typed_interrupt_refusal(monkeypatch, tmp_path, capsys):
+ from vibe import internal_client
+
+ engine = _setup(monkeypatch, tmp_path)
+ _seed(engine, "sesaaa")
+
+ async def _send_now(session_id):
+ return {
+ "status_code": 409,
+ "body": {
+ "ok": False,
+ "session_id": session_id,
+ "code": "stop_failed",
+ "detail": "backend refused Stop",
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "send_now", _send_now)
+
+ code, payload = _run(
+ cli.cmd_session_send_now,
+ ["session", "send-now", "sesaaa"],
+ capsys,
+ )
+
+ assert code == 1
+ assert payload["code"] == "stop_failed"
+ assert payload["error"] == "backend refused Stop"
+ assert payload["details"]["session_id"] == "sesaaa"
+ assert payload["details"]["controller_status_code"] == 409
+
+
+def test_send_now_surfaces_an_idle_flush_failure(monkeypatch, tmp_path, capsys):
+ from vibe import internal_client
+
+ engine = _setup(monkeypatch, tmp_path)
+ _seed(engine, "sesaaa")
+
+ async def _send_now(session_id):
+ return {
+ "status_code": 503,
+ "body": {
+ "ok": False,
+ "session_id": session_id,
+ "code": "flush_failed",
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "send_now", _send_now)
+
+ code, payload = _run(
+ cli.cmd_session_send_now,
+ ["session", "send-now", "sesaaa"],
+ capsys,
+ )
+
+ assert code == 1
+ assert payload["code"] == "flush_failed"
+ assert payload["details"]["session_id"] == "sesaaa"
+ assert payload["details"]["controller_status_code"] == 503
+
+
+def test_send_now_rejects_an_archived_session_before_controller_call(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ from vibe import internal_client
+
+ engine = _setup(monkeypatch, tmp_path)
+ _seed(engine, "sesarch", status="archived")
+
+ async def _send_now(_session_id):
+ raise AssertionError("archived Session must not reach the live controller")
+
+ monkeypatch.setattr(internal_client, "send_now", _send_now)
+
+ code, payload = _run(
+ cli.cmd_session_send_now,
+ ["session", "send-now", "sesarch"],
+ capsys,
+ )
+
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+
+
+def test_send_now_requires_an_explicit_target(capsys):
+ parser = cli.build_parser()
+
+ with pytest.raises(SystemExit) as exc:
+ parser.parse_args(["session", "send-now"])
+
+ assert exc.value.code == 2
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "invalid_arguments"
+ assert payload["help_command"] == "vibe session send-now --help"
+
+
+def test_send_now_and_queue_controls_reject_an_im_backed_session(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ from vibe import internal_client
+
+ 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")
+
+ monkeypatch.setattr(internal_client, "send_now", _send_now)
+
+ send_code, send_payload = _run(
+ cli.cmd_session_send_now,
+ ["session", "send-now", "sesim"],
+ capsys,
+ )
+ list_code, list_payload = _run(
+ cli.cmd_session_queue_list,
+ ["session", "queue", "list", "sesim"],
+ capsys,
+ )
+ remove_code, remove_payload = _run(
+ cli.cmd_session_queue_remove,
+ ["session", "queue", "remove", "sesim", "msg_any"],
+ capsys,
+ )
+
+ assert send_code == 1
+ assert send_payload["code"] == "send_now_unsupported_target"
+ assert list_code == 1
+ assert list_payload["code"] == "session_queue_unsupported_target"
+ assert remove_code == 1
+ assert remove_payload["code"] == "session_queue_unsupported_target"
+
+
+# ------------------------------------------------------------------------ queue
+
+
+def test_queue_list_is_paginated_in_fifo_order_and_exposes_run_identity(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ from storage import messages_service
+
+ engine = _setup(monkeypatch, tmp_path)
+ scope_id = _seed(engine, "sesaaa")
+ with engine.begin() as conn:
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="sesaaa",
+ text="first",
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="sesaaa",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text="second",
+ metadata={
+ "scheduled_provenance": {
+ "platform_specific": {
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run_second",
+ }
+ }
+ },
+ )
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="sesaaa",
+ text="third",
+ )
+
+ code, page1 = _run(
+ cli.cmd_session_queue_list,
+ ["session", "queue", "list", "sesaaa", "--limit", "2"],
+ capsys,
+ )
+
+ assert code == 0
+ assert [row["text"] for row in page1["queued"]] == ["first", "second"]
+ assert [row["position"] for row in page1["queued"]] == [1, 2]
+ assert page1["queued"][0]["run_id"] is None
+ assert page1["queued"][1]["run_id"] == "run_second"
+ assert page1["pagination"]["next_command"] == (
+ "vibe session queue list sesaaa --page 2 --limit 2"
+ )
+
+ code, page2 = _run(
+ cli.cmd_session_queue_list,
+ ["session", "queue", "list", "sesaaa", "--page", "2", "--limit", "2"],
+ capsys,
+ )
+
+ assert code == 0
+ assert [row["text"] for row in page2["queued"]] == ["third"]
+ assert [row["position"] for row in page2["queued"]] == [3]
+ assert page2["pagination"]["has_more"] is False
+
+
+def test_queue_remove_deletes_only_the_named_session_row_and_notifies_web(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ from storage import messages_service
+
+ engine = _setup(monkeypatch, tmp_path)
+ scope_id = _seed(engine, "sesaaa")
+ _seed(engine, "sesbbb", native="proj_b")
+ with engine.begin() as conn:
+ queued = messages_service.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id="sesaaa",
+ text="obsolete",
+ )
+ notified: list[str] = []
+ monkeypatch.setattr(
+ cli,
+ "_post_session_queue_updated_to_live_ui",
+ lambda session_id: notified.append(session_id),
+ )
+
+ code, wrong_session = _run(
+ cli.cmd_session_queue_remove,
+ ["session", "queue", "remove", "sesbbb", queued["id"]],
+ capsys,
+ )
+
+ assert code == 0
+ assert wrong_session["removed"] is False
+ assert wrong_session["status"] == "not_found"
+ assert notified == []
+
+ code, removed = _run(
+ cli.cmd_session_queue_remove,
+ ["session", "queue", "remove", "sesaaa", queued["id"]],
+ capsys,
+ )
+
+ assert code == 0
+ assert removed["removed"] is True
+ assert removed["status"] == "removed"
+ assert notified == ["sesaaa"]
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, "sesaaa") == []
+
+
+def test_queue_remove_cancels_the_agent_run_owned_by_that_row(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ from core.scheduled_tasks import TaskExecutionStore
+ from storage import messages_service
+
+ engine = _setup(monkeypatch, tmp_path)
+ scope_id = _seed(engine, "sesrun")
+ store = TaskExecutionStore()
+ request = store.enqueue_agent_run(
+ session_id="sesrun",
+ message="obsolete delegated work",
+ agent_name="worker",
+ )
+ assert store.claim(request.id) is not None
+ store.requeue(
+ request.id,
+ metadata={"workbench_queue_holds_run": True},
+ )
+ with engine.begin() as conn:
+ queued = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="sesrun",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text=request.message or "",
+ native_message_id=f"agent_run:{request.id}",
+ )
+ monkeypatch.setattr(
+ cli,
+ "_post_session_queue_updated_to_live_ui",
+ lambda _session_id: None,
+ )
+
+ code, removed = _run(
+ cli.cmd_session_queue_remove,
+ ["session", "queue", "remove", "sesrun", queued["id"]],
+ capsys,
+ )
+
+ assert code == 0
+ assert removed["removed"] is True
+ stored = store.get_run(request.id)
+ assert stored is not None
+ assert stored["status"] == "canceled"
+ assert stored["cancel_requested"] is True
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, "sesrun") == []
+
+
+def test_queue_commands_reject_an_archived_session(monkeypatch, tmp_path, capsys):
+ engine = _setup(monkeypatch, tmp_path)
+ _seed(engine, "sesarch", status="archived")
+
+ list_code, list_payload = _run(
+ cli.cmd_session_queue_list,
+ ["session", "queue", "list", "sesarch"],
+ capsys,
+ )
+ remove_code, remove_payload = _run(
+ cli.cmd_session_queue_remove,
+ ["session", "queue", "remove", "sesarch", "msg_any"],
+ capsys,
+ )
+
+ assert list_code == 1
+ assert list_payload["code"] == "session_not_found"
+ assert remove_code == 1
+ assert remove_payload["code"] == "session_not_found"
+
+
# ------------------------------------------------------------------------- update
@@ -518,6 +901,31 @@ def test_cli_activity_endpoint_publishes_with_token(monkeypatch):
assert events[0]["event"] == "updated" and events[0]["title"] == "Renamed"
+def test_cli_activity_endpoint_publishes_queue_updates_with_token(monkeypatch):
+ import vibe.sse_broker as sse_broker
+ from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token
+ from vibe.ui_server import app
+
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ sse_broker.broker,
+ "publish",
+ lambda topic, data: published.append((topic, data)),
+ )
+
+ resp = app.test_client().post(
+ "/api/sessions/sesqueue/cli-activity",
+ json={"event": "queue_updated"},
+ headers={
+ "X-Vibe-Show-Client": "cli",
+ SHOW_CLI_EVENT_TOKEN_HEADER: show_cli_event_token(),
+ },
+ )
+
+ assert resp.status_code == 200
+ assert published == [("queue.updated", {"session_id": "sesqueue"})]
+
+
def test_cli_activity_placement_events_match_patch(monkeypatch):
import vibe.sse_broker as sse_broker
from core.services import sessions as sessions_service
diff --git a/vibe/cli.py b/vibe/cli.py
index e43574e96..1b1b4f3b3 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -35,6 +35,8 @@ from sqlalchemy import select
from config import SettingsStore, paths
from config.v2_config import V2Config
from core.scheduled_tasks import (
+ AGENT_RUN_DELIVERY_QUEUE,
+ AGENT_RUN_DELIVERY_SEND_NOW,
BINDING_FOLLOWS_SESSION_METADATA_KEY,
ScheduledTaskStore,
TaskExecutionStore,
@@ -1117,6 +1119,10 @@ def _agent_run_examples_text() -> str:
"""\
Session target:
Use --session-id to continue an existing Agent Session.
+ Add --send-now to persist the new Run, interrupt its active turn, and dispatch the FIFO queue head.
+ If work is already queued and no new message is needed, 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>
Omit --session-id/--fork-self/--fork-session to create a background Session for --agent.
Inside an Agent shell it inherits the caller scope and invocation cwd; outside one it is standalone with its own Show workspace.
Use --same-scope to explicitly place a new Session in the caller/source Session's scope.
@@ -1141,6 +1147,10 @@ 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 session queue list sesk8m4q2p7x
+ vibe session queue remove sesk8m4q2p7x msg_queued123
+ vibe session send-now sesk8m4q2p7x
Normal terminal examples:
vibe agent run --sync --agent release-reviewer --message 'Review the latest CI result and print it here.'
@@ -4424,6 +4434,18 @@ def cmd_agent_run(args):
example_command="vibe agent run --agent default",
)
session_policy = _validate_run_session_policy(args, help_command="vibe agent run --help")
+ delivery_intent = (
+ AGENT_RUN_DELIVERY_SEND_NOW
+ if bool(getattr(args, "send_now", False))
+ else AGENT_RUN_DELIVERY_QUEUE
+ )
+ if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW and session_policy != "existing":
+ raise TaskCliError(
+ "--send-now requires an existing Agent Session",
+ code="send_now_requires_existing_session",
+ hint="Pass --session-id <session-id>, or omit --send-now for a new or forked Session.",
+ help_command="vibe agent run --help",
+ )
agent_name = (args.agent or "").strip()
if session_policy in {"create", "none"} and not agent_name:
raise TaskCliError(
@@ -4495,6 +4517,20 @@ 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 queue work for an IM-backed Session.",
+ 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,
@@ -4588,6 +4624,7 @@ def cmd_agent_run(args):
parent_run_id=parent_run_id,
callback_session_id=callback_session_id,
callback_active=run_async,
+ delivery_intent=delivery_intent,
metadata=provenance_metadata or None,
)
resolved_scope_id = _scope_id_payload_from_session(session_id)
@@ -4620,6 +4657,12 @@ def cmd_agent_run(args):
"parent_run_id": parent_run_id,
},
}
+ if delivery_intent != AGENT_RUN_DELIVERY_QUEUE:
+ # Keep the long-standing default-queue envelope byte-compatible.
+ # The explicit control intent is surfaced only when the caller opted
+ # into the new behavior.
+ payload["delivery_intent"] = delivery_intent
+ payload["run"]["delivery_intent"] = delivery_intent
if fork_result:
payload["forked_from_session_id"] = fork_result.fork.source_session_id
if fork_result:
@@ -5078,6 +5121,228 @@ def cmd_session_get(args):
return 0
+def cmd_session_send_now(args):
+ """Apply Workbench's Session-level Send now transition without adding work."""
+
+ from core.services import sessions as sessions_service
+ from vibe import internal_client
+
+ session_id = str(getattr(args, "session_id", "") or "").strip()
+ try:
+ 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(
+ TaskCliError(
+ f"session '{session_id}' not found",
+ code="session_not_found",
+ details={"session_id": session_id},
+ ),
+ help_command="vibe session send-now --help",
+ )
+ return 1
+ except internal_client.InternalServerUnavailable as exc:
+ _print_task_error(
+ TaskCliError(
+ "the live Session controller is unavailable",
+ code="internal_unavailable",
+ hint="Keep the queued messages intact and retry after the Avibe service is reachable.",
+ details={"session_id": session_id, "detail": str(exc)},
+ ),
+ help_command="vibe session send-now --help",
+ )
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe session send-now --help")
+ return 1
+
+ raw_status_code = controller_result.get("status_code")
+ try:
+ status_code = int(raw_status_code)
+ except (TypeError, ValueError):
+ status_code = 500
+ body = controller_result.get("body")
+ result = dict(body) if isinstance(body, dict) else {}
+ if not 200 <= status_code < 300 or result.get("ok") is False:
+ code = str(result.get("code") or result.get("status") or "send_now_failed")
+ detail = str(result.get("detail") or result.get("message") or code)
+ _print_task_error(
+ TaskCliError(
+ detail,
+ code=code,
+ hint="The active turn and durable queue were left intact; retry or let the turn finish normally.",
+ details={
+ "session_id": session_id,
+ "controller_status_code": status_code,
+ "controller_response": result,
+ },
+ ),
+ help_command="vibe session send-now --help",
+ )
+ return 1
+
+ _print_cli_payload(
+ "session_send_now",
+ session_id=session_id,
+ status=str(result.get("status") or "unknown"),
+ result=result,
+ )
+ return 0
+
+
+def _queued_agent_run_id(row: dict) -> str | None:
+ metadata = row.get("metadata")
+ if not isinstance(metadata, dict):
+ return None
+ provenance = metadata.get("scheduled_provenance")
+ if not isinstance(provenance, dict):
+ return None
+ platform_specific = provenance.get("platform_specific")
+ if not isinstance(platform_specific, dict):
+ return None
+ if str(platform_specific.get("task_trigger_kind") or "").strip() != "agent_run":
+ return None
+ run_id = str(platform_specific.get("task_execution_id") or "").strip()
+ return run_id or None
+
+
+def _session_queue_row(row: dict, *, position: int) -> dict:
+ return {
+ "position": position,
+ "id": str(row.get("id") or ""),
+ "text": str(row.get("text") or ""),
+ "created_at": row.get("created_at"),
+ "author": row.get("author"),
+ "source": row.get("source"),
+ "run_id": _queued_agent_run_id(row),
+ }
+
+
+def cmd_session_queue_list(args):
+ from core.services import sessions as sessions_service
+ from storage import messages_service
+
+ session_id = str(getattr(args, "session_id", "") or "").strip()
+ try:
+ page_request = _page_request_from_args(
+ args,
+ help_command="vibe session queue list --help",
+ )
+ 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(
+ "queue inspection requires a Web/Workbench Agent Session",
+ code="session_queue_unsupported_target",
+ details={
+ "session_id": session_id,
+ "platform": target.session_key.platform,
+ },
+ )
+ result = messages_service.list_queued_page(
+ conn,
+ session_id,
+ page_request=page_request,
+ )
+ except LookupError:
+ _print_task_error(
+ TaskCliError(
+ f"session '{session_id}' not found",
+ code="session_not_found",
+ details={"session_id": session_id},
+ ),
+ help_command="vibe session queue list --help",
+ )
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe session queue list --help")
+ return 1
+
+ _print_cli_payload(
+ "session_queue",
+ session_id=session_id,
+ queued=[
+ _session_queue_row(
+ row,
+ position=page_request.offset + index,
+ )
+ for index, row in enumerate(result.items, start=1)
+ ],
+ **_paginated_fields(
+ result,
+ command=["vibe", "session", "queue", "list", session_id],
+ ),
+ )
+ return 0
+
+
+def cmd_session_queue_remove(args):
+ from core.services import sessions as sessions_service
+ from storage import messages_service
+ from storage.background import run_update_event_transaction
+
+ session_id = str(getattr(args, "session_id", "") or "").strip()
+ message_id = str(getattr(args, "message_id", "") or "").strip()
+ try:
+ engine = _open_session_engine()
+ with run_update_event_transaction(engine) 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(
+ "queue removal requires a Web/Workbench Agent Session",
+ code="session_queue_unsupported_target",
+ details={
+ "session_id": session_id,
+ "platform": target.session_key.platform,
+ },
+ )
+ removed = messages_service.remove_queued(
+ conn,
+ session_id,
+ message_id,
+ )
+ except LookupError:
+ _print_task_error(
+ TaskCliError(
+ f"session '{session_id}' not found",
+ code="session_not_found",
+ details={"session_id": session_id},
+ ),
+ help_command="vibe session queue remove --help",
+ )
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe session queue remove --help")
+ return 1
+
+ if removed:
+ _post_session_queue_updated_to_live_ui(session_id)
+ _print_cli_payload(
+ "session_queue_remove",
+ session_id=session_id,
+ message_id=message_id,
+ removed=removed,
+ status="removed" if removed else "not_found",
+ )
+ return 0
+
+
def cmd_session_update(args):
from core.services import sessions as sessions_service
@@ -10995,6 +11260,26 @@ def _post_session_activity_to_live_ui(
the DB in a separate process from the in-proc SSE broker, so without this the
rename only shows after a page refresh. Silently no-ops when the UI isn't running
or is unreachable — it must never affect the CLI command's own result."""
+ _post_session_cli_event_to_live_ui(
+ session_id,
+ {
+ "event": "session_updated",
+ "previous_scope_id": previous_scope_id,
+ "previous_visibility": previous_visibility,
+ },
+ )
+
+
+def _post_session_queue_updated_to_live_ui(session_id: str) -> None:
+ """Best-effort queue refresh for Web surfaces after an out-of-process CLI write."""
+
+ _post_session_cli_event_to_live_ui(
+ session_id,
+ {"event": "queue_updated"},
+ )
+
+
+def _post_session_cli_event_to_live_ui(session_id: str, payload: dict) -> None:
from urllib.parse import quote
from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token
@@ -11008,12 +11293,7 @@ def _post_session_activity_to_live_ui(
if not status.get("ui_pid") or not port:
return
url = f"http://{_ui_show_events_host(config)}:{int(port)}/api/sessions/{quote(session_id, safe='')}/cli-activity"
- body = json.dumps(
- {
- "previous_scope_id": previous_scope_id,
- "previous_visibility": previous_visibility,
- }
- ).encode("utf-8")
+ body = json.dumps(payload).encode("utf-8")
http_request = urllib.request.Request(
url,
data=body,
@@ -12367,6 +12647,11 @@ def build_parser():
)
agent_run_parser.add_argument("--agent", help="Avibe Agent name")
agent_run_parser.add_argument("--session-id", help="Existing Agent Session ID to continue")
+ agent_run_parser.add_argument(
+ "--send-now",
+ action="store_true",
+ help="Interrupt the existing Session's active turn and dispatch its FIFO queue head",
+ )
agent_run_parser.add_argument("--fork-session", help="Existing Agent Session ID to fork into a new Session")
agent_run_parser.add_argument("--fork-self", action="store_true", help="Fork this current Agent Session")
agent_run_parser.add_argument("--create-session", action="store_true", help="Create a new Avibe Session ID before running")
@@ -12452,17 +12737,21 @@ def build_parser():
session_parser = subparsers.add_parser(
"session",
- help="List, inspect, and rename Agent sessions",
+ help="Inspect, control, and update Agent sessions",
description=(
"Manage Avibe Agent sessions. 'list' and 'get' are read-only views; "
- "'update' renames a session's title. Archived sessions are soft-deleted "
- "and never surfaced."
+ "'send-now' applies Workbench's queued-head interrupt transition; "
+ "'update' changes title, visibility, or scope. Archived sessions are "
+ "soft-deleted and never surfaced."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe session --help",
error_hint="Run one of the session subcommands below. Start with: vibe session list",
)
- session_subparsers = session_parser.add_subparsers(dest="session_command", metavar="{list,get,update}")
+ session_subparsers = session_parser.add_subparsers(
+ dest="session_command",
+ metavar="{list,get,queue,send-now,update}",
+ )
session_subparsers.required = True
session_list_parser = session_subparsers.add_parser(
"list",
@@ -12489,6 +12778,61 @@ def build_parser():
)
session_get_parser.add_argument("session_id", nargs="?", help="Agent Session ID")
_add_json_noop(session_get_parser)
+ session_send_now_parser = session_subparsers.add_parser(
+ "send-now",
+ help="Interrupt a busy Session and dispatch its existing FIFO queue head",
+ description=(
+ "Apply the same Session-level Send now transition as Workbench without "
+ "adding another message. If the Session is busy, Avibe interrupts the "
+ "active turn and starts the durable FIFO queue head as a new turn. If "
+ "the Session is idle, Avibe starts the queue head directly."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe session send-now --help",
+ )
+ session_send_now_parser.add_argument("session_id", help="Target Agent Session ID")
+ _add_json_noop(session_send_now_parser)
+ session_queue_parser = session_subparsers.add_parser(
+ "queue",
+ help="Inspect or remove queued Session messages",
+ description=(
+ "Inspect a Session's durable FIFO input queue or remove one queued "
+ "message by its stable ID. Queue removal never targets transcript "
+ "messages or reorders the remaining queue."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe session queue --help",
+ )
+ session_queue_subparsers = session_queue_parser.add_subparsers(
+ dest="session_queue_command",
+ metavar="{list,remove}",
+ )
+ session_queue_subparsers.required = True
+ session_queue_list_parser = session_queue_subparsers.add_parser(
+ "list",
+ help="List a Session's queued messages in FIFO order",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe session queue list --help",
+ )
+ session_queue_list_parser.add_argument("session_id", help="Target Agent Session ID")
+ _add_pagination_args(
+ session_queue_list_parser,
+ help_command="vibe session queue list --help",
+ )
+ _add_json_noop(session_queue_list_parser)
+ session_queue_remove_parser = session_queue_subparsers.add_parser(
+ "remove",
+ help="Remove one queued message by stable ID",
+ description=(
+ "Remove one message only when it is still queued in the named "
+ "Session. A stale or cross-Session ID returns removed=false."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe session queue remove --help",
+ )
+ session_queue_remove_parser.add_argument("session_id", help="Target Agent Session ID")
+ session_queue_remove_parser.add_argument("message_id", help="Queued message ID")
+ _add_json_noop(session_queue_remove_parser)
session_update_parser = session_subparsers.add_parser(
"update",
help="Update a session's title, visibility, or scope",
@@ -13636,6 +13980,14 @@ def main():
sys.exit(cmd_session_list(args))
if args.session_command == "get":
sys.exit(cmd_session_get(args))
+ if args.session_command == "queue":
+ if args.session_queue_command == "list":
+ sys.exit(cmd_session_queue_list(args))
+ if args.session_queue_command == "remove":
+ sys.exit(cmd_session_queue_remove(args))
+ parser.error("session queue command is required")
+ if args.session_command == "send-now":
+ sys.exit(cmd_session_send_now(args))
if args.session_command == "update":
sys.exit(cmd_session_update(args))
parser.error("session command is required")
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 279b4229b..3240dd65e 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6749,6 +6749,10 @@ def sessions_cli_activity(session_id: str):
from vibe.sse_broker import broker
payload = request.json or {}
+ if payload.get("event") == "queue_updated":
+ broker.publish("queue.updated", {"session_id": session_id})
+ return jsonify({"ok": True})
+
previous_session = None
if "previous_scope_id" in payload and "previous_visibility" in payload:
previous_session = {
@@ -8281,10 +8285,11 @@ def sessions_queue_list(session_id: str):
def sessions_queue_remove(session_id: str, message_id: str):
"""Drop one queued message (the per-item delete in the queue strip)."""
from storage import messages_service
+ from storage.background import run_update_event_transaction
from vibe.sse_broker import broker
engine = _projects_engine()
- with engine.begin() as conn:
+ with run_update_event_transaction(engine) as conn:
removed = messages_service.remove_queued(conn, session_id, message_id)
if removed:
broker.publish("queue.updated", {"session_id": session_id})