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(org): integrate organization capabilities into master

Maxb93c9d6b286c
diff --cc config/v2_config.py
index ea4c65777,255eada05..549e3f90f
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@@ -7,7 -8,8 +8,8 @@@ import threadin
from dataclasses import dataclass, field, fields
from datetime import datetime
from pathlib import Path
-from typing import List, Literal, Optional, Union
+from typing import List, Literal, Mapping, Optional, Union
+ from urllib.parse import urlsplit, urlunsplit
from config import paths
from config.platform_registry import (
@@@ -1141,10 -1145,36 +1302,36 @@@ class V2Config
avault=avault,
)
+ memory_payload = payload.get("memory") or {}
+ if not isinstance(memory_payload, dict):
+ raise ValueError("Config 'memory' must be an object")
+ memory_processing_payload = memory_payload.get("processing") or {}
+ if not isinstance(memory_processing_payload, dict):
+ raise ValueError("Config 'memory.processing' must be an object")
+ memory_llm_payload = memory_processing_payload.get("llm") or {}
+ memory_embedding_payload = memory_processing_payload.get("embedding") or {}
+ if not isinstance(memory_llm_payload, dict):
+ raise ValueError("Config 'memory.processing.llm' must be an object")
+ if not isinstance(memory_embedding_payload, dict):
+ raise ValueError("Config 'memory.processing.embedding' must be an object")
+ memory = MemoryConfig(
+ enabled=memory_payload.get("enabled", False),
+ embedding_change_pending=memory_payload.get("embedding_change_pending", False),
+ processing=MemoryProcessingConfig(
+ llm=MemoryEndpointConfig(
+ **_filter_dataclass_fields(MemoryEndpointConfig, memory_llm_payload)
+ ),
+ embedding=MemoryEndpointConfig(
+ **_filter_dataclass_fields(MemoryEndpointConfig, memory_embedding_payload)
+ ),
+ ),
+ )
+ memory.validate()
+
model_hub_payload = payload.get("model_hub")
if model_hub_payload is None:
- # Existing installs predate Model Hub and must remain in Direct mode
- # until the user explicitly migrates. Fresh defaults seed Hub mode.
+ # Existing installs predate Model Hub and remain in Direct mode until
+ # the user explicitly opts in after the release capability is enabled.
model_hub = ModelHubConfig()
else:
model_hub = ModelHubConfig.from_payload(model_hub_payload)
diff --cc core/handlers/message_handler.py
index 3427ce874,06e2ec9b6..05030e94a
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@@ -769,263 -674,6 +846,260 @@@ class MessageHandler(BaseHandler)
if callable(mark_complete):
mark_complete(context)
+ async def _admit_human_delivery(
+ self,
+ *,
+ manager: Any,
+ context: MessageContext,
+ dispatch_text: str,
+ display_text: str,
+ processed_files: List[FileAttachment],
+ session_key: str,
+ agent_name: str,
+ session_anchor: str,
+ working_path: str,
+ vibe_agent: Any,
+ delivery_intent: str,
+ downloaded_attachment_paths: List[str],
+ admission_context: dict[str, Any],
+ ) -> bool:
+ """Transfer one IM input to its durable owner before native work."""
+
+ session_id = self.session_handler.ensure_agent_session_id(
+ context,
+ session_key=session_key,
+ agent_name=agent_name,
+ session_anchor=session_anchor,
+ working_path=working_path,
+ vibe_agent_id=getattr(vibe_agent, "id", None),
+ vibe_agent_name=getattr(vibe_agent, "name", None),
+ )
+ if not session_id:
+ raise RuntimeError("Could not reserve the Agent Session before delivery")
+
+ from core.message_priority import priority_for_delivery_intent
+ from core.session_turns import DeliveryRequest
+ from storage import message_deliveries, media_service, messages_service
+ from storage.agent_session_rows import reserve_write_lock
+ from storage.db import get_cached_sqlite_engine
+
+ priority = priority_for_delivery_intent(delivery_intent)
+ scope_id = None
+ request = None
+ duplicate_delivery_id = None
+ try:
+ with get_cached_sqlite_engine().begin() as conn:
+ from core.message_mirror import _scope_id_for_session
+
+ reserve_write_lock(conn)
+ scope_id = _scope_id_for_session(conn, session_id)
+ platform = str(context.platform or "")
+ native_message_id = str(context.message_id or "").strip()
+ if native_message_id and messages_service.native_message_exists(
+ conn,
+ platform=platform,
+ scope_id=scope_id,
+ native_message_id=native_message_id,
+ ):
+ duplicate_delivery_id = ""
+ elif native_message_id:
+ existing = message_deliveries.get_delivery_by_native_identity(
+ conn,
+ platform=platform,
+ native_message_id=native_message_id,
+ scope_id=scope_id,
+ session_id=session_id,
+ normalize_legacy=True,
+ )
+ if existing is not None:
+ duplicate_delivery_id = str(existing["id"])
+
+ if duplicate_delivery_id is None:
+ attachment_refs: list[dict[str, Any]] = []
+ for attachment in processed_files:
+ if not attachment.local_path:
+ continue
+ token = media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind=(
+ "image"
+ if str(attachment.mimetype or "").startswith("image/")
+ else "file"
+ ),
+ source="im_inbound",
+ local_path=attachment.local_path,
+ file_name=attachment.name,
+ content_type=attachment.mimetype,
+ )
+ attachment_refs.append(
+ {
+ "token": token,
+ "name": attachment.name,
+ "mimetype": attachment.mimetype,
+ "size": attachment.size,
+ }
+ )
+
+ if not message_deliveries.has_substantive_input(
+ dispatch_text,
+ has_attachments=bool(attachment_refs),
+ ):
+ raise ValueError(
+ "Message contains no deliverable text or attachment"
+ )
+
+ content = {"text": display_text}
+ if attachment_refs:
+ content["attachments"] = attachment_refs
+ request = DeliveryRequest(
+ session_id=session_id,
+ priority=priority,
+ content=dispatch_text,
+ has_content=True,
+ delivery_id=message_deliveries.new_delivery_id(),
+ scope_id=scope_id,
+ platform=platform,
+ source="user",
+ author="user",
+ message_type="user",
+ author_id=str(context.user_id or "").strip() or None,
+ display_text=display_text,
+ content_json=content,
+ admission_context=admission_context,
+ native_message_id=native_message_id or None,
+ parent_native_message_id=(
+ str(context.thread_id or "").strip() or None
+ ),
+ )
+ reserved = manager.reserve_delivery(conn, request)
+ if str(reserved["id"]) != request.delivery_id:
+ raise RuntimeError(
+ "native Delivery appeared after writer reservation"
+ )
+ except Exception:
+ self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)
+ raise
+
+ if duplicate_delivery_id is not None:
+ self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)
+ if duplicate_delivery_id:
+ payload = dict(context.platform_specific or {})
+ payload["delivery_id"] = duplicate_delivery_id
+ context.platform_specific = payload
+ return True
+
+ if request is None:
+ raise RuntimeError("Delivery reservation did not produce a request")
+ result = await manager.deliver(request, context=context)
+ payload = dict(context.platform_specific or {})
+ payload["delivery_id"] = result.delivery_id
+ context.platform_specific = payload
+ if result.state in {
+ "queued",
+ "pending_steer",
+ "steering",
+ "reconciling_steer",
+ }:
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ return True
+
+ @staticmethod
+ def _cleanup_unowned_attachment_paths(paths: List[str]) -> None:
+ from pathlib import Path
+
+ for path in dict.fromkeys(str(value) for value in paths if value):
+ try:
+ Path(path).unlink(missing_ok=True)
+ except Exception as err:
+ logger.warning("Failed to remove unowned attachment %s: %s", path, err)
+
+ def _is_duplicate_human_delivery(self, context: MessageContext) -> bool:
+ """Reject a retried native event before pre-admission side effects."""
+
+ if self._native_human_event_processed(context):
+ return True
+ platform = str(context.platform or "").strip()
+ native_message_id = str(context.message_id or "").strip()
+ if not platform or not native_message_id:
+ return False
+ try:
+ from storage import message_deliveries, messages_service
+ from storage.db import get_cached_sqlite_engine
+ from core.message_mirror import scope_id_for_context
+
+ scope_id = scope_id_for_context(context)
+
+ with get_cached_sqlite_engine().connect() as conn:
+ if messages_service.native_message_exists(
+ conn,
+ platform=platform,
+ scope_id=scope_id,
+ native_message_id=native_message_id,
+ ):
+ return True
+ return bool(
+ message_deliveries.get_delivery_by_native_identity(
+ conn,
+ platform=platform,
+ native_message_id=native_message_id,
+ scope_id=scope_id,
+ )
+ is not None
+ )
+ except Exception:
+ logger.exception(
+ "Could not preflight native Message dedupe for %s:%s",
+ platform,
+ native_message_id,
+ )
+ return False
+
+ def _native_human_event_processed(self, context: MessageContext) -> bool:
+ message_ts = context.message_id
+ thread_ts = context.thread_id or context.message_id
+ if not message_ts or not thread_ts:
+ return False
++ dedup_keys = self._processed_message_dedup_keys(context, thread_ts, message_ts)
++ legacy_keys = (str(context.channel_id), thread_ts, message_ts)
++ if self._claimed_before_dedup_namespacing(dedup_keys, legacy_keys):
++ return True
+ checker = getattr(self.sessions, "has_processed_message", None)
+ if callable(checker):
- return bool(checker(context.channel_id, thread_ts, message_ts))
++ return bool(checker(*dedup_keys))
+ checker = getattr(self.sessions, "is_message_already_processed", None)
- return bool(
- callable(checker)
- and checker(context.channel_id, thread_ts, message_ts)
- )
++ return bool(callable(checker) and checker(*dedup_keys))
+
+ def _claim_native_human_event(self, context: MessageContext) -> bool:
+ """Fence a native control input that intentionally creates no Delivery."""
+
+ message_ts = context.message_id
+ thread_ts = context.thread_id or context.message_id
+ if not message_ts or not thread_ts:
+ return True
++ dedup_keys = self._processed_message_dedup_keys(context, thread_ts, message_ts)
++ legacy_keys = (str(context.channel_id), thread_ts, message_ts)
+ try_record = getattr(self.sessions, "try_record_processed_message", None)
- if callable(try_record):
- recorded = try_record(context.channel_id, thread_ts, message_ts)
++ if self._claimed_before_dedup_namespacing(dedup_keys, legacy_keys):
++ recorded = False
++ elif callable(try_record):
++ recorded = try_record(*dedup_keys)
+ else:
- recorded = not self.sessions.is_message_already_processed(
- context.channel_id,
- thread_ts,
- message_ts,
- )
++ recorded = not self.sessions.is_message_already_processed(*dedup_keys)
+ if recorded:
- self.sessions.record_processed_message(
- context.channel_id,
- thread_ts,
- message_ts,
- )
++ self.sessions.record_processed_message(*dedup_keys)
+ if not recorded:
+ logger.info(
+ "Skipping already processed message: channel=%s, thread=%s, message=%s",
+ context.channel_id,
+ thread_ts,
+ message_ts,
+ )
+ return bool(recorded)
+
@staticmethod
def _build_agent_request(**kwargs: Any) -> AgentRequest:
try:
diff --cc core/handlers/session_handler.py
index f0ce7dd5e,970126ac1..164891950
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@@ -296,7 -287,25 +302,25 @@@ class SessionHandler(BaseHandler)
agent_name="claude",
session_anchor=base_session_id,
)
+ next_agent_system_prompt = agent_system_prompt
+ if next_agent_system_prompt is None:
+ agent_data = self._load_agent_file(effective_agent, working_path)
+ next_agent_system_prompt = agent_data.get("prompt") if agent_data else None
+ next_system_prompt = self._build_claude_system_prompt(
+ context=context,
+ session_key=session_key,
+ agent_name="claude",
+ session_anchor=base_session_id,
+ agent_system_prompt=next_agent_system_prompt,
+ )
+ if self.claude_system_prompts.get(composite_key) != next_system_prompt:
+ logger.info(
+ "Recreating cached Claude subagent SDK client for %s because avibe system prompt changed",
+ composite_key,
+ )
+ await self.cleanup_session(composite_key)
+ return None
- caller_env = caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+ caller_env = self._caller_env_for_context(context)
if getattr(client, "_vibe_caller_env", {}) != caller_env:
logger.info(
"Recreating cached Claude subagent SDK client for %s because caller context env changed",
diff --cc core/internal_server.py
index a713fa52b,10c5853f5..73bbc51f1
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@@ -31,7 -35,9 +34,10 @@@ import jso
import logging
import os
import socket
+ import stat
+ import tempfile
+ import time
+from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, TYPE_CHECKING
@@@ -73,9 -112,14 +113,14 @@@ def create_app
Factored out so tests can mount the same routes against a fake
controller without spinning up uvicorn.
"""
- from core.inbox_events import bus, mark_controller_process
+ from core.inbox_events import mark_controller_process
mark_controller_process()
+ if memory_ui_secret is None:
+ from core.memory.ui_access import process_ui_read_secret
+
+ memory_ui_secret = process_ui_read_secret()
+ from core.memory.runtime import MemoryStoreUnavailableError
app = FastAPI(
title="avibe internal dispatch",
@@@ -1046,22 -1104,11 +1426,24 @@@ async def _build_dispatch_payload(paylo
channel_id=payload.get("channel_id"),
platform=payload.get("platform"),
thread_id=payload.get("thread_id"),
- message_id=payload.get("message_id"),
+ message_id=payload.get("message_id") or payload.get("user_message_id"),
files=files,
+ memory_cli_admitted=payload.get("memory_cli_admitted") is True,
+ is_ordinary_text=payload.get("is_ordinary_text") is True,
)
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(
+ {
+ "delivery_id": payload.get("user_message_id"),
+ "scope_id": payload.get("scope_id"),
+ "display_text": payload.get("display_text"),
+ "message_content": payload.get("content"),
+ "message_metadata": payload.get("metadata") or {},
+ "author_id": payload.get("author_id"),
+ "author_name": payload.get("author_name"),
+ }
+ )
return text, context
@@@ -1074,38 -1121,28 +1456,43 @@@ def _build_session_context
thread_id: Optional[str] = None,
message_id: Optional[str] = None,
files: Optional[list] = None,
+ memory_cli_admitted: bool = False,
+ is_ordinary_text: bool = False,
) -> MessageContext:
- """Build the avibe ``MessageContext`` for a workbench session.
+ """Rebuild a Session's routing context from its durable scope and target.
Shared by the dispatch endpoint and the cancel endpoint so a stop reuses
the exact same session-routing context (chosen agent / model / effort,
native session id, workdir) the turn ran under — that's what lets cancel
reuse the IM ``/stop`` path to interrupt the right backend session.
- Defaults to ``platform="avibe"``.
+ Workbench and IM Sessions use the same builder; Delivery hydration adds the
+ exact sender and native Message identity afterward.
"""
- # ``agent_session_id`` is the agent_sessions PK; persist_agent_message reads
- # it to attribute avibe agent replies to the right session (IM stamps it at
- # session-resolve time). For avibe the dispatch session_id IS that PK.
+ from core.scheduled_tasks import resolve_session_id_target
+
+ target_info = resolve_session_id_target(session_id)
+ session_row = _lookup_session(session_id)
+ resolved_platform = platform or target_info.session_key.platform or "avibe"
+ is_dm = target_info.session_key.scope_type == "user"
+ resolved_channel_id = channel_id or (
+ session_id
+ if resolved_platform == "avibe"
+ else target_info.session_key.scope_id
+ )
+ resolved_user_id = user_id or (
+ target_info.session_key.scope_id if is_dm else "workbench"
+ )
platform_specific: dict[str, Any] = {
- "workbench_session_id": session_id,
"agent_session_id": session_id,
+ "platform": resolved_platform,
+ "is_dm": is_dm,
}
+ if resolved_platform == "avibe":
+ platform_specific["workbench_session_id"] = session_id
+ if memory_cli_admitted:
+ platform_specific["memory_cli_admitted"] = True
+ session_row = _lookup_session(session_id)
if session_row is not None:
target = {
"id": session_row.get("id"),
diff --cc core/scheduled_tasks.py
index 825b2dbed,61daceb7b..b94b4498c
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@@ -1496,13 -708,13 +1496,18 @@@ class ScheduledTaskStore
cron: Optional[str] = None,
run_at: Optional[str] = None,
timezone_name: str,
+ shell_command: Optional[str] = None,
+ command: Optional[list[str]] = None,
+ timeout_seconds: Optional[float] = None,
metadata: Optional[dict[str, Any]] = None,
+ expected_enabled_agent_id: Optional[str] = None,
+ expected_reference_agent_id: Optional[str] = None,
+ user_context: Any = None,
) -> ScheduledTask:
+ from core.vibe_agents import ensure_agent_name_access
+ from storage.resource_access_service import metadata_with_resource_user_context
+
+ ensure_agent_name_access(agent_name, user_context=user_context)
task = ScheduledTask(
id=uuid4().hex[:12],
name=name,
@@@ -1518,26 -730,11 +1523,26 @@@
cron=cron,
run_at=run_at,
timezone=timezone_name,
- metadata=dict(metadata or {}),
+ metadata=metadata_with_resource_user_context(metadata, user_context),
+ shell_command=shell_command,
+ command=command,
+ timeout_seconds=timeout_seconds,
+ )
+ return self.upsert_task(
+ task,
+ expected_enabled_agent_id=expected_enabled_agent_id,
+ expected_reference_agent_id=expected_reference_agent_id,
)
- return self.upsert_task(task)
def remove_task(self, task_id: str) -> bool:
+ """Delete a task; the mirror rolls back with the delete (HFR-275).
+
+ The safer direction of the same class -- an entry dropped here reads as "gone"
+ and stops the schedule -- but silently, and NOT self-healing: with the row still
+ there and unchanged, ``maybe_reload`` sees no external write, so the task the user
+ was told could not be deleted just stops firing until the process restarts.
+ """
+
if task_id not in self._tasks:
return False
del self._tasks[task_id]
@@@ -1581,19 -772,14 +1586,24 @@@
session_policy: Optional[str] = None,
cwd: Optional[str] = None,
update_cwd: bool = False,
+ shell_command: Optional[str] = None,
+ command: Optional[list[str]] = None,
+ timeout_seconds: Optional[float] = None,
+ update_command_fields: bool = False,
metadata: Optional[dict[str, Any]] = None,
+ expected_enabled_agent_id: Optional[str] = None,
+ expected_reference_agent_id: Optional[str] = None,
+ user_context: Any = None,
) -> ScheduledTask:
+ from core.vibe_agents import ensure_agent_name_access
+ from storage.resource_access_service import metadata_with_resource_user_context
+
+ ensure_agent_name_access(agent_name, user_context=user_context)
task = self._tasks[task_id]
+ # Captured before the first mutation: this is the state the CALLER read
+ # (``vibe task update`` resolved Agents and Sessions from this very object),
+ # and it is what the write below re-asserts.
+ expect = self._read_state(task)
task.name = name
task.session_key = session_key
task.session_id = session_id
@@@ -1610,147 -796,18 +1620,149 @@@
task.cron = cron
task.run_at = run_at
task.timezone = timezone_name
+ if update_command_fields:
+ # Gated like ``cwd``: an edit that says nothing about the command must not
+ # clear it, and ``last_exit_code`` is runtime state no edit ever rewrites.
+ task.shell_command = shell_command
+ task.command = command
+ task.timeout_seconds = timeout_seconds
- if metadata is not None:
- task.metadata = dict(metadata)
+ task.metadata = metadata_with_resource_user_context(
+ metadata if metadata is not None else task.metadata,
+ user_context,
+ )
task.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_scheduled_task(task.to_dict())
- return task
- self._save()
+ if not self._write_task(
+ task,
+ expect,
+ expected_enabled_agent_id=expected_enabled_agent_id,
+ expected_reference_agent_id=expected_reference_agent_id,
+ ):
+ # The edit did NOT land, and its payload would have restored the Session
+ # binding, enabled state and reclaim snapshot the teardown just changed.
+ # Raising is the contract: ``cmd_task_update`` prints an error and exits
+ # non-zero instead of echoing a task the database never accepted.
+ raise DefinitionWriteConflict(task_id, definition_type="scheduled task")
+ if expected_reference_agent_id is not None:
+ self.load()
+ return self._tasks[task_id]
return task
- def mark_task_result(self, task_id: str, *, error: Optional[str], disable_one_shot: bool = True) -> bool:
+ def record_binding_recovery(
+ self,
+ task_id: str,
+ payload: dict[str, Any],
+ *,
+ binding_notice: Optional[dict[str, Any]] = None,
+ ) -> bool:
+ """Durably stamp what was done about a broken session binding.
+
+ Written through the store (not by mutating a task the next
+ ``maybe_reload`` may replace) because it is what makes the notification
+ once-per-transition instead of once-per-fire. When a successful rebind
+ needs its own notice, both rows commit in one SQLite transaction: a failed
+ notice write therefore cannot leave a marker that suppresses every retry.
+ """
+
+ self.maybe_reload()
+ task = self._tasks.get(task_id)
+ if task is None:
+ return False
+ expect = self._read_state(task)
+ metadata = dict(task.metadata or {})
+ metadata[BINDING_RECOVERY_METADATA_KEY] = dict(payload)
+ task.metadata = metadata
+ task.updated_at = _utc_now_iso()
+ # A runtime stamp, not a user action: a lost write is reported by the return
+ # value (the caller already treats ``False`` as "nothing recorded") rather than
+ # by an exception through the fire path.
+ if self._sqlite is not None and binding_notice is not None:
+ try:
+ landed = self._sqlite.upsert_scheduled_task_with_binding_notice(
+ task.to_dict(),
+ expect=expect,
+ notice=binding_notice,
+ )
+ except Exception:
+ self._reload_after_lost_write(task.id)
+ raise
+ if landed:
+ return True
+ self.load()
+ return False
+ return self._write_task(task, expect)
+
+ def list_orphaned_reservations(self, task_id: str) -> list[dict[str, Any]]:
+ """The reserved sessions recorded against ``task_id`` that were never given back."""
+
+ task = self._tasks.get(task_id)
+ if task is None or not isinstance(task.metadata, dict):
+ return []
+ entries = task.metadata.get(ORPHANED_RESERVATIONS_METADATA_KEY)
+ if not isinstance(entries, list):
+ return []
+ return [dict(entry) for entry in entries if isinstance(entry, dict)]
+
+ def record_orphaned_reservations(self, task_id: str, entries: list[dict[str, Any]]) -> bool:
+ """Durably record (or clear) the reservations this definition could not release.
+
+ HFR-276. Written through the store, from a FRESH read, for the same reason
+ ``record_binding_recovery`` is: the caller reaches here on a path where the
+ previous full-row write was already refused, so the mirror it holds is stale
+ and ``_write_task`` has since reloaded the cache. Deriving the expectation from
+ the reloaded row is what makes this write land in the very race that produced
+ the orphan, instead of being refused by the same teardown twice.
+
+ ``False`` means nothing was recorded -- the definition was removed, or a second
+ teardown refused this write too -- and the caller MUST consume it: the whole
+ point of the record is that the id is otherwise unrecoverable, so silently
+ losing it is the same defect one layer further in.
+ """
+
+ self.maybe_reload()
+ task = self._tasks.get(task_id)
+ if task is None:
+ return False
+ expect = self._read_state(task)
+ metadata = dict(task.metadata or {})
+ if entries:
+ metadata[ORPHANED_RESERVATIONS_METADATA_KEY] = [dict(entry) for entry in entries]
+ else:
+ metadata.pop(ORPHANED_RESERVATIONS_METADATA_KEY, None)
+ task.metadata = metadata
+ task.updated_at = _utc_now_iso()
+ return self._write_task(task, expect)
+
+ def mark_task_result(
+ self,
+ task_id: str,
+ *,
+ error: Optional[str],
+ disable_one_shot: bool = True,
+ expected_binding: Optional[tuple[Optional[str], str, str]] = None,
+ exit_code: Optional[int] = None,
+ records_command_outcome: bool = False,
+ timed_out: bool = False,
+ queued_run: Optional[dict[str, Any]] = None,
+ expected_uncanceled_run_id: Optional[str] = None,
+ ) -> bool:
+ """Stamp a fire's outcome; ``False`` means the store refused the write.
+
+ ``queued_run`` is the outbox row this stamp AUTHORISES -- today the
+ ``--on-failure agent`` escalation turn. Passing it makes the stamp and the turn
+ ONE transaction (HFR-269): both land or neither does, so no teardown can commit
+ between them and a failed one-shot ``at`` task cannot be disabled while losing
+ the report that explains why.
+
+ ``records_command_outcome`` marks the ONE stamp that is a command fire's own
+ result, and it is what makes ``exit_code`` authoritative in both directions --
+ see the write below.
+
+ ``expected_uncanceled_run_id`` re-asserts, inside that same transaction, that
+ the fire being stamped has not been stopped -- see
+ ``upsert_scheduled_task_with_queued_run``. Only meaningful alongside
+ ``queued_run``, because it exists to stop a stopped run queuing an Agent turn.
+ """
+
self.maybe_reload()
task = self._tasks.get(task_id)
if task is None:
@@@ -4537,3614 -2066,581 +4549,3625 @@@ class ScheduledTaskService
self.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)
self._drain_dirty = True
- def settle_activity_runs(self, activity: Any) -> list[str]:
- """Settle deferred Runs when a failed/stopped owned Activity is last."""
-
- activity_status = str(getattr(activity, "status", "") or "").strip().lower()
- if activity_status == "completed":
- # A completed Claude task may still produce a user-visible follow-up;
- # that Message owns Run settlement so output and callback stay aligned.
- return []
- terminal_status = "failed" if activity_status == "failed" else "canceled"
- metadata = getattr(activity, "metadata", None) or {}
- run_ids: list[str] = []
- primary = str(getattr(activity, "run_id", "") or "").strip()
- if primary:
- run_ids.append(primary)
- values = metadata.get("run_ids") if isinstance(metadata, dict) else None
- if isinstance(values, list):
- for value in values:
- run_id = str(value or "").strip()
- if run_id and run_id not in run_ids:
- run_ids.append(run_id)
+ # --- the owed-failure-notice drain ---------------------------------------
+ #
+ # Rides the existing 2 s tick beside ``_drain_callbacks``, for the same reason:
+ # a failed run emits no store change anyone else notices, so only a periodic
+ # pass finds it. The durable notice is stamped by whichever UPDATE terminalizes
+ # the row, so a crash between the failure and the delivery loses nothing — which
+ # is the whole point of persisting it rather than notifying inline.
+
+ def _spawn_failure_notice_drain(self) -> None:
+ """Start the owed-notice drain OUTSIDE the store watch, one pass at a time.
+
+ ``_watch_store`` is a single coroutine running every periodic pass in sequence,
+ so awaiting the drain there puts external message delivery on the critical path
+ of the whole service tick. One notice whose delivery does not return stops
+ request draining, callbacks, vault callbacks, the stale-run sweep — and every
+ LATER notice, including the ones reporting the failures that wedge is a symptom
+ of. Nothing looks broken, because the loop is suspended rather than crashed.
+
+ ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` alone would only shorten that stall to the
+ deadline, and a deadline short enough to hold the tick would cancel legitimate
+ deliveries. So the two halves are both required: dispatch takes delivery off the
+ watch, and the deadline bounds the dispatched work.
+
+ SINGLE-FLIGHT is the other half of dispatching. A task per tick would replace a
+ stalled loop with a delivery attempt every 2 s — the durable claim would make
+ most of them stand down, but the pile of coroutines is unbounded and each one
+ re-reads and re-claims. One pass at a time, and a tick that finds the previous
+ pass still running simply skips: the drain is idempotent across ticks by
+ construction, since eligibility is re-read from the row every pass.
+ """
- registry = getattr(getattr(self.controller, "agent_service", None), "activities", None)
- has_blocker = getattr(registry, "has_blocking_run_activity", None)
- has_pending_output = getattr(registry, "has_pending_run_output", None)
- settled: list[str] = []
- for run_id in run_ids:
- self.request_store.defer_run_terminal(
- run_id,
- terminal_status=terminal_status,
- )
- if callable(has_blocker) and has_blocker(run_id):
- continue
- if callable(has_pending_output) and has_pending_output(run_id):
- continue
- error = f"Background Activity {getattr(activity, 'id', '')} {activity_status}"
- if self.request_store.settle_deferred_run(
- run_id,
- error=error,
- ):
- settled.append(run_id)
- if settled:
- self._drain_dirty = True
- return settled
+ task = self._notice_drain_task
+ if task is not None and not task.done():
+ return
+ self._notice_drain_task = asyncio.create_task(self._drain_failure_notices())
+ self._notice_drain_task.add_done_callback(self._on_notice_drain_done)
- async def _drain_vault_callbacks(self) -> None:
- """Auto-resume the requesting session when a vault request reaches a terminal state.
+ @staticmethod
+ def _on_notice_drain_done(task: "asyncio.Task[Any]") -> None:
+ """Retrieve the dispatched pass's exception so it is logged, never swallowed.
- Mirrors :meth:`_drain_callbacks` but for ``vault_requests`` (which resolve outside the run
- store): each row marked ``callback_status='pending'`` is turned into one callback turn via
- the shared :func:`enqueue_session_callback` entry, then marked ``sent``/``skipped``/
- ``failed``. Delivery is at-least-once, matching the run-store callback drain: enqueue and
- the ``sent`` mark are separate writes, so a crash between them re-sends on the next tick.
- Per-row isolation keeps one bad row from aborting the batch or being retried forever.
+ The inline await propagated failures into the watch's own handler. A fire-and-
+ forget task has no such reader, and an unretrieved exception surfaces only as an
+ asyncio "never retrieved" warning at garbage-collection time — which is how a
+ drain that has been failing every tick for a week goes unnoticed.
"""
- if not self._owns_service_instance():
+
+ if task.cancelled():
return
- from storage import vault_service
+ exc = task.exception()
+ if exc is not None:
+ logger.error("owed failure notice drain pass failed: %r", exc, exc_info=exc)
- # Runs every tick, so use the process-local cached engine (never dispose it) rather than
- # allocating a fresh engine per sweep.
- engine = get_cached_sqlite_engine(paths.get_sqlite_state_path())
+ async def _drain_failure_notices(self) -> None:
+ if not self._owns_service_instance():
+ return
+ store = self.request_store._sqlite
+ if store is None:
+ return
try:
- with engine.begin() as conn:
- # Expiry is lazy (only on request reads), so proactively expire overdue pending
- # requests here — otherwise an unattended timed-out request would never arm its
- # callback until some unrelated read touched it. Both happen in one pass.
- vault_service.expire_overdue_requests(conn)
- pending = vault_service.list_pending_request_callbacks(conn)
- except Exception as exc:
- logger.error("Vault request callback sweep failed to load: %s", exc, exc_info=True)
+ owed = store.list_owed_failure_notices(limit=10)
+ except Exception:
+ logger.exception("failed to list owed failure notices")
return
- for row in pending:
- request_id = str(row.get("id") or "")
- if not request_id:
+ # THE FAIRNESS BUDGET, checked between notices and never against one in flight.
+ #
+ # Deliveries inside a pass are serial on purpose (see
+ # ``NOTICE_DRAIN_PASS_BUDGET_SECONDS``), so a batch of wedged rows costs
+ # batch x deadline before the pass returns and every notice stamped in the
+ # meantime waits behind it. Truncating the pass bounds that wait by the budget
+ # plus one delivery instead of by the batch size.
+ #
+ # Between, not during: cancelling a delivery already on the wire would trade a
+ # slow pass for a duplicate, and the walk already has its own deadline. So the
+ # pass always finishes what it started and only stops PULLING more.
+ #
+ # Rows left behind cost nothing — unclaimed, so no attempt consumed and no
+ # backoff armed — and ``list_owed_failure_notices`` orders by
+ # ``next_attempt_at ASC``, so the next pass starts with the oldest of them.
+ started = time.monotonic()
+ budget = failure_notices.NOTICE_DRAIN_PASS_BUDGET_SECONDS
+ for index, run in enumerate(owed):
+ if index and time.monotonic() - started > budget:
+ logger.info(
+ "owed failure notice pass stopped at its %ss budget with %d of %d "
+ "notices unattempted; they keep their attempts and stay eligible",
+ budget,
+ len(owed) - index,
+ len(owed),
+ )
+ break
+ run_id = str(run.get("id") or "")
+ if not run_id:
continue
- # Resolve + enqueue as one guarded step so a bad row is marked (not left to retry
- # forever) and does not abort the rest of the batch.
- status = "skipped"
- try:
- with engine.begin() as conn:
- ready = vault_service.request_callback_ready(conn, row)
- if not ready:
- # Approved access grant not delivery-ready yet (protected relay in flight);
- # leave callback_status='pending' and retry on a later tick.
- continue
- plan = vault_service.resolve_request_callback(row)
- if plan is not None:
- enqueue_session_callback(
- self.request_store,
- session_id=plan.session_id,
- message=plan.message,
- source_actor=f"vault:{request_id}",
- )
- status = "sent"
- except ValueError:
- status = "skipped" # session archived / not a valid target — nothing to resume
- except Exception as exc:
- logger.error("Vault request callback failed for %s: %s", request_id, exc, exc_info=True)
- status = "failed"
try:
- with engine.begin() as conn:
- vault_service.mark_request_callback(conn, request_id, status=status)
- except Exception as exc:
- # Leave callback_status='pending' → retried next tick (bounded, transient).
- logger.error("Vault request callback mark failed for %s: %s", request_id, exc, exc_info=True)
- continue
- if status == "sent":
- # A callback run was enqueued into the run store; drain it promptly.
- self._drain_dirty = True
-
- def _enqueue_callback_run(self, run: dict[str, Any]) -> Optional[TaskExecutionRequest]:
- callback_session_id = str(run.get("callback_session_id") or "").strip()
- if not callback_session_id:
- return None
- run_id = str(run.get("id") or "")
- explicit_delivery = self.request_store.find_explicit_session_delivery(
- parent_run_id=run_id,
- session_id=callback_session_id,
- )
- if explicit_delivery is not None:
- # A lane may explicitly report to its callback Session before its
- # terminal result. That accepted child Run is the callback delivery;
- # do not echo the same final through the automatic fallback too.
- return TaskExecutionRequest.from_dict(explicit_delivery)
- status = _normalize_requested_run_status(run.get("status")) or str(
- run.get("status") or ""
- )
- if status in {"failed", "canceled"}:
- terminal_message = self._fallback_callback_result(run, status=status)
- terminal_callback = enqueue_session_callback(
- self.request_store,
- session_id=callback_session_id,
- message=terminal_message,
- source_actor=f"{run_id}:terminal:{status}",
- parent_run_id=run_id or None,
+ await self._deliver_one_failure_notice(store, run)
+ except Exception:
+ logger.exception("owed failure notice drain failed for run=%s", run_id)
+
+ async def _deliver_one_failure_notice(self, store: Any, run: dict[str, Any]) -> None:
+ run_id = str(run["id"])
+ definition_id = str(run.get("task_id") or run.get("definition_id") or "") or None
+ notice = store.owed_failure_notice(run_id)
+ # Re-read and re-check ELIGIBILITY, not merely the state. The batch was listed
+ # before this pass began and each row is then delivered one at a time, so by
+ # the time a row is reached another owner may already have claimed it — and a
+ # claim is expressed as ``pending`` plus a lease on ``next_attempt_at``, so a
+ # state-only check would read it as free and send a duplicate. This is the same
+ # predicate the listing query used, deliberately: whatever the claim writes has
+ # to be visible to every later reader through one shared definition of
+ # eligibility.
+ now = datetime.now(timezone.utc)
+ if not owed_notice_eligible(notice, now.isoformat()):
+ return
+ # Every write below re-asserts the notice this pass DECIDED FROM. Ownership is
+ # checked once, at the top of the pass, and then the pass awaits delivery — so a
+ # service-lock handoff can leave this coroutine writing behind the new owner's
+ # completed delivery. The expectation makes the loser a no-op instead.
+ expect = notice_write_expectation(notice)
+
+ streak_facts: Optional[dict[str, Any]] = None
+ earlier_unsettled = None
+ # ``bypasses_suppression``, not ``is_interruption``: a binding-change notice is
+ # already scoped by the transition's signature, and reading the streak for one
+ # would be actively wrong — the anchor run SUCCEEDED, so
+ # ``failure_streak_decision`` would sweep in the definition's surrounding
+ # failures and defer the notice behind a canonical row it has nothing to do
+ # with.
+ if definition_id and not failure_notices.bypasses_suppression(notice):
+ earlier_unsettled = store.earliest_unsettled_run_before(
+ definition_id,
+ created_at=str(run.get("created_at") or ""),
+ run_id=run_id,
+ stale_after_seconds=failure_notices.DEFERRAL_STALE_AFTER_SECONDS,
)
- if terminal_callback is not None:
- return terminal_callback
- return enqueue_session_callback(
- self.request_store,
- session_id=callback_session_id,
- message=self._build_callback_message(run),
- source_actor=run_id,
- parent_run_id=run_id or None,
+ if earlier_unsettled is None:
+ # The DECISION facts, not the streak's rows. One statement, so the
+ # boundaries and the notice states inside them come from one SQLite
+ # read snapshot: read separately, a success settling between the
+ # boundary seek and the row read merges two streaks, and a ``sent``
+ # notice from the earlier outage then skips a live one.
+ streak_facts = store.failure_streak_decision(definition_id, run_id)
+
+ # The callback's status is read FRESH, not taken from the listed row: the
+ # batch predates this decision by up to a whole pass, and ``_drain_callbacks``
+ # runs on the same ticks — a stale ``pending`` here would defer a notice whose
+ # callback already landed, and a stale absence would deliver beside it. A
+ # read failure propagates to the drain loop's per-row handler and the row is
+ # retried later, which errs toward one message rather than two.
+ decision = failure_notices.decide(
+ run_id=run_id,
+ definition_id=definition_id,
+ notice=notice,
+ streak_facts=streak_facts,
+ earlier_unsettled=earlier_unsettled,
+ callback_status=store.run_callback_state(run_id),
)
+ if decision.action == failure_notices.ACTION_DEFER:
+ # No attempt consumed — this row has not been tried. But the deferral is
+ # written down rather than merely skipped: a row left immediately-eligible
+ # is re-selected by every tick and keeps occupying the batch, so one
+ # definition with more than a batch worth of pending failures starved
+ # every other definition's notices indefinitely.
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ next_attempt_at=(
+ datetime.now(timezone.utc)
+ + timedelta(seconds=failure_notices.DEFERRAL_RECHECK_SECONDS)
+ ).isoformat(),
+ defer_reason=decision.reason,
+ )
+ logger.debug("failure notice for %s deferred (%s)", run_id, decision.reason)
+ return
+ if decision.action == failure_notices.ACTION_SKIP:
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_SKIPPED,
+ skip_reason=decision.reason,
+ )
+ return
- def _build_callback_message(self, run: dict[str, Any]) -> str:
- status = _normalize_requested_run_status(run.get("status")) or str(run.get("status") or "")
- result_text = str(run.get("result_text") or "").strip()
- if not result_text:
- result_text = self._fallback_callback_result(run, status=status)
- return result_text.strip()
-
- @staticmethod
- def _fallback_callback_result(run: dict[str, Any], *, status: str) -> str:
- parts: list[str] = []
- if run.get("error"):
- parts.append(f"Error: {run['error']}")
- if run.get("stderr"):
- parts.append(str(run["stderr"]))
- if run.get("stdout") and status != "succeeded":
- parts.append(str(run["stdout"]))
- if parts:
- return "\n\n".join(part.strip() for part in parts if part and part.strip())
- if status == "canceled":
- return "The run was canceled before producing a result."
- if status == "failed":
- return "The run failed before producing a result."
- return ""
+ attempt, retry_after = failure_notices.next_attempt(notice)
- def _execution_lock_key(self, request: TaskExecutionRequest) -> Optional[str]:
- """Canonical conversation identity for per-session single-flight.
+ # THE CLAIM, and it must precede the external side effect.
+ #
+ # This one guarded UPDATE does two things at once: it CONSUMES the attempt (so
+ # the number is durable before anything can go wrong with the send — the bound
+ # the raising-rung handler below exists to keep) and it arms a LEASE on
+ # ``next_attempt_at`` marking the row as somebody's until that instant.
+ #
+ # Why here and not after the send. Ownership is checked once per pass and then
+ # the pass AWAITS delivery, so two owners can both hold a listed row: they both
+ # read ``pending``, both walk the ladder, both send, and only then does either
+ # write. A predicate on the write catches the second WRITE and nothing else —
+ # the user already has two messages, and no database can recall one. Nothing
+ # downstream closes it either: ``emit_agent_message`` checks
+ # ``agent_message_exists`` BEFORE the send and persists AFTER it, so both owners
+ # pass that lookup while neither receipt exists. Single-flight has to be
+ # established before the irreversible act, which means before this line.
+ #
+ # The primitive is the CAS that is already here. SQLite evaluates ``expect`` in
+ # the writing statement under its single-writer lock, so a guarded transition
+ # from ``(pending, N)`` is atomic across connections and processes — exactly an
+ # atomic claim, just used earlier. An owner that read before this write loses
+ # the CAS; one that reads after it sees the lease and stands down at the
+ # eligibility check at the top of this method.
+ #
+ # And because the lease is an INSTANT rather than a held lock, a claimant that
+ # dies mid-send releases it by expiry: ``CLAIM_LEASE_SECONDS`` is the recovery
+ # bound, and the recovered pass consumes its own attempt rather than inheriting
+ # the dead one, so the retry ladder stays finite. The residual is at-least-once
+ # delivery, documented on that constant.
+ claimed = store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ attempts=attempt,
+ # Armed at CLAIM time, not from the instant the eligibility check read:
+ # the streak reads above sit between the two, and the lease has to bound
+ # the delivery that is about to start rather than one that already has.
+ next_attempt_at=(
+ datetime.now(timezone.utc)
+ + timedelta(seconds=failure_notices.CLAIM_LEASE_SECONDS)
+ ).isoformat(),
+ )
+ if claimed is None:
+ # Another owner moved this row between our read and our claim. Nothing to
+ # repair and nothing to report: the winner is delivering it, and this pass
+ # must not send. Silent for the same reason the losing write is — a lock
+ # handoff is normal, and an error here would be logged on every one.
+ logger.debug("failure notice for %s already claimed by another owner", run_id)
+ return
+ # Every write below re-asserts what the CLAIM left behind, not what was read
+ # before it.
+ expect = notice_write_expectation(claimed)
- Resolves task-only and session-id-only requests down to one canonical
- key so any two requests targeting the same conversation serialize,
- regardless of which identifier form they carry:
+ evidence = DeliveryEvidence()
+ # THE DEADLINE, over the whole ladder walk rather than one rung.
+ #
+ # The claim above makes a competing owner stand down for the lease, and lease
+ # expiry recovers a claimant that DIES. Neither covers one that never returns:
+ # a transport that accepted the request and hung leaves this coroutine
+ # suspended with the row ineligible and nothing reporting it, so the notice is
+ # owed indefinitely. See ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` for the two-sided
+ # argument for the value; what matters here is the scope and the disposal.
+ #
+ # Scope is the WALK, not the rung: a per-rung bound would let five slow rungs
+ # add up past the lease, and the thing being bounded is how long this claim can
+ # be held.
+ #
+ # Disposal: ``wait_for`` cancels the inner task and AWAITS that cancellation
+ # before raising, so the transport coroutine is dead — not detached to send
+ # behind a replacement claimant's back — by the time the handler below writes
+ # anything. ``asyncio.wait_for`` rather than ``asyncio.timeout`` because the
+ # package supports 3.10, where the latter does not exist.
+ # The ATTEMPT IS NOT THREADED INTO THE WALK, and it used to be. An earlier
+ # revision passed it down because the workspace rung's presence depended on the
+ # attempt number; that design is retired (see ``_failure_notice_targets``' WHEN
+ # block) and the ladder is now the same on every attempt, so the walk needs
+ # nothing from the counter. ``attempt`` still governs everything BELOW — the
+ # backoff instant, ``MAX_ATTEMPTS``, and the dead letter — because those are
+ # properties of the row, not of the address.
+ emit = asyncio.ensure_future(self._emit_failure_notice(run, notice, evidence))
+ try:
+ delivered = await asyncio.wait_for(
+ emit, timeout=failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS
+ )
+ except asyncio.TimeoutError as exc:
+ # WHOSE timeout, asked rather than assumed: from 3.11 ``asyncio.TimeoutError``
+ # is the builtin ``TimeoutError``, so an adapter's own HTTP timeout arrives
+ # here indistinguishable from the deadline. ``emit.cancelled()`` is the
+ # discriminator — only the deadline cancels the walk — and without it the
+ # notice would be stamped with a confident lie about which one happened.
+ delivered = False
+ if emit.cancelled():
+ logger.error(
+ "failure notice delivery timed out for run=%s after %ss; transport cancelled",
+ run_id,
+ failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS,
+ )
+ # The timeout CONSUMES the attempt the claim already made durable: the
+ # retry write below arms the ordinary backoff under the claim's own
+ # expectation, which cannot lose while this claimant's lease holds. A
+ # release (rewinding ``attempts``) would let a permanently hanging
+ # transport retry without bound and never dead-letter.
+ stamped: BaseException = TimeoutError(
+ "failure notice delivery timed out after "
+ f"{failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS}s; transport cancelled"
+ )
+ else:
+ # A rung's OWN timeout, reported as itself: it is an ordinary raising
+ # rung that happens to have picked this exception type.
+ logger.exception("failure notice delivery raised for run=%s", run_id)
+ stamped = exc
+ if evidence.error is None:
+ evidence.error = stamped
+ evidence.error_stage = "deliver"
+ except Exception as exc:
+ # A raising rung CONSUMES an attempt. Previously the exception escaped
+ # between computing the attempt number and persisting it, so the next
+ # 2 s tick recomputed the same number and raised again — an unbounded
+ # retry loop, which is exactly what the backoff exists to prevent. The
+ # bound has to hold for any rung, not just the one that was observed
+ # raising, so this catches rather than enumerating call sites.
+ logger.exception("failure notice delivery raised for run=%s", run_id)
+ delivered = False
+ if evidence.error is None:
+ evidence.error = exc
+ evidence.error_stage = "deliver"
+
+ if delivered and evidence.delivered:
+ # Acknowledged on a durable receipt or on a returned delivery id — never
+ # on a function return. ``emit_replayed_backend_failure`` discards the
+ # notify result and returns normally either way, so a returns-cleanly ack
+ # would flip a lost notice to ``sent`` permanently.
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_SENT,
+ # Re-asserting the attempt the CLAIM already consumed, deliberately
+ # rather than omitting it: this write is the one a reader reconstructs
+ # the delivery from, and it should say which attempt succeeded instead
+ # of leaving that to be inferred from an earlier row version.
+ attempts=attempt,
+ ack_evidence=evidence.ack_evidence,
+ # A post-delivery error (the SSE fan-out raised) is recorded for
+ # diagnosis and must NOT trigger a resend.
+ error=evidence.error_text,
+ )
+ self._drain_dirty = True
+ return
- - ``scheduled``/``task_run`` rows may carry only a ``task_id``; the
- real target lives on the task definition (mirrors
- ``_execute_claimed_request``).
- - a ``session_id`` is resolved to its canonical session key, so it
- matches a legacy/watch run that only carries that ``session_key``.
+ error_text = evidence.error_text or "failure notice delivery produced no evidence"
+ if retry_after is None:
+ # Dead letter, carrying the raised exception's own message rather than a
+ # generic string. Visible rather than silently retrying forever.
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_FAILED,
+ attempts=attempt,
+ error=error_text,
+ )
+ logger.error("failure notice for run %s dead-lettered: %s", run_id, error_text)
+ return
+ next_attempt_at = (
+ datetime.now(timezone.utc) + timedelta(seconds=retry_after)
+ ).isoformat()
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_PENDING,
+ attempts=attempt,
+ next_attempt_at=next_attempt_at,
+ error=error_text,
+ )
- Returns ``None`` for ``create_per_run`` (fresh session each time) and
- unkeyable requests.
+ async def _emit_failure_notice(
+ self,
+ run: dict[str, Any],
+ notice: dict[str, Any],
+ evidence: "DeliveryEvidence",
+ ) -> bool:
+ """Walk D5's delivery ladder for one failed run. True once one rung emitted.
+
+ Evidence is per RUNG, then adopted into the caller's object. One shared
+ ``DeliveryEvidence`` cannot express a ladder: ``delivered`` latches true the
+ moment any rung records an id, so a rung whose ack is REJECTED (see
+ ``_rung_acknowledges``) would both stop the walk and hand the eventual
+ ack/dead-letter another rung's ``ack_evidence``. The caller ends up with the
+ winning rung's evidence, or — when no rung was accepted — the last one's, so
+ the dead letter reports what actually went wrong on the final attempt.
+
+ A rung that RAISES is an unusable rung, not the end of the walk. Every other
+ way a rung can fail to deliver already continues — ``_build_context`` raising,
+ a stale synthetic candidate, an un-acked send — so a delivery that throws
+ (a platform whose settings manager is gone, an adapter that fails before its
+ transport) has to continue too, or the notice spends every attempt on rung (1)
+ and dead-letters without rungs (2)…(5) ever being tried. ``Exception`` and not
+ ``BaseException``: the walk-level deadline cancels this coroutine, and
+ cancellation must unwind the walk rather than advance it past the bound it was
+ cancelled to respect.
+
+ The cost is real and is recorded rather than hidden. A rung that raises AFTER
+ its transport accepted the send, leaving no evidence behind, now delivers again
+ on the next rung. The adapters no longer manufacture that state — post-send
+ bookkeeping is guarded in every one of them, so an already-delivered id is not
+ destroyed on its way out — and what remains is the same at-least-once residual
+ documented on ``CLAIM_LEASE_SECONDS``, narrowed on the retry by the duplicate
+ short-circuit's persisted receipt.
+
+ THE WORKSPACE RUNG IS RESOLVED HERE, NOT WHERE THE LADDER IS BUILT, and that
+ split is the whole reason this method knows the reserved id at all.
+ ``_failure_notice_targets`` appends the reserved id as a CONSTANT — no database
+ access, no row minted — and the resolve-or-create-or-heal happens below, once
+ the walk has actually reached that rung. Two consequences, both wanted:
+
+ * an installation whose rung (1) always delivers never grows the reserved row,
+ even though every ladder it builds ends with the reserved id. The rung is
+ appended to every ladder unconditionally (the round-14 gate), so a
+ build-time resolve would create the row on the FIRST failure of every
+ install, which is the one surviving argument from the design this replaced;
+ * ``_failure_notice_targets`` stays a pure address computation. It is called
+ directly by tests and by ad-hoc inspection, and under a build-time resolve
+ each of those calls would be a write.
+
+ The cost is that the rung can turn out to be UNUSABLE mid-walk, when the
+ workbench database cannot be read or written. That is not a new state — every
+ other rung can be unusable too (``_build_context`` raising, a stale candidate,
+ a send that throws) — and it takes the same disposal: the rung is skipped, the
+ walk continues, and with nothing left to try the notice keeps its ``pending``
+ state and its backoff. It dead-letters visibly only if the database never
+ answers.
"""
- session_policy = request.session_policy
- session_id = request.session_id
- session_key = request.session_key
- task_id = request.task_id
- if request.request_type in {"task_run", "scheduled"} and task_id:
- task = self.store.get_task(task_id)
- if task is not None:
- session_policy = task.session_policy or session_policy
- session_id = task.session_id or session_id
- session_key = task.session_key or session_key
- if session_policy == "create_per_run":
- return None
- if session_id:
- return self._canonical_session_lock(session_id, session_key)
- if session_key:
- return self._normalize_session_key(session_key)
- if task_id:
- return f"task:{task_id}"
- return None
- def _request_target_platform(self, request: TaskExecutionRequest) -> Optional[str]:
- session_key = request.session_key
- session_id = request.session_id
- deliver_key = request.deliver_key
- metadata = request.metadata or {}
- if request.request_type in {"task_run", "scheduled"} and request.task_id:
- task = self.store.get_task(request.task_id)
- if task is not None:
- session_key = task.session_key or session_key
- session_id = task.session_id or session_id
- deliver_key = task.deliver_key or deliver_key
- metadata = task.metadata or metadata
+ body = self._failure_notice_body(run, notice)
+ failure_id = str(notice.get("failure_id") or f"failure:{run['id']}")
+ last_rung: Optional[DeliveryEvidence] = None
+ first_raise: Optional[DeliveryEvidence] = None
+ try:
+ for target, session_id in self._failure_notice_targets(run):
+ if session_id == WORKSPACE_NOTICE_SESSION_ID:
+ # THE LAZY HALF of the reserved rung: resolve-or-create-or-heal now
+ # that the walk has reached it. ``resolve_workspace_notice_session``
+ # always answers with this same reserved id, so nothing about the
+ # target changes — the call is made for its WRITE (create the row,
+ # or repair one that was archived or hidden), not for its return.
+ if self._workspace_notice_session_id() is None:
+ # An unusable rung, disposed of like any other. Recorded only
+ # when no earlier rung left evidence: a preferred rung's own
+ # refusal ("returned send id … without a persisted receipt") is
+ # the more useful diagnosis, and this must not displace it.
+ logger.warning(
+ "failure notice rung unusable: the workspace-notifications "
+ "session could not be resolved for run=%s",
+ run["id"],
+ )
+ if last_rung is None:
+ unusable = DeliveryEvidence()
+ unusable.error = RuntimeError(
+ f"{target.to_key()} rung unusable: the "
+ "workspace-notifications session could not be resolved"
+ )
+ unusable.error_stage = "deliver"
+ last_rung = unusable
+ continue
+ try:
+ context = await self._build_context(
+ target,
+ delivery_target=target,
+ execution_id=str(run["id"]),
+ task_id=str(run.get("task_id") or "") or None,
+ trigger_kind=str(run.get("run_type") or "scheduled"),
+ session_id=session_id,
+ )
+ except Exception:
+ logger.debug("failure notice rung unusable: %s", target, exc_info=True)
+ continue
+ rung = DeliveryEvidence()
+ last_rung = rung
+ # The REPLAY emitter, not the live failure path. A notice is owed only for
+ # a run that is already settled, so this delivers one visible ``notify``
+ # and nothing else: no terminal result, no turn settlement, no auth
+ # prompt, and an identity taken from the durable row rather than from
+ # whatever ``task_execution_id`` this rebuilt context happens to supply.
+ # See ``emit_replayed_backend_failure`` for why each of those is a
+ # property of the emitter instead of an argument to the live one.
+ try:
+ await emit_replayed_backend_failure(
+ self.controller,
+ context,
+ str(run.get("agent_backend") or "harness"),
+ str(run.get("error") or "").strip() or body,
+ display_text=body,
+ failure_id=failure_id,
+ delivery=rung,
+ )
+ except Exception as exc:
+ # This rung is unusable; the ladder is not. See the docstring for
+ # why ``Exception`` and not ``BaseException``.
+ logger.warning(
+ "failure notice rung raised, continuing the walk: %s",
+ target.to_key(),
+ exc_info=True,
+ )
+ if rung.error is None:
+ rung.error = exc
+ rung.error_stage = "deliver"
+ if first_raise is None:
+ first_raise = rung
+ continue
+ if self._rung_acknowledges(target, rung):
+ return True
+ finally:
+ if last_rung is not None:
+ _adopt_delivery_evidence(evidence, last_rung)
+ if evidence.error is None and first_raise is not None:
+ # The winning rung carries no error of its own, so the skipped rung's
+ # does not compete with anything: it is recorded on the acknowledged
+ # row purely for diagnosis, the same way a post-delivery stream error
+ # is, and — like that one — must never be read as a delivery failure.
+ evidence.error = first_raise.error
+ evidence.error_stage = first_raise.error_stage
+ return False
- if session_id:
- return resolve_session_id_target(session_id).session_key.platform
- if session_key:
- try:
- return parse_session_key(session_key).platform
- except ValueError:
- return parse_scope_id(session_key).platform
+ @staticmethod
+ def _rung_acknowledges(target: ParsedSessionKey, rung: "DeliveryEvidence") -> bool:
+ """Whether THIS rung's evidence satisfies its target class's ack source.
+
+ One table lookup and one membership test, deliberately: the question "who may
+ ack on what" is answered once, declaratively, by ``LADDER_ACK_SOURCES`` — see
+ that table for why each class gets the source it does. A predicate that
+ special-cased platforms here is exactly how three review rounds each found a
+ different target class acking on evidence that proved nothing.
+
+ A rejected rung is not a silent one. When the send DID return an id and only
+ the durable receipt is missing, that is recorded on the rung so the eventual
+ retry or dead letter can say why, instead of reporting "produced no
+ evidence" about a send that in fact returned.
+ """
- scope_id = str(metadata.get("session_scope_id") or "").strip()
- if scope_id:
- return parse_scope_id(scope_id).platform
- if deliver_key:
+ source = failure_notice_ack_source(target)
+ if rung.ack_evidence in ACK_EVIDENCE_BY_ACK_SOURCE[source]:
+ return True
+ if (
+ source == ACK_SOURCE_PERSISTED_RECEIPT
+ and rung.error is None
+ and rung.delivered_id is not None
+ ):
+ rung.error = RuntimeError(
+ f"{target.to_key()} rung returned send id {rung.delivered_id} "
+ "without a persisted receipt"
+ )
+ rung.error_stage = STAGE_PERSIST
+ return False
+
+ def _failure_notice_targets(
+ self,
+ run: dict[str, Any],
+ ) -> list[tuple[ParsedSessionKey, Optional[str]]]:
+ """D5's ladder, in order, skipping rungs this run cannot address.
+
+ (1) the definition's delivery key; (2) the bound session's scope while the
+ session is still alive; (3) the scope the definition was created from;
+ (4) a DM to the owner; (5) the workbench inbox.
+
+ Rung (5) carries the definitions no person is addressable for. For one
+ created by a plain ``vibe task add`` at a terminal there is no caller
+ provenance at all, so rungs (3) and (4) are both empty; an unscoped
+ ``create_per_run`` definition can also have no delivery key, and once its
+ per-run session is gone rung (2) goes with it.
+
+ What rung (5) does and does not guarantee, stated honestly because the
+ earlier "always resolves" claim was wrong. The distinction it turns on is
+ between a REAL PERSISTED project scope and a STALE SYNTHETIC project
+ candidate, and the key alone does not tell them apart: rung (5) is spelled
+ ``avibe::project::<session id>``, a candidate this method MANUFACTURES for
+ every run carrying a session id. It becomes a real scope only downstream,
+ where ``persist_agent_message`` looks the session's ``agent_sessions`` row up
+ and takes that row's ``scope_id``.
+
+ AN ARCHIVED OR BACKGROUND ROW IS NOT A DELIVERY SURFACE, and rung (5) is
+ rerouted when the run names one — see ``_rung_five_session_id``. The previous
+ revision claimed
+ the opposite ("the real difference between this rung and rung (2)": that
+ ``_session_row`` has no status filter while ``resolve_session_id_target``
+ refuses an archived session outright). The mechanism is real; the conclusion
+ was wrong, and it is the round-13 P1 on this method (review thread
+ 3676292667). ``persist_agent_message`` does write the row, which is the
+ workbench class's ack source, so the notice is stamped ``sent`` — while
+ ``list_inbox_sessions`` excludes archived and background sessions, so there
+ is no card, no
+ ``inbox.session.updated`` and no push, and the acked notice is never retried.
+ Same class as the round-12 reserved-session hole, opposite remedy: the
+ reserved row is HEALED because nobody may archive it, whereas an ordinary
+ session was archived by its owner ON PURPOSE. Resurrecting it would overrule
+ the user, so the fix is ROUTING.
+
+ With a hard-deleted row the candidate resolves to nothing and
+ ``persist_agent_message`` returns before writing — yet ``AvibeBot.send_message``
+ still hands back a synthetic ``msg_…`` id, so the rung LOOKS delivered. That is
+ why the workbench target class may only acknowledge on a persisted receipt (see
+ ``LADDER_ACK_SOURCES``): a stale candidate leaves the notice retryable instead
+ of marking it ``sent`` against a row that was never written. Pinned by
+ ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``.
+
+ AND EVERY LADDER ENDS WITH THE RESERVED WORKSPACE RUNG (plan :3193, :3215-3222;
+ round-14 gate, review comment 5121007240). One distinct
+ WORKSPACE-NOTIFICATIONS rung is appended after every person/context target, on
+ every attempt, whatever the four rungs above produced — see the WHEN block at
+ the end of this method for why that is unconditional and what it costs. It
+ resolves without a person to address because it is addressed to the workspace
+ instead.
+
+ This method takes NO attempt number and performs NO database access. The
+ reserved rung is appended as a CONSTANT (``WORKSPACE_NOTICE_SESSION_ID``); the
+ resolve-or-create-or-heal happens in ``_emit_failure_notice``, when the walk
+ actually reaches that rung. So the ladder is a pure address computation that is
+ safe to call from a test or an ad-hoc probe, and an installation whose rung (1)
+ always delivers never grows the reserved row even though every ladder it builds
+ names it.
+
+ The rung is therefore appended UNCONDITIONALLY but is not guaranteed USABLE, and
+ that distinction is stated here rather than left to be discovered because an
+ earlier revision's unqualified "always resolves" is the exact claim the plan's
+ own correction had to retract. ``_workspace_notice_session_id`` returns ``None``
+ when the workbench database cannot be read or written; the walk then skips the
+ rung. The consequence is a RETRY, not a loss: the notice keeps its ``pending``
+ state, arms its backoff, and delivers on a later pass once the database answers
+ — and only dead-letters if it never does. That is the same shape as any other
+ unusable rung, which is why it needs no special handling in the drain.
+ """
+
+ rungs: list[tuple[ParsedSessionKey, Optional[str]]] = []
+ seen: set[tuple[str, Optional[str]]] = set()
+
+ def _add(raw_key: Any, session_id: Optional[str]) -> None:
+ key = str(raw_key or "").strip()
+ if not key:
+ return
try:
- return parse_session_key(deliver_key).platform
- except ValueError:
- return parse_scope_id(deliver_key).platform
- return None
+ parsed = parse_session_key(key)
+ except Exception:
+ # ``parse_session_key`` rejects every scope type outside
+ # ``{channel, user}``, and EVERY avibe rung is
+ # ``avibe::project::…`` — rung (2) for any workbench-bound session
+ # (``resolve_session_id_target`` hands back a ``project`` scope for
+ # one), rung (3) for a workbench-created definition, and rung (5)
+ # always. Swallowing that ``ValueError`` silently discarded all of
+ # them, so an Avibe-only definition had an entirely empty ladder.
+ #
+ # Only a bare three-part key falls back. A five-part
+ # ``::thread::`` key is a session key by construction and
+ # ``parse_scope_id`` cannot express one, so it stays on the strict
+ # parser rather than being downgraded to its scope prefix (which
+ # would silently retarget a thread notice at its parent channel).
+ if len(key.split("::")) != 3:
+ return
+ try:
+ parsed = parse_scope_id(key)
+ except Exception:
+ return
+ identity = (parsed.to_key(), session_id)
+ if identity in seen:
+ return
+ seen.add(identity)
+ rungs.append((parsed, session_id))
- def _transport_ready_for_request(self, request: TaskExecutionRequest) -> bool:
- try:
- platform = self._request_target_platform(request)
- except Exception:
- logger.debug("Could not resolve Run %s platform for readiness gating", request.id, exc_info=True)
- return True
- if not platform:
- return True
- is_ready = getattr(self.controller, "is_im_transport_ready", None)
- return bool(is_ready(platform)) if callable(is_ready) else True
+ metadata = run.get("metadata") if isinstance(run.get("metadata"), dict) else {}
+ task = self.store.get_task(str(run.get("task_id") or "")) if run.get("task_id") else None
- def notify_transport_ready(self, platform: str) -> None:
- logger.info("Transport %s ready; scheduled Run queue will be drained", platform)
- self._drain_dirty = True
+ # (1) the definition's delivery key.
+ _add((task.deliver_key if task else None) or run.get("deliver_key"), None)
+
+ # (2) the bound session's scope, only while the session resolves to a visible
+ # delivery surface. Background sessions deliberately suppress delivery, so
+ # persisting and acknowledging a notice there would hide it permanently.
+ session_id = str((task.session_id if task else None) or run.get("session_id") or "").strip()
+ if session_id:
+ try:
+ resolved = resolve_session_id_target(session_id)
+ except Exception:
+ resolved = None
+ if resolved is not None and not resolved.suppress_delivery:
+ _add(resolved.session_key.to_key(), session_id)
+
+ # (3) caller provenance, written at definition creation.
+ caller = _created_by_caller(task, metadata)
+ if caller is not None:
+ _add(caller.get("session_key") or caller.get("scope_id"), None)
+
+ # (4) a DM to the owner, from the same provenance.
+ if caller is not None:
+ platform = str(caller.get("platform") or "").strip()
+ user_id = str(caller.get("user_id") or "").strip()
+ if platform and user_id:
+ _add(f"{platform}::user::{user_id}", None)
+
+ # (5) the workbench inbox, addressed through the run's own session — the rung
+ # that survives rung (2)'s refusal, because ``persist_agent_message`` resolves
+ # the avibe scope from ``_session_row`` (no status filter) where
+ # ``resolve_session_id_target`` demands a live, usable session.
+ #
+ # The key below is a CANDIDATE, not a resolved scope: the session id sits in
+ # the ``project`` slot and, for a MISSING row, nothing here checks that the row
+ # it names still exists. Whether it is real is settled downstream, by whether a
+ # durable ``messages`` row appears — which is exactly what the workbench class's
+ # receipt-only ack source measures, so a candidate for a deleted session
+ # cannot pass itself off as a delivery.
+ #
+ # An archived or background row is the case that measurement CANNOT catch,
+ # so it is caught here instead: see ``_rung_five_session_id``.
+ #
+ # So this rung covers every definition that has ever had a session — every
+ # ``create_once`` / ``create_per_run`` / session-bound definition — addressing
+ # the run's own session while that row is a surface a user can see, and the
+ # workspace inbox when it is not.
+ if session_id:
+ rung_five_session_id = self._rung_five_session_id(session_id)
+ _add(f"avibe::project::{rung_five_session_id}", rung_five_session_id)
+
+ # …AND THE LAST RUNG, for the definitions the four above cannot address at all
+ # (plan :3193, :3215-3222; PR6's own step list, :1256-1259).
+ #
+ # THE EARLIER POSITION HERE WAS WRONG, and the plan says so with a date. It read
+ # that ``persist_agent_message`` returns before writing when an avibe context
+ # resolves neither a scope nor a session row, therefore a session-less
+ # definition has nowhere to put the row, therefore the notice dead-letters
+ # VISIBLY and that is a declared Known-By-Design limitation under #1044. The
+ # first two clauses are still true; the conclusion was not. "Visible in
+ # ``last_error`` and the health badge" is visible to somebody who goes LOOKING,
+ # and D1's whole subject is the runs nobody is watching. A notice with nowhere
+ # to go is a notice that is never written.
+ #
+ # What was actually missing was a HOME, not a widened writer: the blocker is a
+ # session row, so the fix supplies one. ``_workspace_notice_session_id``
+ # resolves-or-creates a single reserved workspace-notifications session, and
+ # rung (5) then addresses it exactly like any other avibe session — the same
+ # ``avibe::project::<session id>`` candidate, satisfied by the same
+ # ``_session_row`` lookup, acked by the same receipt-only policy. Nothing
+ # downstream learns a new row shape.
+ #
+ # WHAT THAT ACTUALLY GETS THE USER, enumerated rather than waved at, because the
+ # previous revision's "the same inbox / unread / realtime / Web Push machinery"
+ # claimed three surfaces the row does not reach:
+ #
+ # * an INBOX CARD (``list_inbox_sessions`` accepts a terminal ``notify``) and the
+ # ``inbox.session.updated`` realtime event that patches an open browser — the
+ # two surfaces the plan's "readable inbox row" is about;
+ # * a LOCAL Web Push, via ``maybe_notify_inbox_message``.
+ #
+ # Residuals, all three properties of pre-existing policy rather than of this rung:
+ # the notice does NOT bump the unread badge (``notify`` carries no ``unread`` in
+ # ``vibe/message_types.json`` and the unread counts are ``result``-only, on purpose
+ # — a failure report is not an unread reply); it is NOT reachable by message
+ # search, which is also ``result``-scoped; and on a REMOTE-ACCESS install push can
+ # find no owner to address, because owner resolution falls back to the local user
+ # only while remote access is off (``core/web_push_notifications.py``). The inbox
+ # card and the realtime event are unaffected by all three.
+ #
+ # WHEN. UNCONDITIONALLY, ONCE, LAST. One distinct workspace-notifications rung
+ # after every person/context target, on every attempt, whether or not the four
+ # rungs above produced anything and whether or not what they produced is stale,
+ # unavailable, or failing delivery. This is the round-14 gate ruling (review
+ # comment 5121007240) and it is a settled decision, not a preference to be
+ # re-litigated by a later revision.
+ #
+ # TWO RETIRED DESIGNS, named so neither comes back:
+ #
+ # (i) round 12's "ONLY WHEN NOTHING ELSE RESOLVED" — the fallback fired only for
+ # an empty ladder. Too narrow by exactly the case #1060 reported (maintainer
+ # note 5120451508): a NON-EMPTY ladder is not a DELIVERABLE one. Rung (5)
+ # above is manufactured from the run's session id and nothing checks that the
+ # row it names still exists, and rungs (3)/(4) can point at the same dead
+ # session. A watch bound to a HARD-DELETED session therefore builds a ladder
+ # that can never persist a receipt: every attempt sends to a candidate that
+ # resolves to nothing, the receipt-only ack source correctly refuses it, the
+ # ``if not rungs`` gate never fires, all six attempts burn, and the notice
+ # dead-letters into ``NOTICE_FAILED`` with nothing written anywhere. That
+ # silent dead letter is the 3.5 hours of silence in #1060's field evidence,
+ # and "visible in ``last_error``" was refuted above for exactly this reason.
+ #
+ # (ii) round 13's FINAL-ATTEMPT fallback (commit ``ce695b42``) — appended last,
+ # but only on attempt ``MAX_ATTEMPTS``. It closed (i)'s hole and was
+ # overruled anyway. Its argument was that a workspace rung present from
+ # attempt 1 converts a TRANSIENT preferred-rung failure into a permanently
+ # workspace-routed notice, since the walk acks the FIRST rung that succeeds.
+ # That reading of the mechanism is correct; the gate weighed the trade and
+ # decided the other way, in terms that leave no conditional room:
+ # "Workspace fallback is mandatory rung 5. Append one distinct
+ # workspace-notifications target after every person/context target, even
+ # when earlier candidates exist but are stale, unavailable, or fail
+ # delivery. It cannot be conditional on rungs being empty."
+ #
+ # THE TRADE, RECORDED RATHER THAN LEFT SILENT, because it is a real behaviour
+ # change and the next reader deserves to find it stated: any walk in which every
+ # preferred rung fails to deliver now reaches this rung on THAT walk, delivers,
+ # and ACKS. So a preferred rung that failed TRANSIENTLY — a platform blip on
+ # attempt 1 — permanently routes that one notice to the workspace inbox; the
+ # notice is never retried to the preferred target, and the user's own channel
+ # does not receive a copy it would have received a minute later. Accepted
+ # explicitly by the maintainer in the ruling above ("…or fail delivery"), on the
+ # judgement that a misrouted notice a user can find beats a notice nobody
+ # receives. Scope of the residual: ONE notice, not the definition — the next
+ # failure builds a fresh ladder and the recovered preferred rung wins it again.
+ #
+ # WHAT KEEPS IT FROM BEING NOISY is the ORDER, which is the one property of
+ # round 12's argument that survives intact. The rung is appended STRICTLY LAST,
+ # after every preferred rung, and the walk returns on the first rung that
+ # acknowledges — so a HEALTHY preferred rung wins every walk and never produces a
+ # workspace card at all. Duplicate cards for a delivered notice's silent per-rung
+ # failures are therefore not reachable; only a walk where NOTHING preferred
+ # delivered gets here. Pinned by
+ # ``test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox``.
+ #
+ # AND ONCE. The reserved id is appended as a CONSTANT, so it collides by identity
+ # with rung (5)'s archived-session reroute (which returns the same constant) and
+ # the ``_add`` seen-set collapses the two into a single rung. An archived-session
+ # ladder holds exactly ONE workspace rung, not two — pinned by
+ # ``test_an_archived_session_ladder_holds_exactly_one_workspace_rung``.
+ #
+ # NO DATABASE ACCESS HERE. Appending the constant costs nothing; the
+ # resolve-or-create-or-heal is done by ``_emit_failure_notice`` when the walk
+ # reaches this rung. That is what keeps the reserved row from being minted on the
+ # first failure of an installation whose rung (1) always delivers — the only part
+ # of round 12's "would create the reserved row for installations that never need
+ # it" that is still load-bearing once the ordering argument above is granted.
+ #
+ # RESIDUAL: ``_workspace_notice_session_id`` returns ``None`` when the workbench
+ # database cannot be read or written, and the walk then SKIPS this rung on every
+ # attempt — so the notice dead-letters exactly as it did before, visibly, with the
+ # last rung's own refusal in ``error``. That path must stay reachable: a fallback
+ # that swallowed the dead letter when it could not itself deliver would replace
+ # one silence with a worse one.
+ _add(f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}", WORKSPACE_NOTICE_SESSION_ID)
+ return rungs
+
+ def _rung_five_session_id(self, session_id: str) -> str:
+ """Which session rung (5) may address: the run's own, or the workspace inbox.
+
+ THE INVISIBLE-SESSION REROUTE. An archived or background
+ ``agent_sessions`` row is WRITABLE but is not a VISIBLE delivery surface,
+ and the notice machinery reads those two as one thing:
+ ``persist_agent_message`` resolves the avibe scope through ``_session_row``,
+ which has no status filter, so the message persists; a persisted receipt is the
+ workbench class's ack source (``LADDER_ACK_SOURCES``), so the rung ACKS and the
+ notice is stamped ``sent`` and never retried; but ``list_inbox_sessions`` and
+ ``get_inbox_session`` exclude archived sessions, so there is no inbox card, no
+ ``inbox.session.updated`` patch for an open browser, and no Web Push. The user is
+ told nothing and the system believes it told them — the exact silence D1 exists
+ to close, and worse than a dead letter, which at least says so.
+
+ The receipt-only ack source CANNOT catch this one. It is the right measurement
+ for a MISSING row (nothing persists, so nothing acks — see
+ ``_failure_notice_targets``' rung-(5) comment and
+ ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``), and it is blind
+ here precisely because the write really does happen. So the check has to be a
+ read, and it has to be here, where the address is chosen.
+
+ WHY REROUTING RATHER THAN HEALING, which is what round 12 did for the same class
+ of hole (``2ceaa865``, the reserved workspace session). That row may never be
+ archived at all — ``archive_session`` refuses its id — so an archived one is
+ corruption and repairing it in place restores the invariant. An ORDINARY session
+ was archived by its owner deliberately. Un-archiving it to deliver a failure
+ notice would overrule a user decision to make a bookkeeping row visible, and it
+ would resurface the whole session, not the notice. The session is not broken; the
+ ADDRESS is. So the notice moves.
+
+ Three outcomes, and only the middle one changes anything:
+
+ * row ABSENT (hard-deleted, or the DB cannot be read): the caller's own
+ candidate, unchanged. Nothing persists, so nothing acks, and the appended
+ workspace rung plus the ``delivery_target_missing`` classification carry the
+ case on the SAME walk. The candidate is
+ also kept for what it documents: rung (5) is a candidate by construction, and
+ removing it here would hide the shape of the ladder from the ack policy that
+ depends on it.
+ * row ARCHIVED OR HIDDEN: the reserved workspace-notifications session, so the
+ notice lands somewhere ``list_inbox_sessions`` will show it. Returned as the
+ bare CONSTANT — this method does not resolve or create the reserved row, so
+ the reroute is a pure address change and the id it returns is identical to the
+ one ``_failure_notice_targets`` appends last, which is what lets the
+ ``_add`` seen-set collapse the two into ONE rung. Whether that row can
+ actually be written is settled later, by the walk. If it cannot, the rung is
+ skipped and the notice stays retryable rather than acking invisibly into the
+ archived row — which is what keeping the caller's candidate here used to do.
+ * an active row whose visibility is explicitly admitted by the inbox: the
+ caller's candidate. The visibility whitelist is shared with inbox queries,
+ so a future value stays hidden until both surfaces opt it in.
+
+ ONE READ, and the TOCTOU is real and bounded: a session archived or hidden
+ between this SELECT and ``persist_agent_message``'s write still acks there.
+ The residual is ONE notice, not a class — the next notice re-reads and reroutes —
+ and closing it would need the status check inside the persisting transaction,
+ which is a writer-side change of a different shape. Not worth trading a
+ per-notice window for a widened writer.
+ """
- def _canonical_session_lock(self, session_id: str, session_key: Optional[str]) -> str:
- cached = self._session_lock_cache.get(session_id)
- if cached is not None:
- return cached
try:
- resolved = resolve_session_id_target(session_id)
- # avibe/workbench sessions are 1:1 with the session id — a project scope
- # holds many INDEPENDENT sessions, so locking on the project key would
- # serialize unrelated conversations. Lock on the concrete session id.
- if resolved.session_key.platform == "avibe" or resolved.session_key.scope_type == "project":
- key = f"sid:{session_id}"
- else:
- key = f"key:{resolved.session_key.to_key()}"
+ with get_cached_sqlite_engine().begin() as conn:
+ row = conn.execute(
+ select(agent_sessions.c.status, agent_sessions.c.visibility).where(
+ agent_sessions.c.id == session_id
+ )
+ ).first()
except Exception:
- # avibe/web sessions (no IM scope) or unresolved ids: fall back to a
- # carried session key if present, else the id is its own identity.
- key = self._normalize_session_key(session_key) if session_key else f"sid:{session_id}"
- self._session_lock_cache[session_id] = key
- return key
+ logger.warning(
+ "failure notice: cannot read session %s status/visibility for rung (5)",
+ session_id,
+ exc_info=True,
+ )
+ return session_id
+ if row is None:
+ return session_id
+ status, visibility = row
+ if str(status) != "archived" and str(visibility) in INBOX_SESSION_VISIBILITIES:
+ return session_id
+ logger.info(
+ "failure notice: session %s is archived or hidden, rerouting rung (5) to the "
+ "workspace-notifications inbox",
+ session_id,
+ )
+ return WORKSPACE_NOTICE_SESSION_ID
+
+ def _workspace_notice_session_id(self) -> Optional[str]:
+ """The reserved workspace-notifications session id, created on first need.
+
+ Lazy on purpose: an installation whose definitions all have a delivery key or a
+ session never grows the row. See
+ ``storage.agent_session_rows.resolve_workspace_notice_session`` for why the
+ identity is a reserved primary key and why the row carries no Scope.
+
+ THREE MECHANISMS KEEP THE ROW USABLE, and they cover three different ways of
+ losing it — the first one alone was not enough:
+
+ * RECREATION covers REMOVAL. Nothing asks the ``/new`` clear path or session
+ eviction for an exemption; if the row is deleted the next notice makes it again.
+ * HEALING covers ARCHIVE and a flipped ``visibility``, which recreation cannot
+ see: the reserved primary key is still there, so nothing recreates, while the
+ row has stopped being a delivery surface. That state fails SILENTLY — the
+ notice still persists through ``_session_row`` (no status filter), still acks
+ on the receipt, and ``list_inbox_sessions`` shows nothing — so
+ ``resolve_workspace_notice_session`` repairs the row in place instead.
+ * THE ``archive_session`` AND ``update_session`` GUARDS cover the UI paths.
+ The row is ``visibility='system'`` — absent from ordinary session lists,
+ admitted by the inbox surfaces — so the remaining door to it is its own
+ inbox card, and ``storage.workbench_sessions_service`` refuses the id on
+ both archive and modify (403). The heal is still needed for a database
+ archived or re-flagged out of band, or before the guards existed.
+
+ Called from the WALK (``_emit_failure_notice``), not from the ladder build. The
+ ladder appends the reserved id as a constant, so this — the only part of the rung
+ that writes — runs exactly when the walk has actually reached it. An install
+ whose preferred rung always delivers therefore never grows the row.
+
+ Returns ``None`` rather than raising: this runs mid-walk for a failure that is
+ already recorded, and an unwritable workbench DB must leave the notice retryable
+ — the pre-existing behaviour — instead of turning one unusable rung into an
+ exception the drain has to classify.
+ """
- @staticmethod
- def _normalize_session_key(session_key: str) -> str:
try:
- return f"key:{parse_session_key(session_key).to_key()}"
+ from storage.agent_session_rows import resolve_workspace_notice_session
+ from storage.db import get_cached_sqlite_engine
+
+ with get_cached_sqlite_engine().begin() as conn:
+ return resolve_workspace_notice_session(
+ conn,
+ # Named once, at CREATE time, by whoever's notice needed it first.
+ title=self._t("harness.notice.workspaceSession"),
+ )
except Exception:
- return f"key:{session_key}"
+ logger.warning(
+ "failure notice: workspace-notifications session unavailable", exc_info=True
+ )
+ return None
- def _spawn_execution(self, request: TaskExecutionRequest, lock_key: Optional[str]) -> None:
- if lock_key is not None:
- self._inflight_sessions.add(lock_key)
- task = asyncio.create_task(self._execute_claimed_request(request))
- self._inflight_executions[request.id] = task
- task.add_done_callback(
- lambda finished, rid=request.id, key=lock_key: self._on_execution_done(rid, key, finished)
- )
+ def _origin_lines(self, caller: Optional[dict[str, Any]]) -> list[str]:
+ """The creation-origin line, plus a deep link when one can be built honestly.
+
+ Zero, one or two lines — never a placeholder. Three separate refusals, each of
+ which independently yields FEWER lines rather than vaguer ones:
+
+ * **No provenance at all.** Every definition created before the origin capture
+ landed, and every definition created from the CLI with no conversation behind
+ it. There is nothing to say, so nothing is said.
+ * **An unmapped platform.** The label is rendered inside a translated sentence,
+ so the wire value goes through ``NOTICE_ORIGIN_PLATFORM_I18N_KEYS`` — a closed
+ map — and never gets interpolated. Same call as
+ ``notice_failure_class_i18n_key``'s: ``None`` means no line, because "Created
+ in: mystery_platform" leaks an identifier into product copy for no benefit.
+ * **No followable link.** ``origin_link`` returns ``None`` for a Feishu/Lark or
+ WeChat origin, for a Workbench origin (a localhost URL is not reachable from
+ the IM notice this may be delivered to), and for any platform whose permalink
+ grammar needs an id that was not captured. The origin TEXT still renders; only
+ the second line is dropped.
+
+ The channel and thread are rendered from the CAPTURED ids — a raw ``C0123`` is
+ the identifier the user's own client shows in a URL, and inventing a display
+ name that was never captured would be a different kind of dishonesty from
+ inventing a link, but the same kind of mistake. The scope is read back out of
+ the same ``session_key`` that rung (3) is addressed to, so the notice cannot
+ name one conversation while the ladder targets another.
+ """
- def _on_execution_done(
- self, request_id: str, lock_key: Optional[str], task: "asyncio.Task[Any]"
- ) -> None:
- self._inflight_executions.pop(request_id, None)
- if lock_key is not None:
- self._inflight_sessions.discard(lock_key)
- self._drain_dirty = True
- # ``_execute_claimed_request`` already records failures and requeues on
- # cancellation; this only surfaces unexpected crashes in the wrapper.
- if task.cancelled():
- return
- exc = task.exception()
- if exc is not None:
- logger.error("Claimed request %s crashed: %r", request_id, exc, exc_info=exc)
+ if not caller:
+ return []
+ platform = str(caller.get("platform") or "").strip()
+ platform_key = failure_notices.notice_origin_platform_i18n_key(platform)
+ if not platform_key:
+ return []
+ platform_label = self._t(platform_key)
- async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:
- error: Optional[str] = None
- should_complete = True
- coalesced_completion_ids: list[str] = _live_coalesced_agent_run_ids(request) or []
- task_id = request.task_id
- session_key = request.session_key
- session_id = request.session_id
- try:
- if request.request_type in {"task_run", "scheduled"}:
- self.store.maybe_reload()
- task = self.store.get_task(request.task_id or "")
- if task is None:
- raise ValueError(f"task '{request.task_id}' not found")
- task_id = task.id
- session_key = task.session_key
- session_id = task.session_id
- result = await self._execute_task(
- task,
- execution_id=request.id,
- disable_one_shot=request.source_kind == "scheduler",
- )
- error = result.error
- session_key = result.session_key
- session_id = result.session_id
- elif request.request_type in {"hook_send", "watch", "webhook"}:
- if not request.prompt:
- raise ValueError("hook request requires prompt")
- user_context = self._resource_user_context(request.metadata)
- if request.session_policy == "create_per_run":
- session_id = self._reserve_runtime_session(
- agent_name=request.agent_name,
- deliver_key=request.deliver_key,
- metadata=request.metadata,
- workdir=request.metadata.get("session_workdir") if isinstance(request.metadata, dict) else None,
- user_context=user_context,
- )
- session_key = ""
- elif not (request.session_id or request.session_key):
- raise ValueError("hook request requires session_id or session_key")
- resource_access_kwargs = (
- {"metadata": request.metadata, "user_context": user_context}
- if user_context is not None
- else {}
+ parsed: Optional[ParsedSessionKey] = None
+ raw_key = str(caller.get("session_key") or caller.get("scope_id") or "").strip()
+ if raw_key:
+ for parser in (parse_session_key, parse_scope_id):
+ try:
+ parsed = parser(raw_key)
+ break
+ except Exception:
+ parsed = None
+ scope_type = parsed.scope_type if parsed is not None else ""
+ scope_id = parsed.scope_id if parsed is not None else ""
+ thread_id = parsed.thread_id if parsed is not None else None
+
+ if scope_type == "channel" and scope_id:
+ if thread_id:
+ origin = self._t(
+ "harness.notice.originChannelThread",
+ platform=platform_label,
+ channel=scope_id,
+ thread=thread_id,
)
- error = await self._execute_request(
- session_key=session_key,
- session_id=session_id,
- post_to=request.post_to,
- deliver_key=request.deliver_key,
- prompt=request.prompt,
- execution_id=request.id,
- task_id=task_id,
- trigger_kind=request.request_type if request.request_type != "hook_send" else "hook",
- agent_name=request.agent_name,
- **resource_access_kwargs,
+ else:
+ origin = self._t(
+ "harness.notice.originChannel",
+ platform=platform_label,
+ channel=scope_id,
)
- elif request.request_type == "agent_run":
- message = _agent_run_message_for_request(request)
- if not message:
- raise ValueError("agent run requires message")
- if not (request.session_id or request.session_key):
- raise ValueError("agent run currently requires session_id or a resolvable session target")
- result = await self._execute_agent_run(
- session_key=request.session_key,
- session_id=request.session_id,
- post_to=request.post_to,
- deliver_key=request.deliver_key,
- message=message,
- execution_id=request.id,
- agent_name=request.agent_name,
- metadata={
- **(request.metadata or {}),
- "source_kind": request.source_kind,
- "source_actor": request.source_actor,
- "parent_run_id": request.parent_run_id,
- "callback_session_id": request.callback_session_id,
- },
+ elif scope_type == "user" and scope_id:
+ origin = self._t(
+ "harness.notice.originDirect",
+ platform=platform_label,
+ user=scope_id,
+ )
+ else:
+ # A known platform with no usable scope — a Workbench (``project``) origin,
+ # or a caller recorded before the session key could be resolved. The
+ # platform alone is still true and still narrows the search.
+ origin = platform_label
+
+ lines = [self._t("harness.notice.origin", origin=origin)]
+ link = origin_link(
+ platform,
+ caller.get("channel_id"),
+ thread_id,
+ caller.get("message_id"),
+ caller.get("workspace_id"),
+ )
+ if link:
+ lines.append(self._t("harness.notice.originLink", url=link))
+ return lines
+
+ def _failure_notice_body(self, run: dict[str, Any], notice: dict[str, Any]) -> str:
+ """Actionable copy: what failed, why, its state, and how to re-run.
+
+ A DM is context-free by construction and rung (5) is not attached to any
+ conversation, so the body has to carry its own context rather than relying on
+ where it happened to land.
+
+ Two classifications decide the copy, and BOTH are asked here by the same
+ predicate the rest of the system uses:
+
+ * the LANE — ``failure_notices.is_interruption``, i.e. membership in
+ ``RUN_INTERRUPTION_REASONS``. Asking by the mere presence of
+ ``interrupt_reason`` told a user "nothing is wrong with the definition
+ itself" for ``no_terminal_result`` / ``refused_concurrent_turn`` /
+ ``transport_unavailable`` / ``queue_hold_expired`` — the recurring per-fire
+ verdicts where the definition is exactly what IS wrong.
+ * the DEFINITION KIND. A watch is not a task: ``vibe task run`` /
+ ``vibe task show`` do not accept a watch id, and ``vibe watch run`` does not
+ exist at all, so a failed watch was handed commands it could not use and an
+ id in place of its name (``get_task`` mirrors scheduled tasks only).
+ """
+
+ definition_id = str(run.get("task_id") or "") or None
+ task = self.store.get_task(definition_id) if definition_id else None
+ # Only for a run whose definition is not a task: the run's own ``run_type``
+ # says so for a watch hook send (``watch``) and for the supervisor heartbeat
+ # (``watch_runtime``), and the definition row is the fallback for a row
+ # rebuilt without one.
+ watch = (
+ self.store.get_watch_definition(definition_id)
+ if task is None and definition_id
+ else None
+ )
+ is_watch = watch is not None or str(run.get("run_type") or "").strip().startswith("watch")
+ name = (
+ (task.name if task else None)
+ or (str((watch or {}).get("name") or "").strip() or None)
+ or definition_id
+ or str(run["id"])
+ )
+ run_id = str(run.get("id") or "").strip()
+ if failure_notices.is_binding_change(notice):
+ return self._binding_notice_body(
+ notice,
+ name=name,
+ definition_id=definition_id,
+ definition_exists=task is not None,
+ run_id=run_id,
+ )
+ reason = str(notice.get("interrupt_reason") or "").strip()
+ error = str(run.get("error") or "").strip() or self._t("harness.notice.unknownError")
+ if failure_notices.is_interruption(notice):
+ # The reason is rendered INSIDE a translated sentence, so it is copy: the
+ # wire value went through a closed label map, never interpolated raw. An
+ # unmapped reason takes the map's localized generic rather than leaking the
+ # identifier — see ``NOTICE_REASON_UNKNOWN_I18N_KEY``.
+ headline = self._t(
+ "harness.notice.interrupted",
+ name=name,
+ reason=self._t(failure_notices.notice_reason_i18n_key(reason)),
+ )
+ else:
+ headline = self._t("harness.notice.failed", name=name)
+ # COMMAND COPY, ORDINARY-FAILED LANE ONLY. A command definition's notice named
+ # the definition and the error but never the command, so "Error: command exited
+ # with status 7: boom" left the reader to go and look up WHAT exited. The lane
+ # gate is deliberate: an interrupted command run is a fact about the SERVICE
+ # (restart, eviction) and not about the command, so that lane keeps the generic
+ # copy the headline already explains.
+ #
+ # The command copy is read off the RUN's own snapshot, falling back to the live
+ # definition only for rows written before the snapshot existed. This notice is
+ # drained asynchronously, so the definition can have been rewritten -- or
+ # deleted -- between the fire and this call; either way ``get_task`` answers
+ # about the wrong execution, or not at all.
+ executed = command_snapshot_of_run(run)
+ command_source = executed if executed is not None else task
+ is_command_failure = (
+ not failure_notices.is_interruption(notice)
+ and command_source is not None
+ and command_source.has_command
+ )
+ lines = [headline]
+ if is_command_failure:
+ command_preview = self._notice_command_preview(command_source)
+ if command_preview:
+ lines.append(self._t("harness.notice.commandLine", command=command_preview))
+ lines.append(self._t("harness.notice.error", error=error))
+ if is_command_failure and run.get("exit_code") is not None:
+ # ONLY when the row actually carries one. A fire that never spawned — a
+ # missing working directory, a supervisor that died during startup — has no
+ # exit code at all, and "Exit code: None" (or a fabricated 0/1) would be
+ # copy about nothing on the very notice that has to be trusted. No stderr
+ # tail line either: the executor already appends the last non-empty stderr
+ # line to the run's ``error``, so the line above carries it and a third
+ # line would print the same text twice.
+ lines.append(self._t("harness.notice.commandExit", exitCode=run.get("exit_code")))
+ if not failure_notices.is_interruption(notice):
+ # D5 asks for "the error and its CLASS", and on this lane the class was
+ # dropped: the interrupted headline was the only place any reason was
+ # rendered, while the per-fire verdicts — ``no_terminal_result``,
+ # ``refused_concurrent_turn``, ``transport_unavailable``,
+ # ``queue_hold_expired`` — stay in the FAILED lane by design and carry a
+ # reason all the same. Its own closed vocabulary, and ``None`` (no line)
+ # when there is no class to name: see ``notice_failure_class_i18n_key``.
+ class_key = failure_notices.notice_failure_class_i18n_key(reason)
+ if class_key:
+ lines.append(
+ self._t("harness.notice.failureClass", failureClass=self._t(class_key))
)
- error = result.error
- should_complete = result.complete_on_return
- if result.requeue_on_return:
- self.request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
- coalesced_completion_ids = list(result.coalesced_completion_ids)
- else:
+ last_success = self._last_success_instant(definition_id)
+ if last_success:
+ # "When it last succeeded" — D5's own list. Omitted rather than rendered as
+ # "never" for a definition that has never succeeded: the notice already says
+ # this fire failed, and a line about the absence of history is noise.
+ lines.append(self._t("harness.notice.lastSucceeded", when=last_success))
+ # WHERE IT CAME FROM — the last item on D5's list, and the one a DM or a
+ # workspace card needs most, because neither is attached to the conversation
+ # that asked for the definition. Omitted whole when nothing was captured, which
+ # is EVERY definition created before this round: there is no backfill and no
+ # migration, because the ids were never recorded and inventing them is the one
+ # thing a provenance line may not do.
+ lines.extend(
+ self._origin_lines(
+ _created_by_caller(task, run.get("metadata") if isinstance(run.get("metadata"), dict) else {})
+ )
+ )
+ if definition_id:
+ lines.append(self._t("harness.notice.definition", id=definition_id))
+ if task is None and watch is None:
+ # The definition row is GONE while the run keeps its ``definition_id``
+ # forever, so EVERY definition-level command is a dead end — checked
+ # before the task/watch split because both halves of that split print
+ # one. ``vibe task run <deleted id>`` parses and then reports "not
+ # found", which is the same class of defect HFR-094 closed for
+ # watches: copy naming an action the user cannot take.
+ lines.extend(self._deleted_definition_lines(run_id))
+ elif is_watch:
+ if watch is not None and not watch.get("enabled", True):
+ # RETIRED IS NOT PAUSED, and the row already says which. A watch
+ # that ran out its ``once`` cycle carries ``retired_at``; a user who
+ # pressed pause leaves it null. Both land on ``enabled = 0``, which
+ # is exactly the ambiguity #1060 reported ("``enabled=0`` is carrying
+ # three meanings") — and printing the resume copy for a retired
+ # watch contradicts the lifecycle projection this same round makes
+ # authoritative: the definition reads FINISHED while its notice
+ # offers ``vibe watch resume``, an action that would arm a watch the
+ # user never paused.
+ #
+ # The distinction is read from the same column the projection's
+ # ``ended`` predicate uses, so the copy and the badge cannot
+ # disagree. A legacy row with no marker keeps the resume copy: its
+ # history genuinely cannot prove which of the two happened, and
+ # ``definition_lifecycle_expression`` makes the same call.
+ if str(watch.get("retired_at") or "").strip():
+ lines.append(self._t("harness.notice.watchRetired"))
+ else:
+ lines.append(self._t("harness.notice.watchPaused", id=definition_id))
+ # No re-run affordance, because there is no ``vibe watch run``: a watch
+ # fires when the thing it waits on happens. ``show`` is the action a
+ # user actually has.
+ lines.append(self._t("harness.notice.watchShow", id=definition_id))
+ else:
+ if task is not None and not task.enabled:
+ # FINISHED IS NOT PAUSED, the task-side twin of the watch branch
+ # above. A failed one-shot is disabled by ``mark_task_result``
+ # (``disable_one_shot``), so ``enabled = 0`` here carries two
+ # meanings — and the paused copy offers ``vibe task resume`` for
+ # a definition the canonical lifecycle projection reads as
+ # FINISHED, an action that re-arms nothing. The distinction is
+ # read from the projection ITSELF (``definition_lifecycle_state``
+ # evaluates the badge's own CASE for this row) rather than
+ # re-derived in Python, so the copy and the badge cannot
+ # disagree — not even in the window where a naive ``run_at`` in
+ # a non-UTC task timezone reads differently to
+ # ``compute_next_run_at`` and to SQLite's UTC clock. The
+ # explicit re-run affordance below stays either way: unlike a
+ # watch, ``vibe task run`` is real and is the honest next step.
+ lifecycle = self._task_lifecycle_state(definition_id, task)
+ if lifecycle == "finished":
+ lines.append(self._t("harness.notice.taskFinished"))
+ elif lifecycle == "paused":
+ lines.append(self._t("harness.notice.paused", id=definition_id))
+ # ``running`` (``vibe task run`` accepts a disabled one-shot, and
+ # an in-flight execution outranks the ended predicate) and
+ # ``waiting`` (a switch the mirror has not caught up with): no
+ # lifecycle line at all. Either copy would contradict the badge,
+ # and the re-run/show affordance below stands on its own.
+ elif task is not None:
+ next_run = compute_next_run_at(
+ enabled=task.enabled,
+ schedule_type=task.schedule_type,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ )
+ if next_run:
+ lines.append(self._t("harness.notice.nextRun", when=next_run))
+ lines.append(self._t("harness.notice.rerun", id=definition_id))
+ return "\n".join(lines)
+
+ @staticmethod
+ def _notice_command_preview(task: Any) -> str:
+ """The one-line command a notice names, or ``""`` for a non-command definition.
+
+ Reads whichever shape the caller has -- a ``ScheduledTask`` or the run's own
+ snapshot -- and hands both to the shared ``command_line_preview``, so the
+ command in a failure notice is the same string ``vibe task list`` showed.
+ """
+
+ return command_line_preview(
+ getattr(task, "shell_command", None), getattr(task, "command", None)
+ )
+
+ def _task_lifecycle_state(self, definition_id: Optional[str], task: Any) -> str:
+ """The lifecycle state the badge shows for this task — asked of the badge.
+
+ The authoritative answer is ``definition_lifecycle_state``, the same SQL CASE
+ every list and count surface evaluates, so the notice copy and the badge share
+ one clock and one parse of ``run_at`` — and one priority order: an in-flight
+ execution outranks the ended predicate, so the caller sees ``running`` rather
+ than a boolean that flattened it into "not finished". The Python inference
+ below it is a FALLBACK for the file backend and for a row the read cannot
+ reach: there is no SQL badge in those worlds to disagree with, and the
+ inference asks the same question the projection encodes
+ (``compute_next_run_at`` returns ``None`` exactly when the named instant is
+ behind us, with ``enabled=True`` so the switch cannot mask the clock).
+ """
+
+ if definition_id:
+ store = getattr(self.request_store, "_sqlite", None)
+ if store is not None:
+ try:
+ state = store.definition_lifecycle_state(
+ definition_id, definition_type="task"
+ )
+ except Exception:
+ logger.debug(
+ "failure notice: lifecycle-state read failed", exc_info=True
+ )
+ state = None
+ if state is not None:
+ return state
+ if task.schedule_type == "at" and not compute_next_run_at(
+ enabled=True,
+ schedule_type=task.schedule_type,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ ):
+ return "finished"
+ return "paused"
+
+ def _last_success_instant(self, definition_id: Optional[str]) -> Optional[str]:
+ """When this definition last succeeded, for the body's own context.
+
+ Read through the request store's SQLite handle, which is where run history lives
+ (the task mirror holds definitions, not runs). ``None`` on the file backend, on a
+ run with no definition, and on any read error: this is one context line on a
+ notice that must still be delivered, so an unanswerable question drops the line
+ rather than the notice.
+ """
+
+ if not definition_id:
+ return None
+ store = getattr(self.request_store, "_sqlite", None)
+ if store is None:
+ return None
+ try:
+ return store.last_success_settled_at(definition_id)
+ except Exception:
+ logger.debug("failure notice: last-success read failed", exc_info=True)
+ return None
+
+ def _deleted_definition_lines(self, run_id: str) -> list[str]:
+ """The only recovery copy a definition that no longer exists can honestly print.
+
+ One place, because both bodies need it and both had the same hole. The run row
+ outlives its definition, so the RUN is what is left to inspect — and
+ ``vibe runs show`` is a real subcommand with an optional positional run id,
+ vetted against the real parser by
+ ``test_a_deleted_definition_notice_names_only_run_level_recovery``.
+
+ No run id (a body rendered from a row rebuilt without one) prints the
+ explanation alone rather than ``vibe runs show`` with nothing after it: an
+ incomplete command is the WI-2 failure mode again, one argument smaller.
+ """
+
+ lines = [self._t("harness.notice.definitionDeleted")]
+ if run_id:
+ lines.append(self._t("harness.notice.runInspect", id=run_id))
+ return lines
+
+ def _binding_notice_body(
+ self,
+ notice: dict[str, Any],
+ *,
+ name: str,
+ definition_id: Optional[str],
+ definition_exists: bool,
+ run_id: str,
+ ) -> str:
+ """Copy for "your pinned session was replaced", which is not a failure report.
+
+ Two things the failure body must not do here. It opens with "failed" and
+ always prints an ``Error:`` line — for a run that SUCCEEDED that reads as a
+ false alarm, and with ``error=None`` the line degrades to "no error text was
+ recorded", which is noise about nothing. And its call to action is ``vibe task
+ run``, whereas the action a user actually wants after an unrequested rebind is
+ to pin the session back or look at what the definition is bound to now.
+
+ Every command named below is a real subcommand (``vibe task update
+ --session-id``, ``vibe task show``); the WI-2 lesson is that invented copy
+ fails nothing but the user. ``definition_exists`` is the second half of that
+ lesson: a rebind notice can outlive its definition by the whole retry/backoff
+ window, and a command that names a row which no longer exists is invented copy
+ by a slower route — it parses, and then reports "not found".
+ """
+
+ binding = notice.get("binding") if isinstance(notice.get("binding"), dict) else {}
+ previous = str(binding.get("previous_session_id") or "").strip()
+ new = str(binding.get("new_session_id") or "").strip()
+ lines = [self._t("harness.notice.rebound", name=name)]
+ if previous and new:
+ lines.append(self._t("harness.notice.reboundSessions", previous=previous, new=new))
+ if binding.get("settings_preserved"):
+ lines.append(self._t("harness.notice.reboundSettingsPreserved"))
+ else:
+ lines.append(self._t("harness.notice.reboundSettingsReset"))
+ if definition_id:
+ lines.append(self._t("harness.notice.definition", id=definition_id))
+ if definition_exists:
+ lines.append(self._t("harness.notice.reboundRepin", id=definition_id))
+ lines.append(self._t("harness.notice.show", id=definition_id))
+ else:
+ # Nothing left to re-pin OR to show. The rebind itself still happened
+ # and the lines above still report it — the news is not suppressed,
+ # only the actions that no longer address anything.
+ lines.extend(self._deleted_definition_lines(run_id))
+ return "\n".join(lines)
+
+ def settle_activity_runs(self, activity: Any) -> list[str]:
+ """Settle deferred Runs when a failed/stopped owned Activity is last."""
+
+ activity_status = str(getattr(activity, "status", "") or "").strip().lower()
+ if activity_status == "completed":
+ # A completed Claude task may still produce a user-visible follow-up;
+ # that Message owns Run settlement so output and callback stay aligned.
+ return []
+ terminal_status = "failed" if activity_status == "failed" else "canceled"
+ metadata = getattr(activity, "metadata", None) or {}
+ run_ids: list[str] = []
+ primary = str(getattr(activity, "run_id", "") or "").strip()
+ if primary:
+ run_ids.append(primary)
+ values = metadata.get("run_ids") if isinstance(metadata, dict) else None
+ if isinstance(values, list):
+ for value in values:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+
+ registry = getattr(getattr(self.controller, "agent_service", None), "activities", None)
+ has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ has_pending_output = getattr(registry, "has_pending_run_output", None)
+ settled: list[str] = []
+ for run_id in run_ids:
+ self.request_store.defer_run_terminal(
+ run_id,
+ terminal_status=terminal_status,
+ )
+ if callable(has_blocker) and has_blocker(run_id):
+ continue
+ if callable(has_pending_output) and has_pending_output(run_id):
+ continue
+ error = f"Background Activity {getattr(activity, 'id', '')} {activity_status}"
+ if self.request_store.settle_deferred_run(
+ run_id,
+ error=error,
+ ):
+ settled.append(run_id)
+ if settled:
+ self._drain_dirty = True
+ return settled
+
+ async def _drain_vault_callbacks(self) -> None:
+ """Auto-resume the requesting session when a vault request reaches a terminal state.
+
+ Mirrors :meth:`_drain_callbacks` but for ``vault_requests`` (which resolve outside the run
+ store): each row marked ``callback_status='pending'`` is turned into one callback turn via
+ the shared :func:`enqueue_session_callback` entry, then marked ``sent``/``skipped``/
+ ``failed``. Delivery is at-least-once, matching the run-store callback drain: enqueue and
+ the ``sent`` mark are separate writes, so a crash between them re-sends on the next tick.
+ Per-row isolation keeps one bad row from aborting the batch or being retried forever.
+ """
+ if not self._owns_service_instance():
+ return
+ from storage import vault_service
+
+ # Runs every tick, so use the process-local cached engine (never dispose it) rather than
+ # allocating a fresh engine per sweep.
+ engine = get_cached_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ # Expiry is lazy (only on request reads), so proactively expire overdue pending
+ # requests here — otherwise an unattended timed-out request would never arm its
+ # callback until some unrelated read touched it. Both happen in one pass.
+ vault_service.expire_overdue_requests(conn)
+ pending = vault_service.list_pending_request_callbacks(conn)
+ except Exception as exc:
+ logger.error("Vault request callback sweep failed to load: %s", exc, exc_info=True)
+ return
+ for row in pending:
+ request_id = str(row.get("id") or "")
+ if not request_id:
+ continue
+ # Resolve + enqueue as one guarded step so a bad row is marked (not left to retry
+ # forever) and does not abort the rest of the batch.
+ status = "skipped"
+ try:
+ with engine.begin() as conn:
+ ready = vault_service.request_callback_ready(conn, row)
+ if not ready:
+ # Approved access grant not delivery-ready yet (protected relay in flight);
+ # leave callback_status='pending' and retry on a later tick.
+ continue
+ plan = vault_service.resolve_request_callback(row)
+ if plan is not None:
+ enqueue_session_callback(
+ self.request_store,
+ session_id=plan.session_id,
+ message=plan.message,
+ source_actor=f"vault:{request_id}",
+ )
+ status = "sent"
+ except ValueError:
+ status = "skipped" # session archived / not a valid target — nothing to resume
+ except Exception as exc:
+ logger.error("Vault request callback failed for %s: %s", request_id, exc, exc_info=True)
+ status = "failed"
+ try:
+ with engine.begin() as conn:
+ vault_service.mark_request_callback(conn, request_id, status=status)
+ except Exception as exc:
+ # Leave callback_status='pending' → retried next tick (bounded, transient).
+ logger.error("Vault request callback mark failed for %s: %s", request_id, exc, exc_info=True)
+ continue
+ if status == "sent":
+ # A callback run was enqueued into the run store; drain it promptly.
+ self._drain_dirty = True
+
+ def _enqueue_callback_run(self, run: dict[str, Any]) -> Optional[TaskExecutionRequest]:
+ callback_session_id = str(run.get("callback_session_id") or "").strip()
+ if not callback_session_id:
+ return None
+ run_id = str(run.get("id") or "")
+ status = _normalize_requested_run_status(run.get("status")) or str(
+ run.get("status") or ""
+ )
+ if status in {"failed", "canceled"}:
+ terminal_message = self._fallback_callback_result(run, status=status)
+ terminal_callback = enqueue_session_callback(
+ self.request_store,
+ session_id=callback_session_id,
+ message=terminal_message,
+ source_actor=f"{run_id}:terminal:{status}",
+ parent_run_id=run_id or None,
+ )
+ if terminal_callback is not None:
+ return terminal_callback
+ return enqueue_session_callback(
+ self.request_store,
+ session_id=callback_session_id,
+ message=self._build_callback_message(run),
+ source_actor=run_id,
+ parent_run_id=run_id or None,
+ )
+
+ def _build_callback_message(self, run: dict[str, Any]) -> str:
+ status = _normalize_requested_run_status(run.get("status")) or str(run.get("status") or "")
+ result_text = str(run.get("result_text") or "").strip()
+ if not result_text:
+ result_text = self._fallback_callback_result(run, status=status)
+ return result_text.strip()
+
+ def _fallback_callback_result(self, run: dict[str, Any], *, status: str) -> str:
+ parts: list[str] = []
+ if run.get("error"):
+ parts.append(f"Error: {run['error']}")
+ if run.get("stderr"):
+ parts.append(str(run["stderr"]))
+ if run.get("stdout") and status != "succeeded":
+ parts.append(str(run["stdout"]))
+ if parts:
+ return "\n\n".join(part.strip() for part in parts if part and part.strip())
+ if status == "canceled":
+ return self._t("harness.run.fallbackResult.canceled")
+ if status == "failed":
+ return self._t("harness.run.fallbackResult.failed")
+ return ""
+
+ def _execution_lock_key(self, request: TaskExecutionRequest) -> Optional[str]:
+ """Canonical conversation identity for per-session single-flight.
+
+ Resolves task-only and session-id-only requests down to one canonical
+ key so any two requests targeting the same conversation serialize,
+ regardless of which identifier form they carry:
+
+ - ``scheduled``/``task_run`` rows may carry only a ``task_id``; the
+ real target lives on the task definition (mirrors
+ ``_execute_claimed_request``).
+ - a ``session_id`` is resolved to its canonical session key, so it
+ matches a legacy/watch run that only carries that ``session_key``.
+
+ Returns ``None`` for ``create_per_run`` (fresh session each time) and
+ unkeyable requests.
+
+ A COMMAND FIRE IS NOT A TURN, so it never takes a conversation's key. The lock
+ exists to stop two Agent turns running in one conversation at once; a command
+ talks to no Agent and holds no native session, yet it is bound to one (an
+ ``--on-failure agent`` definition must be), and ``--timeout`` defaults to six
+ hours -- so inheriting that key let one long backup command leave every queued
+ turn in the conversation skipped as ``session_busy`` for as long as it ran. Its
+ escalation IS a turn, and that is a separate run which takes the lock in the
+ ordinary way. Keyed on the definition rather than dropped to ``None`` so a fire
+ is still serialized against itself.
+ """
+ session_policy = request.session_policy
+ session_id = request.session_id
+ session_key = request.session_key
+ task_id = request.task_id
+ if request.request_type in {"task_run", "scheduled"} and task_id:
+ task = self.store.get_task(task_id)
+ if task is not None:
+ if task.has_command:
+ return f"task:{task_id}"
+ session_policy = task.session_policy or session_policy
+ session_id = task.session_id or session_id
+ session_key = task.session_key or session_key
+ if session_policy == "create_per_run":
+ return None
+ if session_id:
+ return self._canonical_session_lock(session_id, session_key)
+ if session_key:
+ return self._normalize_session_key(session_key)
+ if task_id:
+ return f"task:{task_id}"
+ return None
+
+ def _request_target_platform(self, request: TaskExecutionRequest) -> Optional[str]:
+ session_key = request.session_key
+ session_id = request.session_id
+ deliver_key = request.deliver_key
+ metadata = request.metadata or {}
+ if request.request_type in {"task_run", "scheduled"} and request.task_id:
+ task = self.store.get_task(request.task_id)
+ if task is not None:
+ session_key = task.session_key or session_key
+ session_id = task.session_id or session_id
+ deliver_key = task.deliver_key or deliver_key
+ metadata = task.metadata or metadata
+
+ if session_id:
+ return resolve_session_id_target(session_id).session_key.platform
+ if session_key:
+ try:
+ return parse_session_key(session_key).platform
+ except ValueError:
+ return parse_scope_id(session_key).platform
+
+ scope_id = str(metadata.get("session_scope_id") or "").strip()
+ if scope_id:
+ return parse_scope_id(scope_id).platform
+ if deliver_key:
+ try:
+ return parse_session_key(deliver_key).platform
+ except ValueError:
+ return parse_scope_id(deliver_key).platform
+ return None
+
+ def _transport_ready_for_request(self, request: TaskExecutionRequest) -> bool:
+ if request.request_type in {"task_run", "scheduled"} and request.task_id:
+ task = self.store.get_task(request.task_id)
+ if task is not None and task.has_command:
+ # A command run needs no IM transport: it produces an exit code and
+ # output, not a reply. Gating it on a platform's readiness would hold a
+ # backup or health check queued while an unrelated IM adapter is down.
+ # The failure-notice path owns delivery, and it can be owed later.
+ return True
+ try:
+ platform = self._request_target_platform(request)
+ except Exception:
+ logger.debug("Could not resolve Run %s platform for readiness gating", request.id, exc_info=True)
+ return True
+ if not platform:
+ return True
+ is_ready = getattr(self.controller, "is_im_transport_ready", None)
+ return bool(is_ready(platform)) if callable(is_ready) else True
+
+ def notify_transport_ready(self, platform: str) -> None:
+ logger.info("Transport %s ready; scheduled Run queue will be drained", platform)
+ self._drain_dirty = True
+
+ def _canonical_session_lock(self, session_id: str, session_key: Optional[str]) -> str:
+ cached = self._session_lock_cache.get(session_id)
+ if cached is not None:
+ return cached
+ try:
+ resolved = resolve_session_id_target(session_id)
+ # avibe/workbench sessions are 1:1 with the session id — a project scope
+ # holds many INDEPENDENT sessions, so locking on the project key would
+ # serialize unrelated conversations. Lock on the concrete session id.
+ if resolved.session_key.platform == "avibe" or resolved.session_key.scope_type == "project":
+ key = f"sid:{session_id}"
+ else:
+ key = f"key:{resolved.session_key.to_key()}"
+ except Exception:
+ # avibe/web sessions (no IM scope) or unresolved ids: fall back to a
+ # carried session key if present, else the id is its own identity.
+ key = self._normalize_session_key(session_key) if session_key else f"sid:{session_id}"
+ self._session_lock_cache[session_id] = key
+ return key
+
+ @staticmethod
+ def _normalize_session_key(session_key: str) -> str:
+ try:
+ return f"key:{parse_session_key(session_key).to_key()}"
+ except Exception:
+ return f"key:{session_key}"
+
+ def _spawn_execution(self, request: TaskExecutionRequest, lock_key: Optional[str]) -> None:
+ if lock_key is not None:
+ self._inflight_sessions.add(lock_key)
+ # Recorded BEFORE ``create_task`` so the one way this lock can leak — the
+ # task never being created, hence ``_on_execution_done`` never attached —
+ # still leaves an owner the sweep can trace back to a dead execution.
+ self._session_lock_owners[lock_key] = request.id
+ task = asyncio.create_task(self._execute_claimed_request(request))
+ self._inflight_executions[request.id] = task
+ self._inflight_requests[request.id] = request
+ task.add_done_callback(
+ lambda finished, rid=request.id, key=lock_key: self._on_execution_done(rid, key, finished)
+ )
+
+ def _on_execution_done(
+ self, request_id: str, lock_key: Optional[str], task: "asyncio.Task[Any]"
+ ) -> None:
+ self._inflight_executions.pop(request_id, None)
+ request = self._inflight_requests.pop(request_id, None)
+ interruption = self._inflight_cancellation_causes.pop(
+ request_id,
+ SETTLED_BY_INTERRUPTED,
+ )
+ if lock_key is not None:
+ self._inflight_sessions.discard(lock_key)
+ # Only if it is still OURS: a later execution may already have taken the
+ # same key, and stealing its owner entry would make the sweep read that
+ # live lock as leaked.
+ if self._session_lock_owners.get(lock_key) == request_id:
+ self._session_lock_owners.pop(lock_key, None)
+ self._drain_dirty = True
+ # ``_execute_claimed_request`` already terminalizes cancellations and
+ # records ordinary failures. A task cancelled before its coroutine enters
+ # has no execution to settle; put that bare claim back in the queue.
+ if task.cancelled():
+ if request is not None:
+ try:
+ current = self.request_store.get_run(request.id)
+ if not current or current.get("status") in TERMINAL_RUN_STATUSES:
+ return
+ if (
+ current.get("pid") is None
+ ):
+ self.request_store.requeue(request.id)
+ return
+ written_status = self.request_store.complete(
+ request,
+ ok=False,
+ error=self._t(SETTLEMENT_I18N_KEYS[interruption]),
+ interrupt_reason=interruption,
+ )
+ if written_status is not None and request.task_id and request.request_type in {
+ "task_run",
+ "scheduled",
+ }:
+ self._project_terminal_definition_result(
+ self.request_store.get_run(request.id),
+ execution_id=request.id,
+ expected_status=written_status,
+ )
+ self.reconcile_jobs()
+ except Exception:
+ logger.exception(
+ "Failed to terminalize canceled claimed request %s",
+ request_id,
+ )
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.error("Claimed request %s crashed: %r", request_id, exc, exc_info=exc)
+
+ async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:
+ if not self.request_store.mark_execution_started(request.id):
+ # A terminal result or explicit cancellation won after claim but before
+ # this coroutine entered. Do not dispatch work whose Run no longer owns
+ # the execution boundary.
+ return
+ request = self.request_store.refresh_claimed_request(request)
+ error: Optional[str] = None
+ #: The structured CLASS of this run's failure, when the failure has one. Kept
+ #: beside ``error`` rather than parsed back out of it: the text is a sentence
+ #: for a human, this is the value the notice's lane and label are chosen from.
+ interrupt_reason: Optional[str] = None
+ failure_code: Optional[str] = None
+ should_complete = True
+ settled_out_of_band = False
+ recover_queue_on_return = False
+ reconcile_delivery_on_return = False
+ project_terminal_definition_on_cancel = False
+ task_id = request.task_id
+ session_key = request.session_key
+ session_id = request.session_id
+ #: Command-fire outcome facts. They stay ``None`` for every other request type,
+ #: which is what keeps those rows' columns untouched.
+ exit_code: Optional[int] = None
+ stdout: Optional[str] = None
+ stderr: Optional[str] = None
+ #: The already-durable escalation turn a failed ``--on-failure agent`` command
+ #: fire queued, or ``None``. Recorded on THIS run's metadata by ``complete()``,
+ #: which is what stops the same failure being reported twice.
+ escalation_run_id: Optional[str] = None
+ try:
+ if request.request_type in {"task_run", "scheduled"}:
+ self.store.maybe_reload()
+ task = self.store.get_task(request.task_id or "")
+ if task is None:
+ raise ValueError(f"task '{request.task_id}' not found")
+ task_id = task.id
+ session_key = task.session_key
+ session_id = task.session_id
+ task_agent_id = (
+ request.agent_id
+ if task.agent_name and task.agent_name == request.agent_name
+ else None
+ )
+ result = await self._execute_task(
+ task,
+ execution_id=request.id,
+ disable_one_shot=request.source_kind == "scheduler",
+ agent_id=task_agent_id,
+ )
+ error = result.error
+ session_key = result.session_key
+ session_id = result.session_id
+ failure_code = result.failure_code
+ should_complete = result.complete_on_return
+ reconcile_delivery_on_return = result.reconcile_delivery_on_return
+ exit_code = result.exit_code
+ stdout = result.stdout
+ stderr = result.stderr
+ escalation_run_id = result.escalation_run_id
+ elif request.request_type in {
+ "hook_send",
+ "watch",
+ "webhook",
+ "task_escalation",
+ }:
+ if not request.prompt:
+ raise ValueError("hook request requires prompt")
++ user_context = self._resource_user_context(request.metadata)
+ if request.session_policy == "create_per_run":
+ session_id = self._reserve_runtime_session(
+ agent_name=request.agent_name,
+ agent_id=request.agent_id,
+ deliver_key=request.deliver_key,
+ metadata=request.metadata,
+ workdir=request.metadata.get("session_workdir") if isinstance(request.metadata, dict) else None,
++ user_context=user_context,
+ )
+ session_key = ""
+ elif not (request.session_id or request.session_key):
+ raise ValueError("hook request requires session_id or session_key")
+ dispatch_result = await self._execute_request(
+ session_key=session_key,
+ session_id=session_id,
+ post_to=request.post_to,
+ deliver_key=request.deliver_key,
+ prompt=request.prompt,
+ execution_id=request.id,
+ task_id=task_id,
+ # ``delivery_intent_for_trigger`` has a CLOSED vocabulary, and an
+ # escalation IS a hook send -- an out-of-band turn a definition
+ # queued -- so it takes the hook intent rather than a new one no
+ # mapping knows. Provenance is not lost: the run row still carries
+ # ``run_type="task_escalation"`` and the failed fire's
+ # ``parent_run_id``.
+ trigger_kind=(
+ "hook"
+ if request.request_type in {"hook_send", "task_escalation"}
+ else request.request_type
+ ),
+ agent_name=request.agent_name,
++ metadata=request.metadata,
++ user_context=user_context,
+ _capture_dispatch_result=True,
+ **({"agent_id": request.agent_id} if request.agent_id else {}),
+ )
+ if isinstance(dispatch_result, TaskDispatchResult):
+ error = dispatch_result.error
+ should_complete = dispatch_result.complete_on_return
+ else:
+ error = dispatch_result
+ elif request.request_type == "agent_run":
+ message = _agent_run_message_for_request(request)
+ if not message.strip():
+ # Whitespace-only counts as absent. ``MessageHandler`` returns
+ # early for a blank prompt without dispatching an agent, so
+ # accepting one here produced a run that could never receive a
+ # terminal result. Fail it at the door instead.
+ raise ValueError("agent run requires message")
+ if not (request.session_id or request.session_key):
+ raise ValueError("agent run currently requires session_id or a resolvable session target")
+ result = await self._execute_agent_run(
+ session_key=request.session_key,
+ session_id=request.session_id,
+ post_to=request.post_to,
+ deliver_key=request.deliver_key,
+ message=message,
+ execution_id=request.id,
+ agent_name=request.agent_name,
+ **({"agent_id": request.agent_id} if request.agent_id else {}),
+ metadata={
+ **(request.metadata or {}),
+ "source_kind": request.source_kind,
+ "source_actor": request.source_actor,
+ "parent_run_id": request.parent_run_id,
+ "callback_session_id": request.callback_session_id,
+ },
+ )
+ 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:
+ requeue_metadata: dict[str, Any] = {}
+ 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)
+ else:
raise ValueError(f"unknown task request type: {request.request_type}")
except asyncio.CancelledError:
- self.request_store.requeue(request.id)
- should_complete = False
+ interrupt_reason = self._execution_interruption(request.id)
+ error = self._t(SETTLEMENT_I18N_KEYS[interrupt_reason])
+ should_complete = True
+ settled_out_of_band = False
+ recover_queue_on_return = False
+ project_terminal_definition_on_cancel = request.request_type in {
+ "task_run",
+ "scheduled",
+ }
raise
+ except UnresolvableSessionTarget as exc:
+ # THE RUN'S DELIVERY TARGET IS GONE, and that is a CLASS of failure rather
+ # than one more error string. #1060's field evidence is the case: a watch
+ # pinned to a session that ceased to exist failed three deliveries and
+ # stopped, and the only recorded cause anywhere was ``last_exit_code = 75``
+ # — the user's own ``--retry-exit-code``, i.e. the waiter's healthy
+ # "nothing new yet" signal. The error TEXT was already right here (it names
+ # the missing session id); what was missing was a structured class, so the
+ # notice could say the failure is about the DESTINATION and a reader could
+ # tell it apart from the work itself breaking.
+ #
+ # Placed at the top level, not nested around the hook branch, so a run type
+ # added later inherits the classification instead of having to remember it.
+ # It cannot over-reach: ``UnresolvableSessionTarget`` is a distinct type
+ # raised only by ``resolve_session_id_target``, never by a transient fault.
+ #
+ # Which branches actually arrive here. ``watch`` / ``hook_send`` / ``webhook``
+ # and ``agent_run`` do — none of them resolves the target before dispatch, so
+ # this is their first and only handler. ``task_run`` does NOT: ``_execute_task``
+ # catches the same type first, runs the binding recovery
+ # (``_recover_pinned_session_binding``), and absorbs a failed rebind retry in
+ # its own ``except``. That asymmetry is deliberate and predates this handler —
+ # a task has a definition to rebind or pause, and its recovery already stamps
+ # a ``binding_change`` notice of its own.
+ #
+ # ONLY ``reason == "missing"`` IS CLASSIFIED. ``archived`` is left
+ # unclassified on purpose: an archived session's row still exists, and the
+ # honest description of that failure is "the session is inert", not "it no
+ # longer exists". Its NOTICE is still deliverable — rung (5) reroutes an
+ # archived session to the workspace inbox rather than writing into a row
+ # ``list_inbox_sessions`` hides (see ``_rung_five_session_id``) — so the
+ # reader is not left with an unnamed failure they cannot see. A wrong class
+ # is worse than no class — the label is the one line in the notice a reader
+ # trusts about the shape of the failure — and
+ # ``notice_failure_class_i18n_key`` already renders NO line rather than a
+ # generic one when there is nothing to name. Same for ``unusable``.
+ error = str(exc)
+ failure_code = FAILURE_CODE_UNRESOLVABLE_TARGET
+ if exc.reason == "missing":
+ interrupt_reason = INTERRUPT_REASON_DELIVERY_TARGET_MISSING
+ logger.error(
+ "Task execution request %s cannot reach its delivery target: %s",
+ request.id,
+ exc,
+ exc_info=True,
+ )
+ should_complete = True
+ settled_out_of_band = False
+ except Exception as exc:
+ error = str(exc)
+ logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
+ should_complete = True
+ settled_out_of_band = False
+ finally:
+ if should_complete:
+ written_status = self.request_store.complete(
+ request,
+ ok=not error,
+ error=error,
+ task_id=task_id,
+ session_key=session_key,
+ session_id=session_id,
+ interrupt_reason=interrupt_reason,
+ failure_code=failure_code,
+ exit_code=exit_code,
+ stdout=stdout,
+ stderr=stderr,
+ escalation_run_id=escalation_run_id,
+ )
+ # A STOP THAT NEVER BECAME A ``CancelledError``. ``cancel_run`` can
+ # commit its flag after the work returned, so ``complete`` normalizes
+ # this run to ``canceled`` while the coroutine ran to the end without
+ # ever being interrupted -- and a command stamp refused by that same
+ # flag then left the definition still reporting the fire BEFORE this
+ # one. Read from the status ACTUALLY written rather than from
+ # ``project_terminal_definition_on_cancel``, which says only that the
+ # cancellation arrived the usual way: a service shutdown cancels the
+ # same coroutine and settles ``interrupted``, which is a stop of the
+ # SERVICE and not of this fire.
+ fire_was_stopped = written_status == "canceled" and request.request_type in {
+ "task_run",
+ "scheduled",
+ }
+ if fire_was_stopped:
+ # BEFORE the projection, because the escalation is claimable the
+ # whole time this coroutine is still finishing up.
+ self._retract_escalation_of_stopped_fire(request.id)
+ if written_status is not None and (
+ # The projection is the lane that settles a canceled fire.
+ project_terminal_definition_on_cancel
+ or fire_was_stopped
+ ):
+ self._project_terminal_definition_result(
+ self.request_store.get_run(request.id),
+ execution_id=request.id,
+ expected_status=written_status,
+ )
+ self.reconcile_jobs()
+ if reconcile_delivery_on_return and session_id:
+ manager = getattr(self.controller, "session_turns", None)
+ reconcile_delivery = getattr(
+ manager,
+ "reconcile_terminal_run_delivery",
+ None,
+ )
+ if callable(reconcile_delivery):
+ try:
+ await reconcile_delivery(request.id, session_id=session_id)
+ except Exception:
+ logger.exception(
+ "Failed to reconcile terminal task Delivery: run=%s session=%s",
+ request.id,
+ session_id,
+ )
+ if should_complete or settled_out_of_band:
+ # An out-of-band settlement still made this run terminal, so it owes
+ # the same callback follow-through as ``complete()``.
+ await self._drain_callbacks()
+ if (
+ request.request_type == "agent_run"
+ and session_id
+ and (
+ should_complete
+ or settled_out_of_band
+ or recover_queue_on_return
+ )
+ and interrupt_reason is None
+ ):
+ 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,
+ )
+
+ def _runtime_default_workdir(self) -> Optional[str]:
+ """The configured directory Agent work runs in, when nothing closer answered.
+
+ Last stop before the ``~/.avibe`` fallback, and the reason that fallback is now
+ nearly unreachable: a definition can legitimately carry no ``cwd`` and no
+ readable Session -- a per-run binding created before
+ ``_command_definition_spawn_cwd`` recorded one, or a definition written straight
+ through the API -- and the product state directory is the worst possible place to
+ run a user's command. ``runtime.default_cwd`` is where this install's Agent turns
+ already run, so it is the same answer the escalation Session would get.
+
+ Validated here rather than trusted: an unset or deleted ``default_cwd`` must fall
+ through to the fallback below, not fail the fire with ``workdirMissing``.
+ """
+
+ config = getattr(self.controller, "config", None)
+ candidate = getattr(getattr(config, "runtime", None), "default_cwd", None)
+ if not isinstance(candidate, str) or not candidate.strip():
+ return None
+ resolved = os.path.abspath(os.path.expanduser(candidate.strip()))
+ return resolved if os.path.isdir(resolved) else None
+
+ def _bound_session_workdir(self, task: ScheduledTask) -> Optional[str]:
+ """Where a command with no stored ``cwd`` should run: its binding's directory.
+
+ ``--cwd`` is REFUSED for a definition bound to an existing Session
+ (``cwd_with_existing_session``), on the rule that the Session owns its working
+ directory -- so an escalating command task legitimately stores ``cwd=None``. A
+ message task loses nothing to that: the Agent turn starts in the Session's
+ workdir. A command has no turn to inherit it from, so ``None`` fell through to
+ the ``~/.avibe`` fallback and ``--shell './scripts/sync.sh'`` -- the form the
+ docs use -- ran from the product state directory, with the one flag that could
+ have said otherwise rejected by the Session rule.
+
+ Read live rather than copied into the definition at creation time, so the
+ command follows a Session whose workdir was later changed, and so a per-run
+ binding that does not exist yet simply reads as "no answer" (``None``) instead
+ of a stale one. Best effort by design: a missing row, a NULL workdir or a read
+ failure all fall back rather than failing the fire, and the fallback is still
+ validated by the ``isdir`` check below.
+ """
+
+ session_id = str(task.session_id or "").strip()
+ if not session_id:
+ return None
+ try:
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(paths.get_sqlite_state_path())
+ try:
+ row = service.get_agent_session_by_id(session_id)
+ finally:
+ # One store per FIRE, so it must not outlive the read: each one
+ # carries an engine and an invalidation probe, and a cron command
+ # running every minute would otherwise accumulate a connection a
+ # minute for the life of the service.
+ service.close()
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning(
+ "Could not read the workdir of Session %s bound to task %s: %s",
+ session_id,
+ task.id,
+ exc,
+ )
+ return None
+ if not row:
+ return None
+ return str(row.get("workdir") or "").strip() or None
+
+ async def _execute_command_task(
+ self, task: ScheduledTask, *, execution_id: str, disable_one_shot: bool
+ ) -> TaskExecutionResult:
+ """Run one command definition's fire and record its outcome.
+
+ The command runner owns the process mechanics -- spawn, spec handshake,
+ timeout, cancellation and tree teardown -- so this method owns only scheduled
+ task policy: where to run, how long to allow, and how the outcome is written
+ to the definition and the run row.
+
+ Every ORDERLY stop reaches the child through the runner: a timeout kills the
+ tree from inside, while a service stop and a ``vibe runs cancel`` both cancel
+ the awaiting coroutine, which the runner turns into a tree teardown (see
+ ``_propagate_requested_cancellations`` for how the cancel flag becomes that
+ cancellation). A SIGKILLed or crashed service reaches it through none of them:
+ no ``CancelledError`` is ever delivered, and the isolated supervisor keeps its
+ command running -- so a later fire of the same cron would start a second
+ backup or migration beside the orphan. ``on_spawn`` therefore persists the
+ worker identity on the run for ``_reap_orphaned_command_workers`` to find on
+ the next start, and the ``finally`` clears it the moment the child is reaped.
+
+ That identity lives in the run's ``metadata``, NOT in its ``pid`` column: that
+ column holds the SERVICE pid, written by ``mark_execution_started`` for the
+ recovery gate, and must not be repurposed.
+ """
+
+ error: Optional[str] = None
+ exit_code: Optional[int] = None
+ stdout_value: Optional[str] = None
+ stderr_value: Optional[str] = None
+ #: Whether the SCHEDULER stopped this fire, as opposed to the command choosing
+ #: its own exit status. Recorded separately because the two are indistinguishable
+ #: from the code alone: the runner reports a timeout as 124, and ``timeout 5 ...``
+ #: inside a shell command reports a real one as 124 too.
+ timed_out = False
+
+ # BEFORE anything can fail, and before the spawn: the enqueue predicted this
+ # command from the definition as it stood then, and the executor re-read the
+ # definition after claiming. This is the copy that will actually run.
+ self._record_executed_command(execution_id, task)
+
+ spawn_cwd = (
+ task.cwd
+ or self._bound_session_workdir(task)
+ or self._runtime_default_workdir()
+ )
+ if not spawn_cwd:
+ stable_cwd = paths.get_vibe_remote_dir()
+ stable_cwd.mkdir(parents=True, exist_ok=True)
+ spawn_cwd = str(stable_cwd)
+
+ if not os.path.isdir(spawn_cwd):
+ # Do NOT spawn: ``create_subprocess_exec`` would raise a bare
+ # ``NotADirectoryError``/``FileNotFoundError`` whose text does not name the
+ # directory the user configured.
+ error = self._t("harness.command.workdirMissing", cwd=spawn_cwd)
+ else:
+ effective_timeout = (
+ task.timeout_seconds
+ if task.timeout_seconds is not None
+ else COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS
+ )
+ try:
+ result = await run_supervised_command(
+ command=task.command,
+ shell_command=task.shell_command,
+ cwd=spawn_cwd,
+ timeout_seconds=effective_timeout,
+ label=f"scheduled task {task.id}",
+ on_spawn=lambda pid, identity: self._require_command_worker_record(
+ execution_id, identity
+ ),
+ max_output_bytes=COMMAND_TASK_OUTPUT_CAP_BYTES,
+ )
+ except SupervisedCommandStartupError as exc:
+ # Its own clause, BEFORE the broad one: the class subclasses
+ # ``RuntimeError``, so a single ``except Exception`` would swallow it and
+ # report the worker's startup failure as an ordinary command error.
+ error = self._localize_worker_error(exc.detail) or self._t(
+ "harness.command.supervisorExitedDuringStartup"
+ )
+ except Exception as exc:
+ error = str(exc)
+ logger.error(
+ "Scheduled task %s command failed: %s", task.id, exc, exc_info=True
+ )
+ else:
+ exit_code = result.exit_code
+ # THE WORKER'S OWN FAILURES ARRIVE HERE, not only through
+ # ``SupervisedCommandStartupError``: that is raised solely when the
+ # stdin handshake breaks, so a worker that accepted the spec and THEN
+ # could not spawn (an argv whose executable does not exist is the
+ # ordinary case) simply exits 1 with its machine-readable error line on
+ # stderr. Left undecoded, that raw JSON became the definition's
+ # ``last_error``, the failure notice, and the Agent escalation prompt.
+ worker_error = decode_watch_worker_error(result.stderr or "")
+ stderr_value = self._localize_worker_error(result.stderr)
+ stdout_value = result.stdout
+ if result.timed_out:
+ # Both streams are kept: whatever the command printed before it
+ # hung is the only evidence of WHY it hung, and a timeout has no
+ # exit status that explains itself. The runner preserves the
+ # capped readers' buffers across the kill for exactly this.
+ timed_out = True
+ error = self._t(
+ "harness.command.timedOut",
+ seconds=_format_seconds(effective_timeout),
+ )
+ elif worker_error is not None:
+ # THE SUPERVISOR'S EXIT STATUS IS NOT THE COMMAND'S. ``main()``
+ # returns 1 for both of its own failures, so a spawn the worker
+ # could not perform arrived here as ``exit_code == 1`` and was
+ # published as a fact about the user's command: "Exit code: 1" in
+ # the failure notice and the escalation prompt, ``last_exit_code = 1``
+ # on the definition, an ``exit_code`` in the run row that
+ # ``vibe runs show`` prints -- for a command that never started, and
+ # alongside "Command exited with status 1" contradicting the
+ # supervisor sentence in the same message. There IS no command exit
+ # status in this outcome, and ``None`` is how this lane spells that
+ # (the handshake failure above reports it the same way). The error
+ # line the worker wrote is the discriminator, decoded rather than
+ # sniffed: only the supervisor emits it, before any of the command's
+ # own output can reach the stream, and a command that forged it is
+ # already reporting itself as a supervisor failure through
+ # ``_localize_worker_error`` -- losing an exit code it lied about is
+ # the smaller half of that.
+ #
+ # The WATCH lane keeps its exit code here by design: a cycle's status
+ # drives ``retry_exit_codes`` and ``_CycleResult`` has no "no status"
+ # to spell, so leave that behaviour to the lane that owns it.
+ exit_code = None
+ error = stderr_value or self._t(
+ "harness.command.unknownSupervisorFailure"
+ )
+ elif exit_code:
+ detail = _last_nonempty_line(stderr_value)
+ error = (
+ self._t(
+ "harness.command.exitedWithDetail",
+ code=exit_code,
+ detail=detail,
+ )
+ if detail
+ else self._t("harness.command.exited", code=exit_code)
+ )
+ finally:
+ # Reached on success, on failure, and on the ``CancelledError`` a
+ # stop raises: by the time control is here the runner has reaped
+ # the tree, so the stored identity now names a dead pid that the
+ # OS is free to hand to something else.
+ self._clear_command_worker(execution_id)
+
+ # THE ESCALATION IS COMPOSED BEFORE THE STAMP AND QUEUED BY IT. A definition
+ # carrying ``on_failure == "agent"`` owes the user ONE Agent turn per failed
+ # fire, carrying the report -- and that turn is what the stamp AUTHORISES, so
+ # the two must be one transaction (HFR-269, ``core/watches.py``: "TWO COMMITS
+ # ARE NOT ONE DECISION"). Split in two, a teardown landing between them queues
+ # an escalation under a definition that no longer authorises it, and an
+ # exception between them disables a failed one-shot while LOSING the report.
+ #
+ # Never ``enqueue_definition_run``: that writer re-reads the definition and
+ # RAISES on a disabled one, and a failed ``at`` task is disabled by the very
+ # stamp that authorises this turn.
+ escalation_request = None
+ if error and task.on_failure == "agent":
+ escalation_request = self.request_store.build_hook_send(
+ session_key=task.session_key or "",
+ session_id=task.session_id,
+ prompt=self._escalation_prompt(
+ task,
+ run_id=execution_id,
+ error=error,
+ exit_code=exit_code,
+ stdout=stdout_value,
+ stderr=stderr_value,
+ ),
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ agent_name=task.agent_name,
+ session_policy=task.session_policy,
+ run_type="task_escalation",
+ definition_id=task.id,
+ source_kind="scheduler",
+ parent_run_id=execution_id,
+ metadata=dict(task.metadata or {}),
+ )
+ stamped = self.store.mark_task_result(
+ task.id,
+ error=error,
+ disable_one_shot=disable_one_shot,
+ exit_code=exit_code,
+ # This IS the command fire's own result, so its ``exit_code`` -- including
+ # ``None`` for a fire that never spawned -- is the whole truth about the
+ # definition's last status.
+ records_command_outcome=True,
+ timed_out=timed_out,
+ # THE BINDING THIS FIRE STARTED AGAINST, and only when a turn is being
+ # authorised. ``mark_task_result`` reloads the mirror and derives its
+ # compare-and-set expectation from the RELOADED row, so a ``/new`` reclaim
+ # committed while the command ran becomes the expectation -- it matches, and
+ # the stamp lands. Harmless while the stamp wrote only bookkeeping; not
+ # harmless now that it queues an Agent turn, because the escalation above was
+ # composed from the PRE-EXECUTION task and would be durably queued against
+ # the session the reclaim just tore down, with the notice suppressed in its
+ # favour. Refusing instead rolls both halves back and leaves the failure to
+ # the owed-notice ladder.
+ expected_binding=(
+ (task.session_id, task.session_key, task.schedule_type)
+ if escalation_request is not None
+ else None
+ ),
+ # AND THAT THIS FIRE HAS NOT BEEN STOPPED, re-read server-side for the same
+ # reason and in the same transaction. A ``vibe runs cancel`` committed while
+ # the command was exiting settles the run ``canceled`` a moment later, and
+ # without this the turn it authorises would already be durably queued: the
+ # user stops a job and the job answers by starting an Agent.
+ expected_uncanceled_run_id=(
+ execution_id if escalation_request is not None else None
+ ),
+ queued_run=(
+ self.request_store.queued_run_payload(escalation_request)
+ if escalation_request is not None
+ else None
+ ),
+ )
+ # ONLY when the stamp landed. A refusal rolled the escalation row back with it,
+ # so claiming an escalation id here would suppress the failure notice in favour
+ # of a turn that does not exist -- and the failure would be silent.
+ escalation_run_id = (
+ escalation_request.id if escalation_request is not None and stamped else None
+ )
+ if not stamped:
+ # Same refusal as the message path (HFR-261/HFR-264): the definition was
+ # reclaimed, repointed or removed while this fire was running, so nothing
+ # was stored. A would-be success must not be reported as one.
+ logger.warning(
+ "Scheduled task %s produced a result the store refused to stamp; "
+ "reporting the run as failed",
+ task.id,
+ )
+ if not error:
+ error = self._t(_TASK_RESULT_NOT_RECORDED_I18N_KEY)
+ # An ``at`` command task just disabled itself; the APScheduler job must drop.
+ self.reconcile_jobs()
+ return TaskExecutionResult(
+ error=error,
+ session_key=task.session_key or "",
+ session_id=task.session_id,
+ failure_code=None,
+ complete_on_return=True,
+ exit_code=exit_code,
+ stdout=stdout_value,
+ stderr=stderr_value,
+ escalation_run_id=escalation_run_id,
+ )
+
+ def _escalation_prompt(
+ self,
+ task: ScheduledTask,
+ *,
+ run_id: str,
+ error: str,
+ exit_code: Optional[int],
+ stdout: Optional[str],
+ stderr: Optional[str],
+ ) -> str:
+ """The Agent-facing failure report a ``--shell ... --on-failure agent`` fire sends.
+
+ NOT i18n'd, deliberately, and the watch completion-hook prompts are the
+ precedent: this text is read by an AGENT, not shown to a user. It is the input
+ to a turn, so the reply it produces is what the user actually reads -- and that
+ reply is written in whatever language the conversation is in. Localizing the
+ input would only make the instructions the model follows vary by locale.
+
+ The user's own stored message comes FIRST when there is one: it is the standing
+ instruction ("open a ticket if the backup fails"), and the machine-generated
+ report is the evidence it operates on.
+ """
+
+ lines: list[str] = []
+ stored_message = (task.prompt or "").strip()
+ if stored_message:
+ lines.append(stored_message)
+ lines.append("")
+ label = (task.name or "").strip()
+ lines.append(
+ f"A scheduled command task failed: {label} ({task.id})"
+ if label
+ else f"A scheduled command task failed: {task.id}"
+ )
+ command_preview = self._notice_command_preview(task)
+ if command_preview:
+ lines.append(f"Command: {command_preview}")
+ # ``error`` already names the outcome in the only form that covers every branch:
+ # the exit status, the timeout, a missing working directory, or the supervisor's
+ # own startup detail. The exit code line is added only when the fire actually
+ # produced one -- a run that never spawned has none, and "Exit code: None" would
+ # be a fabricated fact on the one message that has to be trusted.
+ lines.append(f"Outcome: {error}")
+ if exit_code is not None:
+ lines.append(f"Exit code: {exit_code}")
+ stdout_tail = _last_nonempty_line(stdout)
+ if stdout_tail:
+ lines.append(f"Last stdout line: {stdout_tail}")
+ stderr_tail = _last_nonempty_line(stderr)
+ if stderr_tail:
+ lines.append(f"Last stderr line: {stderr_tail}")
+ lines.append(f"Run id: {run_id}")
+ lines.append(f"Inspect with: vibe runs show {run_id}")
+ return "\n".join(lines)
+
+ async def _execute_task(
+ self,
+ task: ScheduledTask,
+ *,
+ execution_id: str,
+ disable_one_shot: bool,
+ agent_id: Optional[str] = None,
+ ) -> TaskExecutionResult:
+ error: Optional[str] = None
+ complete_on_return = True
+ reconcile_delivery_on_return = False
+ failure_code: Optional[str] = None
+ session_id = task.session_id
+ session_key = task.session_key
++ user_context = self._resource_user_context(task.metadata)
+ binding_change: Optional[SessionBindingChange] = None
+ # HFR-276: an earlier fire of THIS definition may have reserved a replacement
+ # session it could not give back. The id is recorded on the definition, so the
+ # retry belongs here -- before the fire, so a cleanup that succeeds is off the
+ # books whatever this run does, and outside the ``try`` because it reports
+ # itself and must never be mistaken for the run's own failure.
+ self._retry_orphaned_reservations(task)
+ if task.has_command:
+ # A command definition runs a subprocess instead of prompting an Agent, so
+ # none of the session/binding machinery below applies to it. An
+ # ``on_failure == "agent"`` definition queues its escalation turn from in
+ # there, in the same transaction as its result stamp -- it does not dispatch
+ # one from here.
+ return await self._execute_command_task(
+ task, execution_id=execution_id, disable_one_shot=disable_one_shot
+ )
+ try:
+ if task.session_policy == "create_per_run":
+ session_id = self._reserve_runtime_session(
+ agent_name=task.agent_name,
+ agent_id=agent_id,
+ deliver_key=task.deliver_key,
+ metadata=task.metadata,
+ workdir=task.cwd,
++ user_context=user_context,
+ )
+ session_key = ""
+ dispatch_result = await self._execute_request(
+ session_key=session_key,
+ session_id=session_id,
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ prompt=task.prompt,
+ execution_id=execution_id,
+ task_id=task.id,
+ trigger_kind="scheduled",
+ agent_name=task.agent_name,
++ metadata=task.metadata,
++ user_context=user_context,
+ _capture_dispatch_result=True,
+ **({"agent_id": agent_id} if agent_id else {}),
+ )
+ if isinstance(dispatch_result, TaskDispatchResult):
+ error = dispatch_result.error
+ complete_on_return = dispatch_result.complete_on_return
+ else:
+ error = dispatch_result
+ except UnresolvableSessionTarget as exc:
+ # The pinned session no longer resolves. Left alone this definition
+ # re-fires and re-fails on every schedule with nobody told, so classify
+ # first: a ``create_once`` definition reserved its own session and may
+ # re-reserve one, anything else is user-pinned and gets paused. Either
+ # way the user is told exactly once.
+ logger.error("Scheduled task %s has an unresolvable session binding: %s", task.id, exc)
+ binding_change = self._recover_pinned_session_binding(task, exc)
+ error = binding_change.detail
+ failure_code = FAILURE_CODE_UNRESOLVABLE_TARGET
+ if binding_change.action == "rebound" and binding_change.new_session_id:
+ # The binding failure was repaired. Any error from the retried turn
+ # is a new backend/dispatch outcome, not another member of the
+ # unresolvable-target auto-pause streak.
+ failure_code = None
+ session_id = binding_change.new_session_id
+ session_key = ""
+ try:
+ dispatch_result = await self._execute_request(
+ session_key=session_key,
+ session_id=session_id,
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ prompt=task.prompt,
+ execution_id=execution_id,
+ task_id=task.id,
+ trigger_kind="scheduled",
+ agent_name=task.agent_name,
++ metadata=task.metadata,
++ user_context=user_context,
+ _capture_dispatch_result=True,
+ **(
+ {"agent_id": agent_id}
+ if agent_id and task.agent_name
+ else {}
+ ),
+ )
+ if isinstance(dispatch_result, TaskDispatchResult):
+ error = dispatch_result.error
+ complete_on_return = dispatch_result.complete_on_return
+ else:
+ error = dispatch_result
+ except Exception as retry_exc:
+ error = str(retry_exc)
+ logger.error(
+ "Scheduled task %s failed after rebinding to %s: %s",
+ task.id,
+ session_id,
+ retry_exc,
+ exc_info=True,
+ )
except Exception as exc:
error = str(exc)
- logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
- should_complete = True
- finally:
- if should_complete:
- if coalesced_completion_ids:
- self.request_store.complete_coalesced(
- request,
- coalesced_completion_ids,
- ok=not error,
- error=error,
+ logger.error("Scheduled task %s failed: %s", task.id, exc, exc_info=True)
+ if not self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot):
+ # The TERMINAL STAMP was refused (HFR-261): the definition was reclaimed,
+ # repointed, soft-deleted or removed while this fire was running, so
+ # ``last_run_at`` / ``last_error`` / the one-shot disable are NOT stored.
+ # Returning a result whose ``error`` is ``None`` here made
+ # ``_execute_claimed_request`` complete the run ``ok=True`` -- the database
+ # refused the stale stamp and both the caller AND the run ledger reported
+ # success, while an ``at`` task that was never disabled can fire again.
+ # Carried on the EXISTING error channel: a non-empty ``error`` is already
+ # what makes ``complete(ok=not error)`` record the run as failed and what
+ # the CLI and the Harness detail pane show. A real failure keeps its own
+ # message; only a would-be success gains one. If a durable Delivery owns
+ # the run, the caller reconciles that exact owner after the failed run
+ # write commits so the Turn cannot later replace it with success.
+ logger.warning(
+ "Scheduled task %s produced a result the store refused to stamp; "
+ "reporting the run as failed",
+ task.id,
+ )
+ if not error:
+ error = self._t(_TASK_RESULT_NOT_RECORDED_I18N_KEY)
+ reconcile_delivery_on_return = not complete_on_return
+ complete_on_return = True
+ if binding_change is not None:
+ # ``execution_id`` IS the run row's id on every path that reaches here
+ # (``_execute_claimed_request`` passes ``request.id``), and this runs
+ # BEFORE ``complete()`` settles the row — so a notice stamped now rides
+ # into the terminal write instead of racing it. ``run_error`` decides
+ # whether the binding news may take the notice slot at all: a rebind whose
+ # retry failed already owes an ordinary failure notice, and that one must
+ # not be displaced.
+ await self._emit_binding_change(
+ binding_change, run_id=execution_id, run_error=error
+ )
+ self.reconcile_jobs()
+ return TaskExecutionResult(
+ error=error,
+ session_key=session_key,
+ session_id=session_id,
+ failure_code=failure_code if error else None,
+ complete_on_return=complete_on_return,
+ reconcile_delivery_on_return=reconcile_delivery_on_return,
+ )
+
+ async def _execute_agent_run(
+ self,
+ *,
+ session_key: Optional[str],
+ post_to: Optional[str],
+ deliver_key: Optional[str],
+ message: str,
+ execution_id: str,
+ session_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ ) -> AgentRunExecutionResult:
+ """Execute one direct Agent Run and wait for the real terminal result.
+
+ Direct ``vibe agent run`` records model one concrete Agent turn. Async
+ backends (Codex/Claude) return from ``handle_scheduled_message`` once the
+ prompt is submitted, while their actual result arrives later through
+ ``emit_agent_message``. Use the shared dispatch sink so the run stays
+ ``running`` until that terminal result is emitted.
+
+ The run may only stay ``running`` when the sink was released BY that terminal
+ result. Any other release (no agent was dispatched, an external stop, a
+ refused concurrent turn) means no result will ever arrive, so this method
+ settles the run itself — otherwise the row is a permanent zombie, and its
+ callback and session status hang with it. See
+ ``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 "")
+ delivery_target = self._resolve_delivery_target(
+ session_target=target,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ )
+ context = await self._build_context(
+ target,
+ delivery_target=delivery_target,
+ execution_id=execution_id,
+ trigger_kind="agent_run",
+ session_id=session_id,
+ agent_name=agent_name,
+ agent_id=agent_id,
+ target_info=target_info,
+ metadata=metadata,
+ )
+
+ 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 session_id and gate is not None:
+ if delivery_intent != AGENT_RUN_DELIVERY_STEER:
+ 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.delivery_owner_transferred
+ ),
+ recover_queue_on_return=bool(
+ isinstance(state, TurnSubmissionResult)
+ and state.delivery_status == "flush_failed"
+ ),
+ delivery_outcome=delivery_outcome,
+ )
+ if route == "duplicate":
+ return AgentRunExecutionResult(
+ error=None,
+ complete_on_return=True,
+ )
+ return AgentRunExecutionResult(
+ error=None,
+ complete_on_return=False,
+ delivery_outcome=delivery_outcome,
+ )
+
+ async def _noop_chunk(_envelope: dict) -> None:
+ return None
+
+ outcome = await dispatch_turn_with_outcome(
+ self.controller,
+ context,
+ message,
+ source=SOURCE_SCHEDULED,
+ on_chunk=_noop_chunk,
+ )
+ if outcome.error:
+ return AgentRunExecutionResult(error=str(outcome.error), complete_on_return=True)
+ if outcome.settled_by is not None and outcome.settled_by not in SETTLEMENTS_WITHOUT_RESULT:
+ # Somebody else owns this run's terminal state: either the backend emitted
+ # its real terminal result (``terminal_result``), or a terminal output
+ # closed the turn while deliberately keeping the run elsewhere
+ # (``turn_only_result`` — the requeued Activity behind a Claude delivery
+ # failure). Tested as membership rather than "anything but
+ # ``terminal_result``" so a future release reason cannot be misread as a
+ # zombie (Codex P1).
+ return AgentRunExecutionResult(error=None, complete_on_return=False)
+ settled_by = outcome.settled_by or SETTLED_BY_NO_TERMINAL_RESULT
+ if outcome.settled_by is None:
+ # Unreachable: this path always passes ``on_chunk``. Settle rather than
+ # trust an unexplained release — a wrong ``failed`` is recoverable, a
+ # zombie is not.
+ logger.warning(
+ "agent run %s dispatched without a turn sink; settling as %s",
+ execution_id,
+ settled_by,
+ )
+ error_text = self._t(
+ SETTLEMENT_I18N_KEYS.get(settled_by, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT])
+ )
+ supported, _settled = self._settle_agent_run_without_result(
+ execution_id,
+ settled_by=settled_by,
+ error=error_text,
+ )
+ if not supported:
+ # Legacy file store: no guarded writer exists, so fall back to the
+ # ``finally`` completion path rather than leave the run open.
+ return AgentRunExecutionResult(error=error_text, complete_on_return=True)
+ return AgentRunExecutionResult(
+ error=error_text,
+ complete_on_return=False,
+ settled_out_of_band=True,
+ )
+
+ def settle_agent_runs_without_result(
+ self,
+ execution_ids: Sequence[str],
+ *,
+ settled_by: str,
+ ) -> None:
+ """Settle runs whose turn ended without a terminal result, on the TURN lane.
+
+ ``_execute_agent_run`` can only settle the runs it dispatched itself. An
+ avibe-targeted run goes through ``session_turn_gate.submit_scheduled``, which
+ returns while the turn is still running, so ``SessionTurnManager`` calls this
+ when that turn ends without a result (Codex P1). Same guarded writer, same
+ i18n text as the drain lane — the only difference is who noticed.
+
+ A settled run's terminal callback is delivered by the drain, so mark it dirty
+ rather than waiting up to a full tick.
+ """
+
+ settled_any = False
+ error_text = self._t(
+ SETTLEMENT_I18N_KEYS.get(settled_by, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT])
+ )
+ for raw_execution_id in execution_ids:
+ execution_id = str(raw_execution_id or "").strip()
+ if not execution_id:
+ continue
+ _supported, settled = self._settle_agent_run_without_result(
+ execution_id,
+ settled_by=settled_by,
+ error=error_text,
+ )
+ if settled is None:
+ continue
+ settled_any = True
+ self._project_terminal_definition_result(
+ self.request_store.get_run(execution_id),
+ execution_id=execution_id,
+ expected_status=settled,
+ )
+ if settled_any:
+ self._drain_dirty = True
+
+ def settle_agent_runs_from_terminal_turn(
+ self,
+ execution_ids: Sequence[str],
+ *,
+ turn_id: str,
+ outcome: str,
+ settled_by: str | None,
+ evidence_kind: str | None,
+ evidence: Mapping[str, Any],
+ ) -> None:
+ """Settle late accepted Runs from their immutable Turn snapshot."""
+
+ if settled_by in SETTLEMENTS_WITHOUT_RESULT:
+ self.settle_agent_runs_without_result(
+ execution_ids,
+ settled_by=str(settled_by),
+ )
+ return
+ if evidence.get("settles_run") is not True:
+ return
+ store = self.request_store.sqlite_backend
+ if store is None:
+ logger.warning(
+ "cannot settle late accepted Agent Runs for Turn=%s without SQLite",
+ turn_id,
+ )
+ return
+ terminal_status = {
+ "completed": "succeeded",
+ "failed": "failed",
+ "canceled": "canceled",
+ }.get(outcome)
+ if terminal_status is None:
+ return
+ result_text = str(evidence.get("result_text") or "")
+ terminal_error = evidence.get("terminal_error")
+ message_id = str(evidence.get("message_id") or "").strip() or None
+ output_provenance = evidence.get("output_provenance")
+ output_provenance = (
+ dict(output_provenance) if isinstance(output_provenance, Mapping) else {}
+ )
+ output_id = str(output_provenance.get("output_id") or "").strip()
+ if not output_id and output_provenance.get("sequence") is not None:
+ output_id = f"sequence:{output_provenance['sequence']}"
+ if not output_id:
+ output_id = "terminal"
+ registry = getattr(
+ getattr(getattr(self, "controller", None), "agent_service", None),
+ "activities",
+ None,
+ )
+ has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ settled_any = False
+ for raw_execution_id in execution_ids:
+ execution_id = str(raw_execution_id or "").strip()
+ if not execution_id:
+ continue
+ run_terminal_status = terminal_status
+ if callable(has_blocker) and has_blocker(execution_id):
+ if not store.defer_run_terminal(
+ execution_id,
+ terminal_status=terminal_status,
+ result_text=result_text,
+ error=(
+ str(terminal_error) if terminal_error is not None else None
+ ),
+ ):
+ logger.warning(
+ "failed to defer late terminal settlement for Run=%s Turn=%s",
+ execution_id,
+ turn_id,
+ )
+ run_terminal_status = None
+ result = store.record_run_output(
+ execution_id,
+ output_id=output_id,
+ text=result_text,
+ message_id=message_id,
+ provenance={
+ **output_provenance,
+ "turn_id": turn_id,
+ "evidence_kind": evidence_kind,
+ "settled_by": settled_by,
+ },
+ terminal_status=run_terminal_status,
+ error=str(terminal_error) if terminal_error is not None else None,
+ )
+ settled_any = settled_any or bool(
+ result.get("terminal_transition") or result.get("text_backfilled")
+ )
+ if settled_any:
+ self._drain_dirty = True
+
+ def _retract_escalation_of_stopped_fire(self, execution_id: str) -> None:
+ """Take back the Agent turn a fire queued, once the user stops that fire.
+
+ A failed ``--on-failure agent`` fire commits its stamp and its escalation in ONE
+ transaction, guarded on the fire not being cancelled (HFR-269). That guard can
+ only see the cancels that exist WHEN IT COMMITS: ``cancel_run`` on a running fire
+ writes a flag, and the flag can land after the stamp has already returned --
+ ``settle_run_terminal`` then re-reads it and normalizes this fire to ``canceled``
+ while the durable escalation sits queued and claimable. The user stops a job and
+ the job answers by starting an Agent, which is the same defect the compare-and-set
+ was written for, one lane further along.
+
+ WHY RETRACTION AND NOT ONE BIGGER TRANSACTION. The enqueue has to commit with the
+ STAMP -- that is what authorises the turn, and splitting them is what HFR-269
+ closed -- while this settlement happens later, in another lane, after
+ ``reconcile_jobs``. There is no single transaction that holds both without
+ reopening the window it fixed. So the escalation is committed optimistically and
+ withdrawn by whoever settles the fire against it.
+
+ NEITHER REPORT IS OWED HERE, and that is deliberate. ``canceled`` is written only
+ when the user asked for this fire to stop (``_cancel_aware_terminal_status``), and
+ a stopped fire owes no failure notice -- the same rule SCT-027 relies on when a
+ teardown cancels the fire itself. Re-arming the notice instead would alert the
+ user about a job they had just stopped, which is this defect's mirror image. The
+ failure is not lost either way: the stamp landed, so the definition still reports
+ it.
+
+ Found by LINKAGE rather than from the local ``escalation_run_id``: a
+ ``CancelledError`` delivered anywhere after the stamp skips the assignment
+ entirely, and the escalation is durable by then regardless.
+
+ THIS IS THE SECOND OF TWO GUARDS, and it is the weaker one. Retraction can only
+ take back a row that is still queued: ``cancel_run`` on an escalation the
+ dispatch loop has already claimed writes a flag, and the turn lane does not
+ watch that flag (see ``_propagate_requested_cancellations`` for why a turn's
+ stop belongs to the lane that owns it). So the claim itself refuses an
+ escalation whose fire is already cancelled
+ (``_escalates_a_stopped_fire``), which is what actually makes the ordering
+ between these two lanes irrelevant: whichever runs first, no Agent turn starts
+ for a stopped fire. What remains is only an escalation claimed BEFORE the user's
+ stop landed -- a turn that was legitimately in flight when the request arrived,
+ which is the same thing that happens to any other out-of-band turn and is
+ stopped from the turn lane, not from here.
+ """
+
+ try:
+ escalation = self.request_store.find_escalation_run(parent_run_id=execution_id)
+ except Exception:
+ logger.exception(
+ "Failed to look for the escalation queued by stopped Run %s", execution_id
+ )
+ return
+ if escalation is None:
+ return
+ escalation_id = str(escalation.get("id") or "").strip()
+ status = str(
+ _normalize_requested_run_status(escalation.get("status"))
+ or escalation.get("status")
+ or ""
+ ).strip()
+ if not escalation_id or status in TERMINAL_RUN_STATUSES:
+ # Already settled -- including by the claim door, which refuses an
+ # escalation whose fire is cancelled and terminalizes it as ``canceled``
+ # exactly as this would have.
+ return
+ try:
+ retracted = self.request_store.cancel_run(escalation_id)
+ except Exception:
+ logger.exception(
+ "Failed to retract escalation Run %s for stopped Run %s",
+ escalation_id,
+ execution_id,
+ )
+ return
+ if retracted:
+ logger.info(
+ "Retracted escalation Run %s: its command fire %s was stopped",
+ escalation_id,
+ execution_id,
+ )
+
+ def _project_terminal_definition_result(
+ self,
+ run: Optional[dict[str, Any]],
+ *,
+ execution_id: str,
+ expected_status: str,
+ ) -> None:
+ """Project only the exact terminal transition the caller actually won."""
+
+ if run is None:
+ return
+ status = str(run.get("status") or "").strip()
+ if status != expected_status or status not in TERMINAL_RUN_STATUSES:
+ return
+ definition_id = str(
+ run.get("definition_id") or run.get("task_id") or ""
+ ).strip()
+ if not definition_id:
+ return
+ self.store.maybe_reload()
+ task = self.store.get_task(definition_id)
+ if task is None:
+ return
+ run_session_id = str(run.get("session_id") or "").strip()
+ task_session_id = str(task.session_id or "").strip()
+ run_session_key = str(
+ run.get("legacy_session_key") or run.get("session_key") or ""
+ ).strip()
+ task_session_key = str(task.session_key or "").strip()
+ if (
+ run_session_id != task_session_id
+ or run_session_key != task_session_key
+ ):
+ logger.warning(
+ "Run %s no longer matches scheduled definition %s; skipping result projection",
+ execution_id,
+ definition_id,
+ )
+ return
+ error = None if status == "succeeded" else str(run.get("error") or "").strip()
+ if status != "succeeded" and not error:
+ metadata = run.get("metadata")
+ interruption = (
+ str(metadata.get("interrupt_reason") or "").strip()
+ if isinstance(metadata, dict)
+ else ""
+ )
+ key = SETTLEMENT_I18N_KEYS.get(interruption)
+ if key is not None:
+ error = self._t(key)
+ if status != "succeeded" and not error:
+ logger.warning(
+ "Terminal Run %s has no failure detail; skipping definition %s projection",
+ execution_id,
+ definition_id,
+ )
+ return
+ retire_one_shot = (
+ str(run.get("source_kind") or "") == "scheduler"
+ and task.schedule_type == "at"
+ )
+ # A COMMAND fire that ends here ended without reaching its own result stamp --
+ # cancelled, or interrupted by shutdown -- so this projection IS that fire's
+ # authoritative outcome, and it has no exit status to report. Saying so
+ # (``records_command_outcome``) is what clears the previous fire's code;
+ # without it the row read "exited 7" beside a run the user had just stopped.
+ # Only for command runs: the generic lane must never blank the column on
+ # behalf of a message task, which never had a code of its own.
+ records_command_outcome = (
+ command_snapshot_of_run(run) is not None or task.has_command
+ )
+ raw_exit_code = run.get("exit_code")
+ try:
+ recorded = self.store.mark_task_result(
+ task.id,
+ error=error,
+ disable_one_shot=retire_one_shot,
+ exit_code=int(raw_exit_code) if raw_exit_code is not None else None,
+ records_command_outcome=records_command_outcome,
+ expected_binding=(
+ task.session_id,
+ task.session_key,
+ task.schedule_type,
+ ),
+ )
+ except Exception:
+ logger.exception(
+ "Failed to project terminal Run %s to definition %s",
+ execution_id,
+ definition_id,
+ )
+ return
+ if not recorded:
+ logger.warning(
+ "Definition %s changed before terminal Run %s could be projected",
+ definition_id,
+ execution_id,
+ )
+ return
+ if retire_one_shot:
+ try:
+ if self.scheduler.get_job(task.id) is not None:
+ self.scheduler.remove_job(task.id)
+ self._job_signatures.pop(task.id, None)
+ except Exception:
+ logger.exception(
+ "Failed to retire scheduler job for terminal definition %s",
+ definition_id,
+ )
+
+ def _settle_agent_run_without_result(
+ self,
+ execution_id: str,
+ *,
+ settled_by: str,
+ error: str,
+ ) -> tuple[bool, Optional[str]]:
+ """Terminalize a run whose turn ended without a terminal result.
+
+ Deliberately NOT routed through ``_execute_claimed_request``'s ``finally``:
+ that path writes via ``update_run_status``, whose UPDATE has no status
+ predicate and would clobber a row a concurrent ``vibe runs cancel`` already
+ settled. ``settle_without_result`` is scoped to ``queued|running`` and maps a
+ cancel-requested run to ``canceled`` inside its own transaction.
+
+ The terminal status comes from ``SETTLEMENT_TERMINAL_STATUS``: an explicit
+ user stop is ``canceled``, an infrastructure fault is ``failed``.
+
+ Returns whether the guarded writer exists and the status written by this
+ exact terminal compare-and-set. An already-terminal row returns a supported
+ writer with no status, so callers cannot project a result they did not settle.
+ """
+
+ if not self.request_store.supports_guarded_settlement():
+ return False, None
+ settled = self.request_store.settle_without_result(
+ execution_id,
+ terminal_status=SETTLEMENT_TERMINAL_STATUS.get(settled_by, "failed"),
+ error=error,
+ metadata={"interrupt_reason": settled_by},
+ )
+ if settled is None:
+ logger.info(
+ "Agent run %s was already settled elsewhere (%s)",
+ execution_id,
+ settled_by,
+ )
+ else:
+ logger.warning(
+ "Agent run %s settled %s without a terminal result (%s)",
+ execution_id,
+ settled,
+ settled_by,
+ )
+ return True, settled
+
+ # --- pinned session binding recovery -------------------------------------
+ #
+ # One choke point: classify -> maybe rebind -> maybe pause -> notify once.
+ # The pause predicate is task-scoped (only a task has a definition to pause)
+ # but the notification is not, so a run type added later inherits the
+ # behaviour by default rather than by remembering to wire it.
+
+ def _recover_pinned_session_binding(
+ self,
+ task: ScheduledTask,
+ exc: UnresolvableSessionTarget,
+ ) -> SessionBindingChange:
+ previous = str(exc.session_id or task.session_id or "") or None
+ snapshot = None
+ if isinstance(task.metadata, dict):
+ candidate = task.metadata.get(SESSION_SETTINGS_SNAPSHOT_KEY)
+ if isinstance(candidate, dict):
+ snapshot = candidate
+
+ scope_id = ""
+ if isinstance(task.metadata, dict):
+ scope_id = str(task.metadata.get("session_scope_id") or "").strip()
+
+ # ``existing`` is user-pinned: re-pointing it would lose the continuity the
+ # pin exists to guarantee, so it is never rebound. Only ``create_once``
+ # reserved its own session and may reserve another; ``create_per_run``
+ # never reaches here because it reserves before every fire.
+ if task.session_policy == "create_once" and (scope_id or task.deliver_key):
+ rebound = self._rebind_create_once_session(task, snapshot)
+ if rebound is not None:
+ new_session_id, settings_preserved = rebound
+ if not settings_preserved:
+ # Record the choice as an explicit, durable state, not as an
+ # absent ``agent_name``: ``vibe task update`` re-resolves an
+ # omitted Agent and writes it back, so without the flag the
+ # next unrelated edit re-pins the Agent this recovery dropped.
+ task.metadata = {
+ **(task.metadata if isinstance(task.metadata, dict) else {}),
+ BINDING_FOLLOWS_SESSION_METADATA_KEY: True,
+ }
+ if not settings_preserved and task.agent_name:
+ # The reset rebind could not use the definition's own Agent --
+ # that is WHY it reset. Leaving the pin in place makes the
+ # storage fix cosmetic: ``_build_context`` sends it as
+ # ``vibe_agent_name``, which ``MessageHandler`` prioritises
+ # OVER the session row's Agent, so every fire would dispatch
+ # under the Agent that was just found unusable while the row
+ # says otherwise. Dropping the pin hands authority back to the
+ # rebound session, which is where a ``create_once``
+ # definition's Agent identity belongs -- and persisting it
+ # below is what makes the choice survive to the NEXT fire, not
+ # just this retry.
+ logger.info(
+ "Task %s dropped its stale Agent pin %r during a reset rebind; "
+ "the rebound session's Agent now governs",
+ task.id,
+ task.agent_name,
+ )
+ task.agent_name = None
+ if not self._persist_task_session_id(task, new_session_id):
+ # THE REBIND DID NOT LAND (HFR-268). ``new_session_id`` is left
+ # unset on purpose: it is what ``_execute_task`` reads to decide
+ # whether to retry the fire, so an unstored rebind cannot dispatch
+ # a turn. The action is its own transition rather than "rebound" so
+ # that the durable ``binding_recovery`` marker and the notice both
+ # describe what actually happened -- reporting a rebind here is the
+ # HFR-266 lie one layer up.
+ #
+ # AND THE REPLACEMENT IS GIVEN BACK (HFR-270). The reservation
+ # already COMMITTED -- a different store, a different transaction,
+ # and for a standalone placement a mkdir as well -- so a refusal
+ # that only declined to dispatch left a live, unreferenced
+ # background session and its workspace behind, one more per fire
+ # that loses this race, with nothing that will ever run, list or
+ # delete them.
+ #
+ # AND THE ANSWER TO "WAS IT?" IS CONSUMED (HFR-276). The release is
+ # deliberately never fatal, so a locked database or an I/O fault
+ # returns ``False`` with the reservation still live: reporting
+ # "reclaimed" there is HFR-266's lie one layer inside HFR-270's fix,
+ # and the id -- random, never written to the definition -- would be
+ # lost with the log line. The losing branch records it instead, so
+ # the leak is TRACKED and a later fire can finish the job.
+ release_reason = f"the rebind of harness definition {task.id} was refused"
+ prefix = (
+ f"not rebound: {exc}. The definition was reclaimed, re-pointed or "
+ "removed while a replacement session was being reserved, so the "
+ "rebind was not stored and this run did not execute."
+ )
+ if self._release_reserved_session(new_session_id, reason=release_reason):
+ return SessionBindingChange(
+ action="reclaimed",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=(
+ f"{prefix} The next run re-resolves from the stored definition."
+ ),
+ )
+ tracked = self._track_orphaned_reservation(
+ task.id, new_session_id, release_reason
)
- else:
- self.request_store.complete(
- request,
- ok=not error,
- error=error,
- task_id=task_id,
- session_key=session_key,
- session_id=session_id,
+ if tracked == "recorded":
+ cleanup = (
+ f"The replacement session {new_session_id} could NOT be given "
+ "back and is recorded on this definition; the next run retries "
+ "the cleanup."
+ )
+ elif tracked == "stamped":
+ cleanup = (
+ f"The replacement session {new_session_id} could NOT be given "
+ "back, and the record of it could not be stored either; its own "
+ "row names this definition, so the next run recovers it from "
+ "that stamp."
+ )
+ else:
+ cleanup = (
+ f"The replacement session {new_session_id} could NOT be given "
+ "back, and this definition no longer exists, so no later run "
+ "will look for it; it is reported here and in the logs only."
+ )
+ return SessionBindingChange(
+ action="orphaned",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=f"{prefix} {cleanup}",
+ orphaned_session_id=new_session_id,
+ orphan_tracked=tracked != "untracked",
)
- 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 settings_preserved:
+ detail = (
+ f"rebound to a new agent session {new_session_id}; the previous session "
+ f"({previous}) was deleted. Its workdir/agent/model were preserved."
)
- 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,
- )
+ else:
+ detail = (
+ f"rebound to a new agent session {new_session_id}; the previous session "
+ f"({previous}) was deleted and its settings could not be recovered, so "
+ "scope defaults were used."
+ )
+ return SessionBindingChange(
+ action="rebound",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=detail,
+ new_session_id=new_session_id,
+ settings_preserved=settings_preserved,
+ )
- async def _execute_task(
+ prior_failures = self.request_store.consecutive_definition_failures_with_code(
+ task.id,
+ FAILURE_CODE_UNRESOLVABLE_TARGET,
+ limit=UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES - 1,
+ )
+ failure_number = prior_failures + 1
+ if failure_number < UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES:
+ return SessionBindingChange(
+ action="failing",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=self._t(
+ "harness.run.bindingUnresolvedRetry",
+ session=previous or "",
+ attempt=failure_number,
+ threshold=UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES,
+ id=task.id,
+ ),
+ )
+
+ self._pause_task(task)
+ return SessionBindingChange(
+ action="paused",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=self._t(
+ "harness.run.bindingUnresolvedPaused",
+ session=previous or "",
+ id=task.id,
+ ),
+ )
+
+ def _rebind_create_once_session(
self,
task: ScheduledTask,
- *,
- execution_id: str,
- disable_one_shot: bool,
- ) -> TaskExecutionResult:
- error: Optional[str] = None
- session_id = task.session_id
- session_key = task.session_key
- user_context = self._resource_user_context(task.metadata)
- try:
- if task.session_policy == "create_per_run":
+ snapshot: Optional[dict[str, Any]],
+ ) -> Optional[tuple[str, bool]]:
+ """Reserve a replacement session, preserving the lost one's settings.
+
+ Returns ``(session_id, settings_preserved)``, or ``None`` when no session
+ could be reserved at all. The snapshot is written by the reclaim that ran
+ when the old row was deleted; where it is absent — a definition orphaned
+ before that landed — the rebind falls back to scope defaults and says so,
+ so the user can tell a preserved rebind from a reset one.
+ """
+
+ # Local, like every other ``core.vibe_agents`` use in this module (the Agent
+ # catalog pulls in migrations/importer, which must not run at import time).
+ from core.vibe_agents import AgentUnavailableError
+
+ attempts: list[tuple[dict[str, Any], bool]] = []
+ if snapshot:
+ attempts.append(
+ (
+ {
+ "agent_name": snapshot.get("agent_name") or task.agent_name,
+ "workdir": snapshot.get("workdir") or task.cwd,
+ "model": snapshot.get("model"),
+ "reasoning_effort": snapshot.get("reasoning_effort"),
+ },
+ True,
+ )
+ )
+ # The non-preserving attempt must NOT re-send the definition's own Agent.
+ # For a ``create_once`` definition ``task.agent_name`` is the same name the
+ # snapshot carries, so when that Agent has been deleted or disabled the
+ # fallback repeats the identical ``require_enabled`` failure and the
+ # definition is paused -- when degrading to scope defaults is the entire
+ # reason this attempt exists, and is what its own notice claims it did.
+ # ``None`` is unambiguous here: ``_reserve_runtime_session`` reads it as
+ # "resolve the scope Agent, else the default Agent", which is precisely
+ # the intent. Only ``model``/``reasoning_effort`` need a sentinel, because
+ # for them ``None`` is also a value a snapshot can legitimately carry.
+ attempts.append(({"agent_name": None, "workdir": task.cwd}, False))
+
+ for overrides, preserved in attempts:
+ try:
session_id = self._reserve_runtime_session(
- agent_name=task.agent_name,
deliver_key=task.deliver_key,
metadata=task.metadata,
- workdir=task.cwd,
- user_context=user_context,
+ definition_id=task.id,
++ user_context=self._resource_user_context(task.metadata),
+ **overrides,
)
- session_key = ""
- resource_access_kwargs = (
- {"metadata": task.metadata, "user_context": user_context}
- if user_context is not None
- else {}
- )
- error = await self._execute_request(
- session_key=session_key,
- session_id=session_id,
- post_to=task.post_to,
- deliver_key=task.deliver_key,
- prompt=task.prompt,
- execution_id=execution_id,
- task_id=task.id,
- trigger_kind="scheduled",
- agent_name=task.agent_name,
- **resource_access_kwargs,
- )
- except asyncio.CancelledError:
- self.reconcile_jobs()
- raise
- except Exception as exc:
- error = str(exc)
- logger.error("Scheduled task %s failed: %s", task.id, exc, exc_info=True)
- self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot)
- self.reconcile_jobs()
- return TaskExecutionResult(error=error, session_key=session_key, session_id=session_id)
-
- async def _execute_agent_run(
- self,
- *,
- session_key: Optional[str],
- post_to: Optional[str],
- deliver_key: Optional[str],
- message: str,
- execution_id: str,
- session_id: Optional[str] = None,
- agent_name: Optional[str] = None,
- metadata: Optional[dict[str, Any]] = None,
- ) -> AgentRunExecutionResult:
- """Execute one direct Agent Run and wait for the real terminal result.
+ except AgentUnavailableError as exc:
+ # THE ONLY CONDITION THIS FALLBACK IS FOR: a snapshot naming an Agent
+ # the user has since deleted or disabled must degrade to scope
+ # defaults, not to a permanent failure (HFR-243).
+ #
+ # NARROW ON PURPOSE (HFR-265). A bare ``except Exception`` here read
+ # SQLite contention, a migration failure and a filesystem error as
+ # "that Agent is gone": the retry then succeeded against scope
+ # defaults, ``_persist_task_session_id`` wrote the reset route, and the
+ # definition PERMANENTLY lost the Agent/model the snapshot was holding
+ # for it -- a transient fault turned into data loss, with the notice
+ # claiming the settings "could not be recovered". Same shape as a broad
+ # ``OperationalError`` retry, and the reason the deleted/disabled case
+ # now has a type of its own instead of being inferred from a failure.
+ logger.warning(
+ "Rebind reservation for task %s cannot use Agent %r (%s, preserved=%s): %s",
+ task.id,
+ exc.agent_name,
+ exc.reason,
+ preserved,
+ exc,
+ )
+ continue
+ if session_id:
+ return session_id, preserved
+ return None
- Direct ``vibe agent run`` records model one concrete Agent turn. Async
- backends (Codex/Claude) return from ``handle_scheduled_message`` once the
- prompt is submitted, while their actual result arrives later through
- ``emit_agent_message``. Use the shared dispatch sink so the run stays
- ``running`` until that terminal result is emitted.
+ def _persist_task_session_id(self, task: ScheduledTask, session_id: str) -> bool:
+ """Store the rebind. ``False`` means the guard refused it — do NOT act on it.
+
+ HFR-268. This used to swallow the conflict and return ``None``, and the comment
+ said "the rebind stands for THIS fire only". It does not. The refusal is the
+ database saying the definition was reclaimed, repointed or SOFT-DELETED inside
+ the window (``expect.deleted_at`` is ``None``, so a ``RECLAIM_DELETE`` refuses
+ here too), and the caller went on to dispatch the prompt and post the reply
+ into the freshly reserved session anyway: the same shape as HFR-267, except the
+ guard WAS asked first and its answer was dropped rather than never requested.
+ A ``/new`` that pauses a ``create_once`` task mid-fire would tell the user the
+ task was paused and then deliver a turn for it.
"""
- from core.services.dispatch import SOURCE_SCHEDULED, dispatch_turn
- target_info = resolve_session_id_target(session_id) if session_id else None
- self._require_execution_agent_access(
- agent_name=agent_name,
- target_info=target_info,
- user_context=self._resource_user_context(metadata),
- )
- target = target_info.session_key if target_info else parse_session_key(session_key or "")
- delivery_target = self._resolve_delivery_target(
- session_target=target,
- post_to=post_to,
- deliver_key=deliver_key,
- )
- context = await self._build_context(
- target,
- delivery_target=delivery_target,
- execution_id=execution_id,
- trigger_kind="agent_run",
+ try:
+ self._write_task_session_id(task, session_id)
+ except DefinitionWriteConflict as exc:
+ logger.warning("Could not persist the rebind for task %s: %s", task.id, exc)
+ return False
+ return True
+
+ def _write_task_session_id(self, task: ScheduledTask, session_id: str) -> None:
+ self.store.update_task(
+ task.id,
+ name=task.name,
+ session_key=task.session_key,
session_id=session_id,
- agent_name=agent_name,
- target_info=target_info,
- metadata=metadata,
+ prompt=task.prompt,
+ schedule_type=task.schedule_type,
+ agent_name=task.agent_name,
+ session_policy=task.session_policy,
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ cwd=task.cwd,
+ update_cwd=False,
+ metadata=task.metadata,
)
- gate = getattr(self.controller, "session_turn_gate", None)
- 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,
- execution_ids=_live_coalesced_agent_run_ids(
- TaskExecutionRequest(
- id=execution_id,
- request_type="agent_run",
- metadata=metadata or {},
- )
- )
- or [execution_id],
+ def _pause_task(self, task: ScheduledTask) -> None:
+ try:
+ self.store.set_enabled(task.id, False)
+ except KeyError:
+ logger.debug("Task %s vanished before it could be paused", task.id)
+ except DefinitionWriteConflict:
+ # A teardown got there first (``/new`` pauses, the archive dialog
+ # soft-deletes). The definition is already off; re-writing the whole row
+ # from this stale mirror would only restore what the teardown cleared.
+ logger.debug("Task %s was already reclaimed before it could be paused", task.id)
+
+ async def _emit_binding_change(
+ self,
+ change: SessionBindingChange,
+ *,
+ run_id: Optional[str] = None,
+ run_error: Optional[str] = None,
+ ) -> None:
+ """Notify once per binding transition, never once per fire.
+
+ A daily cron on a dead session would otherwise notify every day. The
+ dedup key is the transition, so a rebind (whose previous session id
+ differs each time) always notifies while a definition re-fired against the
+ same dead session stays quiet.
+
+ The dedup marker IS the guarantee, so the notification is conditional on it
+ landing: ``record_binding_recovery`` is a guarded write (HFR-261) that
+ refuses when the definition was reclaimed, repointed or removed inside the
+ window, and ignoring that ``False`` delivered a notice with nothing durable
+ behind it — "once per transition" for a marker that was never stored, i.e.
+ once per fire, forever, describing a recovery the stored definition no
+ longer reflects (HFR-266).
+ """
+
+ task = self.store.get_task(change.task_id)
+ if task is None:
+ return
+ recorded = task.metadata.get(BINDING_RECOVERY_METADATA_KEY) if isinstance(task.metadata, dict) else None
+ if isinstance(recorded, dict) and recorded.get("signature") == change.signature:
+ return
+ recovery_payload = {
+ "signature": change.signature,
+ "action": change.action,
+ "reason": change.reason,
+ "previous_session_id": change.previous_session_id,
+ "new_session_id": change.new_session_id,
+ "settings_preserved": change.settings_preserved,
+ "at": _utc_now_iso(),
+ # Only on the HFR-276 branch, so the recorded shape of every other
+ # transition is unchanged.
+ **(
+ {
+ "orphaned_session_id": change.orphaned_session_id,
+ "orphan_tracked": change.orphan_tracked,
+ }
+ if change.orphaned_session_id
+ else {}
+ ),
+ }
+ binding_notice = None
+ if (
+ run_id
+ and change.action == "rebound"
+ and change.new_session_id
+ and not run_error
+ and self.store._sqlite is not None
+ ):
+ binding_notice = {
+ "run_id": run_id,
+ "task_id": change.task_id,
+ "signature": change.signature,
+ "action": change.action,
+ "reason": change.reason,
+ "previous_session_id": change.previous_session_id,
+ "new_session_id": change.new_session_id,
+ "settings_preserved": change.settings_preserved,
+ }
+ try:
+ recorded_recovery = self.store.record_binding_recovery(
+ change.task_id,
+ recovery_payload,
+ binding_notice=binding_notice,
)
- if stale_queue_rows:
- try:
- from core.inbox_events import bus
+ except Exception:
+ logger.exception(
+ "Not notifying the binding %s for task %s: its recovery marker and "
+ "notice could not be committed together",
+ change.action,
+ change.task_id,
+ )
+ return
+ if not recorded_recovery:
+ logger.warning(
+ "Not notifying the binding %s for task %s: the recovery record was "
+ "refused, so the definition was reclaimed, repointed or removed and "
+ "this transition no longer describes it",
+ change.action,
+ change.task_id,
+ )
+ return
+ await self._notify_binding_change(task, change)
- 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":
- live_ids = _live_coalesced_agent_run_ids(
- TaskExecutionRequest(
- id=execution_id,
- request_type="agent_run",
- metadata=metadata or {},
- )
- )
- return AgentRunExecutionResult(
- error=None,
- complete_on_return=True,
- coalesced_completion_ids=tuple(live_ids or [execution_id]),
- )
- return AgentRunExecutionResult(error=None, complete_on_return=False)
+ async def _notify_binding_change(self, task: ScheduledTask, change: SessionBindingChange) -> None:
+ """Single delivery seam for a binding change.
- async def _noop_chunk(_envelope: dict) -> None:
- return None
+ Deliberately the only place that decides how the user hears about this.
- result = await dispatch_turn(
- self.controller,
- context,
- message,
- source=SOURCE_SCHEDULED,
- on_chunk=_noop_chunk,
+ The durable half was already written by the time we get here (``last_error``
+ plus ``metadata.binding_recovery``), and the run row's owed notice — which the
+ drain delivers through D5's ladder — carries the user-visible half. For
+ ``paused`` / ``reclaimed`` / ``orphaned`` that notice comes from the terminal
+ transition, because those fires end failed. For ``rebound`` the retry succeeds
+ and no transition owes anything, so ``record_binding_recovery`` commits the
+ marker and notice together before this log seam is reached.
+
+ Either way this seam does not deliver anything itself: doing so would produce
+ a SECOND message for one event, and it would be the un-retried one, since only
+ the owed notice has a receipt/backoff/dead-letter protocol behind it.
+
+ What it does own is the log line, which is the operator's view of a
+ transition that is per-BINDING rather than per-fire.
+ """
+
+ logger.warning(
+ "Harness definition %s binding %s (reason=%s previous=%s new=%s preserved=%s): %s",
+ task.id,
+ change.action,
+ change.reason,
+ change.previous_session_id,
+ change.new_session_id,
+ change.settings_preserved,
+ change.detail,
)
- if result:
- return AgentRunExecutionResult(error=str(result), complete_on_return=True)
- return AgentRunExecutionResult(error=None, complete_on_return=False)
+
+ def audit_definition_bindings(self) -> list[tuple[str, str]]:
+ """Report enabled definitions whose pinned session no longer resolves.
+
+ Startup integrity check: a broken binding is otherwise invisible until the
+ next fire, which for a weekly cron is a week of silence.
+ """
+
+ broken: list[tuple[str, str]] = []
+ for task in self.store.list_tasks():
+ if not task.enabled or not task.session_id:
+ continue
+ try:
+ resolve_session_id_target(task.session_id)
+ except UnresolvableSessionTarget as exc:
+ broken.append((task.id, str(exc)))
+ except Exception:
+ # Never let an integrity probe take down startup.
+ logger.debug("Binding audit skipped task %s", task.id, exc_info=True)
+ if broken:
+ logger.warning(
+ "%d harness definition(s) point at an unresolvable agent session: %s",
+ len(broken),
+ "; ".join(f"{task_id} ({reason})" for task_id, reason in broken),
+ )
+ return broken
def _reserve_runtime_session(
self,
@@@ -8154,37 -2649,8 +8177,38 @@@
deliver_key: Optional[str],
metadata: Optional[dict[str, Any]] = None,
workdir: Optional[str] = None,
+ model: Any = _UNSET,
+ reasoning_effort: Any = _UNSET,
+ definition_id: Optional[str] = None,
+ user_context: Any = None,
) -> str:
+ """Reserve a background session for a run.
+
+ ``model`` / ``reasoning_effort`` override the resolved Agent's values. A
+ ``create_once`` rebind passes the snapshot of the session it lost (D3):
+ without them this re-resolves the CURRENT Agent and silently changes the
+ task's settings, because ``run_definitions`` has no column for either.
+
+ Both take ``_UNSET`` rather than ``None`` as "not supplied". An explicit
+ ``None`` means the reclaimed session pinned nothing and must keep pinning
+ nothing; treating that as "not supplied" hands it the Agent's current
+ model, which is a settings change recorded as a settings-preserving
+ recovery. Omitting them is unchanged: the Agent's values are used.
+
+ ``agent_name=None`` (or omitted) means "resolve the scope Agent, else the
+ default Agent" -- the deliberate reset the non-preserving rebind wants.
+
+ ``definition_id`` stamps the reserved row with the reserving definition's id,
+ inside the reservation's own transaction (HFR-276): if the reservation
+ committed, the durable handle committed with it, so an orphan whose
+ ``orphaned_reservations`` record write is later refused by the same fault that
+ refused the release is still recoverable from the row itself. Passed ONLY by
+ the ``create_once`` recovery rebind, whose fires serialize on the pinned
+ session's lock -- a ``create_per_run`` reservation is legitimately unbound and
+ unreferenced between its reserve and its dispatch, and fires of such a
+ definition can overlap, so stamping one would put a live reservation inside
+ the sweep's definition of an orphan.
+ """
scope_id = ""
if isinstance(metadata, dict):
scope_id = str(metadata.get("session_scope_id") or "").strip()
@@@ -8208,18 -2674,15 +8232,24 @@@
ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(config_paths.get_state_dir()))
agent_store = VibeAgentStore()
try:
- scope_target = self._resolve_scope_agent_target(scope_id) if scope_id and not agent_name else _ScopeAgentTarget(None)
+ scope_target = (
+ self._resolve_scope_agent_target(scope_id)
+ if scope_id and not agent_name and not agent_id
+ else _ScopeAgentTarget(None)
+ )
resolved_agent_name = agent_name or scope_target.agent_name
- agent = agent_store.require_enabled(resolved_agent_name) if resolved_agent_name else agent_store.get_default_agent()
+ if agent_id:
+ agent = agent_store.require_reference_by_id(agent_id)
+ elif resolved_agent_name:
+ agent = agent_store.require_reference(resolved_agent_name)
+ else:
+ agent = agent_store.get_default_agent()
+ if agent is not None and user_context is not None:
+ agent = agent_store.require_accessible(
+ agent.name,
+ user_context=user_context,
+ enabled_only=True,
+ )
finally:
agent_store.close()
if agent is None:
@@@ -8625,10 -2756,15 +8655,17 @@@
trigger_kind: str,
session_id: Optional[str] = None,
agent_name: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ user_context: Any = None,
- ) -> Optional[str]:
+ _capture_dispatch_result: bool = False,
+ ) -> Optional[str] | TaskDispatchResult:
target_info = resolve_session_id_target(session_id) if session_id else None
+ self._require_execution_agent_access(
+ agent_name=agent_name,
+ target_info=target_info,
+ user_context=user_context,
+ )
target = target_info.session_key if target_info else parse_session_key(session_key or "")
delivery_target = self._resolve_delivery_target(
session_target=target,
@@@ -8643,8 -2779,8 +8680,9 @@@
trigger_kind=trigger_kind,
session_id=session_id,
agent_name=agent_name,
+ agent_id=agent_id,
target_info=target_info,
+ metadata=metadata,
)
# A scheduled avibe turn drives the sidebar dot through the SAME two
# chokepoints as any other turn — inbound AgentService.handle_message
@@@ -8682,9 -2807,46 +8720,48 @@@
message=prompt,
parsed_session_key=target,
)
+ result = TaskDispatchResult(error=error)
+ return result if _capture_dispatch_result else result.error
+ @staticmethod
+ def _resource_user_context(metadata: Optional[dict[str, Any]]) -> Any:
+ from storage.resource_access_service import resource_user_context_from_metadata
+
+ return resource_user_context_from_metadata(metadata)
+
+ @staticmethod
+ def _require_execution_agent_access(
+ *,
+ agent_name: Optional[str],
+ target_info: Optional[ResolvedSessionIdTarget],
+ user_context: Any,
+ ) -> None:
+ if user_context is None:
+ return
+
+ from core.vibe_agents import VibeAgentAccessError, VibeAgentStore, ensure_agent_selection_access
+
+ selected_name = str(agent_name or "").strip() or None
+ selected_id = None
+ if selected_name is None and target_info is not None:
+ selected_name = str(target_info.agent_name or "").strip() or None
+ selected_id = str(target_info.agent_id or "").strip() or None
+ if selected_name is None and selected_id is None:
+ raise VibeAgentAccessError("Agent access is not permitted.")
+
+ store = VibeAgentStore()
+ try:
+ with store.engine.connect() as connection:
+ ensure_agent_selection_access(
+ connection,
+ agent_name=selected_name,
+ agent_id=selected_id,
+ user_context=user_context,
+ missing_is_error=True,
+ )
+ finally:
+ store.close()
+
async def _build_context(
self,
target: ParsedSessionKey,
diff --cc core/services/session_fork.py
index f2f86c147,77249f5db..ab17b8c1e
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@@ -10,47 -10,23 +10,48 @@@ from __future__ import annotation
import json
import secrets
from dataclasses import dataclass
+from datetime import datetime, timezone
from pathlib import Path
- from typing import Any, Optional
+ from typing import Any, Mapping, Optional
from config import paths
- from core.backend_failure import is_backend_failure_notification
+ from core.backend_failure import BACKEND_FAILURE_EVENT, is_backend_failure_notification
+ from vibe.authorization import AuthorizationContext, require_instance_role
from vibe.i18n import t
from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn
+from vibe.message_types import spec_for, types_with
TRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}
-# ``silent`` is the invisible completion marker (messages_service.SILENT_TYPE): a turn
-# that finished with no user-visible reply is still TERMINAL, so a fork created after
-# it must not trim/roll back the completed turn as if it were still running.
-TERMINAL_AGENT_OUTPUT_TYPES = {"result", "error", "silent"}
-SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {"assistant", *TERMINAL_AGENT_OUTPUT_TYPES}
+# Turn settlement is read from ``session_turns`` below, so a reply-less completion
+# cannot be mistaken for a still-running input.
+TERMINAL_AGENT_OUTPUT_TYPES = {
+ message_type
+ for message_type in types_with("activityRole")
+ if spec_for(message_type)["activityRole"] == "terminal"
+}
+SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {
+ message_type
+ for message_type in types_with("activityRole")
+ if spec_for(message_type)["activityRole"] in {"activity", "terminal"}
+}
ACTIVE_SOURCE_RUN_STATUSES = ("pending", "queued", "processing", "running")
INPUT_TURN_MESSAGE_TYPES = tuple(message_type for _, message_type in INPUT_TURN_AUTHOR_TYPES)
+_CONDITIONAL_TERMINAL_TYPES = types_with("terminalWhenEvents")
+_FORK_ANCHOR_TYPES = tuple(
+ dict.fromkeys(
+ (
+ *types_with("transcript"),
+ *(
+ message_type
+ for message_type in types_with("activityRole")
+ if message_type in TERMINAL_AGENT_OUTPUT_TYPES
+ ),
+ )
+ )
+)
+
+SESSION_AGENT_UNAVAILABLE_CODE = "session_agent_unavailable"
+SESSION_AGENT_UNAVAILABLE_I18N_KEY = "error.sessionFork.agentUnavailable"
class SessionForkError(ValueError):
@@@ -181,7 -146,18 +185,19 @@@ def reserve_forked_session
agent_store = VibeAgentStore(path)
try:
with engine.begin() as conn:
+ reserve_write_lock(conn)
+ if not context.is_instance_owner:
+ from storage import project_access_service
+
+ if not project_access_service.role_allows(
+ project_access_service.get_effective_session_role(
+ conn,
+ context,
+ source_session_id,
+ ),
+ "editor",
+ ):
+ raise SessionForkError("source_not_found")
row = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == str(source_session_id)).limit(1)
).mappings().first()
diff --cc core/services/sessions.py
index 97d0ed373,8dc2a817b..f955a695b
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@@ -37,8 -37,7 +37,9 @@@ from typing import Optiona
from config import paths
from storage.workbench_sessions_service import (
+ ProjectAccessDeniedError,
+ ReservedSessionError,
+ SessionArchivedError,
SessionBackendLockedError,
archive_session,
backfill_session_title,
@@@ -50,18 -49,14 +51,20 @@@
is_session_archived,
list_sessions,
list_sessions_page,
+ reset_running_agent_status,
+ require_enabled_agent_backend,
+ require_enabled_agent_identity,
set_agent_status,
touch_session,
update_session,
)
+from vibe.i18n import t as i18n_t
__all__ = [
+ "ProjectAccessDeniedError",
+ "SESSION_ARCHIVED_I18N_KEY",
+ "ReservedSessionError",
+ "SessionArchivedError",
"SessionBackendLockedError",
"archive_session",
"backfill_session_title",
@@@ -73,8 -68,8 +76,9 @@@
"is_session_archived",
"list_sessions",
"list_sessions_page",
+ "reset_running_agent_status",
"set_agent_status",
+ "session_archived_message",
"touch_session",
"update_session",
"reserve_agent_session",
diff --cc core/session_turns.py
index 15c94fe4b,f1191b69f..90b7db197
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@@ -17,47 -19,24 +17,51 @@@ from __future__ import annotation
import asyncio
import json
import logging
-from dataclasses import dataclass
+import uuid
+from dataclasses import dataclass, replace
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Any, Callable, Optional
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
-from sqlalchemy import select
-from sqlalchemy.engine import Engine
+from sqlalchemy import select, update
+from sqlalchemy.engine import Connection, Engine
from sqlalchemy.exc import IntegrityError
- from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATA
+ from core.web_push_notifications import (
+ WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA,
+ WEB_PUSH_USER_KEY_METADATA,
+ WEB_PUSH_USER_KEYS_METADATA,
+ )
-from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
+from core.native_dispatch_phase import backend_dispatch_attempted
+from core.run_settlement import (
+ SETTLEMENTS_WITHOUT_RESULT,
+ SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ SETTLED_BY_RESTARTED,
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_TERMINAL_RESULT,
+)
+from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn_with_outcome
+from core.services.agent_steering import (
+ SteerOutcome,
+ SteerReconcileRequest,
+ SteerRequest,
+ active_steer_identity,
+ reconcile_steer_attempt,
+ result as steer_result,
+ steer_active_turn,
+)
from storage import messages_service
+from storage import message_deliveries as delivery_store
+from storage.agent_session_rows import reserve_write_lock
from storage.db import get_cached_sqlite_engine
from storage.background import normalize_run_status
-from storage.models import agent_runs, messages
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ message_deliveries as delivery_rows,
+ session_turns as session_turn_rows,
+)
from storage.workbench_sessions_service import derive_session_harness_activities
from core.message_output import terminal_turn_output
from vibe.i18n import t as i18n_t
@@@ -116,64 -87,10 +120,66 @@@ _TERMINAL_RESULT_LATCH_KEY = "_avibe_te
_FLUSH_REBUILT_KEYS = frozenset(
{"platform", "is_dm", "workbench_session_id", "agent_session_id", "agent_session_target", "turn_token"}
)
+_EXECUTION_ROUTING_KEYS = _FLUSH_REBUILT_KEYS | frozenset(
+ {
+ "vibe_agent_id",
+ "vibe_agent_name",
+ "scheduled_target_agent_name",
+ "resolved_vibe_agent",
+ }
+)
SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"
+ MEMORY_USER_ID_METADATA = "_memory_user_id"
+ MEMORY_ORDINARY_TEXT_METADATA = "_memory_ordinary_text"
+_NON_RESTORABLE_RUNTIME_BACKENDS = frozenset({"claude", "codex"})
+_MAX_AUTOMATIC_UNKNOWN_START_REPLAYS = 1
+_UNKNOWN_START_REPLAY_INSTRUCTION = (
+ "[Avibe recovery: this request may have been delivered before restart. "
+ "Before any irreversible action, check whether the work is already complete.]\n\n"
+)
+
+
+def _start_replay_count(deliveries: list[dict[str, Any]]) -> int:
+ counts: list[int] = []
+ for delivery in deliveries:
+ try:
+ history = json.loads(str(delivery.get("delivery_history_json") or "{}"))
+ except (TypeError, ValueError, json.JSONDecodeError):
+ history = {}
+ events = history.get("events") if isinstance(history, dict) else None
+ counts.append(
+ sum(
+ 1
+ for event in events or []
+ if isinstance(event, dict)
+ and event.get("kind") == "start"
+ and event.get("outcome") == "restart_replayed"
+ )
+ )
+ return max(counts, default=0)
+
+
+def _opencode_native_session_id(native_turn_id: str | None) -> str | None:
+ value = str(native_turn_id or "").strip()
+ if not value.startswith("opencode:"):
+ return None
+ native_session_id, separator, generation = value[len("opencode:") :].rpartition(":")
+ if not separator or not native_session_id or not generation:
+ return None
+ return native_session_id
+
+
+def _same_opencode_native_session(
+ persisted_native_turn_id: str | None,
+ restored_native_turn_id: str | None,
+) -> bool:
+ persisted_session = _opencode_native_session_id(persisted_native_turn_id)
+ return bool(
+ persisted_session
+ and persisted_session == _opencode_native_session_id(restored_native_turn_id)
+ )
+
def capture_scheduled_provenance(context: "MessageContext") -> dict:
"""Capture the scheduled run's provenance to persist on its queued row so
@@@ -272,47 -228,30 +278,59 @@@ def _scheduled_merge_key(row: dict[str
)
-def _within_scheduled_merge_window(previous: dict, current: dict) -> bool:
- prev_ts = _parse_queue_timestamp(previous.get("created_at"))
- current_ts = _parse_queue_timestamp(current.get("created_at"))
- if prev_ts is None or current_ts is None:
- return False
- delta = (current_ts - prev_ts).total_seconds()
- return 0 <= delta <= SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS
-
+def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Return the one compatible leading segment a Turn may claim."""
-def _collect_scheduled_segment(rows: list[dict]) -> list[dict]:
if not rows:
return []
- first_key = _scheduled_merge_key(rows[0])
- if first_key is None:
+ message_identity = delivery_store.message_merge_identity(rows[0])
+ scheduled_key = _scheduled_merge_key(rows[0])
+ if _scheduled_provenance(rows[0]) is not None and scheduled_key is None:
return [rows[0]]
- segment = [rows[0]]
- latest = rows[0]
- for row in rows[1:]:
- if _scheduled_merge_key(row) != first_key:
+ if scheduled_key is not None:
+ segment = [rows[0]]
+ latest = rows[0]
+ for row in rows[1:]:
+ previous = _parse_queue_timestamp(latest.get("submitted_at"))
+ current = _parse_queue_timestamp(row.get("submitted_at"))
+ if (
+ delivery_store.message_merge_identity(row) != message_identity
+ or _scheduled_merge_key(row) != scheduled_key
+ or previous is None
+ or current is None
+ ):
+ break
+ delta = (current - previous).total_seconds()
+ if delta < 0 or delta > SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS:
+ break
+ segment.append(row)
+ latest = row
+ return segment
+
+ segment: list[dict[str, Any]] = []
++ segment_owner: str | None = None
+ for row in rows:
+ if _scheduled_provenance(row) is not None:
+ break
+ if delivery_store.message_merge_identity(row) != message_identity:
break
- if not _within_scheduled_merge_window(latest, row):
++ metadata = row.get("metadata") or {}
++ owner = str(metadata.get(MEMORY_USER_ID_METADATA) or "").strip() or None
++ if segment and (
++ owner is None
++ or segment_owner is None
++ or owner != segment_owner
++ ):
++ break
+ native_message_id = str(row.get("native_message_id") or "").strip()
+ if native_message_id:
+ if not segment:
+ segment.append(row)
break
segment.append(row)
- latest = row
++ segment_owner = owner
++ if owner is None:
++ break
return segment
@@@ -877,3682 -684,508 +895,3763 @@@ class SessionTurnManager
# Chunks are discarded — the browser renders from ``message.new``.
return None
- async def submit(
- self,
- session_id: Optional[str],
- context: "MessageContext",
- text: str,
- *,
- source: str = SOURCE_HUMAN,
- enqueue: Optional[Callable[[], None]] = None,
- ) -> str:
- """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.
-
- Returns ``"ran"`` or ``"enqueued"``. The busy / pre-existing-queue decision,
- the idle-with-queue drain, and the run are unified here; the caller supplies
- ``enqueue`` — a 0-arg callable that persists the SOURCE-specific queued row
- (Chat promotes its pre-saved pending row; the scheduler appends a harness
- row) — because that row's shape depends on the request. The in_flight check
- and the enqueue have no ``await`` between them (single-threaded loop), so a
- running turn cannot end + flush in the gap — the enqueue stays atomic.
- """
- 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 "ran"
+ def _delivery_context(self, session_id: str) -> "MessageContext":
+ if self._build_context is None:
+ raise RuntimeError("Session delivery context builder is not bound")
+ return self._build_context(session_id)
+
+ def _delivery_backend(self, session_id: str, context: Optional["MessageContext"]) -> tuple[str, "MessageContext"]:
+ resolved = context or self._delivery_context(session_id)
+ with self._sqlite_engine().connect() as conn:
+ backend = str(
+ conn.execute(
+ select(agent_sessions.c.agent_backend).where(
+ agent_sessions.c.id == session_id
+ )
+ ).scalar_one_or_none()
+ or ""
+ ).strip()
+ if not backend:
+ backend = self._context_backend(resolved)
+ if not backend:
+ raise RuntimeError(f"Session {session_id} has no resolved backend")
+ return backend, resolved
- 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:
- should_enqueue = True
- self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
- elif busy:
- should_enqueue = True
- else:
- with self._sqlite_engine().connect() as conn:
- should_enqueue = bool(messages_service.list_queued(conn, session_id))
- if should_enqueue:
- if enqueue is not None:
- enqueue()
- if 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
- # (the later flush emits its own queue.updated when it pops). This
- # closes the enqueue-time gap for BOTH Chat and scheduled sends.
- from core.inbox_events import bus
+ @staticmethod
+ def _delivery_snapshot(request: DeliveryRequest) -> dict[str, Any]:
+ if request.content is None:
+ raise ValueError("content Delivery requires a Message snapshot")
+ return delivery_store.message_snapshot(
+ scope_id=request.scope_id,
+ session_id=request.session_id,
+ platform=request.platform,
+ author=request.author,
+ source=request.source,
+ message_type=request.message_type,
+ text=request.display_text if request.display_text is not None else request.content,
+ content=request.content_json,
+ metadata=request.metadata,
+ author_id=request.author_id,
+ author_name=request.author_name,
+ native_message_id=request.native_message_id,
+ parent_native_message_id=request.parent_native_message_id,
+ )
- bus.publish("queue.updated", {"session_id": session_id})
- else:
- # Idle + pre-existing queue → no running turn to flush behind, so
- # drain the whole queue (this row included) now, in order. flush_queue
- # publishes queue.updated itself.
- await self.flush_queue(session_id)
- return "enqueued"
- await self._run(session_id, context, text, source=source)
- return "ran"
+ def _request_from_delivery(
+ self,
+ delivery: dict[str, Any],
+ *,
+ has_attachments: bool = False,
+ ) -> DeliveryRequest:
+ payload = delivery_store.delivery_payload(delivery)
+ return DeliveryRequest(
+ session_id=str(delivery["session_id"]),
+ priority=str(delivery["priority"]),
+ content=str(delivery.get("dispatch_text") or ""),
+ has_content=delivery_store.has_substantive_content(
+ delivery,
+ has_attachments=has_attachments,
+ ),
+ delivery_id=str(delivery["id"]),
+ scope_id=payload.get("scope_id"),
+ platform=str(payload.get("platform") or "avibe"),
+ source=str(payload.get("source") or "user"),
+ author=str(payload.get("author") or "user"),
+ message_type=str(payload.get("type") or "user"),
+ author_id=payload.get("author_id"),
+ author_name=payload.get("author_name"),
+ display_text=str(payload.get("text") or ""),
+ content_json=dict(payload.get("content") or {}),
+ metadata=dict(payload.get("metadata") or {}),
+ native_message_id=payload.get("native_message_id"),
+ parent_native_message_id=payload.get("parent_native_message_id"),
+ )
- async def _run(
+ def _committed_delivery_result(
self,
- session_id: Optional[str],
- context: "MessageContext",
- text: str,
+ delivery_id: str,
*,
- source: str = SOURCE_HUMAN,
- ) -> None:
- """Start a fire-and-forget turn and HOLD it open until it settles.
+ attempted_turn_id: str | None = None,
+ ) -> DeliveryResult:
+ """Return the exact post-transition Delivery instead of a cached claim."""
+
+ with self._sqlite_engine().connect() as conn:
+ delivery = delivery_store.get_delivery(conn, delivery_id)
+ if delivery is None:
+ raise RuntimeError(f"durable Delivery disappeared after transition: {delivery_id}")
+ turn_id = str(
+ delivery.get("turn_id")
+ or delivery.get("current_target_turn_id")
+ or attempted_turn_id
+ or ""
+ ).strip()
+ return DeliveryResult(
+ delivery_id,
+ str(delivery.get("message_id") or "").strip() or None,
+ str(delivery["state"]),
+ turn_id or None,
+ )
- A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime so
- ``in_flight`` stays populated (Stop works) and the session-level
- ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
- working indicator. On NATURAL completion the queue is flushed: messages the
- user sent while this turn ran are merged + run as the next turn. A user Stop
- (cancellation) does NOT flush — the queue is kept per the user's "don't
- clear the queue on stop" rule — unless ``send-now`` opted this session into
- ``flush_on_cancel``. The reply reaches the browser over ``message.new``.
+ @staticmethod
+ def _claim_start_batch(
+ conn: Connection,
+ *,
+ turn_id: str,
+ session_id: str,
+ backend: str,
+ deliveries: list[dict[str, Any]],
+ dispatch_text: str,
+ attempt_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Claim a Delivery batch and all linked Agent Runs atomically."""
+
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for delivery in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, delivery)
+ )
+ )
+ if run_ids:
+ from storage.background import claim_agent_runs_for_turn_in_connection
+
+ claimed_run_ids = claim_agent_runs_for_turn_in_connection(conn, run_ids)
+ if claimed_run_ids != run_ids:
+ raise RuntimeError("Delivery batch contains an unclaimable Agent Run")
+ return delivery_store.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend=backend,
+ deliveries=deliveries,
+ dispatch_text=dispatch_text,
+ attempt_id=attempt_id,
+ )
- ``source`` selects the human vs. scheduler turn path in ``dispatch_turn``;
- a scheduled / watch run passes ``SOURCE_SCHEDULED`` so it goes through the
- SAME gate (in_flight + turn.start/turn.end + queue draining) as a Chat turn.
- There is NO turn-duration timeout: a long agent runs for hours and is freed
- only by a real terminal signal (Phase 1a — STUCK/sentinel removed).
- """
- from core.inbox_events import bus
+ @staticmethod
+ def _cancel_runs_for_retired_delivery(
+ conn: Connection,
+ delivery: dict[str, Any] | None,
+ ) -> list[str]:
+ """Make Delivery retirement and exact Run cancellation one transaction."""
- async def _runner() -> None:
- cancelled = False
- failed = False
- try:
- await dispatch_turn(
- self.controller,
- context,
- text,
- source=source,
- # ALWAYS pass the no-op sink — even for scheduled runs. It isn't
- # about the browser (chunks are discarded; avibe renders from
- # message.new); it makes ``dispatch_turn`` HOLD the turn open
- # until the backend's terminal result, keeping ``in_flight``
- # populated for the turn's whole lifetime. With ``on_chunk=None``
- # an async backend (Codex/Claude) returns at prompt-submit, so the
- # slot would free + a Chat send could preempt the still-running
- # scheduled turn (Codex P2).
- on_chunk=self._noop_chunk,
+ if delivery is None or delivery.get("state") != "retired":
+ return []
+ from storage.background import (
+ cancel_agent_runs_for_retired_deliveries_in_connection,
+ )
+
+ return cancel_agent_runs_for_retired_deliveries_in_connection(
+ conn,
+ session_id=str(delivery["session_id"]),
+ delivery_ids=[str(delivery["id"])],
+ )
+
+ @classmethod
+ def _record_definitive_delivery_attempt(
+ cls,
+ conn: Connection,
+ delivery_id: str,
+ **kwargs: Any,
+ ) -> dict[str, Any] | None:
+ delivery = delivery_store.record_definitive_attempt(
+ conn,
+ delivery_id,
+ **kwargs,
+ )
+ cls._cancel_runs_for_retired_delivery(conn, delivery)
+ return delivery
+
+ @classmethod
+ def _retire_delivery_not_written(
+ cls,
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+ *,
+ reason: str,
+ ) -> bool:
+ retired = delivery_store.retire_not_written(
+ conn,
+ session_id,
+ delivery_id,
+ reason=reason,
+ )
+ if retired:
+ cls._cancel_runs_for_retired_delivery(
+ conn,
+ delivery_store.get_delivery(conn, delivery_id),
+ )
+ return retired
+
+ def _claim_fifo_batch_in_transaction(
+ self,
+ conn: Connection,
+ *,
+ session_id: str,
+ backend: str,
+ ) -> str | None:
+ """Claim the exact open FIFO head while the caller owns SQLite's writer slot."""
+
+ if (
+ delivery_store.active_turn(conn, session_id) is not None
+ or delivery_store.queue_is_held(conn, session_id)
+ or backend in self._draining_backends
+ ):
+ return None
+ while True:
+ head = delivery_store.claimable_fifo_head(conn, session_id)
+ queued = delivery_store.claimable_fifo_prefix(conn, session_id)
+ if head is None or not queued or str(queued[0]["id"]) != str(head["id"]):
+ return None
+ segment_payloads = _collect_delivery_segment(queued)
+ segment = [
+ delivery_store.get_delivery(conn, str(row["id"]))
+ for row in segment_payloads
+ ]
+ if not segment or any(row is None for row in segment):
+ return None
+ delivery_rows = [row for row in segment if row is not None]
+ invalid_rows = [
+ row
+ for row in delivery_rows
+ if not self._has_resolvable_delivery_input(conn, row)
+ ]
+ if invalid_rows:
+ for row in invalid_rows:
+ if not self._retire_delivery_not_written(
+ conn,
+ session_id,
+ str(row["id"]),
+ reason="invalid_input_before_fifo_claim",
+ ):
+ raise RuntimeError("invalid FIFO Delivery retirement lost")
+ logger.warning(
+ "retired queued Delivery=%s because it has no resolvable input",
+ row["id"],
+ )
+ continue
+ turn_id = delivery_store.new_turn_id()
+ self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend=backend,
+ deliveries=delivery_rows,
+ dispatch_text=_segment_dispatch_text(segment_payloads),
+ )
+ return turn_id
+
+ def _hydrate_delivery_context(
+ self,
+ context: "MessageContext",
+ delivery: dict[str, Any],
+ ) -> dict[str, Any]:
+ """Restore dispatch inputs only from the durable Delivery snapshot."""
+
+ payload = delivery_store.delivery_payload(delivery)
+ context.platform = str(payload.get("platform") or context.platform or "avibe")
+ native_message_id = str(payload.get("native_message_id") or "").strip()
+ context.message_id = (
+ native_message_id
+ if context.platform != "avibe" and native_message_id
+ else str(delivery["id"])
+ )
+ if payload.get("author_id"):
+ context.user_id = str(payload["author_id"])
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(
+ {
+ "delivery_id": str(delivery["id"]),
+ "scope_id": payload.get("scope_id"),
+ "display_text": payload.get("text") or "",
+ "message_content": dict(payload.get("content") or {}),
+ "message_metadata": dict(payload.get("metadata") or {}),
+ "author_id": payload.get("author_id"),
+ "author_name": payload.get("author_name"),
+ "native_message_id": payload.get("native_message_id"),
+ "delivery_admission_context": (
+ delivery_store.delivery_admission_context(delivery)
+ ),
+ }
+ )
+ from core.workbench_media import (
+ file_attachments_from_specs,
+ resolve_attachment_specs,
+ )
+
+ attachments = (payload.get("content") or {}).get("attachments") or []
+ with self._sqlite_engine().connect() as conn:
+ specs = resolve_attachment_specs(
+ conn,
+ session_id=str(delivery["session_id"]),
+ attachments=attachments,
+ )
+ context.files = file_attachments_from_specs(specs)
+ return payload
+
+ @staticmethod
+ def _has_resolvable_delivery_input(
+ conn: Connection,
+ delivery: dict[str, Any],
+ ) -> bool:
+ payload = delivery_store.delivery_payload(delivery)
+ from core.workbench_media import resolve_attachment_specs
+
+ specs = resolve_attachment_specs(
+ conn,
+ session_id=str(delivery["session_id"]),
+ attachments=(payload.get("content") or {}).get("attachments") or [],
+ )
+ return delivery_store.has_substantive_content(
+ delivery,
+ has_attachments=bool(specs),
+ )
+
+ @staticmethod
+ def _delivery_has_attachment_references(delivery: dict[str, Any]) -> bool:
+ payload = delivery_store.delivery_payload(delivery)
+ return bool((payload.get("content") or {}).get("attachments"))
+
+ def _hydrate_delivery_batch_context(
+ self,
+ context: "MessageContext",
+ deliveries: list[dict[str, Any]],
+ ) -> dict[str, Any]:
+ if not deliveries:
+ raise RuntimeError("a durable Turn has no initial Delivery batch")
+ first = self._hydrate_delivery_context(context, deliveries[0])
+ payloads = [delivery_store.delivery_payload(row) for row in deliveries]
++ metadata_rows = [
++ dict(payload.get("metadata") or {})
++ for payload in payloads
++ ]
++ memory_metadata_present = any(
++ any(
++ key in metadata
++ for key in (
++ MEMORY_USER_ID_METADATA,
++ MEMORY_ORDINARY_TEXT_METADATA,
++ "_memory_cli_admitted",
++ )
++ )
++ for metadata in metadata_rows
++ )
++ memory_users = list(
++ dict.fromkeys(
++ user_id
++ for metadata in metadata_rows
++ if (user_id := str(metadata.get(MEMORY_USER_ID_METADATA) or "").strip())
++ )
++ )
++ web_push_owners = list(
++ dict.fromkeys(
++ owner
++ for metadata in metadata_rows
++ for value in (
++ [metadata.get(WEB_PUSH_USER_KEY_METADATA)]
++ + (
++ metadata.get(WEB_PUSH_USER_KEYS_METADATA)
++ if isinstance(metadata.get(WEB_PUSH_USER_KEYS_METADATA), list)
++ else []
++ )
++ )
++ if (owner := str(value or "").strip())
++ )
++ )
++ merged_metadata = dict(metadata_rows[0])
++ merged_metadata.pop(WEB_PUSH_USER_KEY_METADATA, None)
++ merged_metadata.pop(WEB_PUSH_USER_KEYS_METADATA, None)
++ if len(web_push_owners) == 1:
++ merged_metadata[WEB_PUSH_USER_KEY_METADATA] = web_push_owners[0]
++ elif web_push_owners:
++ merged_metadata[WEB_PUSH_USER_KEYS_METADATA] = web_push_owners
++ authorization_contexts: dict[str, dict[str, Any]] = {}
++ for metadata in metadata_rows:
++ raw_contexts = metadata.get(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA)
++ if not isinstance(raw_contexts, list):
++ continue
++ for raw_context in raw_contexts:
++ if not isinstance(raw_context, dict):
++ continue
++ user_key = str(raw_context.get("user_key") or "").strip()
++ if user_key in web_push_owners:
++ authorization_contexts[user_key] = raw_context
++ if authorization_contexts:
++ merged_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = list(
++ authorization_contexts.values()
++ )
++ if memory_metadata_present:
++ memory_user = memory_users[0] if len(memory_users) == 1 else None
++ memory_ordinary_text = all(
++ metadata.get(MEMORY_ORDINARY_TEXT_METADATA) is True
++ for metadata in metadata_rows
++ )
++ memory_cli_admitted = all(
++ metadata.get("_memory_cli_admitted") is True
++ for metadata in metadata_rows
++ )
++ merged_metadata[MEMORY_ORDINARY_TEXT_METADATA] = memory_ordinary_text
++ merged_metadata["_memory_cli_admitted"] = memory_cli_admitted
++ if memory_user:
++ merged_metadata[MEMORY_USER_ID_METADATA] = memory_user
++ context.user_id = memory_user
++ context.is_ordinary_text = memory_ordinary_text
++ if memory_cli_admitted:
++ context.platform_specific["memory_cli_admitted"] = True
++ else:
++ context.platform_specific.pop("memory_cli_admitted", None)
++ first["metadata"] = merged_metadata
++ context.platform_specific["message_metadata"] = merged_metadata
+ attachments = [
+ attachment
+ for payload in payloads
+ for attachment in ((payload.get("content") or {}).get("attachments") or [])
+ ]
+ from core.workbench_media import (
+ file_attachments_from_specs,
+ resolve_attachment_specs,
+ )
+
+ with self._sqlite_engine().connect() as conn:
+ specs = resolve_attachment_specs(
+ conn,
+ session_id=str(deliveries[0]["session_id"]),
+ attachments=attachments,
+ )
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ context.files = file_attachments_from_specs(specs)
+ context.platform_specific.update(
+ {
+ "delivery_id": str(deliveries[0]["id"]),
+ "delivery_ids": [str(row["id"]) for row in deliveries],
+ "message_content": {
+ "text": "\n".join(
+ str(payload.get("text") or "")
+ for payload in payloads
+ if str(payload.get("text") or "")
+ ),
+ **({"attachments": attachments} if attachments else {}),
+ },
+ }
+ )
+ self._append_accepted_agent_run_ids(context.platform_specific, run_ids)
+ return first
+
+ @staticmethod
+ def _insert_delivery(
+ conn: Connection,
+ request: DeliveryRequest,
+ *,
+ priority: str,
+ state: str,
+ ) -> dict[str, Any]:
+ delivery_id = request.delivery_id or delivery_store.new_delivery_id()
+ existing = delivery_store.get_delivery(conn, delivery_id)
+ if existing is not None:
+ if existing["session_id"] != request.session_id:
+ raise ValueError("Delivery does not belong to the target Session")
+ return existing
+ dedupe_key = delivery_store.native_dedupe_key(
+ request.platform,
+ request.native_message_id,
+ scope_id=request.scope_id,
+ )
+ if dedupe_key:
+ existing = delivery_store.get_delivery_by_native_identity(
+ conn,
+ platform=request.platform,
+ native_message_id=str(request.native_message_id or ""),
+ scope_id=request.scope_id,
+ session_id=request.session_id,
+ normalize_legacy=True,
+ )
+ if existing is not None:
+ if existing["session_id"] != request.session_id:
+ raise ValueError("Delivery dedupe identity belongs to another Session")
+ return existing
+ return delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=request.session_id,
+ priority=priority,
+ state=state,
+ snapshot=SessionTurnManager._delivery_snapshot(request),
+ dispatch_text=str(request.content or ""),
+ dedupe_key=dedupe_key,
+ history_event={
+ "kind": "admission",
+ "priority": priority,
+ "state": state,
+ **(
+ {"context": dict(request.admission_context)}
+ if request.admission_context
+ else {}
+ ),
+ },
+ )
+
+ @staticmethod
+ def reserve_delivery(
+ conn: Connection,
+ request: DeliveryRequest,
+ ) -> dict[str, Any]:
+ """Persist a producer-owned content reservation in the caller's transaction."""
+
+ if request.content is None:
+ raise ValueError("content Delivery requires a Message snapshot")
+ if request.priority not in {"p1", "p3"}:
+ raise ValueError("content reservation requires P1 or P3 priority")
+ return SessionTurnManager._insert_delivery(
+ conn,
+ request,
+ priority=request.priority,
+ state="reserved",
+ )
+
+ def _active_identity(
+ self,
+ backend: str,
+ session_id: str,
+ logical_turn_id: str,
+ ) -> tuple[str, str] | None:
+ return active_steer_identity(
+ self.controller,
+ backend,
+ session_id,
+ expected_logical_turn_id=logical_turn_id,
+ )
+
+ async def _steer(self, backend: str, request: SteerRequest):
+ return await steer_active_turn(self.controller, backend, request)
+
+ async def _attempt_steer(self, backend: str, request: SteerRequest):
+ try:
+ return await self._steer(backend, request)
+ except Exception as exc:
+ logger.exception(
+ "native steering outcome is unknown for Session=%s Turn=%s",
+ request.target_session_id,
+ request.expected_logical_turn_id,
+ )
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="adapter_error",
+ error_type=type(exc).__name__,
+ )
+
+ async def _reconcile_steer_attempt(
+ self,
+ backend: str,
+ request: SteerReconcileRequest,
+ ):
+ try:
+ return await reconcile_steer_attempt(self.controller, backend, request)
+ except Exception as exc:
+ logger.exception(
+ "native steering reconciliation failed for Session=%s Turn=%s Attempt=%s",
+ request.target_session_id,
+ request.expected_logical_turn_id,
+ request.attempt_id,
+ )
+ return steer_result(
+ SteerOutcome.UNKNOWN,
+ reason="adapter_reconciliation_error",
+ error_type=type(exc).__name__,
+ )
+
+ def _observe_active_delivery_turn(
+ self,
+ session_id: str,
+ ) -> tuple[dict[str, Any] | None, tuple[str, str] | None]:
+ with self._sqlite_engine().connect() as conn:
+ turn = delivery_store.active_turn(conn, session_id)
+ if turn is None:
+ return turn, None
+ identity = self._active_identity(
+ str(turn["backend"]),
+ session_id,
+ str(turn["id"]),
+ )
+ persisted_native_id = str(turn.get("native_turn_id") or "").strip()
+ if identity is None and turn["state"] == "active" and persisted_native_id:
+ identity = (str(turn["id"]), persisted_native_id)
+ if identity is not None and turn["state"] != "active":
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, str(turn["id"]))
+ if latest is None or latest["state"] not in delivery_store.TURN_OWNER_STATES:
+ return latest, None
+ bound = delivery_store.bind_native_start(
+ conn,
+ str(turn["id"]),
+ expected_version=int(latest["version"]),
+ runtime_key=latest.get("runtime_key"),
+ runtime_turn_id=latest.get("runtime_turn_id"),
+ native_turn_id=identity[1],
+ )
+ if bound is None:
+ return latest, None
+ turn = bound
+ return turn, identity
+
+ async def deliver(
+ self,
+ request: DeliveryRequest,
+ *,
+ context: Optional["MessageContext"] = None,
+ ) -> DeliveryResult:
+ """Execute the private durable P0/P1/P3 ownership state machine."""
+
+ if not request.session_id:
+ raise ValueError("Session delivery requires a Session id")
+ if request.priority not in {"p0", "p1", "p3"}:
+ raise ValueError(f"unsupported delivery priority: {request.priority}")
+ content_present = (
+ request.has_content
+ if request.has_content is not None
+ else bool(request.content)
+ )
+ if not content_present and request.content == "":
+ request = replace(request, content=None)
+ if request.priority == "p3" and not content_present:
+ raise ValueError("P3 requires content")
+ backend, resolved_context = self._delivery_backend(request.session_id, context)
+ if request.priority == "p3":
+ return await self._admit_p3(request, backend, resolved_context)
+ if request.priority == "p1":
+ return await self._admit_p1(request, backend, resolved_context)
+ return await self._admit_p0(request, backend, resolved_context)
+
+ async def _admit_p3(
+ self,
+ request: DeliveryRequest,
+ backend: str,
+ context: "MessageContext",
+ ) -> DeliveryResult:
+ turn_id: str | None = None
+ delivery_turn_id: str | None = None
+ start_context: MessageContext | None = None
+ delivery: dict[str, Any]
+ backend_draining = backend in self._draining_backends
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == request.session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ existing = (
+ delivery_store.get_delivery(conn, request.delivery_id)
+ if request.delivery_id
+ else None
+ )
+ if existing is not None and existing["state"] in {"reserved", "queued"}:
+ self._retire_delivery_not_written(
+ conn,
+ request.session_id,
+ str(existing["id"]),
+ reason="session_archived",
+ )
+ return DeliveryResult(str(existing["id"]), None, "retired")
+ raise ValueError("Session is archived")
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p3",
+ state="queued",
+ )
+ if delivery["state"] not in {"queued", "reserved"}:
+ return DeliveryResult(
+ str(delivery["id"]),
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ str(delivery.get("turn_id") or delivery.get("current_target_turn_id") or "")
+ or None,
+ )
+ if delivery["state"] == "reserved":
+ queued = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"state": "queued"},
+ history_event={"kind": "queue", "reason": "p3_admission"},
+ )
+ if queued is None:
+ raise RuntimeError("P3 queue claim lost after writer reservation")
+ delivery = queued
+ active = delivery_store.active_turn(conn, request.session_id)
+ if active is None and not backend_draining:
+ held = delivery_store.queue_is_held(conn, request.session_id)
+ queued_payloads = delivery_store.claimable_fifo_prefix(
+ conn, request.session_id
+ )
+ held_fence = (
+ delivery_store.ordering_head(
+ conn,
+ request.session_id,
+ include_claimable=False,
+ )
+ if held
+ else None
+ )
+ if held and held_fence is not None:
+ segment_payloads = []
+ elif held:
+ segment_payloads = [delivery_store.delivery_payload(delivery)]
+ else:
+ segment_payloads = _collect_delivery_segment(queued_payloads)
+ segment = [
+ delivery_store.get_delivery(conn, str(row["id"]))
+ for row in segment_payloads
+ ]
+ if segment and all(row is not None for row in segment):
+ turn_id = delivery_store.new_turn_id()
+ claimed_batch = self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=request.session_id,
+ backend=backend,
+ deliveries=[row for row in segment if row is not None],
+ dispatch_text=_segment_dispatch_text(segment_payloads),
+ )
+ for claimed in claimed_batch["deliveries"]:
+ if str(claimed["id"]) == str(delivery["id"]):
+ delivery = claimed
+ delivery_turn_id = turn_id
+ if int(claimed.get("turn_position") or 0) == 0:
+ start_context = context
+ break
+ if backend_draining:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ request.session_id
+ )
+ if turn_id:
+ await self._start_persisted_turn(turn_id, context=start_context)
+ return self._committed_delivery_result(
+ str(delivery["id"]),
+ attempted_turn_id=turn_id,
+ )
+ return DeliveryResult(
+ str(delivery["id"]),
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ delivery_turn_id,
+ )
+
+ async def _admit_p1(
+ self,
+ request: DeliveryRequest,
+ backend: str,
+ context: "MessageContext",
+ ) -> DeliveryResult:
+ if request.content is None:
+ return await self._promote_fifo_head(
+ request.session_id,
+ backend,
+ context,
+ expected_delivery_id=request.expected_delivery_id,
+ )
+
+ observed, identity = self._observe_active_delivery_turn(request.session_id)
+ observed_id = str((observed or {}).get("id") or "") or None
+ attempt_id: str | None = None
+ native_id: str | None = None
+ turn_id: str | None = None
+ steer_backend = backend
+ delivery: dict[str, Any]
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == request.session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ existing = (
+ delivery_store.get_delivery(conn, request.delivery_id)
+ if request.delivery_id
+ else None
+ )
+ if existing is not None and existing["state"] == "reserved":
+ self._retire_delivery_not_written(
+ conn,
+ request.session_id,
+ str(existing["id"]),
+ reason="session_archived",
+ )
+ return DeliveryResult(str(existing["id"]), None, "retired")
+ raise ValueError("Session is archived")
+ current = delivery_store.active_turn(conn, request.session_id)
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p1",
+ state="reserved",
+ )
+ if delivery["state"] != "reserved":
+ return DeliveryResult(
+ str(delivery["id"]),
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ str(delivery.get("current_target_turn_id") or "") or None,
+ )
+ same_active = bool(
+ current is not None
+ and observed_id
+ and str(current["id"]) == observed_id
+ and current["state"] == "active"
+ and identity is not None
+ and identity[0] == observed_id
+ )
+ if current is not None and self._delivery_has_attachment_references(delivery):
+ claimed = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "steer",
+ "turn_id": str(current["id"]),
+ "outcome": "attachments_require_new_turn",
+ },
+ )
+ if claimed is None:
+ raise RuntimeError("attachment P1 fallback claim lost")
+ delivery = claimed
+ elif same_active:
+ attempt_id = delivery_store.new_attempt_id()
+ native_id = str(identity[1])
+ turn_id = observed_id
+ steer_backend = str(current["backend"])
+ claimed = delivery_store.open_steer_attempt(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_id,
+ )
+ if claimed is None:
+ raise RuntimeError("P1 steer claim lost after writer reservation")
+ delivery = claimed
+ elif current is None:
+ turn_id = delivery_store.new_turn_id()
+ if observed_id:
+ delivery = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={},
+ history_event={
+ "kind": "admission",
+ "turn_id": observed_id,
+ "outcome": "observed_turn_settled_before_claim",
+ },
+ ) or delivery
+ claimed_batch = self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=request.session_id,
+ backend=backend,
+ deliveries=[delivery],
+ dispatch_text=str(delivery.get("dispatch_text") or ""),
+ )
+ delivery = claimed_batch["deliveries"][0]
+ elif observed_id and str(current["id"]) == observed_id:
+ attempt_id = delivery_store.new_attempt_id()
+ pending_rows = delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=[delivery],
+ turn_id=str(current["id"]),
+ attempt_id=attempt_id,
+ )
+ delivery = pending_rows[0]
+ turn_id = str(current["id"])
+ else:
+ claimed = delivery_store.cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "steer",
+ "turn_id": observed_id,
+ "outcome": "target_changed_before_claim",
+ "current_turn_id": str(current["id"]),
+ },
+ )
+ if claimed is None:
+ raise RuntimeError("P1 stale-target fallback claim lost")
+ delivery = claimed
+
+ if delivery["state"] == "claimed" and turn_id:
+ await self._start_persisted_turn(turn_id, context=context)
+ return self._committed_delivery_result(
+ str(delivery["id"]),
+ attempted_turn_id=turn_id,
+ )
+ elif delivery["state"] == "steering" and turn_id and attempt_id and native_id:
+ receipt = await self._attempt_steer(
+ steer_backend,
+ SteerRequest(
+ target_session_id=request.session_id,
+ expected_logical_turn_id=turn_id,
+ expected_native_turn_id=native_id,
+ text=str(delivery.get("dispatch_text") or ""),
+ attempt_id=attempt_id,
+ ),
+ )
+ return await self._finish_steer(str(delivery["id"]), receipt, context=context)
+ return DeliveryResult(str(delivery["id"]), None, str(delivery["state"]), turn_id)
+
+ async def _promote_fifo_head(
+ self,
+ session_id: str,
+ backend: str,
+ context: "MessageContext",
+ *,
+ expected_delivery_id: str | None = None,
+ ) -> DeliveryResult:
+ with self._sqlite_engine().connect() as conn:
+ observed_head = delivery_store.ordering_head(conn, session_id)
+ observed_segment_payloads = _collect_delivery_segment(
+ delivery_store.claimable_fifo_prefix(conn, session_id)
+ )
+ if observed_head is None:
+ return DeliveryResult(None, None, "empty")
+ observed_owner_id = str(observed_head["id"])
+ if expected_delivery_id and observed_owner_id != expected_delivery_id:
+ return DeliveryResult(
+ expected_delivery_id,
+ None,
+ "refused",
+ reason="stale_head",
+ )
+ if observed_head["state"] != "queued":
+ return DeliveryResult(
+ observed_owner_id,
+ None,
+ "refused",
+ reason="ordering_fence",
+ )
+ observed_turn, identity = self._observe_active_delivery_turn(session_id)
+ observed_turn_id = str((observed_turn or {}).get("id") or "") or None
+ observed_segment_ids = [str(row["id"]) for row in observed_segment_payloads]
+ if not observed_segment_ids or observed_segment_ids[0] != observed_owner_id:
+ return DeliveryResult(observed_owner_id, None, "refused", reason="stale_head")
+ delivery_id = observed_owner_id
+ turn_id: str | None = None
+ attempt_id: str | None = None
+ native_id: str | None = None
+ steer_backend = backend
+ claimed_rows: list[dict[str, Any]] = []
+ dispatch_text = _segment_dispatch_text(observed_segment_payloads)
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ if status != "active":
+ return DeliveryResult(observed_owner_id, None, "refused", reason="session_archived")
+ current_head = delivery_store.ordering_head(conn, session_id)
+ if (
+ current_head is None
+ or str(current_head["id"]) != observed_owner_id
+ or (
+ expected_delivery_id
+ and str(current_head["id"]) != expected_delivery_id
+ )
+ ):
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "refused",
+ reason="stale_head",
+ )
+ if current_head["state"] != "queued":
+ return DeliveryResult(delivery_id, None, "refused", reason="ordering_fence")
+ current_segment_payloads = _collect_delivery_segment(
+ delivery_store.claimable_fifo_prefix(conn, session_id)
+ )
+ if [str(row["id"]) for row in current_segment_payloads[: len(observed_segment_ids)]] != observed_segment_ids:
+ return DeliveryResult(delivery_id, None, "refused", reason="stale_head")
+ segment = [
+ delivery_store.get_delivery(conn, candidate_id)
+ for candidate_id in observed_segment_ids
+ ]
+ if any(row is None or row["state"] != "queued" for row in segment):
+ return DeliveryResult(delivery_id, None, "refused", reason="stale_head")
+ delivery_rows = [row for row in segment if row is not None]
+ current_turn = delivery_store.active_turn(conn, session_id)
+ if current_turn is None:
+ turn_id = delivery_store.new_turn_id()
+ claimed = self._claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend=backend,
+ deliveries=delivery_rows,
+ dispatch_text=dispatch_text,
+ )
+ claimed_rows = claimed["deliveries"]
+ elif any(
+ self._delivery_has_attachment_references(row)
+ for row in delivery_rows
+ ):
+ if not delivery_store.set_queue_hold(conn, session_id, held=False):
+ raise RuntimeError("attachment queue promotion lost its Session hold CAS")
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "queued",
+ str(current_turn["id"]),
+ reason="attachments_wait_for_new_turn",
+ )
+ elif (
+ observed_turn_id
+ and str(current_turn["id"]) == observed_turn_id
+ and current_turn["state"] == "active"
+ and identity is not None
+ and identity[0] == observed_turn_id
+ ):
+ turn_id = observed_turn_id
+ attempt_id = delivery_store.new_attempt_id()
+ native_id = str(identity[1])
+ steer_backend = str(current_turn["backend"])
+ claimed_rows = delivery_store.open_steer_attempt_batch(
+ conn,
+ deliveries=delivery_rows,
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_id,
+ )
+ elif observed_turn_id and str(current_turn["id"]) == observed_turn_id:
+ turn_id = str(current_turn["id"])
+ attempt_id = delivery_store.new_attempt_id()
+ claimed_rows = delivery_store.open_pending_steer_batch(
+ conn,
+ deliveries=delivery_rows,
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ )
+ else:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "refused",
+ reason="stale_turn",
+ )
+ if not claimed_rows:
+ return DeliveryResult(delivery_id, None, "refused", reason="claim_lost")
+ if not delivery_store.set_queue_hold(conn, session_id, held=False):
+ raise RuntimeError("successful queue promotion lost its Session hold CAS")
+
+ leader = claimed_rows[0]
+ if leader["state"] == "claimed" and turn_id:
+ await self._start_persisted_turn(turn_id)
+ return self._committed_delivery_result(
+ delivery_id,
+ attempted_turn_id=turn_id,
+ )
+ elif leader["state"] == "steering" and turn_id and attempt_id and native_id:
+ receipt = await self._attempt_steer(
+ steer_backend,
+ SteerRequest(
+ target_session_id=session_id,
+ expected_logical_turn_id=turn_id,
+ expected_native_turn_id=native_id,
+ text=dispatch_text,
+ attempt_id=attempt_id,
+ ),
+ )
+ return await self._finish_steer(delivery_id, receipt, context=context)
+ return DeliveryResult(delivery_id, None, str(leader["state"]), turn_id)
+
+ async def _finish_steer(
+ self,
+ delivery_id: str,
+ receipt: Any,
+ *,
+ context: Optional["MessageContext"],
+ ) -> DeliveryResult:
+ outcome = getattr(receipt, "outcome", SteerOutcome.UNKNOWN)
+ outcome_value = str(getattr(outcome, "value", outcome))
+ body = {
+ "reason": getattr(receipt, "reason", None),
+ "details": dict(getattr(receipt, "details", {}) or {}),
+ }
+ should_drain = False
+ materialized = False
+ saved: dict[str, Any] | None = None
+ accepted_run_ids: list[str] = []
+ terminal_target: dict[str, Any] | None = None
+ session_id = ""
+ try:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ delivery = delivery_store.get_delivery(conn, delivery_id)
+ if delivery is None:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ reason="missing_delivery",
+ )
+ target_turn_id = str(delivery.get("current_target_turn_id") or "")
+ session_id = str(delivery["session_id"])
+ attempt_id = str(delivery.get("current_attempt_id") or "")
+ attempt_rows = (
+ delivery_store.attempt_deliveries(conn, attempt_id)
+ if attempt_id
+ else [delivery]
+ )
+ if outcome_value == SteerOutcome.ACCEPTED.value:
+ accepted_run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in attempt_rows
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ accepted_rows = delivery_store.materialize_steer_acceptance(
+ conn,
+ leader_delivery_id=delivery_id,
+ expected_attempt_id=attempt_id,
+ turn_id=target_turn_id,
+ evidence={"kind": "steer_receipt", "receipt": body},
+ )
+ if not accepted_rows:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ target_turn_id or None,
+ "receipt_cas_lost",
+ )
+ saved = accepted_rows[0]
+ materialized = True
+ target_turn = delivery_store.get_turn(conn, target_turn_id)
+ if (
+ accepted_run_ids
+ and target_turn is not None
+ and target_turn["state"] == "terminal"
+ ):
+ terminal_target = target_turn
+ if outcome_value == SteerOutcome.UNKNOWN.value:
+ unknown_rows = [
+ row
+ if row["state"] == "reconciling_steer"
+ else delivery_store.mark_attempt_unknown(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ receipt=body,
+ )
+ for row in attempt_rows
+ ]
+ saved = unknown_rows[0] if unknown_rows else None
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ target_turn_id or None,
+ None if unknown_rows and all(unknown_rows) else "receipt_cas_lost",
+ )
+ if not materialized:
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == str(delivery["session_id"])
+ )
+ ).scalar_one_or_none()
+ next_state = "queued" if session_status == "active" else "retired"
+ fallback_rows = [
+ self._record_definitive_delivery_attempt(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=(str(row["state"]),),
+ outcome=outcome_value,
+ next_state=next_state,
+ next_priority="p3",
+ receipt=body,
+ )
+ for row in attempt_rows
+ ]
+ if not fallback_rows or not all(fallback_rows):
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ target_turn_id or None,
+ "fallback_cas_lost",
+ )
+ saved = fallback_rows[0]
+ should_drain = saved is not None and saved["state"] == "queued"
+ except Exception:
+ logger.exception("failed to persist steering receipt for delivery=%s", delivery_id)
+ try:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ leader = delivery_store.get_delivery(conn, delivery_id)
+ lost_attempt_id = str((leader or {}).get("current_attempt_id") or "")
+ for row in delivery_store.attempt_deliveries(conn, lost_attempt_id):
+ if row["state"] == "steering":
+ delivery_store.mark_attempt_unknown(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ receipt={"reason": "receipt_persistence_lost"},
+ )
+ except Exception:
+ logger.exception(
+ "failed to persist unknown steer fence for delivery=%s",
+ delivery_id,
+ )
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "reconciling_steer",
+ reason="receipt_persistence_lost",
+ )
+
+ if materialized:
+ self._attach_accepted_agent_runs(
+ session_id=session_id,
+ turn_id=target_turn_id,
+ run_ids=accepted_run_ids,
+ context=context,
+ )
+ if terminal_target is not None:
+ self._settle_agent_run_ids_from_terminal_turn(
+ accepted_run_ids,
+ terminal_target,
+ )
+ self._publish_materialized_delivery(delivery_id)
+ return DeliveryResult(
+ delivery_id,
+ str((saved or {}).get("message_id") or delivery_id),
+ "accepted",
+ target_turn_id or None,
+ )
+ if should_drain:
+ await self.drain_delivery_queue(session_id)
+ return self._committed_delivery_result(
+ delivery_id,
+ )
+ return DeliveryResult(
+ delivery_id,
+ None,
+ str((saved or {}).get("state") or "reconciling_steer"),
+ None,
+ )
+
+ async def _admit_p0(
+ self,
+ request: DeliveryRequest,
+ backend: str,
+ context: "MessageContext",
+ ) -> DeliveryResult:
+ delivery_id: str | None = None
+ successor_id: str | None = None
+ interrupt_target_id: str | None = None
+ should_interrupt = False
+ joined = False
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == request.session_id
+ )
+ ).scalar_one_or_none()
+ current = delivery_store.active_turn(conn, request.session_id)
+ if request.content is not None and session_status != "active":
+ existing = (
+ delivery_store.get_delivery(conn, request.delivery_id)
+ if request.delivery_id
+ else None
+ )
+ if existing is not None and existing["state"] == "reserved":
+ self._retire_delivery_not_written(
+ conn,
+ request.session_id,
+ str(existing["id"]),
+ reason="session_archived",
+ )
+ return DeliveryResult(str(existing["id"]), None, "retired")
+ raise ValueError("Session is archived")
+ current_id = str((current or {}).get("id") or "") or None
+ if current is None:
+ if request.content is None:
+ observed_turn_id = str(request.expected_turn_id or "").strip()
+ if observed_turn_id:
+ observed_turn = delivery_store.get_turn(conn, observed_turn_id)
+ if (
+ observed_turn is not None
+ and observed_turn["session_id"] == request.session_id
+ and observed_turn["state"] == "terminal"
+ ):
+ delivery_store.set_queue_hold(
+ conn,
+ request.session_id,
+ held=True,
+ )
+ return DeliveryResult(None, None, "settled", reason="not_active")
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p0",
+ state="reserved",
+ )
+ delivery_id = str(delivery["id"])
+ successor_id = delivery_store.new_turn_id()
+ self._claim_start_batch(
+ conn,
+ turn_id=successor_id,
+ session_id=request.session_id,
+ backend=backend,
+ deliveries=[delivery],
+ dispatch_text=str(delivery.get("dispatch_text") or ""),
+ )
+ else:
+ interrupt_target_id = current_id
+ delivery = None
+ queue_was_held = delivery_store.queue_is_held(
+ conn,
+ request.session_id,
+ )
+ control_in_progress = current.get("control_state") in {
+ "pending",
+ "interrupting",
+ "waiting_terminal",
+ "reconciling",
+ }
+ if request.content is not None:
+ delivery = self._insert_delivery(
+ conn,
+ request,
+ priority="p0",
+ state="reserved",
+ )
+ delivery_id = str(delivery["id"])
+ if delivery["state"] != "reserved":
+ return DeliveryResult(
+ delivery_id,
+ str(delivery.get("message_id") or "") or None,
+ str(delivery["state"]),
+ str(delivery.get("current_target_turn_id") or "") or None,
+ )
+ if control_in_progress:
+ joined = True
+ if request.content is None and current.get("control_mode") == "replace":
+ successor_turn_id = str(
+ current.get("control_successor_turn_id") or ""
+ )
+ successor_delivery_id = str(
+ current.get("control_successor_delivery_id") or ""
+ )
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ successor_delivery = delivery_store.get_delivery(
+ conn,
+ successor_delivery_id,
+ )
+ if (
+ successor is None
+ or successor["state"] != "waiting"
+ or successor_delivery is None
+ or successor_delivery["state"] != "interrupt_waiting"
+ ):
+ return DeliveryResult(
+ None,
+ None,
+ "refused",
+ current_id,
+ "replacement_supersede_lost",
+ )
+ terminalized = self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="explicit_stop",
+ evidence_kind="replacement_superseded_by_stop",
+ )
+ retired = self._record_definitive_delivery_attempt(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ outcome="not_written",
+ next_state="retired",
+ receipt={"kind": "replacement_superseded_by_stop"},
+ )
+ if not terminalized.get("changed") or retired is None:
+ raise RuntimeError("replacement supersession lost")
+ delivery_store.set_queue_hold(
+ conn,
+ request.session_id,
+ held=True,
+ )
+ superseded = delivery_store.cas_turn(
+ conn,
+ current_id,
+ expected_version=int(current["version"]),
+ expected_states=(str(current["state"]),),
+ values={
+ "control_mode": "stop_only",
+ "control_successor_delivery_id": None,
+ "control_successor_turn_id": None,
+ },
+ )
+ if superseded is None:
+ raise RuntimeError("replacement control supersession lost")
+ if delivery is not None:
+ # Only the control-slot winner may replace the active Turn.
+ # A content loser remains one FIFO submission and never calls Stop.
+ queued = delivery_store.cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"priority": "p3", "state": "queued"},
+ history_event={
+ "kind": "interrupt_join",
+ "target_turn_id": current_id,
+ "outcome": "coalesced_to_queue",
+ },
+ )
+ if queued is None:
+ raise RuntimeError("concurrent P0 loser queue claim lost")
+ else:
+ # Only an empty-P0 Stop establishes a backlog hold. A content-P0
+ # replacement preserves whatever policy already existed; its
+ # successor may bypass that policy but must not rewrite it.
+ if delivery_id is None:
+ delivery_store.set_queue_hold(
+ conn,
+ request.session_id,
+ held=True,
+ )
+ if delivery_id is not None:
+ successor_id = delivery_store.new_turn_id()
+ delivery_store.insert_turn(
+ conn,
+ turn_id=successor_id,
+ session_id=request.session_id,
+ initial_delivery_id=delivery_id,
+ state="waiting",
+ backend=backend,
+ )
+ claimed_delivery = delivery_store.cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={
+ "priority": "p0",
+ "state": "interrupt_waiting",
+ "turn_id": successor_id,
+ "turn_role": "initial",
+ "turn_position": 0,
+ },
+ history_event={
+ "kind": "interrupt_join",
+ "target_turn_id": current_id,
+ "successor_turn_id": successor_id,
+ "outcome": "control_slot_claimed",
+ },
+ )
+ if claimed_delivery is None:
+ raise RuntimeError("P0 successor reservation claim lost")
+ attempt_id = delivery_store.new_attempt_id()
+ claimed_control = delivery_store.cas_turn(
+ conn,
+ current_id,
+ expected_version=int(current["version"]),
+ expected_states=(str(current["state"]),),
+ values={
+ "control_state": (
+ "interrupting" if current["state"] == "active" else "pending"
+ ),
+ "control_mode": "replace" if delivery_id else "stop_only",
+ "control_attempt_id": attempt_id,
+ "control_expected_native_turn_id": current.get("native_turn_id"),
+ "control_receipt_outcome": None,
+ "control_receipt_json": json.dumps(
+ {"queue_hold_was_held": queue_was_held},
+ sort_keys=True,
+ ),
+ "control_successor_delivery_id": delivery_id,
+ "control_successor_turn_id": successor_id,
+ },
+ )
+ if claimed_control is None:
+ raise RuntimeError("P0 control-slot claim lost")
+ should_interrupt = current["state"] == "active"
+
+ if current is None and successor_id:
+ await self._start_persisted_turn(successor_id, context=context)
+ return self._committed_delivery_result(
+ str(delivery_id),
+ attempted_turn_id=successor_id,
+ )
+ if joined:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "queued" if delivery_id else "interrupt_waiting",
+ interrupt_target_id,
+ "joined_existing_interrupt",
+ )
+ if not should_interrupt:
+ return DeliveryResult(
+ delivery_id,
+ None,
+ "interrupt_waiting",
+ interrupt_target_id,
+ )
+ interrupted = await self._interrupt_durable_turn(
+ request.session_id,
+ interrupt_target_id,
+ )
+ return DeliveryResult(
+ delivery_id,
+ None,
+ str(interrupted.get("state") or "reconciling"),
+ interrupt_target_id,
+ interrupted.get("reason"),
+ )
+
+ async def _interrupt_durable_turn(
+ self,
+ session_id: str,
+ logical_turn_id: str | None,
+ ) -> dict[str, Any]:
+ turn = self.in_flight.get(session_id)
+ runtime_turn = turn
+ if (
+ turn is None
+ or not logical_turn_id
+ or turn.logical_turn_id != logical_turn_id
+ or turn.task.done()
+ ):
+ runtime_turn = None
+ stop_context = runtime_turn.context if runtime_turn is not None else None
+ unavailable_reason = "runtime_owner_unavailable"
+ if stop_context is None and logical_turn_id:
+ with self._sqlite_engine().connect() as conn:
+ durable_turn = delivery_store.get_turn(conn, logical_turn_id)
+ active_turn = delivery_store.active_turn(conn, session_id)
+ exact_owner = bool(
+ durable_turn is not None
+ and active_turn is not None
+ and str(active_turn["id"]) == logical_turn_id
+ and durable_turn["state"] == "active"
+ and str(durable_turn.get("native_turn_id") or "").strip()
+ )
+ identity = (
+ self._active_identity(
+ str(durable_turn["backend"]),
+ session_id,
+ logical_turn_id,
+ )
+ if exact_owner
+ else None
+ )
+ if identity == (
+ logical_turn_id,
+ str((durable_turn or {}).get("native_turn_id") or "").strip(),
+ ):
+ try:
+ stop_context = self._delivery_context(session_id)
+ except Exception:
+ logger.exception(
+ "failed to rebuild restored interrupt context for Session=%s",
+ session_id,
+ )
+ unavailable_reason = "runtime_context_unavailable"
+ else:
+ if stop_context.platform_specific is None:
+ stop_context.platform_specific = {}
+ stop_context.platform_specific.update(
+ {
+ "turn_token": logical_turn_id,
+ "agent_runtime_turn_key": str(
+ durable_turn.get("runtime_key") or ""
+ ),
+ "agent_runtime_turn_token": str(
+ durable_turn.get("runtime_turn_id") or ""
+ ),
+ }
+ )
+ if stop_context is None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ durable_turn = delivery_store.get_turn(conn, str(logical_turn_id or ""))
+ if durable_turn is None:
+ return {"state": "reconciling", "reason": "turn_missing"}
+ if durable_turn.get("control_state") == "interrupting":
+ saved = delivery_store.cas_turn(
+ conn,
+ str(logical_turn_id),
+ expected_version=int(durable_turn["version"]),
+ expected_states=(str(durable_turn["state"]),),
+ values={
+ "control_state": "reconciling",
+ "control_receipt_outcome": "unknown",
+ "control_receipt_json": json.dumps(
+ {"reason": unavailable_reason},
+ sort_keys=True,
+ ),
+ },
+ )
+ if saved is None:
+ return {"state": "reconciling", "reason": "receipt_cas_lost"}
+ return {"state": "reconciling", "reason": unavailable_reason}
+ if stop_context.platform_specific is None:
+ stop_context.platform_specific = {}
+ stop_context.platform_specific["suppress_stop_no_active_notice"] = True
+ if runtime_turn is not None:
+ runtime_turn.cancel_settled_by = SETTLED_BY_STOPPED
+ stop_error = False
+ try:
+ stopped = bool(
+ await self.controller.command_handler.handle_stop(stop_context)
+ )
+ except Exception:
+ logger.exception("durable P0 interrupt failed for Session=%s", session_id)
+ stopped = False
+ stop_error = True
+ if not stopped and runtime_turn is not None:
+ runtime_turn.cancel_settled_by = None
+ terminal_proven = False
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ durable_turn = delivery_store.get_turn(conn, str(logical_turn_id or ""))
+ if durable_turn is None:
+ return {"state": "reconciling", "reason": "turn_missing"}
+ if durable_turn.get("control_state") != "interrupting":
+ return {
+ "state": str(durable_turn.get("control_state") or "reconciling"),
+ "reason": None,
+ }
+ if stopped:
+ saved = delivery_store.cas_turn(
+ conn,
+ str(logical_turn_id),
+ expected_version=int(durable_turn["version"]),
+ expected_states=(str(durable_turn["state"]),),
+ values={
+ "control_state": "waiting_terminal",
+ "control_receipt_outcome": "accepted",
+ "control_receipt_json": json.dumps(
+ {"kind": "stop_receipt"}, sort_keys=True
+ ),
+ },
)
- except asyncio.CancelledError:
- cancelled = True
- raise
- except Exception:
- # dispatch_turn raised before any backend turn was actually
- # dispatched (missing/disabled backend, synchronous setup error).
- # No agent reply was produced, so this is a terminal FAILURE — it must
- # NOT auto-flush the send-while-busy queue onto a fresh turn (Codex
- # P2). (An explicit send-now flush_on_cancel still flushes.)
- failed = True
- logger.exception("internal async dispatch failed for session=%s", session_id)
- finally:
- if isinstance(session_id, str):
- # The turn is over — the agent emitted its terminal result, the
- # user stopped it, or dispatch raised before any backend turn.
- # NO turn-duration timeout: the slot is freed only by a real
- # terminal signal here (Phase 1a — STUCK/sentinel removed).
- turn = self.in_flight.pop(session_id, None)
- if turn is not None:
- bus.publish("turn.end", {"session_id": session_id})
- # Converge the no-terminal-result outcome onto the OUTBOUND status
- # chokepoint. The normal path already emitted a terminal result;
- # only ``failed`` reaches here without one: dispatch raised before
- # any backend turn (missing/disabled backend) → empty error result
- # → dot red. This is a real terminal FAILURE, not a timeout.
- if failed:
- await self.controller.emit_agent_message(
- context,
- "result",
- "",
- is_error=True,
- output=terminal_turn_output(),
+ return {
+ "state": "waiting_terminal" if saved is not None else "reconciling",
+ "reason": None if saved is not None else "receipt_cas_lost",
+ }
+ reason = str(
+ (getattr(stop_context, "platform_specific", None) or {}).get(
+ "stop_failure_reason"
+ )
+ or ""
+ )
+ definitive = not stop_error and reason in {"not_active", "refused"}
+ terminal_proven = definitive and reason == "not_active"
+ fallback_state: str | None = None
+ successor_delivery_id = str(
+ durable_turn.get("control_successor_delivery_id") or ""
+ )
+ successor_turn_id = str(
+ durable_turn.get("control_successor_turn_id") or ""
+ )
+ if definitive and not terminal_proven and successor_delivery_id and successor_turn_id:
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ successor_delivery = delivery_store.get_delivery(
+ conn,
+ successor_delivery_id,
+ )
+ if (
+ successor is not None
+ and successor["state"] == "waiting"
+ and successor_delivery is not None
+ and successor_delivery["state"] == "interrupt_waiting"
+ ):
+ terminalized = self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="interrupt_refused",
+ evidence_kind="definitive_stop_receipt",
+ evidence={"reason": reason},
+ )
+ queued = delivery_store.cas_delivery(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ values={
+ "state": "queued",
+ "priority": "p3",
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ },
+ history_event={
+ "kind": "interrupt_join",
+ "attempt_id": durable_turn.get("control_attempt_id"),
+ "turn_id": str(durable_turn["id"]),
+ "outcome": "refused_to_p3",
+ "receipt": {"reason": reason},
+ },
+ )
+ if not terminalized.get("changed") or queued is None:
+ raise RuntimeError("definitive P0 refusal fallback lost")
+ fallback_state = "queued"
+ if (
+ definitive
+ and not terminal_proven
+ and durable_turn.get("control_mode") == "replace"
+ ):
+ try:
+ control_context = json.loads(
+ str(durable_turn.get("control_receipt_json") or "{}")
+ )
+ except (TypeError, ValueError):
+ control_context = {}
+ delivery_store.set_queue_hold(
+ conn,
+ session_id,
+ held=bool(control_context.get("queue_hold_was_held")),
+ )
+ saved = delivery_store.cas_turn(
+ conn,
+ str(logical_turn_id),
+ expected_version=int(durable_turn["version"]),
+ expected_states=(str(durable_turn["state"]),),
+ values={
+ "control_state": (
+ "waiting_terminal"
+ if terminal_proven
+ else "refused"
+ if definitive
+ else "reconciling"
+ ),
+ "control_receipt_outcome": (
+ "not_active"
+ if terminal_proven
+ else "refused"
+ if definitive
+ else "unknown"
+ ),
+ "control_receipt_json": json.dumps(
+ {"reason": reason or "stop_error"}, sort_keys=True
+ ),
+ },
+ )
+ receipt_result = {
+ "state": fallback_state or ("refused" if definitive else "reconciling"),
+ "reason": (
+ reason
+ if definitive
+ else "stop_unknown"
+ if saved is not None
+ else "receipt_cas_lost"
+ ),
+ }
+ if terminal_proven and saved is not None:
+ terminal = self._terminalize_durable_turn(
+ str(logical_turn_id),
+ "canceled",
+ settled_by="adapter_not_active",
+ evidence_kind="stop_not_active",
+ evidence={"reason": "not_active"},
+ )
+ projected = self.in_flight.get(session_id)
+ if (
+ projected is not None
+ and projected.logical_turn_id == logical_turn_id
+ and not projected.task.done()
+ ):
+ projected.cancel_settled_by = "adapter_not_active"
+ projected.task.cancel()
+ await asyncio.gather(projected.task, return_exceptions=True)
+ if self.in_flight.get(session_id) is projected and projected is not None:
+ self.in_flight.pop(session_id, None)
+ from core.inbox_events import bus
+
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, logical_turn_id),
+ )
+ successor_turn_id = await self._resume_linked_control_successor(
+ session_id,
+ str(logical_turn_id),
+ )
+ return {
+ "state": "claimed" if successor_turn_id else "settled",
+ "reason": "not_active",
+ }
+ return receipt_result
+
+ async def _start_persisted_turn(
+ self,
+ turn_id: str,
+ *,
+ context: Optional["MessageContext"] = None,
+ ) -> bool:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is None or turn["state"] != "starting":
+ return False
+ backend = str(turn.get("backend") or "").strip()
+ if backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ str(turn["session_id"])
+ )
+ return False
+ deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ delivery = deliveries[0] if deliveries else None
+ if (
+ delivery is None
+ or any(row["state"] != "claimed" for row in deliveries)
+ or not turn.get("start_attempt_id")
+ or not turn.get("dispatch_sha256")
+ ):
+ logger.error("durable Turn has no exact start-attempt owner: %s", turn_id)
+ return False
+ attempt_id = str(turn["start_attempt_id"])
+ # The row stays ``starting`` until native acceptance, so the live
+ # projection is the launch fence for concurrent resume callers.
+ projected = self.in_flight.get(str(turn["session_id"]))
+ if projected is not None and not projected.task.done():
+ return projected.logical_turn_id == turn_id
+ try:
+ resolved = (
+ self._delivery_context(str(turn["session_id"]))
+ if self._build_context is not None
+ else context
+ )
+ if resolved is None:
+ raise RuntimeError("durable native start has no Session routing context")
+ except Exception:
+ logger.exception("durable native start failed before dispatch for Turn=%s", turn_id)
+ self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="pre_write_failure",
+ evidence_kind="context_build_failed",
+ )
+ return False
+ archived_before_dispatch = False
+ run_terminal_before_dispatch = False
+ invalid_delivery_ids: set[str] = set()
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == str(turn["session_id"])
+ )
+ ).scalar_one_or_none()
+ fresh_deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ fresh_delivery = fresh_deliveries[0] if fresh_deliveries else None
+ if (
+ latest is None
+ or latest["state"] != "starting"
+ or latest.get("start_attempt_id") != attempt_id
+ or fresh_delivery is None
+ or latest.get("initial_delivery_id") != fresh_delivery.get("id")
+ or any(row["state"] != "claimed" for row in fresh_deliveries)
+ ):
+ return False
+ turn = latest
+ deliveries = fresh_deliveries
+ delivery = fresh_delivery
+ archived_before_dispatch = session_status != "active"
+ invalid_delivery_ids = {
+ str(row["id"])
+ for row in deliveries
+ if not self._has_resolvable_delivery_input(conn, row)
+ }
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ if not archived_before_dispatch and run_ids:
+ run_rows = {
+ str(row["id"]): row
+ for row in conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ agent_runs.c.metadata_json,
+ ).where(agent_runs.c.id.in_(run_ids))
+ ).mappings()
+ }
+ for run_id in run_ids:
+ run_row = run_rows.get(run_id)
+ if run_row is None:
+ continue
+ run_status = normalize_run_status(run_row["status"])
+ if bool(run_row["cancel_requested"]) or run_status not in {
+ "queued",
+ "running",
+ }:
+ run_terminal_before_dispatch = True
+ if archived_before_dispatch:
+ self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="session_archive",
+ evidence_kind="archive_won_before_native_dispatch",
+ )
+ return False
+ if run_terminal_before_dispatch:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="agent_run_terminal",
+ evidence_kind="agent_run_terminal_before_native_dispatch",
+ )
+ if terminal.get("changed"):
+ await self._resume_post_terminal(str(turn["session_id"]))
+ return False
+ if invalid_delivery_ids:
+ logger.error(
+ "durable Turn=%s lost its resolvable input before native dispatch",
+ turn_id,
+ )
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="invalid_input",
+ evidence_kind="invalid_input_before_native_dispatch",
+ retire_unwritten_delivery_ids=invalid_delivery_ids,
+ )
+ if terminal.get("changed"):
+ self._publish_queue_update(str(turn["session_id"]))
+ await self._resume_post_terminal(str(turn["session_id"]))
+ return False
+ try:
+ delivery_payload = self._hydrate_delivery_batch_context(resolved, deliveries)
+ resolved.platform_specific["turn_token"] = turn_id
+ resolved.platform_specific["delivery_start_attempt_id"] = attempt_id
+ metadata = delivery_payload.get("metadata") or {}
+ provenance = metadata.get(SCHEDULED_PROVENANCE_KEY)
+ source = SOURCE_HUMAN
+ if isinstance(provenance, dict):
+ source = SOURCE_SCHEDULED
+ native_message_id = str(provenance.get("message_id") or "").strip()
+ resolved.message_id = native_message_id or str(delivery["id"])
+ preserved = provenance.get("platform_specific")
+ if isinstance(preserved, dict):
+ if resolved.platform_specific is None:
+ resolved.platform_specific = {}
+ resolved.platform_specific.update(
+ {
+ key: value
+ for key, value in preserved.items()
+ if key not in _EXECUTION_ROUTING_KEYS
+ }
+ )
+ else:
+ native_message_id = str(
+ delivery_payload.get("native_message_id") or ""
+ ).strip()
+ resolved.message_id = (
+ native_message_id
+ if resolved.platform != "avibe" and native_message_id
+ else str(delivery["id"])
+ )
+ text = str(turn.get("dispatch_text") or "")
+ except Exception:
+ logger.exception(
+ "durable native start failed during pre-dispatch preparation for Turn=%s",
+ turn_id,
+ )
+ self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="pre_write_failure",
+ evidence_kind="dispatch_preparation_failed",
+ )
+ return False
+ try:
+ await self._run(
+ str(turn["session_id"]),
+ resolved,
+ text,
+ source=source,
+ logical_turn_id=turn_id,
+ delivery_id=str((delivery or {}).get("id") or "") or None,
+ durable_preallocated=True,
+ )
+ return True
+ except Exception:
+ logger.exception("durable native start became ambiguous for Turn=%s", turn_id)
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ if (
+ latest is not None
+ and latest["state"] == "starting"
+ and latest.get("start_attempt_id") == attempt_id
+ ):
+ delivery_store.mark_start_unknown(
+ conn,
+ expected_version=int(latest["version"]),
+ turn_id=turn_id,
+ receipt={"reason": "dispatch_may_have_written"},
+ )
+ return False
+
+ async def drain_delivery_queue(self, session_id: str) -> bool:
+ turn_id: str | None = None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ backend = str(
+ conn.execute(
+ select(agent_sessions.c.agent_backend).where(
+ agent_sessions.c.id == session_id
+ )
+ ).scalar_one_or_none()
+ or ""
+ ).strip()
+ if not backend:
+ raise RuntimeError(f"Session {session_id} has no resolved backend")
+ if backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(
+ session_id
+ )
+ return False
+ turn_id = self._claim_fifo_batch_in_transaction(
+ conn,
+ session_id=session_id,
+ backend=backend,
+ )
+ if turn_id is None:
+ return False
+ return await self._start_persisted_turn(turn_id)
+
+ @staticmethod
+ def _write_terminal_snapshot(
+ conn: Connection,
+ turn_id: str,
+ *,
+ outcome: str,
+ settled_by: str | None,
+ evidence_kind: str,
+ evidence: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """The only low-level terminal write; callers add reconciliation around it."""
+
+ return delivery_store.terminalize_turn(
+ conn,
+ turn_id,
+ outcome=outcome,
+ settled_by=settled_by,
+ evidence_kind=evidence_kind,
+ evidence=evidence,
+ )
+
+ def _terminalize_durable_turn(
+ self,
+ turn_id: str,
+ outcome: str,
+ *,
+ settled_by: str | None = None,
+ evidence_kind: str = "terminal_reconciliation",
+ evidence: dict[str, Any] | None = None,
+ expected_start_attempt_id: str | None = None,
+ replay_unknown_start: bool = False,
+ abandon_unaccepted_start: bool = False,
+ retire_unwritten_delivery_ids: set[str] | None = None,
+ resume_successors: bool = True,
+ ) -> dict[str, Any]:
+ if not self._durable_schema_available():
+ return {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": None,
+ "preserve_queue": False,
+ }
+ result: dict[str, Any]
+ materialized_id: str | None = None
+ terminal_run_ids: list[str] = []
+ projected_status: str | None = None
+ status_changed = False
+ replayed_unknown_start = False
+ unknown_start_exhausted = False
+ unknown_start_run_ids: list[str] = []
+ forced_retire_ids = retire_unwritten_delivery_ids or set()
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, turn_id)
+ if (
+ turn is None
+ or turn["state"] == "terminal"
+ or (
+ expected_start_attempt_id is not None
+ and turn.get("start_attempt_id") != expected_start_attempt_id
+ )
+ ):
+ result = {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": None,
+ "preserve_queue": delivery_store.queue_is_held(
+ conn, str((turn or {}).get("session_id") or "")
+ ),
+ }
+ else:
+ if outcome not in {"completed", "failed", "canceled", "not_written"}:
+ raise ValueError(f"invalid semantic Turn outcome: {outcome}")
+ session_id = str(turn["session_id"])
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ initial_batch = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ unknown_start_reconciliation = bool(
+ replay_unknown_start
+ and outcome == "failed"
+ and initial_batch
+ and all(row["state"] == "claimed" for row in initial_batch)
+ and turn.get("start_receipt_outcome") == "unknown"
+ )
+ abandoned_start = bool(
+ abandon_unaccepted_start
+ and outcome == "failed"
+ and initial_batch
+ and all(row["state"] == "claimed" for row in initial_batch)
+ and turn.get("start_receipt_outcome") != "accepted"
+ )
+ if (
+ initial_batch
+ and all(row["state"] == "claimed" for row in initial_batch)
+ and outcome != "not_written"
+ and turn.get("start_receipt_outcome") != "accepted"
+ and not unknown_start_reconciliation
+ and not abandoned_start
+ ):
+ return {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": None,
+ "preserve_queue": True,
+ "reason": "start_acceptance_unproven",
+ }
+ if initial_batch and all(row["state"] == "claimed" for row in initial_batch):
+ if abandoned_start:
+ for initial in initial_batch:
+ retired = self._record_definitive_delivery_attempt(
+ conn,
+ str(initial["id"]),
+ expected_version=int(initial["version"]),
+ expected_states=("claimed",),
+ outcome="backend_refresh_failed",
+ next_state="retired",
+ receipt={"kind": evidence_kind, **(evidence or {})},
+ )
+ if retired is None:
+ raise RuntimeError(
+ "terminal settlement lost an unresolved start Delivery"
+ )
+ elif unknown_start_reconciliation:
+ run_rows = []
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for initial in initial_batch
+ for run_id in delivery_store.agent_run_ids_for_delivery(
+ conn, initial
+ )
+ )
)
- # Flush intents ride on the popped Turn (set by cancel / send_now),
- # so they retire with it — no parallel set to discard. Don't flush
- # after a plain Stop (keep the queue) or a terminal failure; send-now
- # still forces a flush via flush_on_cancel.
- should_flush = (
- (not cancelled and not failed and not (turn is not None and turn.stop_no_flush))
- or (turn is not None and turn.flush_on_cancel)
+ if run_ids:
+ run_rows = list(
+ conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ ).where(agent_runs.c.id.in_(run_ids))
+ ).mappings()
+ )
+ run_can_replay = len(run_rows) == len(run_ids) and all(
+ not bool(row["cancel_requested"])
+ and normalize_run_status(row["status"]) in {"queued", "running"}
+ for row in run_rows
+ )
+ replayed_unknown_start = bool(
+ session_status == "active"
+ and not turn.get("control_mode")
+ and run_can_replay
+ and _start_replay_count(initial_batch)
+ < _MAX_AUTOMATIC_UNKNOWN_START_REPLAYS
+ )
+ unknown_start_exhausted = not replayed_unknown_start
+ unknown_start_run_ids = run_ids
+ next_state = "queued" if replayed_unknown_start else "retired"
+ attempt_outcome = (
+ "restart_replayed"
+ if replayed_unknown_start
+ else "restart_retry_exhausted"
+ )
+ for initial in initial_batch:
+ reconciled = self._record_definitive_delivery_attempt(
+ conn,
+ str(initial["id"]),
+ expected_version=int(initial["version"]),
+ expected_states=("claimed",),
+ outcome=attempt_outcome,
+ next_state=next_state,
+ next_priority=str(initial["priority"]),
+ receipt={"kind": evidence_kind, **(evidence or {})},
+ )
+ if reconciled is None:
+ raise RuntimeError(
+ "unknown start recovery lost a Delivery batch CAS"
+ )
+ elif outcome == "not_written":
+ for initial in initial_batch:
+ retire_unwritten = str(initial["id"]) in forced_retire_ids
+ owned_run_terminal = False
+ run_ids = (
+ []
+ if retire_unwritten
+ else delivery_store.agent_run_ids_for_delivery(conn, initial)
+ )
+ if run_ids:
+ run_rows = list(
+ conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ ).where(
+ agent_runs.c.id.in_(run_ids)
+ )
+ ).mappings()
+ )
+ owned_run_terminal = bool(
+ run_rows
+ and all(
+ bool(row["cancel_requested"])
+ or normalize_run_status(row["status"])
+ not in {"queued", "running"}
+ for row in run_rows
+ )
+ )
+ next_state = "queued"
+ if retire_unwritten or session_status != "active" or owned_run_terminal:
+ next_state = "retired"
+ definitive = self._record_definitive_delivery_attempt(
+ conn,
+ str(initial["id"]),
+ expected_version=int(initial["version"]),
+ expected_states=("claimed",),
+ outcome=("invalid_input" if retire_unwritten else "not_written"),
+ next_state=next_state,
+ next_priority="p3",
+ receipt={"kind": evidence_kind, **(evidence or {})},
+ )
+ if definitive is None:
+ raise RuntimeError(
+ "terminal no-write evidence lost a Delivery batch CAS"
+ )
+ else:
+ accepted = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "terminal_proof", "outcome": outcome},
+ )
+ if not accepted:
+ raise RuntimeError(
+ "terminal evidence could not materialize initial Delivery batch"
+ )
+ materialized_id = str(accepted[0].get("message_id") or accepted[0]["id"])
+ settled = self._write_terminal_snapshot(
+ conn,
+ turn_id,
+ outcome=outcome,
+ settled_by=settled_by,
+ evidence_kind=evidence_kind,
+ evidence=evidence,
+ )
+ if not settled.get("changed"):
+ result = {
+ "changed": False,
+ "successor_turn_id": None,
+ "delivery_id": materialized_id,
+ "preserve_queue": delivery_store.queue_is_held(conn, session_id),
+ }
+ else:
+ # A never-called steer has definitive negative evidence once
+ # its exact target Turn settles. In-flight and unknown attempts
+ # remain untouched because they may already have written.
+ pending_rows = conn.execute(
+ select(delivery_store.message_deliveries).where(
+ delivery_store.message_deliveries.c.session_id == session_id,
+ delivery_store.message_deliveries.c.state == "pending_steer",
+ delivery_store.message_deliveries.c.current_target_turn_id == turn_id,
+ )
+ ).mappings()
+ for pending_row in pending_rows:
+ fallback = self._record_definitive_delivery_attempt(
+ conn,
+ str(pending_row["id"]),
+ expected_version=int(pending_row["version"]),
+ expected_states=("pending_steer",),
+ outcome="not_active",
+ next_state=("queued" if session_status == "active" else "retired"),
+ next_priority="p3",
+ receipt={"kind": "target_turn_terminal", "turn_id": turn_id},
+ )
+ if fallback is None:
+ raise RuntimeError("pending steer terminal fallback lost")
+
+ successor_turn_id = str(turn.get("control_successor_turn_id") or "")
+ successor_delivery_id = str(
+ turn.get("control_successor_delivery_id") or ""
)
- backend = self._context_backend(context)
- if should_flush and backend in self._draining_backends:
- self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
- elif should_flush:
- await self.flush_queue(session_id)
+ claimed_successor: str | None = None
+ if (
+ successor_turn_id
+ and successor_delivery_id
+ and turn.get("control_state")
+ in {"pending", "interrupting", "waiting_terminal", "reconciling"}
+ ):
+ successor = delivery_store.get_turn(conn, successor_turn_id)
+ successor_delivery = delivery_store.get_delivery(
+ conn, successor_delivery_id
+ )
+ if (
+ successor is not None
+ and successor["state"] == "waiting"
+ and successor_delivery is not None
+ and successor_delivery["state"] == "interrupt_waiting"
+ ):
+ if session_status != "active":
+ self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by="session_archive",
+ evidence_kind="unstarted_successor_retired",
+ )
+ retired = self._record_definitive_delivery_attempt(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ outcome="not_written",
+ next_state="retired",
+ receipt={"kind": "session_archive"},
+ )
+ if retired is None:
+ raise RuntimeError("archived P0 successor retirement lost")
+ elif resume_successors:
+ started = delivery_store.activate_waiting_successor(
+ conn,
+ turn=successor,
+ delivery=successor_delivery,
+ )
+ if started is None:
+ raise RuntimeError(
+ "P0 successor claim lost after terminal proof"
+ )
+ claimed_successor = successor_turn_id
+ else:
+ deferred = self._write_terminal_snapshot(
+ conn,
+ successor_turn_id,
+ outcome="not_written",
+ settled_by=settled_by,
+ evidence_kind="service_shutdown_deferred_successor",
+ evidence={"reason": "service_shutdown"},
+ )
+ queued = delivery_store.cas_delivery(
+ conn,
+ successor_delivery_id,
+ expected_version=int(successor_delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ values={
+ "state": "queued",
+ "priority": "p3",
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ },
+ history_event={
+ "kind": "interrupt_join",
+ "turn_id": turn_id,
+ "outcome": "service_shutdown_deferred",
+ },
+ )
+ if not deferred.get("changed") or queued is None:
+ raise RuntimeError(
+ "service shutdown lost its deferred successor"
+ )
+ if (
+ claimed_successor is None
+ and resume_successors
+ and replayed_unknown_start
+ and session_status == "active"
+ ):
+ retry_rows = [
+ delivery_store.get_delivery(conn, str(initial["id"]))
+ for initial in initial_batch
+ ]
+ if any(row is None or row["state"] != "queued" for row in retry_rows):
+ raise RuntimeError(
+ "unknown start recovery lost its replayable Delivery batch"
+ )
+ claimed_successor = delivery_store.new_turn_id()
+ self._claim_start_batch(
+ conn,
+ turn_id=claimed_successor,
+ session_id=session_id,
+ backend=str(turn["backend"]),
+ deliveries=[row for row in retry_rows if row is not None],
+ dispatch_text=(
+ _UNKNOWN_START_REPLAY_INSTRUCTION
+ + str(turn.get("dispatch_text") or "")
+ ),
+ )
+ if (
+ claimed_successor is None
+ and resume_successors
+ and outcome == "completed"
+ and session_status == "active"
+ ):
+ claimed_successor = self._claim_fifo_batch_in_transaction(
+ conn,
+ session_id=session_id,
+ backend=str(turn["backend"]),
+ )
+ latest_turn = delivery_store.get_turn(conn, turn_id)
+ if latest_turn is not None and latest_turn.get("control_state") in {
+ "pending",
+ "interrupting",
+ "waiting_terminal",
+ "reconciling",
+ }:
+ delivery_store.cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(latest_turn["version"]),
+ expected_states=("terminal",),
+ values={
+ "control_state": "settled",
+ "control_receipt_outcome": (
+ latest_turn.get("control_receipt_outcome") or "accepted"
+ ),
+ },
+ )
+ result = {
+ "changed": True,
+ "successor_turn_id": claimed_successor,
+ "delivery_id": materialized_id,
+ "preserve_queue": delivery_store.queue_is_held(conn, session_id),
+ "unknown_start_exhausted": unknown_start_exhausted,
+ }
+ terminal_run_ids = (
+ unknown_start_run_ids
+ if unknown_start_exhausted
+ else delivery_store.accepted_agent_run_ids_for_turn(
+ conn,
+ turn_id,
+ )
+ )
+ projected_status = (
+ "running"
+ if claimed_successor
+ else "failed"
+ if outcome == "failed"
+ else "idle"
+ )
+ projected = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.agent_status != projected_status)
+ .values(agent_status=projected_status)
+ )
+ status_changed = bool(projected.rowcount)
+ if result.get("changed"):
+ run_settled_by = (
+ SETTLED_BY_NO_TERMINAL_RESULT
+ if result.get("unknown_start_exhausted")
+ else settled_by
+ )
+ self._settle_agent_run_ids(terminal_run_ids, run_settled_by)
+ if materialized_id:
+ self._publish_materialized_delivery(materialized_id)
+ if result.get("changed"):
+ self._publish_terminal_inbox_update(session_id)
+ if status_changed and projected_status is not None:
+ from core.inbox_events import bus
+
+ bus.publish(
+ "session.status",
+ {"session_id": session_id, "agent_status": projected_status},
+ )
+ return result
- task = asyncio.create_task(_runner(), name="internal-dispatch-async")
- if isinstance(session_id, str) and session_id:
- self.in_flight[session_id] = Turn(
- task=task,
- context=context,
- started_at=_utc_now_iso(),
+ def reconcile_start_attempt_not_written(
+ self,
+ turn_id: str,
+ attempt_id: str,
+ *,
+ backend: str,
+ ) -> bool:
+ """Consume exact adapter proof that a persisted start never reached native."""
+
+ if not turn_id or not attempt_id:
+ return False
+ result = self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by="adapter_start_absent",
+ evidence_kind="native_start_attempt_absent",
+ evidence={"backend": backend, "attempt_id": attempt_id},
+ expected_start_attempt_id=attempt_id,
+ )
+ return bool(result.get("changed"))
+
+ def _settle_durable_prewrite_failure(
+ self,
+ turn_id: str,
+ *,
+ outcome: str,
+ ) -> dict[str, Any]:
+ """Settle definitive no-write evidence at the terminal chokepoint."""
+ return self._terminalize_durable_turn(
+ turn_id,
+ "not_written",
+ settled_by=outcome,
+ evidence_kind="definitive_prewrite_failure",
+ evidence={"reason": outcome},
+ )
+
+ def _reconcile_durable_runner_release(
+ self,
+ turn_id: str,
+ *,
+ cancelled: bool,
+ failed: bool,
+ prewrite_refused: bool,
+ definitive_prewrite_exit: bool,
+ settled_by: str | None,
+ terminal_is_error: bool,
+ ) -> dict[str, Any]:
+ """Contain post-native ownership writes so runner cleanup always finishes."""
+
+ try:
+ if cancelled:
+ interruption = settled_by or SETTLED_BY_STOPPED
+ return self._terminalize_durable_turn(
+ turn_id,
+ "canceled" if interruption == SETTLED_BY_STOPPED else "failed",
+ settled_by=interruption,
+ evidence_kind=(
+ "service_shutdown"
+ if interruption == SETTLED_BY_RESTARTED
+ else "runner_release"
+ ),
+ evidence=(
+ {"reason": "scheduled_service_shutdown"}
+ if interruption == SETTLED_BY_RESTARTED
+ else None
+ ),
+ resume_successors=interruption != SETTLED_BY_RESTARTED,
+ )
+ if failed:
+ # Dispatch may have written before raising. Preserve starting work
+ # for exact-evidence recovery instead of replaying it.
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, turn_id)
+ if turn is not None and turn["state"] == "starting":
+ delivery_store.mark_start_unknown(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ receipt={"reason": "runner_dispatch_failure"},
+ )
+ return {}
+ if prewrite_refused:
+ return self._settle_durable_prewrite_failure(
+ turn_id,
+ outcome=SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ )
+ if definitive_prewrite_exit:
+ return self._settle_durable_prewrite_failure(
+ turn_id,
+ outcome=SETTLED_BY_NO_TERMINAL_RESULT,
+ )
+ if settled_by is not None:
+ return self._terminalize_durable_turn(
+ turn_id,
+ self._durable_terminal_outcome(
+ is_error=terminal_is_error,
+ settled_by=settled_by,
+ ),
+ settled_by=settled_by,
+ evidence_kind="runner_release",
+ )
+ except Exception:
+ logger.exception(
+ "normal turn durable terminal reconciliation deferred for Turn=%s",
+ turn_id,
)
- # Make the DB row authoritative at ACCEPTANCE, not at dispatch start:
- # ``update_session``'s backend lock re-checks ``agent_status`` inside
- # its UPDATE predicate, so writing ``running`` synchronously here —
- # before the loop can start the dispatch task — closes the startup
- # window where a cross-backend PATCH could land while the row still
- # read idle (and would then be silently undone by the bind-time
- # backfill). The inbound chokepoint's own ``running`` write becomes a
- # no-op; every terminal path still settles the status (outbound
- # chokepoint / cancel / startup recovery).
- self.controller.set_agent_status(session_id, "running")
- bus.publish("turn.start", {"session_id": session_id})
+ return {}
+
+ async def terminalize_turn(self, turn_id: str, *, outcome: str = "completed") -> bool:
+ result = self._terminalize_durable_turn(
+ turn_id,
+ outcome,
+ settled_by="explicit_terminalize",
+ evidence_kind="explicit_terminalize",
+ )
+ successor_id = str(result.get("successor_turn_id") or "")
+ if successor_id:
+ await self._start_persisted_turn(successor_id)
+ elif result.get("changed") and not result.get("preserve_queue"):
+ with self._sqlite_engine().connect() as conn:
+ terminal = delivery_store.get_turn(conn, turn_id)
+ if terminal is not None:
+ await self.drain_delivery_queue(str(terminal["session_id"]))
+ return bool(result.get("changed"))
- async def flush_queue(self, session_id: str) -> bool:
- """Drain the send-while-busy queue ONE segment per call — the turn's
- completion re-flushes the next, so segments run in order, one at a time.
-
- A leading run of consecutive USER rows is merged into a single user turn (the
- user's choice — one dispatch, not N). A SCHEDULED row (it carries stored
- provenance) is NOT merged: it runs as its OWN ``SOURCE_SCHEDULED`` turn with
- its delivery / attribution provenance restored, so a scheduled run that was
- enqueued behind an active turn keeps its suppress-delivery / delivery-target /
- source when it finally runs (#84). Returns True if a turn was started, False
- on an empty queue / failure."""
- from core.inbox_events import bus
- from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs
- from storage.background import run_update_event_transaction
+ async def _run_pending_interrupt(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ ) -> None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ pending = delivery_store.pending_control_for_turn(conn, logical_turn_id)
+ if pending is None:
+ return
+ claimed = delivery_store.cas_turn(
+ conn,
+ logical_turn_id,
+ expected_version=int(pending["version"]),
+ expected_states=("active",),
+ values={"control_state": "interrupting"},
+ )
+ if claimed is not None:
+ await self._interrupt_durable_turn(session_id, logical_turn_id)
+
+ async def _run_pending_steers(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ context: "MessageContext",
+ ) -> None:
+ while True:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, logical_turn_id)
+ if (
+ turn is None
+ or turn["session_id"] != session_id
+ or turn["state"] != "active"
+ or delivery_store.pending_control_for_turn(conn, logical_turn_id)
+ is not None
+ ):
+ return
+ native_turn_id = str(turn.get("native_turn_id") or "").strip()
+ pending = delivery_store.pending_steer_for_turn(conn, logical_turn_id)
+ if not native_turn_id or pending is None:
+ return
+ attempt_id = str(pending.get("current_attempt_id") or "")
+ pending_batch = delivery_store.attempt_deliveries(conn, attempt_id)
+ if not attempt_id or not pending_batch:
+ return
+ claimed_batch = delivery_store.open_steer_attempt_batch(
+ conn,
+ deliveries=pending_batch,
+ turn_id=logical_turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=native_turn_id,
+ )
+ if not claimed_batch:
+ continue
+ steer_text = "\n".join(
+ str(row.get("dispatch_text") or "")
+ for row in claimed_batch
+ if str(row.get("dispatch_text") or "")
+ )
+ backend = str(turn["backend"])
+ delivery_id = str(claimed_batch[0]["id"])
+ receipt = await self._attempt_steer(
+ backend,
+ SteerRequest(
+ target_session_id=session_id,
+ expected_logical_turn_id=logical_turn_id,
+ expected_native_turn_id=native_turn_id,
+ text=steer_text,
+ attempt_id=attempt_id,
+ ),
+ )
+ await self._finish_steer(delivery_id, receipt, context=context)
+
+ def _publish_materialized_delivery(self, delivery_id: str) -> None:
+ """Publish one accepted immutable Message after its transaction commits."""
+
+ try:
+ with self._sqlite_engine().connect() as conn:
+ row = messages_service.get_message(conn, delivery_id)
+ inbox_row = (
+ messages_service.get_inbox_session(
+ conn,
+ str(row.get("session_id") or ""),
+ platform="avibe",
+ )
+ if row is not None and row.get("session_id")
+ else None
+ )
+ if row is None:
+ return
+ from core.inbox_events import bus
+
+ bus.publish("message.new", row)
+ bus.publish(
+ "queue.updated",
+ {"session_id": row.get("session_id")},
+ )
+ bus.publish(
+ "session.activity",
+ {
+ "session_id": row.get("session_id"),
+ "scope_id": row.get("scope_id"),
+ "event": (
+ "show_event" if row.get("type") == messages_service.ANNOTATION_TYPE else "user_message"
+ ),
+ },
+ )
+ if inbox_row is not None:
+ bus.publish("inbox.session.updated", inbox_row)
+ except Exception:
+ logger.exception("accepted Delivery publish failed for %s", delivery_id)
- if not session_id:
- return False
- if self._build_context is None:
- logger.error("queue flush: no build_context bound for session=%s", session_id)
- return False
+ @staticmethod
+ def _publish_queue_update(session_id: str) -> None:
try:
- context = await asyncio.to_thread(self._build_context, session_id)
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
except Exception:
- logger.exception("queue flush: failed to build context for session=%s", session_id)
- return False
- backend = self._context_backend(context)
- if backend in self._draining_backends:
- self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
- return False
+ logger.exception("Delivery queue update publish failed for %s", session_id)
+
+ def _publish_terminal_inbox_update(self, session_id: str) -> None:
+ """Publish the Inbox projection only after terminal ownership commits."""
- is_scheduled = False
- scheduled_text = ""
- scheduled_prov: dict = {}
- scheduled_message_id = None
- scheduled_native_ids: list[str] = []
- dropped_duplicate_segment = False
- user_row = None
- inbox_row = None
- attachment_specs: list = []
- pending_agent_run_ids: list[str] = []
- pending_scheduled_segment: list[dict] = []
- claimed_agent_run_ids: list[str] = []
- engine = self._sqlite_engine()
try:
- with run_update_event_transaction(engine) as conn:
- rows = messages_service.list_queued(
+ with self._sqlite_engine().connect() as conn:
+ inbox_row = messages_service.get_inbox_session(
conn,
session_id,
- include_private_metadata=True,
+ platform="avibe",
)
- if not rows:
- return False
- if _scheduled_provenance(rows[0]) is not None:
- from storage.background import inspect_queued_runs_for_workbench_in_connection
-
- # Scheduled segment: a leading run of same-definition harness
- # rows within the rolling merge window runs as one scheduled
- # turn. Rows remain visible individually while queued; only the
- # Agent-facing dispatch is coalesced.
- is_scheduled = True
- initial_segment = _collect_scheduled_segment(rows)
- claimed_row_ids = _scheduled_claimed_queue_row_ids(conn, initial_segment)
- if claimed_row_ids:
- messages_service.delete_queued(conn, list(claimed_row_ids))
- bus.publish("queue.updated", {"session_id": session_id})
- segment = [r for r in initial_segment if str(r.get("id") or "") not in claimed_row_ids]
- if not segment:
- dropped_duplicate_segment = True
- else:
- segment = initial_segment
- if dropped_duplicate_segment:
- pass
- else:
- if _scheduled_segment_trigger_kind(segment) == "agent_run":
- run_ids = _scheduled_segment_execution_ids(segment)
- queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(conn, run_ids)
- if stale_run_ids:
- stale_set = set(stale_run_ids)
- queued_set = set(queued_run_ids)
- stale_row_ids = _scheduled_segment_stale_row_ids(segment, queued_set)
- if stale_row_ids:
- messages_service.delete_queued(conn, stale_row_ids)
- bus.publish("queue.updated", {"session_id": session_id})
- logger.info(
- "queue flush: removed stale coalesced agent_run rows before dispatching survivors: %s",
- ",".join(sorted(stale_set)),
- )
- segment = _scheduled_segment_rows_for_execution_ids(segment, queued_set)
- if not segment:
- dropped_duplicate_segment = True
+ if inbox_row is None:
+ return
+ from core.inbox_events import bus
- if dropped_duplicate_segment:
- pass
- else:
- scheduled_text = _build_scheduled_segment_text(segment)
- scheduled_native_ids = _scheduled_segment_native_ids(segment)
- prov = _scheduled_provenance(segment[0]) or {}
- scheduled_message_id = scheduled_native_ids[0] if scheduled_native_ids else None
- scheduled_prov = prov.get("platform_specific") or {}
- if len(segment) > 1:
- scheduled_prov = dict(scheduled_prov)
- scheduled_prov["coalesced_queue"] = {
- "count": len(segment),
- "window_seconds": SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS,
- "message_ids": [r.get("id") for r in segment if r.get("id")],
- "native_message_ids": scheduled_native_ids,
- "execution_ids": queued_run_ids
- if _scheduled_segment_trigger_kind(segment) == "agent_run"
- else _scheduled_segment_execution_ids(segment),
- }
- if scheduled_prov.get("task_trigger_kind") == "agent_run" and queued_run_ids:
- pending_agent_run_ids = list(queued_run_ids)
- scheduled_prov = _filter_coalesced_agent_run_provenance(
- scheduled_prov,
- pending_agent_run_ids,
- )
- scheduled_message_id = f"agent_run:{pending_agent_run_ids[0]}"
- coalesced = scheduled_prov.get("coalesced_queue")
- if isinstance(coalesced, dict):
- coalesced_prompt = str(coalesced.get("prompt") or "")
- if coalesced_prompt:
- scheduled_text = coalesced_prompt
- pending_scheduled_segment = segment
+ bus.publish("inbox.session.updated", inbox_row)
+ except Exception:
+ logger.debug(
+ "terminal Inbox projection failed for Session=%s",
+ session_id,
+ exc_info=True,
+ )
+
+ def on_native_start(
+ self,
+ context: "MessageContext",
+ *,
+ backend: str,
+ runtime_key: str,
+ runtime_turn_id: str,
+ ) -> asyncio.Task[None] | None:
+ logical_turn_id = str(
+ (getattr(context, "platform_specific", None) or {}).get("turn_token") or ""
+ ).strip()
+ session_id = self.controller._session_id_from_context(context) if self.controller else None
+ if not logical_turn_id or not session_id:
+ return
+ if not self._durable_schema_available():
+ return
+ try:
+ identity = self._active_identity(backend, session_id, logical_turn_id)
+ native_turn_id = identity[1] if identity and identity[0] == logical_turn_id else None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ turn = delivery_store.get_turn(conn, logical_turn_id)
+ if turn is None or turn["session_id"] != session_id:
+ return
+ bound = delivery_store.bind_native_start(
+ conn,
+ logical_turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=runtime_key,
+ runtime_turn_id=runtime_turn_id,
+ native_turn_id=native_turn_id,
+ )
+ materialized: list[dict[str, Any]] = []
+ if bound is not None:
+ materialized = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=logical_turn_id,
+ evidence={
+ "kind": "native_start",
+ "runtime_key": runtime_key,
+ "runtime_turn_id": runtime_turn_id,
+ "native_turn_id": native_turn_id,
+ },
+ )
+ if not materialized:
+ raise RuntimeError("native start could not materialize initial Delivery batch")
+ has_pending_interrupt = bool(
+ bound is not None
+ and delivery_store.pending_control_for_turn(conn, logical_turn_id)
+ )
+ has_pending_steer = bool(
+ bound is not None
+ and native_turn_id
+ and not has_pending_interrupt
+ and delivery_store.pending_steer_for_turn(conn, logical_turn_id)
+ )
+ except Exception:
+ logger.exception(
+ "durable native start binding deferred to reconciliation for Turn=%s",
+ logical_turn_id,
+ )
+ return None
+ if materialized:
+ self._publish_materialized_delivery(
+ str(materialized[0].get("message_id") or materialized[0]["id"])
+ )
+ if has_pending_interrupt:
+ return asyncio.create_task(
+ self._run_pending_interrupt(session_id, logical_turn_id),
+ name=f"durable-interrupt:{session_id}",
+ )
+ if has_pending_steer:
+ return asyncio.create_task(
+ self._run_pending_steers(session_id, logical_turn_id, context),
+ name=f"durable-steer:{session_id}",
+ )
+ return None
+
+ async def _resume_after_native_terminal(
+ self,
+ session_id: str,
+ logical_turn_id: str,
+ ) -> None:
+ try:
+ current = self.in_flight.get(session_id)
+ if current is not None and current.logical_turn_id == logical_turn_id:
+ await asyncio.gather(current.task, return_exceptions=True)
+ await self._resume_post_terminal(session_id)
+ except Exception:
+ logger.exception(
+ "failed to resume durable Session after native terminal: %s",
+ session_id,
+ )
+
+ def on_native_terminal(
+ self,
+ context: "MessageContext",
+ *,
+ outcome: str,
+ ) -> asyncio.Task[None] | None:
+ payload = getattr(context, "platform_specific", None) or {}
+ logical_turn_id = str(payload.get("turn_token") or "").strip()
+ runtime_turn_id = str(payload.get("agent_runtime_turn_token") or "").strip()
+ if not logical_turn_id:
+ return None
+ if not self._durable_schema_available():
+ return None
+ if outcome == "terminal":
+ get_sink = getattr(self.controller, "get_turn_sink", None)
+ get_key = getattr(self.controller, "_get_session_key", None)
+ if callable(get_sink) and callable(get_key):
+ try:
+ sink = get_sink(get_key(context))
+ except Exception:
+ logger.debug("failed to inspect native terminal Turn sink", exc_info=True)
else:
- # User segment: the leading run of consecutive non-scheduled rows
- # for one resolved user. Missing identity rows remain isolated.
- segment = []
- segment_owner = None
- for r in rows:
- if _scheduled_provenance(r) is not None:
- break
- owner = (r.get("metadata") or {}).get(MEMORY_USER_ID_METADATA)
- owner = owner.strip() if isinstance(owner, str) and owner.strip() else None
- if segment and (owner is None or segment_owner is None or owner != segment_owner):
- break
- segment.append(r)
- segment_owner = owner
- if owner is None:
- break
- if segment and not pending_agent_run_ids:
- messages_service.delete_queued(conn, [r["id"] for r in segment])
- if not is_scheduled:
- texts = [r.get("text") for r in segment if (r.get("text") or "").strip()]
- # Carry attachments queued in this user segment so a file
- # attached while the agent was busy still reaches the merged
- # turn. An attachment-ONLY segment has empty texts but must
- # still run (the agent reads the files), so guard on both.
- queued_attachments = [
- att
- for r in segment
- for att in ((r.get("content") or {}).get("attachments") or [])
- ]
- if not texts and not queued_attachments:
- return False
- memory_user = segment_owner
- web_push_owners = list(
- dict.fromkeys(
- owner.strip()
- for row in segment
- if isinstance(
- (owner := (row.get("metadata") or {}).get(WEB_PUSH_USER_KEY_METADATA)),
- str,
+ if (
+ isinstance(sink, dict)
+ and sink.get("done_event") is not None
+ and str(sink.get("turn_token") or "") == logical_turn_id
+ ):
+ # The result hook captured this exact sink before output
+ # delivery. Its waiter owns the authoritative completed /
+ # failed / canceled outcome after sink settlement.
+ return None
+ with self._sqlite_engine().connect() as conn:
+ turn = delivery_store.get_turn(conn, logical_turn_id)
+ if turn is None or turn["state"] not in delivery_store.TURN_OWNER_STATES:
+ return None
+ expected_runtime_id = str(turn.get("runtime_turn_id") or "").strip()
+ if expected_runtime_id and runtime_turn_id != expected_runtime_id:
+ return None
+ session_id = str(turn["session_id"])
+ semantic_outcome = outcome if outcome in {
+ "completed",
+ "failed",
+ "canceled",
+ "not_written",
+ } else "completed"
+ result = self._terminalize_durable_turn(
+ logical_turn_id,
+ semantic_outcome,
+ settled_by="native_terminal",
+ evidence_kind="native_terminal",
+ evidence={"reported_outcome": outcome},
+ )
+ current = self.in_flight.get(session_id)
+ should_resume = bool(result.get("successor_turn_id")) or (
+ current is None and not bool(result.get("preserve_queue"))
+ )
+ if result.get("changed") and should_resume:
+ return asyncio.create_task(
+ self._resume_after_native_terminal(session_id, logical_turn_id),
+ name=f"durable-terminal-resume:{session_id}",
+ )
+ return None
+
+ async def recover_durable_delivery_state(
+ self,
+ session_id: str | None = None,
+ *,
+ service_restart: bool = False,
+ ) -> list[str]:
+ """Restore exact owners after backend restore, then project status.
+
+ ``service_restart`` is the proof that process-bound Claude/Codex runtimes
+ cannot still be executing in another live controller recovery pass.
+ """
+
+ with self._sqlite_engine().connect() as conn:
+ turns = delivery_store.recovery_turns(conn, session_id)
+ pending_interrupts: list[tuple[str, str]] = []
+ pending_steers: list[tuple[str, str]] = []
+ unresolved_starts: list[tuple[str, str, str]] = []
+ lost_active_turns: list[tuple[str, str, str, str]] = []
+ recovered: list[str] = []
+ materialized_ids: set[str] = set()
+ for turn in turns:
+ turn_id = str(turn["id"])
+ target_session = str(turn["session_id"])
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ terminal_stop_receipt = bool(
+ latest is not None
+ and latest["state"] in delivery_store.TURN_OWNER_STATES
+ and latest.get("control_receipt_outcome") == "not_active"
+ )
+ if terminal_stop_receipt:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "canceled",
+ settled_by="adapter_not_active",
+ evidence_kind="stop_not_active",
+ evidence={"reason": "not_active", "source": "recovery"},
+ )
+ recovered.append(target_session)
+ projected = self.in_flight.get(target_session)
+ if (
+ projected is not None
+ and projected.logical_turn_id == turn_id
+ and not projected.task.done()
+ ):
+ projected.cancel_settled_by = "adapter_not_active"
+ projected.task.cancel()
+ await asyncio.gather(projected.task, return_exceptions=True)
+ if self.in_flight.get(target_session) is projected:
+ self.in_flight.pop(target_session, None)
+ successor_turn_id = str(terminal.get("successor_turn_id") or "")
+ if successor_turn_id:
+ await self._start_persisted_turn(successor_turn_id)
+ continue
+ identity = self._active_identity(
+ str(turn["backend"]),
+ target_session,
+ turn_id,
+ )
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ if latest is None or latest["state"] not in delivery_store.TURN_OWNER_STATES:
+ continue
+ if turn["state"] == "waiting" and latest["state"] == "starting":
+ # This successor was activated by an earlier reconciliation in
+ # this same pass. Its native start is live now, not crash residue.
+ continue
+ if identity and identity[0] == turn_id:
+ bound = delivery_store.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(latest["version"]),
+ runtime_key=latest.get("runtime_key"),
+ runtime_turn_id=latest.get("runtime_turn_id"),
+ native_turn_id=identity[1],
+ )
+ if (
+ bound is None
+ and latest["state"] == "active"
+ and latest.get("start_receipt_outcome") == "accepted"
+ and str(latest.get("backend") or "") == "opencode"
+ and _same_opencode_native_session(
+ latest.get("native_turn_id"),
+ identity[1],
+ )
+ ):
+ bound = delivery_store.rebind_restored_native_generation(
+ conn,
+ turn_id,
+ expected_version=int(latest["version"]),
+ expected_native_turn_id=str(latest["native_turn_id"]),
+ restored_native_turn_id=identity[1],
+ )
+ if bound is not None:
+ initial_batch = delivery_store.initial_deliveries_for_turn(
+ conn, turn_id
+ )
+ if initial_batch and all(
+ delivery["state"] == "claimed"
+ for delivery in initial_batch
+ ):
+ materialized = delivery_store.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "restored_native_identity", "native_turn_id": identity[1]},
)
- and owner.strip()
+ if materialized:
+ materialized_ids.add(
+ str(
+ materialized[0].get("message_id")
+ or materialized[0]["id"]
+ )
+ )
+ recovered.append(target_session)
+ if delivery_store.pending_control_for_turn(conn, turn_id):
+ pending_interrupts.append((target_session, turn_id))
+ elif identity[1] and delivery_store.pending_steer_for_turn(
+ conn,
+ turn_id,
+ ):
+ pending_steers.append((target_session, turn_id))
+ continue
+ delivery = delivery_store.delivery_for_turn(conn, turn_id)
+ if delivery is None:
+ raise RuntimeError(f"durable Turn {turn_id} lost its initial Delivery")
+ if latest["state"] == "starting" and latest.get(
+ "start_receipt_outcome"
+ ) is None:
+ latest = delivery_store.mark_start_unknown(
+ conn,
+ turn_id,
+ expected_version=int(latest["version"]),
+ receipt={"reason": "restart_without_native_evidence"},
+ )
+ if (
+ latest is not None
+ and latest["state"] == "starting"
+ and latest.get("start_receipt_outcome") == "unknown"
+ and str(latest.get("backend") or "")
+ in _NON_RESTORABLE_RUNTIME_BACKENDS
+ ):
+ unresolved_starts.append(
+ (
+ target_session,
+ turn_id,
+ str(latest.get("start_attempt_id") or ""),
)
)
- web_push_owner = web_push_owners[0] if len(web_push_owners) == 1 else None
- memory_cli_admitted = all(
- (row.get("metadata") or {}).get("_memory_cli_admitted") is True for row in segment
+ elif (
+ latest is not None
+ and latest["state"] == "active"
+ and latest.get("start_receipt_outcome") == "accepted"
+ and service_restart
+ and str(latest.get("backend") or "")
+ in _NON_RESTORABLE_RUNTIME_BACKENDS
+ ):
+ lost_active_turns.append(
+ (
+ target_session,
+ turn_id,
+ str(latest.get("start_attempt_id") or ""),
+ str(latest.get("backend") or ""),
+ )
)
- memory_ordinary_text = all(
- (row.get("metadata") or {}).get(MEMORY_ORDINARY_TEXT_METADATA) is True
- for row in segment
+
+ for target_session, turn_id, attempt_id, backend in lost_active_turns:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "failed",
+ settled_by=SETTLED_BY_NO_TERMINAL_RESULT,
+ evidence_kind="restart_runtime_missing",
+ evidence={
+ "backend": backend,
+ "reason": "accepted_turn_runtime_not_restorable",
+ },
+ expected_start_attempt_id=attempt_id,
+ )
+ if not terminal.get("changed"):
+ continue
+ recovered.append(target_session)
+ successor_turn_id = str(terminal.get("successor_turn_id") or "")
+ if successor_turn_id:
+ await self._start_persisted_turn(successor_turn_id)
+
+ for target_session, turn_id, attempt_id in unresolved_starts:
+ terminal = self._terminalize_durable_turn(
+ turn_id,
+ "failed",
+ settled_by="restart_unknown_start",
+ evidence_kind="restart_unknown_start",
+ evidence={
+ "reason": "native_start_acceptance_unrecoverable",
+ "automatic_replay_limit": _MAX_AUTOMATIC_UNKNOWN_START_REPLAYS,
+ },
+ expected_start_attempt_id=attempt_id,
+ replay_unknown_start=True,
+ )
+ if not terminal.get("changed"):
+ continue
+ recovered.append(target_session)
+ retry_turn_id = str(terminal.get("successor_turn_id") or "")
+ if retry_turn_id:
+ await self._start_persisted_turn(retry_turn_id)
+
+ with self._sqlite_engine().connect() as conn:
+ unresolved = delivery_store.unresolved_deliveries(conn, session_id)
+ steer_attempts: list[tuple[dict[str, Any], str]] = []
+ seen_attempt_ids: set[str] = set()
+ for attempt in unresolved:
+ if attempt["state"] not in {"steering", "reconciling_steer"}:
+ continue
+ attempt_id = str(attempt.get("current_attempt_id") or "")
+ target_turn_id = str(attempt.get("current_target_turn_id") or "")
+ expected_native_id = str(
+ attempt.get("current_expected_native_turn_id") or ""
+ )
+ if (
+ not attempt_id
+ or attempt_id in seen_attempt_ids
+ or not target_turn_id
+ or not expected_native_id
+ ):
+ continue
+ target_turn = delivery_store.get_turn(conn, target_turn_id)
+ if target_turn is None:
+ continue
+ seen_attempt_ids.add(attempt_id)
+ steer_attempts.append((attempt, str(target_turn["backend"])))
+
+ for attempt, backend in steer_attempts:
+ attempt_id = str(attempt["current_attempt_id"])
+ target_turn_id = str(attempt["current_target_turn_id"])
+ receipt = await self._reconcile_steer_attempt(
+ backend,
+ SteerReconcileRequest(
+ target_session_id=str(attempt["session_id"]),
+ expected_logical_turn_id=target_turn_id,
+ expected_native_turn_id=str(
+ attempt["current_expected_native_turn_id"]
+ ),
+ attempt_id=attempt_id,
+ ),
+ )
+ outcome = getattr(receipt, "outcome", SteerOutcome.UNKNOWN)
+ if (
+ str(getattr(outcome, "value", outcome)) == SteerOutcome.UNKNOWN.value
+ and attempt["state"] == "reconciling_steer"
+ ):
+ continue
+ result = await self._finish_steer(
+ str(attempt["id"]),
+ receipt,
+ context=None,
+ )
+ if result.state != "reconciling_steer":
+ recovered.append(str(attempt["session_id"]))
+
+ for target_session, turn_id in pending_interrupts:
+ await self._run_pending_interrupt(target_session, turn_id)
+ for target_session, turn_id in pending_steers:
+ await self._run_pending_steers(
+ target_session,
+ turn_id,
+ self._delivery_context(target_session),
+ )
+ # Reservations are definitive pre-write admissions left between the UI /
+ # Harness transaction and controller claim. Re-enter the same manager path
+ # after adapter restoration; its writer CAS makes concurrent recovery and
+ # a late original dispatch idempotent.
+ with self._sqlite_engine().connect() as conn:
+ reservations = delivery_store.recoverable_reservations(conn, session_id)
+ for reservation in reservations:
+ target_session = str(reservation["session_id"])
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_delivery(conn, str(reservation["id"]))
+ if latest is None or latest["state"] != "reserved":
+ continue
+ retired = False
+ if not self._has_resolvable_delivery_input(conn, latest):
+ retired = delivery_store.retire_reserved(
+ conn,
+ target_session,
+ str(latest["id"]),
+ reason="empty_or_invalid_reserved_submission",
)
- user_metadata = {
- MEMORY_ORDINARY_TEXT_METADATA: memory_ordinary_text,
- "_memory_cli_admitted": memory_cli_admitted,
- }
- if memory_user:
- user_metadata[MEMORY_USER_ID_METADATA] = memory_user
- if web_push_owner:
- user_metadata[WEB_PUSH_USER_KEY_METADATA] = web_push_owner
- elif web_push_owners:
- user_metadata[WEB_PUSH_USER_KEYS_METADATA] = web_push_owners
- authorization_contexts: dict[str, dict[str, Any]] = {}
- for row in segment:
- raw_contexts = (row.get("metadata") or {}).get(
- WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA
- )
- if not isinstance(raw_contexts, list):
- continue
- for raw_context in raw_contexts:
- if not isinstance(raw_context, dict):
- continue
- context_user_key = raw_context.get("user_key")
- if context_user_key in web_push_owners:
- authorization_contexts[str(context_user_key)] = raw_context
- if authorization_contexts:
- user_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = list(
- authorization_contexts.values()
+ if retired:
+ retired_delivery = delivery_store.get_delivery(
+ conn,
+ str(latest["id"]),
)
- attachment_specs = resolve_attachment_specs(
- conn, session_id=session_id, attachments=queued_attachments
+ self._cancel_runs_for_retired_delivery(conn, retired_delivery)
+ else:
+ reservation = latest
+ if retired:
+ logger.warning(
+ "retired reserved Delivery=%s because it has no resolvable input",
+ reservation["id"],
+ )
+ recovered.append(target_session)
+ continue
+ try:
+ context = self._delivery_context(target_session)
+ self._hydrate_delivery_context(context, reservation)
+ result = await self.deliver(
+ self._request_from_delivery(
+ reservation,
+ has_attachments=bool(context.files),
+ ),
+ context=context,
+ )
+ except Exception:
+ logger.exception(
+ "failed to recover reserved Delivery=%s",
+ reservation["id"],
+ )
+ else:
+ if result.state != "reserved":
+ recovered.append(target_session)
+ with self._sqlite_engine().connect() as conn:
+ terminal_run_owners = delivery_store.terminal_turn_agent_run_owners(
+ conn,
+ session_id,
+ )
+ all_run_ids = {
+ run_id
+ for _terminal_turn, run_ids in terminal_run_owners
+ for run_id in run_ids
+ }
+ statuses = {
+ str(row["id"]): normalize_run_status(row["status"])
+ for row in conn.execute(
+ select(agent_runs.c.id, agent_runs.c.status).where(
+ agent_runs.c.id.in_(all_run_ids)
)
- user_row = messages_service.append(
- conn,
- scope_id=segment[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type="user",
- text="\n".join(texts),
- content={"attachments": queued_attachments} if queued_attachments else None,
- metadata=user_metadata,
- author_id=web_push_owner,
- )
- inbox_row = messages_service.get_inbox_session(conn, session_id)
- except Exception:
- logger.exception("queue flush: failed to claim/merge for session=%s", session_id)
- return False
+ ).mappings()
+ }
+ unsettled_owners: list[tuple[dict[str, Any], list[str]]] = []
+ for terminal_turn, run_ids in terminal_run_owners:
+ unsettled = [
+ run_id
+ for run_id in run_ids
+ if statuses.get(run_id) in {"queued", "running"}
+ ]
+ if unsettled:
+ unsettled_owners.append((terminal_turn, unsettled))
+ for terminal_turn, run_ids in unsettled_owners:
+ self._settle_agent_run_ids_from_terminal_turn(run_ids, terminal_turn)
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ queued_without_owner = set(
+ delivery_store.queued_session_ids_without_live_turns(conn, session_id)
+ )
+ for target_session in sorted(queued_without_owner):
+ await self._resume_post_terminal(target_session)
+ for delivery_id in sorted(materialized_ids):
+ self._publish_materialized_delivery(delivery_id)
+ self.project_durable_agent_status()
+ return sorted(set(recovered))
+
+ def project_durable_agent_status(self) -> None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ live = delivery_store.session_ids_with_live_turns(conn)
+ owned = delivery_store.session_ids_with_turn_history(conn)
+ idle = owned - live
+ if idle:
+ cleared = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id.in_(idle))
+ .where(agent_sessions.c.status == "active")
+ .where(agent_sessions.c.agent_status == "running")
+ .values(agent_status="idle")
+ )
+ _ = cleared.rowcount
+ if live:
+ running = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id.in_(live))
+ .where(agent_sessions.c.status == "active")
+ .where(agent_sessions.c.agent_status != "running")
+ .values(agent_status="running")
+ )
+ _ = running.rowcount
- if dropped_duplicate_segment:
- return await self.flush_queue(session_id)
+ async def _resume_durable_session(self, session_id: str) -> None:
+ with self._sqlite_engine().connect() as conn:
+ owner = delivery_store.active_turn(conn, session_id)
+ if owner is None:
+ await self.drain_delivery_queue(session_id)
+ elif owner["state"] == "starting":
+ await self._start_persisted_turn(str(owner["id"]))
- # Surface the flushed (merged) user message + bump the inbox card so other
- # workbench views re-rank / flip 'replied' without waiting for the result
- # (Codex P2). A scheduled segment has NO user row — its prompt is mirrored by
- # its own dispatch, exactly as a non-enqueued scheduled run. Either way the
- # queue changed.
- if user_row is not None:
- bus.publish("message.new", user_row)
- if inbox_row is not None:
- bus.publish("inbox.session.updated", inbox_row)
- bus.publish("queue.updated", {"session_id": session_id})
+ async def _resume_linked_control_successor(
+ self,
+ session_id: str,
+ terminal_turn_id: str,
+ ) -> str | None:
+ """Start only the exact replacement linked from a settled control Turn."""
+ with self._sqlite_engine().connect() as conn:
+ terminal = delivery_store.get_turn(conn, terminal_turn_id)
+ successor_id = str(
+ (terminal or {}).get("control_successor_turn_id") or ""
+ )
+ owner = delivery_store.active_turn(conn, session_id)
+ if (
+ terminal is None
+ or terminal["state"] != "terminal"
+ or str(terminal["session_id"]) != session_id
+ or terminal.get("control_mode") != "replace"
+ or not successor_id
+ or owner is None
+ or str(owner["id"]) != successor_id
+ or owner["state"] != "starting"
+ ):
+ return None
+ await self._start_persisted_turn(successor_id)
+ return successor_id
- if not is_scheduled:
- # Carry the queued segment's uploaded files into the merged turn.
- context.files = file_attachments_from_specs(attachment_specs)
- context.user_id = memory_user or "workbench"
- context.message_id = str(segment[-1]["id"])
- context.is_ordinary_text = memory_ordinary_text
- if context.platform_specific is None:
- context.platform_specific = {}
- if memory_cli_admitted:
- context.platform_specific["memory_cli_admitted"] = True
- else:
- context.platform_specific.pop("memory_cli_admitted", None)
- await self._run(session_id, context, user_row.get("text") or "")
+ async def _resume_post_terminal(self, session_id: str) -> None:
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ owner = delivery_store.active_turn(conn, session_id)
+ if owner is not None:
+ await self._resume_durable_session(session_id)
else:
- # Restore the scheduled run's delivery / source provenance onto the rebuilt
- # (fresh-routing) context, then run as SOURCE_SCHEDULED — not a plain user
- # turn — so suppress_delivery / the delivery target / the task attribution
- # carry through the queue (#84).
- #
- # The coalesced native-id set is split deliberately: the first id is
- # assigned to this visible harness prompt, while later ids have already
- # been preserved as hidden dedupe marker rows during the queue claim.
- if context.platform_specific is None:
- context.platform_specific = {}
- context.platform_specific.update(scheduled_prov)
- if scheduled_message_id is not None:
- # Restore the stable scheduled:/watch:/webhook: native id so the
- # flushed prompt persists + dedupes under it (Codex P2), not None.
- context.message_id = scheduled_message_id
- if pending_agent_run_ids:
- retry_agent_run_flush = False
- try:
- with run_update_event_transaction(engine) as conn:
- claimed_run_ids = _claim_agent_run_segment_and_retire_queue(
- conn,
- run_ids=pending_agent_run_ids,
- segment=pending_scheduled_segment,
+ await self.drain_delivery_queue(session_id)
+
+ def _turn_has_terminal_run(self, turn_id: str) -> bool:
+ with self._sqlite_engine().connect() as conn:
+ deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for delivery in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(
+ conn, delivery
+ )
+ )
+ )
+ if not run_ids:
+ return False
+ statuses = {
+ str(row["id"]): normalize_run_status(row["status"])
+ for row in conn.execute(
+ select(agent_runs.c.id, agent_runs.c.status).where(
+ agent_runs.c.id.in_(run_ids)
+ )
+ ).mappings()
+ }
+ return any(
+ statuses.get(run_id) not in {"queued", "running"}
+ for run_id in run_ids
+ )
+
+ async def submit(
+ self,
+ session_id: Optional[str],
+ context: "MessageContext",
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ delivery_intent: Literal["queue", "send_now", "steer"] = "queue",
+ ) -> TurnSubmissionResult:
+ """Admit one caller through the durable Delivery owner."""
+ from core.message_priority import priority_for_delivery_intent
+
+ priority = priority_for_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",
+ delivery_status="ran" if delivery_intent == "send_now" else None,
+ )
+
+ spec = dict(getattr(context, "platform_specific", None) or {})
+ with self._sqlite_engine().connect() as conn:
+ busy = delivery_store.active_turn(conn, session_id) is not None
+ source_value = "harness" if source == SOURCE_SCHEDULED else "user"
+ delivery_id = str(spec.get("delivery_id") or "").strip() or None
+ native_message_id = str(spec.get("native_message_id") or "").strip() or None
+ if native_message_id is None and source == SOURCE_SCHEDULED:
+ native_message_id = str(getattr(context, "message_id", None) or "").strip() or None
+ if delivery_id is None:
+ candidate = str(getattr(context, "message_id", None) or "").strip()
+ if candidate.startswith("msg_"):
+ delivery_id = candidate
+ request = DeliveryRequest(
+ session_id=session_id,
+ priority=priority,
+ content=text,
+ has_content=delivery_store.has_substantive_input(
+ text,
+ has_attachments=bool(getattr(context, "files", None)),
+ ),
+ delivery_id=delivery_id,
+ scope_id=str(spec.get("scope_id") or "").strip() or None,
+ platform=str(getattr(context, "platform", None) or "avibe"),
+ source=source_value,
+ author="harness" if source == SOURCE_SCHEDULED else "user",
+ message_type="harness" if source == SOURCE_SCHEDULED else "user",
+ display_text=str(spec.get("display_text") or text),
+ content_json=spec.get("message_content") if isinstance(spec.get("message_content"), dict) else None,
+ metadata=spec.get("message_metadata") if isinstance(spec.get("message_metadata"), dict) else {},
+ author_id=str(spec.get("author_id") or "").strip() or None,
+ author_name=str(spec.get("author_name") or "").strip() or None,
+ native_message_id=native_message_id,
+ )
+ result = await self.deliver(request, context=context)
+ enqueued_states = {
+ "queued",
+ "pending_steer",
+ "steering",
+ "reconciling_steer",
+ "interrupt_waiting",
+ }
+ enqueued = result.state in enqueued_states
+ if enqueued:
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ return TurnSubmissionResult(
+ route="enqueued" if enqueued else "ran",
+ queue_persisted=True,
+ target_was_busy=busy,
+ delivery_status=result.state if delivery_intent == "send_now" else None,
+ )
+
+ async def _run(
+ self,
+ session_id: Optional[str],
+ context: "MessageContext",
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ logical_turn_id: str | None = None,
+ delivery_id: str | None = None,
+ durable_preallocated: bool = False,
+ ) -> None:
+ """Start a fire-and-forget turn and HOLD it open until it settles.
+
+ A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime so
+ ``in_flight`` stays populated (Stop works) and the session-level
+ ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
+ working indicator. On NATURAL completion the queue is flushed: messages the
+ user sent while this turn ran are merged + run as the next turn when the
+ durable Session hold is open. Stop and replacement policy lives in that
+ hold plus the durable Turn control slot, not on this process task.
+
+ ``source`` selects the human vs. scheduler turn path in ``dispatch_turn``;
+ a scheduled / watch run passes ``SOURCE_SCHEDULED`` so it goes through the
+ SAME gate (in_flight + turn.start/turn.end + queue draining) as a Chat turn.
+ There is NO turn-duration timeout: a long agent runs for hours and is freed
+ only by a real terminal signal (Phase 1a — STUCK/sentinel removed).
+ """
+ from core.inbox_events import bus
+
+ durable_turn_registered = durable_preallocated
+ if durable_preallocated and not logical_turn_id:
+ raise ValueError("preallocated durable Turn requires its logical id")
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context_turn_id = str(context.platform_specific.get("turn_token") or "").strip()
+ if isinstance(session_id, str) and session_id:
+ if self._durable_schema_available() and not durable_preallocated:
+ raise RuntimeError("Session native dispatch requires a preallocated Delivery Turn")
+ logical_turn_id = logical_turn_id or context_turn_id or uuid.uuid4().hex
+ else:
+ logical_turn_id = logical_turn_id or context_turn_id or uuid.uuid4().hex
+ context.platform_specific["turn_token"] = logical_turn_id
+
+ async def _runner() -> None:
+ cancelled = False
+ failed = False
+ prewrite_refused = False
+ definitive_prewrite_exit = False
+ # How this turn's waiter was released, in the ``core.run_settlement``
+ # vocabulary. Anything other than a real terminal result means no result
+ # is coming, so an ``agent_runs`` row this turn owns has to be settled
+ # here — the gate lane returns to ``_execute_agent_run`` long before the
+ # turn ends, so nobody downstream can do it (Codex P1).
+ settled_by: Optional[str] = None
+ try:
+ if (
+ durable_turn_registered
+ and logical_turn_id
+ and self._turn_has_terminal_run(logical_turn_id)
+ ):
+ prewrite_refused = True
+ self._terminalize_durable_turn(
+ logical_turn_id,
+ "not_written",
+ settled_by="terminal_run",
+ evidence_kind="terminal_run_before_native_dispatch",
+ )
+ return
+ outcome = await dispatch_turn_with_outcome(
+ self.controller,
+ context,
+ text,
+ source=source,
+ # ALWAYS pass the no-op sink — even for scheduled runs. It isn't
+ # about the browser (chunks are discarded; avibe renders from
+ # message.new); it makes ``dispatch_turn`` HOLD the turn open
+ # until the backend's terminal result, keeping ``in_flight``
+ # populated for the turn's whole lifetime. With ``on_chunk=None``
+ # an async backend (Codex/Claude) returns at prompt-submit, so the
+ # slot would free + a Chat send could preempt the still-running
+ # scheduled turn (Codex P2).
+ on_chunk=self._noop_chunk,
+ )
+ settled_by = outcome.settled_by
+ definitive_prewrite_exit = outcome.backend_dispatch_attempted is False
+ except asyncio.CancelledError:
+ cancelled = True
+ # Do NOT decide the reason here: the canceller knows it, and it is
+ # recorded on the Turn (``cancel_settled_by``) which is only popped
+ # in the ``finally`` below. A plain Stop leaves it unset and reads
+ # as ``SETTLED_BY_STOPPED``; a backend runtime refresh sets its own
+ # value so it is not misreported as a user stop (Codex P1).
+ raise
+ except Exception:
+ # Preserve the exact boundary phase even when the handler's own
+ # terminal-error persistence raises. A proven pre-write failure is
+ # safe to requeue; anything at or beyond adapter entry is logged and
+ # retained as an unknown start instead of guessing that it was absent.
+ definitive_prewrite_exit = backend_dispatch_attempted(context) is False
+ failed = not definitive_prewrite_exit
+ settled_by = SETTLED_BY_NO_TERMINAL_RESULT
+ logger.exception("internal async dispatch failed for session=%s", session_id)
+ finally:
+ if isinstance(session_id, str):
+ durable_terminal_result: dict[str, Any] = {}
+ prewrite_refused = prewrite_refused or (
+ settled_by == SETTLED_BY_REFUSED_CONCURRENT_TURN
+ )
+ # The turn is over — the agent emitted its terminal result, the
+ # user stopped it, or dispatch raised before any backend turn.
+ # NO turn-duration timeout: the slot is freed only by a real
+ # terminal signal here (Phase 1a — STUCK/sentinel removed).
+ current = self.in_flight.get(session_id)
+ turn = (
+ current
+ if current is not None
+ and current.task is asyncio.current_task()
+ and current.logical_turn_id == logical_turn_id
+ else None
+ )
+ terminal_is_error = bool(
+ turn is not None and turn.terminal_is_error
+ )
+ if turn is not None:
+ self.in_flight.pop(session_id, None)
+ if turn is not None:
+ bus.publish(
+ "turn.end",
+ _turn_event_payload(session_id, logical_turn_id),
)
- if set(claimed_run_ids) != set(pending_agent_run_ids):
- queued_run_ids, stale_run_ids = inspect_queued_runs_for_workbench_in_connection(
- conn,
- pending_agent_run_ids,
- )
- stale_set = set(stale_run_ids)
- stale_row_ids = _scheduled_segment_stale_row_ids(
- pending_scheduled_segment,
- set(queued_run_ids),
+ if cancelled:
+ # Attribute the cancellation to whoever caused it. The Turn
+ # carries the cause when the canceller had a more specific one
+ # than "the user stopped this"; a plain Stop / send-now leaves
+ # it unset, and ``stopped`` (→ ``canceled``) stays the default
+ # reading of a cancelled turn.
+ settled_by = (
+ getattr(turn, "cancel_settled_by", None) if turn is not None else None
+ ) or SETTLED_BY_STOPPED
+ self._settle_model_hub_turn(context, settled_by)
+ if logical_turn_id and durable_turn_registered:
+ durable_terminal_result = self._reconcile_durable_runner_release(
+ logical_turn_id,
+ cancelled=cancelled,
+ failed=failed,
+ prewrite_refused=prewrite_refused,
+ definitive_prewrite_exit=definitive_prewrite_exit,
+ settled_by=settled_by,
+ terminal_is_error=terminal_is_error,
+ )
+ # Only definitive pre-write failure may synthesize an empty
+ # terminal result. Once native work may have produced output, a
+ # persistence failure leaves the durable Turn unresolved for
+ # exact reconciliation; an empty fallback would overwrite that
+ # evidence with a fabricated terminal response.
+ if definitive_prewrite_exit:
+ try:
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_turn_output(),
)
- if stale_row_ids:
- messages_service.delete_queued(conn, stale_row_ids)
- bus.publish("queue.updated", {"session_id": session_id})
- logger.info(
- "queue flush: skipped coalesced agent_run segment because some runs are no longer queued: %s",
- ",".join(sorted(set(pending_agent_run_ids) - set(claimed_run_ids))),
+ except Exception:
+ logger.exception(
+ "failed to persist terminal dispatch error for session=%s",
+ session_id,
)
- if queued_run_ids:
- retry_agent_run_flush = True
- else:
- return False
- if retry_agent_run_flush:
- return await self.flush_queue(session_id)
- claimed_agent_run_ids = claimed_run_ids
- bus.publish("queue.updated", {"session_id": session_id})
- except Exception:
- logger.warning(
- "queue flush: failed to claim coalesced agent_run segment for session=%s",
- session_id,
- exc_info=True,
+ # Settle before flushing: the next turn must not start while a run
+ # this one owned is still ``running``. Placed after the failure
+ # emit above so the honest outbound terminal writes first and this
+ # guarded write degrades to a no-op.
+ self._settle_turn_owned_agent_runs(context, settled_by)
+ # Durable Session policy is the only backlog authority. Legacy
+ # non-DB turns conservatively avoid draining after Stop/failure.
+ preserve_durable_queue = bool(
+ durable_turn_registered
+ and durable_terminal_result.get("preserve_queue")
)
- return False
- try:
- await self._run(session_id, context, scheduled_text, source=SOURCE_SCHEDULED)
- except Exception:
- if claimed_agent_run_ids:
- try:
- from storage.background import reset_workbench_claimed_runs_in_connection
+ should_flush = (
+ not preserve_durable_queue
+ and not cancelled
+ and not failed
+ and not prewrite_refused
+ and not definitive_prewrite_exit
+ and settled_by != SETTLED_BY_STOPPED
+ )
+ backend = self._context_backend(context)
+ if should_flush and backend in self._draining_backends:
+ self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
+ elif should_flush:
+ if durable_turn_registered:
+ await self._resume_post_terminal(session_id)
+ else:
+ await self.flush_queue(session_id)
+ elif (
+ durable_turn_registered
+ and settled_by != SETTLED_BY_RESTARTED
+ ):
+ # Stop may persist the old Turn's terminal snapshot before
+ # releasing this runner. In that ordering the terminal CAS
+ # already activated the linked P0 successor, so this runner
+ # sees an idempotent no-op instead of the successor ID.
+ await self._resume_linked_control_successor(
+ session_id,
+ str(logical_turn_id or ""),
+ )
- with run_update_event_transaction(engine) as conn:
- reset_workbench_claimed_runs_in_connection(conn, claimed_agent_run_ids)
- _restore_queued_rows(conn, pending_scheduled_segment)
- except Exception:
- logger.exception("queue flush: failed to reset claimed agent runs for session=%s", session_id)
- logger.exception("queue flush: failed to start scheduled segment for session=%s", session_id)
- return False
- if not pending_agent_run_ids:
- if pending_scheduled_segment:
- with engine.begin() as conn:
- messages_service.delete_queued(conn, [r["id"] for r in pending_scheduled_segment])
- bus.publish("queue.updated", {"session_id": session_id})
- try:
- with engine.begin() as conn:
- _write_coalesced_native_id_markers(conn, segment)
- except Exception:
- logger.exception("queue flush: failed to preserve coalesced native ids for session=%s", session_id)
- return False
- return True
+ task = asyncio.create_task(_runner(), name="internal-dispatch-async")
+ if isinstance(session_id, str) and session_id:
+ self.in_flight[session_id] = Turn(
+ task=task,
+ context=context,
+ started_at=_utc_now_iso(),
+ logical_turn_id=logical_turn_id,
+ delivery_id=delivery_id,
+ )
+ # Make the DB row authoritative at ACCEPTANCE, not at dispatch start:
+ # ``update_session``'s backend lock re-checks ``agent_status`` inside
+ # its UPDATE predicate, so writing ``running`` synchronously here —
+ # before the loop can start the dispatch task — closes the startup
+ # window where a cross-backend PATCH could land while the row still
+ # read idle (and would then be silently undone by the bind-time
+ # backfill). The inbound chokepoint's own ``running`` write becomes a
+ # no-op; every terminal path still settles the status (outbound
+ # chokepoint / cancel / startup recovery).
+ self.controller.set_agent_status(session_id, "running")
+ bus.publish(
+ "turn.start",
+ _turn_event_payload(session_id, logical_turn_id),
+ )
+
+ async def flush_queue(self, session_id: str) -> bool:
+ """Drain one claimable Delivery through the sole FIFO owner."""
+ return await self.drain_delivery_queue(session_id)
+
+ async def reconcile_terminal_run_delivery(
+ self,
+ run_id: str,
+ *,
+ session_id: str,
+ ) -> dict[str, Any]:
+ """Retire an exact terminal Run input when no native effect is possible."""
+
+ retired = False
+ state: str | None = None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ run = conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.session_id,
+ agent_runs.c.delivery_id,
+ )
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().first()
+ if (
+ run is None
+ or normalize_run_status(run["status"]) in {"queued", "running"}
+ or str(run["session_id"] or "") != session_id
+ or not run["delivery_id"]
+ ):
+ return {"changed": False, "state": None}
+ delivery = delivery_store.get_delivery(conn, str(run["delivery_id"]))
+ if delivery is None or str(delivery["session_id"]) != session_id:
+ return {"changed": False, "state": None}
+ state = str(delivery["state"])
+ if delivery_store.policy_for(state).run_cancel == "retire":
+ retired = self._retire_delivery_not_written(
+ conn,
+ session_id,
+ str(delivery["id"]),
+ reason="terminal_run_before_native_write",
+ )
+ if retired:
+ state = "retired"
+ if retired:
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ return {"changed": retired, "state": state}
async def recover_persisted_agent_run_queue(
self,
diff --cc core/vibe_agents.py
index 7293dd49d,b3b91a34c..c4b872092
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@@ -12,7 -12,8 +12,8 @@@ from typing import Any, Iterable, Mappi
from uuid import uuid4
import yaml
-from sqlalchemy import select
+from sqlalchemy import func, or_, select
+ from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
from config import paths
@@@ -20,16 -20,8 +21,17 @@@ from storage.agent_session_rows import
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.migrations import guard_source_checkout_default_state_migration, run_migrations
-from storage.models import agent_sessions, agents, run_definitions, scope_settings, state_meta
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ agents,
+ messages,
+ run_definitions,
+ scope_settings,
+ state_meta,
+)
+from storage.session_reclaim import DEFINITION_AGENT_BINDING_REVISION_KEY
+ from vibe.authorization import trusted_local_context
logger = logging.getLogger(__name__)
@@@ -51,72 -33,24 +53,95 @@@ RECOMMENDED_AGENT_MODELS =
_UNSET = object()
+class AgentUnavailableError(ValueError):
+ """The named Agent cannot be used: it does not exist, or it is disabled.
+
+ A TYPED contract for the one condition a caller may legitimately degrade for.
+ Resolution can fail two ways that look identical as strings but must not be
+ treated identically: the Agent is GONE (the user deleted or disabled it — a
+ settled fact, so falling back to scope/default settings is the recovery), or
+ the CATALOG could not be read (SQLite contention, a migration failure, a
+ filesystem error — transient, and falling back would convert an infrastructure
+ fault into a permanent settings change on the definition that retried).
+
+ ``core/scheduled_tasks.py``'s preserved ``create_once`` rebind is the caller
+ that made the distinction load-bearing: it catches this type NARROWLY, so an
+ operational fault propagates with the definition's route and lifecycle
+ untouched instead of being recorded as "settings could not be recovered".
+
+ Subclasses ``ValueError`` so every existing ``except ValueError`` caller — the
+ CLI, the UI server, the controller's route resolution — keeps its current
+ behaviour and its current message.
+ """
+
+ def __init__(self, message: str, *, agent_name: str, reason: str) -> None:
+ super().__init__(message)
+ #: The name as requested, which for ``missing`` is all there is.
+ self.agent_name = str(agent_name)
+ #: ``"missing"``, ``"disabled"``, or ``"no_default"``.
+ self.reason = str(reason)
+
+
+class AgentArchiveError(ValueError):
+ """A catalog rule refused an otherwise valid archive request."""
+
+ def __init__(self, *, code: str, agent_name: str) -> None:
+ super().__init__(code)
+ self.code = code
+ self.agent_name = str(agent_name)
+
+
+class AgentArchivedEditError(ValueError):
+ """An archived Agent is read-only on public mutation surfaces."""
+
+ code = "agent_archived_read_only"
+
+ def __init__(self, *, agent_name: str) -> None:
+ super().__init__(self.code)
+ self.agent_name = str(agent_name)
+
+
+class AgentReferenceRewriteError(ValueError):
+ """A durable Agent reference cannot be rewritten without losing data."""
+
+ code = "agent_reference_metadata_invalid"
+
+ def __init__(self) -> None:
+ super().__init__(self.code)
+
+
+class AgentNameValidationError(ValueError):
+ """A public Agent name violates a catalog namespace rule."""
+
+ def __init__(self, *, code: str, agent_name: str) -> None:
+ super().__init__(code)
+ self.code = code
+ self.agent_name = str(agent_name)
+
+
+ class VibeAgentAccessError(PermissionError):
+ """Raised when the caller is not allowed to use a Vibe Agent."""
+
+
-def get_agent_resource_metadata(connection: Connection, resource_id: str) -> dict[str, str] | None:
++def get_agent_resource_metadata(
++ connection: Connection,
++ resource_id: str,
++) -> dict[str, str] | None:
+ """Return the safe Agent fields allowed in the hosted resource index."""
+
+ row = connection.execute(
- select(agents.c.name, agents.c.updated_at).where(agents.c.id == resource_id).limit(1)
++ select(agents.c.name, agents.c.updated_at)
++ .where(agents.c.id == resource_id)
++ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return None
+ return {
+ "display_name": str(row["name"]),
+ "updated_at": str(row["updated_at"]),
+ }
+
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@@@ -192,100 -83,104 +217,196 @@@ def _json_loads(value: str | None, defa
return default
+ def resolve_resource_access_context(user_context: Any = None):
+ """Resolve request ACL context while preserving local service behavior."""
+
+ from storage import resource_access_service
+
+ return resource_access_service.resolve_resource_access_context(user_context)
+
+
+ def ensure_agent_selection_access(
- connection,
++ connection: Connection,
+ *,
+ agent_name: str | None = None,
+ agent_id: str | None = None,
+ user_context: Any = None,
+ missing_is_error: bool = False,
+ ) -> "VibeAgent | None":
- """Return a selected Agent only when the request may use it.
-
- ``agent_id`` is the ACL resource identifier. A supplied name and id must
- resolve to the same row so a caller cannot authorize one Agent and persist
- another in a session or background definition.
- """
++ """Resolve an Agent and require use access to that exact resource."""
+
+ from storage import resource_access_service
+
+ selected_name = str(agent_name or "").strip()
+ selected_id = str(agent_id or "").strip()
+ if not selected_name and not selected_id:
+ return None
+
+ context = resolve_resource_access_context(user_context)
+ statement = select(agents)
+ if selected_id:
+ statement = statement.where(agents.c.id == selected_id)
+ if selected_name:
- statement = statement.where(agents.c.normalized_name == normalize_agent_name(selected_name))
++ statement = statement.where(
++ agents.c.normalized_name == normalize_agent_name(selected_name)
++ )
+ row = connection.execute(statement.limit(1)).mappings().first()
+ if row is None:
+ if context.is_remote or missing_is_error:
+ raise LookupError("Agent not found")
- # Older local callers may hold a backend/name pairing that predates the
- # Vibe Agent catalog. Preserve that local compatibility; a remote
- # request never receives the same exception.
+ return None
+
+ agent = VibeAgentStore._from_row(row)
- if not resource_access_service.can_use_resource(context, "agent", agent.id, connection=connection):
++ if not resource_access_service.can_use_resource(
++ context,
++ "agent",
++ agent.id,
++ connection=connection,
++ ):
+ raise VibeAgentAccessError("Agent access is not permitted.")
+ return agent
+
+
-def ensure_agent_name_access(agent_name: str | None, *, user_context: Any = None) -> None:
- """Reject a remote task/watch binding to an inaccessible named Agent.
-
- Local task and watch definitions are created outside an HTTP request and
- intentionally retain their existing trusted-local behavior. A remote
- request gets the same id-backed authorization used by session creation.
- """
++def ensure_agent_name_access(
++ agent_name: str | None,
++ *,
++ user_context: Any = None,
++) -> None:
++ """Reject a remote task/watch binding to an inaccessible named Agent."""
+
+ if not str(agent_name or "").strip():
+ return
+ context = resolve_resource_access_context(user_context)
+ if not context.is_remote:
+ return
+ store = VibeAgentStore()
+ try:
+ store.require_accessible(str(agent_name), user_context=context)
+ finally:
+ store.close()
+
+
+ def _require_agent_create_access(user_context: Any) -> None:
+ if user_context.can_manage_agents:
+ return
+ raise VibeAgentAccessError("Agent access is not permitted.")
+
+
+ def _require_agent_onboarding_access(user_context: Any):
+ """Require owner-equivalent access for Organization Agent publication."""
+
+ context = resolve_resource_access_context(user_context)
+ if context.is_trusted_local or context.is_instance_owner:
+ return context
+ raise VibeAgentAccessError("Agent access is not permitted.")
+
+
+ def _agent_onboarding_counts(inventory: list[dict[str, Any]]) -> dict[str, int]:
+ return {
+ "total": len(inventory),
+ "system": sum(item.get("source") in {"builtin", "system"} for item in inventory),
+ "custom": sum(item.get("source") not in {"builtin", "system"} for item in inventory),
+ "not_onboarded": sum(item.get("status") == "not_onboarded" for item in inventory),
+ "private": sum(item.get("status") == "private" for item in inventory),
+ "published": sum(item.get("status") == "published" for item in inventory),
+ "conflicts": sum(item.get("status") == "managed_elsewhere" for item in inventory),
+ }
+
+
+def _rewrite_scope_agent_name(
+ raw: str | None,
+ reference_names: frozenset[str],
+ new_name: str,
+) -> tuple[str, bool]:
+ payload = _json_loads(raw, {})
+ if not isinstance(payload, dict):
+ return raw or "{}", False
+ routing = payload.get("routing")
+ if not isinstance(routing, dict):
+ return raw or "{}", False
+ changed = False
+ for key in ("agent_name", "agent"):
+ if _matches_agent_reference(routing.get(key), reference_names):
+ routing[key] = new_name
+ changed = True
+ return (_json_dumps(payload), True) if changed else (raw or "{}", False)
+
+
+def _rewrite_definition_agent_name(
+ raw: str | None,
+ reference_names: frozenset[str],
+ new_name: str,
+ *,
+ direct_binding_changed: bool,
+ revision: str,
+) -> tuple[str, bool]:
+ try:
+ payload = json.loads("{}" if raw is None else raw)
+ except (TypeError, ValueError) as exc:
+ if direct_binding_changed:
+ raise AgentReferenceRewriteError() from exc
+ return raw or "{}", False
+ if not isinstance(payload, dict):
+ if direct_binding_changed:
+ raise AgentReferenceRewriteError()
+ return raw or "{}", False
+ changed = direct_binding_changed
+ snapshot = payload.get("session_settings_snapshot")
+ if isinstance(snapshot, dict) and _matches_agent_reference(
+ snapshot.get("agent_name"), reference_names
+ ):
+ snapshot["agent_name"] = new_name
+ changed = True
+ if not changed:
+ return raw or "{}", False
+ payload[DEFINITION_AGENT_BINDING_REVISION_KEY] = revision
+ return _json_dumps(payload), True
+
+
+def _rewrite_scheduled_agent_provenance(
+ raw: str | None,
+ reference_names: frozenset[str],
+ new_name: str,
+ *,
+ agent_id: str,
+) -> tuple[str, bool]:
+ """Move routing names captured in scheduled submission metadata."""
+
+ try:
+ payload = json.loads(raw or "{}")
+ except (TypeError, ValueError):
+ return raw or "{}", False
+ if not isinstance(payload, dict):
+ return raw or "{}", False
+ provenance = payload.get("scheduled_provenance")
+ if not isinstance(provenance, dict):
+ return raw or "{}", False
+ spec = provenance.get("platform_specific")
+ if not isinstance(spec, dict):
+ return raw or "{}", False
+
+ changed = False
+ for key in ("vibe_agent_name", "scheduled_target_agent_name"):
+ if _owns_agent_reference(
+ spec.get("vibe_agent_id"),
+ spec.get(key),
+ agent_id=agent_id,
+ reference_names=reference_names,
+ ):
+ spec[key] = new_name
+ changed = True
+ target = spec.get("agent_session_target")
+ if isinstance(target, dict) and _owns_agent_reference(
+ target.get("agent_id"),
+ target.get("agent_name"),
+ agent_id=agent_id,
+ reference_names=reference_names,
+ ):
+ target["agent_name"] = new_name
+ changed = True
+ return (_json_dumps(payload), True) if changed else (raw or "{}", False)
+
+
@dataclass(frozen=True)
class VibeAgent:
id: str
@@@ -305,50 -199,90 +426,131 @@@
updated_at: str = field(default_factory=_utc_now_iso)
def to_dict(self) -> dict[str, Any]:
- return asdict(self)
+ payload = asdict(self)
+ payload["archived"] = self.archived_at is not None
+ payload["display_name"] = archived_agent_original_name(self) or self.name
+ return payload
+
+
+@dataclass(frozen=True)
+class AgentArchiveResult:
+ agent: VibeAgent
+ original_name: str
+ archived_name: str
+ references: dict[str, int]
+ default_agent_name: Optional[str] = None
+
+
+def archived_agent_original_name(agent: VibeAgent) -> Optional[str]:
+ if agent.archived_at is None:
+ return None
+ archive_metadata = agent.metadata.get(AGENT_ARCHIVE_METADATA_KEY)
+ if not isinstance(archive_metadata, dict):
+ return None
+ original_name = str(archive_metadata.get("original_name") or "").strip()
+ return original_name or None
+
+
+def agent_reference_is_usable(
+ *,
+ enabled: bool,
+ archived_at: Optional[str],
+ metadata: Mapping[str, Any] | None,
+) -> bool:
+ """Return whether an Agent may back an existing durable reference."""
+
+ if enabled:
+ return True
+ archive_metadata = (metadata or {}).get(AGENT_ARCHIVE_METADATA_KEY)
+ archived_was_enabled = (
+ archive_metadata.get("was_enabled", True)
+ if isinstance(archive_metadata, dict)
+ else True
+ )
+ return archived_at is not None and bool(archived_was_enabled)
+ def resolve_effective_default_agent(connection, *, enabled_only: bool = True) -> VibeAgent | None:
+ """Resolve the same instance-wide default used by runtime dispatch."""
+
+ raw_name = connection.execute(
+ select(state_meta.c.value_json).where(state_meta.c.key == DEFAULT_AGENT_META_KEY).limit(1)
+ ).scalar_one_or_none()
+ configured_name = _json_loads(raw_name, None)
+ candidates = [configured_name, DEFAULT_AGENT_NAME]
+ seen: set[str] = set()
+ for candidate in candidates:
+ if not isinstance(candidate, str) or not candidate.strip():
+ continue
+ try:
+ normalized = normalize_agent_name(candidate)
+ except ValueError:
+ continue
+ if normalized in seen:
+ continue
+ seen.add(normalized)
+ statement = select(agents).where(agents.c.normalized_name == normalized)
+ if enabled_only:
+ statement = statement.where(agents.c.enabled == 1)
+ row = connection.execute(statement.limit(1)).mappings().first()
+ if row is not None:
+ return VibeAgentStore._from_row(row)
+
+ if not enabled_only:
+ return None
+ row = connection.execute(select(agents).where(agents.c.enabled == 1).order_by(agents.c.name).limit(1)).mappings().first()
+ return VibeAgentStore._from_row(row) if row is not None else None
+
+
+ def ensure_default_agent_access(
+ connection,
+ *,
+ user_context: Any = None,
+ missing_is_error: bool = False,
+ ) -> VibeAgent | None:
+ """Resolve and authorize the effective default Agent for a remote caller."""
+
+ from storage import resource_access_service
+
+ context = resolve_resource_access_context(user_context)
+ agent = resolve_effective_default_agent(connection)
+ if agent is None:
+ if context.is_remote or missing_is_error:
+ raise LookupError("Default Agent not found")
+ return None
+ if not resource_access_service.can_use_resource(
+ context,
+ "agent",
+ agent.id,
+ connection=connection,
+ ):
+ raise VibeAgentAccessError("Agent access is not permitted.")
+ return agent
+
+
+ def ensure_session_agent_access(
+ connection,
+ session: dict[str, Any],
+ *,
+ user_context: Any = None,
+ ) -> VibeAgent | None:
+ """Revalidate the Agent selected by a persisted session before dispatch."""
+
+ context = resolve_resource_access_context(user_context)
+ if session.get("agent_id") or session.get("agent_name"):
+ return ensure_agent_selection_access(
+ connection,
+ agent_name=session.get("agent_name"),
+ agent_id=session.get("agent_id"),
+ user_context=context,
+ )
+ if not session.get("agent_backend"):
+ return ensure_default_agent_access(connection, user_context=context)
+ if context.is_remote:
+ raise VibeAgentAccessError("Agent access is not permitted.")
+ return None
+
+
@dataclass(frozen=True)
class AgentImportCandidate:
name: str
@@@ -388,41 -321,133 +590,161 @@@ class VibeAgentStore
def maybe_reload(self) -> bool:
return self._probe.has_external_write()
- def list_agents(self, *, include_disabled: bool = True, user_context: Any = None) -> list[VibeAgent]:
+ def prefill_missing_models(self) -> int:
+ """Materialize release recommendations on legacy model-less Agents."""
+
+ now = _utc_now_iso()
+ updated = 0
+ with self.engine.begin() as conn:
+ for backend, model in RECOMMENDED_AGENT_MODELS.items():
+ result = conn.execute(
+ agents.update()
+ .where(agents.c.backend == backend)
+ .where(agents.c.archived_at.is_(None))
+ .where(agents.c.model.is_(None) | (func.trim(agents.c.model) == ""))
+ .values(model=model, updated_at=now)
+ )
+ updated += int(result.rowcount or 0)
+ return updated
+
+ def list_agents(
+ self,
+ *,
+ include_disabled: bool = True,
+ include_archived: bool = False,
++ user_context: Any = None,
+ ) -> list[VibeAgent]:
+ from storage import resource_access_service
+
+ context = resolve_resource_access_context(user_context)
with self.engine.connect() as conn:
stmt = select(agents).order_by(agents.c.name)
if not include_disabled:
- stmt = stmt.where(agents.c.enabled == 1)
+ if include_archived:
+ stmt = stmt.where(or_(agents.c.enabled == 1, agents.c.archived_at.is_not(None)))
+ else:
+ stmt = stmt.where(agents.c.enabled == 1)
+ if not include_archived:
+ stmt = stmt.where(agents.c.archived_at.is_(None))
- rows = conn.execute(stmt).mappings()
+ rows = conn.execute(stmt).mappings().all()
+ rows = resource_access_service.filter_accessible_resources(
+ context,
+ "agent",
+ rows,
+ connection=conn,
+ )
return [self._from_row(row) for row in rows]
+ def organization_onboarding_inventory(self, *, user_context: Any = None) -> dict[str, Any]:
+ """Return the safe owner inventory for explicit Organization onboarding."""
+
+ from storage import resource_access_service
+
+ context = _require_agent_onboarding_access(user_context)
+ organization_id = context.organization_id if context.is_active_organization_member else None
+ if not organization_id or not context.subject:
+ return {
+ "available": False,
+ "organization_id": None,
+ "agents": [],
+ "counts": _agent_onboarding_counts([]),
+ }
+
+ with self.engine.connect() as conn:
+ rows = conn.execute(select(agents).order_by(agents.c.name)).mappings().all()
+ policies = {
+ str(policy["resource_id"]): policy
+ for policy in resource_access_service.list_resource_policies(
+ resource_kind="agent",
+ connection=conn,
+ )
+ }
+
+ inventory: list[dict[str, Any]] = []
+ for row in rows:
+ agent = self._from_row(row)
+ policy = policies.get(agent.id)
+ visible_policy = policy if policy and policy.get("organization_id") == organization_id else None
+ if policy is None:
+ status = "not_onboarded"
+ elif visible_policy is None:
+ status = "managed_elsewhere"
+ elif visible_policy.get("access_level") == "private":
+ status = "private"
+ else:
+ status = "published"
+ inventory.append(
+ {
+ "id": agent.id,
+ "name": agent.name,
+ "backend": agent.backend,
+ "source": agent.source,
+ "enabled": agent.enabled,
+ "status": status,
+ "access_level": visible_policy.get("access_level") if visible_policy else None,
+ "group_ids": list(visible_policy.get("group_ids") or []) if visible_policy else [],
+ "policy_revision": int(visible_policy.get("policy_revision") or 0) if visible_policy else None,
+ "applied_acl_revision": (
+ int(visible_policy.get("last_applied_control_plane_revision") or 0)
+ if visible_policy
+ else None
+ ),
+ }
+ )
+ return {
+ "available": True,
+ "organization_id": organization_id,
+ "agents": inventory,
+ "counts": _agent_onboarding_counts(inventory),
+ }
+
+ def onboard_organization_agents(self, *, user_context: Any = None) -> dict[str, Any]:
+ """Register every missing Agent as private without replacing any ACL."""
+
+ from storage import resource_access_service
+
+ context = _require_agent_onboarding_access(user_context)
+ if not context.is_active_organization_member or not context.organization_id or not context.subject:
+ raise VibeAgentAccessError("Agent access is not permitted.")
+
+ created = 0
+ unchanged = 0
+ conflicts = 0
+ with self.engine.begin() as conn:
+ rows = conn.execute(select(agents).order_by(agents.c.name)).mappings().all()
+ policies = {
+ str(policy["resource_id"]): policy
+ for policy in resource_access_service.list_resource_policies(
+ resource_kind="agent",
+ connection=conn,
+ )
+ }
+ for row in rows:
+ agent = self._from_row(row)
+ existing = policies.get(agent.id)
+ if existing is not None:
+ if existing.get("organization_id") == context.organization_id:
+ unchanged += 1
+ else:
+ conflicts += 1
+ continue
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="agent",
+ resource_id=agent.id,
+ organization_id=context.organization_id,
+ owner_user_id=context.subject,
+ owner_email=context.email,
+ access_level="private",
+ created_by_user_id=context.subject,
+ updated_by_user_id=context.subject,
+ )
+ created += 1
+
+ result = self.organization_onboarding_inventory(user_context=context)
+ result.update({"created": created, "unchanged": unchanged, "conflicts": conflicts})
+ return result
+
def get(self, name: str) -> Optional[VibeAgent]:
normalized = normalize_agent_name(name)
with self.engine.connect() as conn:
@@@ -453,41 -464,50 +775,81 @@@
def require_enabled(self, name: str) -> VibeAgent:
agent = self.require(name)
- if not agent.enabled:
- raise ValueError(f"agent '{agent.name}' is disabled")
+ if not agent.enabled or agent.archived_at is not None:
+ raise AgentUnavailableError(
+ f"agent '{agent.name}' is disabled", agent_name=agent.name, reason="disabled"
+ )
+ return agent
+
+ def require_reference(self, name: str) -> VibeAgent:
+ """Resolve a durable Agent reference, including a disabled archive."""
+
+ return self._require_reference_agent(self.require(name))
+
+ def require_reference_by_id(self, agent_id: str) -> VibeAgent:
+ """Resolve a durable Agent identity across rename/archive operations."""
+
+ agent = self.get_by_id(agent_id)
+ if agent is None:
+ raise AgentUnavailableError(
+ f"agent id '{agent_id}' not found",
+ agent_name=str(agent_id),
+ reason="missing",
+ )
+ return self._require_reference_agent(agent)
+
+ @staticmethod
+ def _require_reference_agent(agent: VibeAgent) -> VibeAgent:
+ if not agent_reference_is_usable(
+ enabled=agent.enabled,
+ archived_at=agent.archived_at,
+ metadata=agent.metadata,
+ ):
+ raise AgentUnavailableError(
+ f"agent '{agent.name}' is disabled", agent_name=agent.name, reason="disabled"
+ )
return agent
+ def require_accessible(self, name: str, *, user_context: Any = None, enabled_only: bool = False) -> VibeAgent:
+ """Return an Agent only when the caller may use its ACL resource."""
+
+ try:
+ with self.engine.connect() as conn:
+ agent = ensure_agent_selection_access(
+ conn,
+ agent_name=name,
+ user_context=user_context,
+ missing_is_error=True,
+ )
+ except LookupError as exc:
+ raise ValueError(f"agent '{name}' not found") from exc
+ assert agent is not None
+ if enabled_only and not agent.enabled:
+ raise ValueError(f"agent '{agent.name}' is disabled")
+ return agent
+
+ def require_manageable(self, name: str, *, user_context: Any = None) -> VibeAgent:
+ """Return an Agent only when the caller may change its resource."""
+
+ from storage import resource_access_service
+
+ context = resolve_resource_access_context(user_context)
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agents).where(agents.c.normalized_name == normalize_agent_name(name)).limit(1)
+ ).mappings().first()
+ if row is None:
+ raise ValueError(f"agent '{name}' not found")
+ agent = self._from_row(row)
+ if not resource_access_service.can_manage_resource_acl(
+ context,
+ "agent",
+ agent.id,
+ connection=conn,
+ ):
+ raise VibeAgentAccessError("Agent access is not permitted.")
+ return agent
+
def create(
self,
*,
@@@ -501,9 -521,14 +863,15 @@@
source_ref: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
enabled: bool = True,
+ user_context: Any = None,
) -> VibeAgent:
+ from storage import resource_access_service
+
- normalized = normalize_agent_name(name)
+ raw_name, normalized = _validated_public_agent_name(name)
+ normalized_backend = validate_agent_backend(backend)
+ context = resolve_resource_access_context(user_context)
+ if source != "builtin":
+ _require_agent_create_access(context)
now = _utc_now_iso()
agent = VibeAgent(
id=uuid4().hex[:12],
@@@ -538,290 -575,32 +918,308 @@@
system_prompt: Any = _UNSET,
metadata: Any = _UNSET,
enabled: Any = _UNSET,
+ user_context: Any = None,
) -> VibeAgent:
- existing = self.require_manageable(name, user_context=user_context)
- values: dict[str, Any] = {"updated_at": _utc_now_iso()}
- if description is not _UNSET:
- values["description"] = _clean_optional(description)
- if model is not _UNSET:
- values["model"] = _clean_optional(model)
- if reasoning_effort is not _UNSET:
- values["reasoning_effort"] = _clean_optional(reasoning_effort)
- if system_prompt is not _UNSET:
- values["system_prompt"] = _clean_optional(system_prompt)
- if metadata is not _UNSET:
- values["metadata_json"] = _json_dumps(dict(metadata or {}))
- if enabled is not _UNSET:
- values["enabled"] = 1 if bool(enabled) else 0
+ normalized = normalize_agent_name(name)
++ self.require_manageable(name, user_context=user_context)
with self.engine.begin() as conn:
- conn.execute(agents.update().where(agents.c.id == existing.id).values(**values))
- return self.require(name)
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agents).where(agents.c.normalized_name == normalized).limit(1)
+ ).mappings().first()
+ if row is None:
+ raise AgentUnavailableError(
+ f"agent '{name}' not found", agent_name=name, reason="missing"
+ )
+ existing = self._from_row(row)
+ if existing.archived_at is not None:
+ raise AgentArchivedEditError(agent_name=name)
+
+ values: dict[str, Any] = {"updated_at": _utc_now_iso()}
+ if description is not _UNSET:
+ values["description"] = _clean_optional(description)
+ if model is not _UNSET:
+ values["model"] = _clean_optional(model) or recommended_agent_model(existing.backend)
+ if reasoning_effort is not _UNSET:
+ values["reasoning_effort"] = _clean_optional(reasoning_effort)
+ if system_prompt is not _UNSET:
+ values["system_prompt"] = _clean_optional(system_prompt)
+ if metadata is not _UNSET:
+ values["metadata_json"] = _json_dumps(dict(metadata or {}))
+ if enabled is not _UNSET:
+ values["enabled"] = 1 if bool(enabled) else 0
+ result = conn.execute(
+ agents.update()
+ .where(agents.c.id == existing.id)
+ .where(agents.c.archived_at.is_(None))
+ .values(**values)
+ )
+ if result.rowcount != 1:
+ raise AgentArchivedEditError(agent_name=name)
+ updated = conn.execute(
+ select(agents).where(agents.c.id == existing.id).limit(1)
+ ).mappings().one()
+ return self._from_row(updated)
- def set_enabled(self, name: str, enabled: bool) -> VibeAgent:
- return self.update(name, enabled=enabled)
+ def set_enabled(self, name: str, enabled: bool, *, user_context: Any = None) -> VibeAgent:
+ return self.update(name, enabled=enabled, user_context=user_context)
- def rename(self, name: str, new_name: str) -> VibeAgent:
++ def rename(
++ self,
++ name: str,
++ new_name: str,
++ *,
++ user_context: Any = None,
++ ) -> VibeAgent:
++ self.require_manageable(name, user_context=user_context)
+ raw_new_name, new_normalized = _validated_public_agent_name(new_name)
+ old_normalized = normalize_agent_name(name)
+ now = _utc_now_iso()
+ try:
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agents).where(agents.c.normalized_name == old_normalized).limit(1)
+ ).mappings().first()
+ if row is None:
+ raise AgentUnavailableError(
+ f"agent '{name}' not found", agent_name=name, reason="missing"
+ )
+ agent = self._from_row(row)
+ if agent.archived_at is not None:
+ raise AgentArchivedEditError(agent_name=name)
+ if is_builtin_default_agent(agent):
+ raise ValueError(f"agent '{agent.name}' is built in and cannot be renamed")
+ if new_normalized == agent.normalized_name:
+ if raw_new_name == agent.name:
+ return agent
+ collision = conn.execute(
+ select(agents.c.id)
+ .where(agents.c.normalized_name == new_normalized)
+ .where(agents.c.id != agent.id)
+ .limit(1)
+ ).first()
+ if collision is not None:
+ raise ValueError(f"agent '{new_name}' already exists")
+
+ conn.execute(
+ agents.update()
+ .where(agents.c.id == agent.id)
+ .values(name=raw_new_name, normalized_name=new_normalized, updated_at=now)
+ )
+ self._rewrite_references(
+ conn,
+ agent_id=agent.id,
+ reference_names=frozenset((agent.name, agent.normalized_name)),
+ new_name=raw_new_name,
+ revision=now,
+ )
+ default_name = self._default_agent_name(conn)
+ try:
+ default_matches = (
+ default_name is not None
+ and normalize_agent_name(default_name) == agent.normalized_name
+ )
+ except ValueError:
+ default_matches = False
+ if default_matches:
+ self._write_default_agent_name(conn, raw_new_name, now=now)
+ updated = conn.execute(
+ select(agents).where(agents.c.id == agent.id).limit(1)
+ ).mappings().one()
+ except IntegrityError as exc:
+ raise ValueError(f"agent '{new_name}' already exists") from exc
+ return self._from_row(updated)
+
- def archive(self, name: str) -> Optional[AgentArchiveResult]:
++ def archive(
++ self,
++ name: str,
++ *,
++ user_context: Any = None,
++ ) -> Optional[AgentArchiveResult]:
+ normalized = normalize_agent_name(name)
+ now = _utc_now_iso()
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agents).where(agents.c.normalized_name == normalized).limit(1)
+ ).mappings().first()
+ if row is None:
+ legacy = self._legacy_archive_for_original_name(conn, normalized)
+ if legacy is None:
+ return None
++ self.require_manageable(legacy.name, user_context=user_context)
+ return self._compact_legacy_archive(conn, legacy, now=now)
+ agent = self._from_row(row)
++ self.require_manageable(agent.name, user_context=user_context)
+ if is_builtin_default_agent(agent):
+ raise AgentArchiveError(
+ code="agent_builtin",
+ agent_name=agent.name,
+ )
+ if agent.archived_at is not None:
+ if agent.name.startswith(LEGACY_ARCHIVED_AGENT_NAME_PREFIX):
+ return self._compact_legacy_archive(conn, agent, now=now)
+ raise AgentArchiveError(
+ code="agent_already_archived",
+ agent_name=agent.name,
+ )
+
+ default_name = self._default_agent_name(conn)
+ effective_default = self._effective_default_agent(conn)
+ explicit_default_matches = (
+ default_name is not None
+ and normalize_agent_name(default_name) == agent.normalized_name
+ )
+ replacement = None
+ if effective_default is not None and effective_default.id == agent.id:
+ replacement = self._archive_default_replacement(conn, agent)
+ if replacement is None:
+ raise AgentArchiveError(
+ code="agent_no_default_replacement",
+ agent_name=agent.name,
+ )
+ elif explicit_default_matches:
+ replacement = effective_default
+
+ archived_name, archived_normalized = self._available_archive_name(
+ conn,
+ normalized_name=agent.normalized_name,
+ )
+
+ reference_names = frozenset((agent.name, agent.normalized_name))
+ references = self._reference_counts(conn, reference_names, agent_id=agent.id)
+ archive_metadata = {
+ "original_name": agent.name,
+ "archived_at": now,
+ "was_enabled": agent.enabled,
+ }
+ metadata = {**agent.metadata, AGENT_ARCHIVE_METADATA_KEY: archive_metadata}
+ conn.execute(
+ agents.update()
+ .where(agents.c.id == agent.id)
+ .values(
+ name=archived_name,
+ normalized_name=archived_normalized,
+ enabled=0,
+ metadata_json=_json_dumps(metadata),
+ archived_at=now,
+ updated_at=now,
+ )
+ )
+ self._rewrite_references(
+ conn,
+ agent_id=agent.id,
+ reference_names=reference_names,
+ new_name=archived_name,
+ revision=now,
+ )
+ if replacement is not None:
+ self._write_default_agent_name(conn, replacement.name, now=now)
+ remaining_default_name = replacement.name
+ elif explicit_default_matches:
+ conn.execute(state_meta.delete().where(state_meta.c.key == DEFAULT_AGENT_META_KEY))
+ remaining_default_name = None
+ else:
+ remaining_default_name = default_name
+
+ archived_agent = VibeAgent(
+ **{
+ **asdict(agent),
+ "name": archived_name,
+ "normalized_name": archived_normalized,
+ "enabled": False,
+ "metadata": metadata,
+ "archived_at": now,
+ "updated_at": now,
+ }
+ )
+ return AgentArchiveResult(
+ agent=archived_agent,
+ original_name=agent.name,
+ archived_name=archived_name,
+ references=references,
+ default_agent_name=remaining_default_name,
+ )
+
+ @staticmethod
+ def _available_archive_name(conn: Any, *, normalized_name: str) -> tuple[str, str]:
+ slug = str(normalized_name or "agent").strip("-_")[:ARCHIVED_AGENT_SLUG_LENGTH] or "agent"
+ while True:
+ token = uuid4().hex[:ARCHIVED_AGENT_TOKEN_LENGTH]
+ archived_name = f"{ARCHIVED_AGENT_NAME_PREFIX}{slug}-{token}"
+ archived_normalized = normalize_agent_name(archived_name)
+ collision = conn.execute(
+ select(agents.c.id).where(agents.c.normalized_name == archived_normalized).limit(1)
+ ).first()
+ if collision is None:
+ return archived_name, archived_normalized
+
+ @staticmethod
+ def _legacy_archive_for_original_name(conn: Any, normalized_name: str) -> Optional[VibeAgent]:
+ rows = conn.execute(
+ select(agents)
+ .where(agents.c.archived_at.is_not(None))
+ .order_by(agents.c.updated_at.desc())
+ ).mappings()
+ for row in rows:
+ agent = VibeAgentStore._from_row(row)
+ if not agent.name.startswith(LEGACY_ARCHIVED_AGENT_NAME_PREFIX):
+ continue
+ original_name = archived_agent_original_name(agent)
+ if original_name and normalize_agent_name(original_name) == normalized_name:
+ return agent
+ return None
+
+ def _compact_legacy_archive(
+ self,
+ conn: Any,
+ agent: VibeAgent,
+ *,
+ now: str,
+ ) -> AgentArchiveResult:
+ original_name = archived_agent_original_name(agent) or agent.name
+ archived_name, archived_normalized = self._available_archive_name(
+ conn,
+ normalized_name=normalize_agent_name(original_name),
+ )
+ reference_names = frozenset((agent.name, agent.normalized_name))
+ references = self._reference_counts(conn, reference_names, agent_id=agent.id)
+ conn.execute(
+ agents.update()
+ .where(agents.c.id == agent.id)
+ .values(
+ name=archived_name,
+ normalized_name=archived_normalized,
+ updated_at=now,
+ )
+ )
+ self._rewrite_references(
+ conn,
+ agent_id=agent.id,
+ reference_names=reference_names,
+ new_name=archived_name,
+ revision=now,
+ )
+ archived_agent = VibeAgent(
+ **{
+ **asdict(agent),
+ "name": archived_name,
+ "normalized_name": archived_normalized,
+ "updated_at": now,
+ }
+ )
+ return AgentArchiveResult(
+ agent=archived_agent,
+ original_name=original_name,
+ archived_name=archived_name,
+ references=references,
+ default_agent_name=self._default_agent_name(conn),
+ )
+
- def remove(self, name: str) -> bool:
+ def remove(self, name: str, *, user_context: Any = None) -> bool:
+ from storage import resource_access_service
+
agent = self.get(name)
if agent is None:
return False
@@@ -837,211 -620,29 +1238,216 @@@
if agent is None:
return {}
with self.engine.connect() as conn:
- scope_count = conn.execute(
- select(scope_settings.c.scope_id).where(scope_settings.c.agent_name == agent.name)
- ).fetchall()
- session_count = conn.execute(
- select(agent_sessions.c.id).where(agent_sessions.c.agent_name == agent.name)
- ).fetchall()
- definition_count = conn.execute(
- select(run_definitions.c.id)
- .where(run_definitions.c.agent_name == agent.name)
- .where(run_definitions.c.deleted_at.is_(None))
- ).fetchall()
+ return self._reference_counts(
+ conn,
+ frozenset((agent.name, agent.normalized_name)),
+ agent_id=agent.id,
+ )
+
+ @staticmethod
+ def _reference_counts(
+ conn: Any,
+ reference_names: frozenset[str],
+ *,
+ agent_id: str,
+ ) -> dict[str, int]:
+ reference_names = _normalized_agent_reference_names(reference_names)
+ scope_names = conn.execute(
+ select(scope_settings.c.agent_name).where(scope_settings.c.agent_name.is_not(None))
+ ).scalars()
+ session_rows = conn.execute(
+ select(agent_sessions.c.agent_id, agent_sessions.c.agent_name)
+ ).mappings()
+ definition_names = conn.execute(
+ select(run_definitions.c.agent_name)
+ .where(run_definitions.c.agent_name.is_not(None))
+ .where(run_definitions.c.deleted_at.is_(None))
+ ).scalars()
return {
- "scopes": len(scope_count),
- "sessions": len(session_count),
- "definitions": len(definition_count),
+ "scopes": sum(_matches_agent_reference(name, reference_names) for name in scope_names),
+ "sessions": sum(
+ _owns_agent_reference(
+ row["agent_id"],
+ row["agent_name"],
+ agent_id=agent_id,
+ reference_names=reference_names,
+ )
+ for row in session_rows
+ ),
+ "definitions": sum(
+ _matches_agent_reference(name, reference_names) for name in definition_names
+ ),
}
+ @staticmethod
+ def _rewrite_references(
+ conn: Any,
+ *,
+ agent_id: str,
+ reference_names: frozenset[str],
+ new_name: str,
+ revision: str,
+ ) -> None:
+ reference_names = _normalized_agent_reference_names(reference_names)
+ session_ids = [
+ row["id"]
+ for row in conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.agent_id, agent_sessions.c.agent_name)
+ ).mappings()
+ if _owns_agent_reference(
+ row["agent_id"],
+ row["agent_name"],
+ agent_id=agent_id,
+ reference_names=reference_names,
+ )
+ ]
+ if session_ids:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id.in_(session_ids))
+ .values(agent_id=agent_id, agent_name=new_name)
+ )
+
+ run_ids = [
+ row["id"]
+ for row in conn.execute(
+ select(agent_runs.c.id, agent_runs.c.agent_id, agent_runs.c.agent_name)
+ .where(agent_runs.c.status.in_(("pending", "queued", "processing", "running")))
+ ).mappings()
+ if _owns_agent_reference(
+ row["agent_id"],
+ row["agent_name"],
+ agent_id=agent_id,
+ reference_names=reference_names,
+ )
+ ]
+ if run_ids:
+ conn.execute(
+ agent_runs.update()
+ .where(agent_runs.c.id.in_(run_ids))
+ .values(agent_id=agent_id, agent_name=new_name)
+ )
+
+ scope_rows = conn.execute(
+ select(scope_settings.c.scope_id, scope_settings.c.agent_name, scope_settings.c.settings_json)
+ ).mappings().all()
+ for row in scope_rows:
+ values: dict[str, Any] = {}
+ if _matches_agent_reference(row["agent_name"], reference_names):
+ values["agent_name"] = new_name
+ settings, changed = _rewrite_scope_agent_name(
+ row["settings_json"], reference_names, new_name
+ )
+ if changed:
+ values["settings_json"] = settings
+ if values:
+ conn.execute(
+ scope_settings.update()
+ .where(scope_settings.c.scope_id == row["scope_id"])
+ .values(**values)
+ )
+
+ definition_rows = conn.execute(
+ select(run_definitions.c.id, run_definitions.c.agent_name, run_definitions.c.metadata_json)
+ .where(run_definitions.c.deleted_at.is_(None))
+ ).mappings().all()
+ for row in definition_rows:
+ values = {}
+ direct_binding_changed = _matches_agent_reference(row["agent_name"], reference_names)
+ if direct_binding_changed:
+ values["agent_name"] = new_name
+ metadata, changed = _rewrite_definition_agent_name(
+ row["metadata_json"],
+ reference_names,
+ new_name,
+ direct_binding_changed=direct_binding_changed,
+ revision=revision,
+ )
+ if changed:
+ values["metadata_json"] = metadata
+ if values:
+ conn.execute(
+ run_definitions.update()
+ .where(run_definitions.c.id == row["id"])
+ .values(**values)
+ )
+
+ @staticmethod
+ def _default_agent_name(conn: Any) -> Optional[str]:
+ value = conn.execute(
+ select(state_meta.c.value_json).where(state_meta.c.key == DEFAULT_AGENT_META_KEY).limit(1)
+ ).scalar_one_or_none()
+ payload = _json_loads(value, None)
+ return str(payload).strip() if payload else None
+
+ @staticmethod
+ def _write_default_agent_name(conn: Any, name: str, *, now: str) -> None:
+ conn.execute(state_meta.delete().where(state_meta.c.key == DEFAULT_AGENT_META_KEY))
+ conn.execute(
+ state_meta.insert().values(
+ key=DEFAULT_AGENT_META_KEY,
+ value_json=_json_dumps(name),
+ updated_at=now,
+ )
+ )
+
+ @staticmethod
+ def _archive_default_replacement(conn: Any, archived: VibeAgent) -> Optional[VibeAgent]:
+ rows = conn.execute(
+ select(agents)
+ .where(agents.c.id != archived.id)
+ .where(agents.c.enabled == 1)
+ .where(agents.c.archived_at.is_(None))
+ .order_by(agents.c.name)
+ ).mappings()
+ candidates = [VibeAgentStore._from_row(row) for row in rows]
+ for candidate in candidates:
+ if candidate.backend == archived.backend and is_builtin_default_agent(candidate):
+ return candidate
+ for candidate in candidates:
+ if candidate.backend == archived.backend:
+ return candidate
+ return candidates[0] if candidates else None
+
+ @staticmethod
+ def _effective_default_agent(conn: Any) -> Optional[VibeAgent]:
+ explicit_name = VibeAgentStore._default_agent_name(conn)
+ if explicit_name:
+ explicit = conn.execute(
+ select(agents)
+ .where(agents.c.normalized_name == normalize_agent_name(explicit_name))
+ .where(agents.c.enabled == 1)
+ .where(agents.c.archived_at.is_(None))
+ .limit(1)
+ ).mappings().first()
+ if explicit is not None:
+ return VibeAgentStore._from_row(explicit)
+
+ fallback = conn.execute(
+ select(agents)
+ .where(agents.c.normalized_name == normalize_agent_name(DEFAULT_AGENT_NAME))
+ .where(agents.c.enabled == 1)
+ .where(agents.c.archived_at.is_(None))
+ .limit(1)
+ ).mappings().first()
+ if fallback is not None:
+ return VibeAgentStore._from_row(fallback)
+
+ first_enabled = conn.execute(
+ select(agents)
+ .where(agents.c.enabled == 1)
+ .where(agents.c.archived_at.is_(None))
+ .order_by(agents.c.name)
+ .limit(1)
+ ).mappings().first()
+ return VibeAgentStore._from_row(first_enabled) if first_enabled is not None else None
+
- def import_candidates(self, candidates: Iterable[AgentImportCandidate]) -> AgentImportResult:
+ def import_candidates(
+ self,
+ candidates: Iterable[AgentImportCandidate],
+ *,
+ user_context: Any = None,
+ ) -> AgentImportResult:
imported: list[VibeAgent] = []
skipped: list[dict[str, Any]] = []
for candidate in candidates:
@@@ -1183,42 -798,30 +1603,38 @@@
def get_default_agent_name(self) -> Optional[str]:
with self.engine.connect() as conn:
- value = conn.execute(
- select(state_meta.c.value_json).where(state_meta.c.key == DEFAULT_AGENT_META_KEY).limit(1)
- ).scalar_one_or_none()
- payload = _json_loads(value, None)
- return str(payload).strip() if payload else None
+ return self._default_agent_name(conn)
- def set_default_agent_name(self, name: str) -> None:
- def set_default_agent_name(self, name: str, *, user_context: Any = None) -> None:
- agent = self.require_manageable(name, user_context=user_context)
- if not agent.enabled:
- raise ValueError(f"agent '{agent.name}' is disabled")
++ def set_default_agent_name(
++ self,
++ name: str,
++ *,
++ user_context: Any = None,
++ ) -> None:
+ normalized = normalize_agent_name(name)
++ self.require_manageable(name, user_context=user_context)
now = _utc_now_iso()
with self.engine.begin() as conn:
- conn.execute(state_meta.delete().where(state_meta.c.key == DEFAULT_AGENT_META_KEY))
- conn.execute(
- state_meta.insert().values(
- key=DEFAULT_AGENT_META_KEY,
- value_json=_json_dumps(agent.name),
- updated_at=now,
+ reserve_write_lock(conn)
+ row = conn.execute(
+ select(agents).where(agents.c.normalized_name == normalized).limit(1)
+ ).mappings().first()
+ if row is None:
+ raise AgentUnavailableError(
+ f"agent '{name}' not found", agent_name=name, reason="missing"
)
- )
+ agent = self._from_row(row)
+ if not agent.enabled or agent.archived_at is not None:
+ raise AgentUnavailableError(
+ f"agent '{agent.name}' is disabled",
+ agent_name=agent.name,
+ reason="disabled",
+ )
+ self._write_default_agent_name(conn, agent.name, now=now)
def get_default_agent(self, *, enabled_only: bool = True) -> Optional[VibeAgent]:
- name = self.get_default_agent_name()
- if name:
- agent = self.get(name)
- if agent is not None and (agent.enabled or not enabled_only):
- return agent
- fallback = self.get(DEFAULT_AGENT_NAME)
- if fallback is not None and (fallback.enabled or not enabled_only):
- return fallback
- if enabled_only:
- agents_list = self.list_agents(include_disabled=False)
- return agents_list[0] if agents_list else None
- return None
+ with self.engine.connect() as conn:
+ return resolve_effective_default_agent(conn, enabled_only=enabled_only)
@staticmethod
def _from_row(row: Any) -> VibeAgent:
diff --cc core/watches.py
index cffcefc09,a7e3db1e8..47647b44f
--- a/core/watches.py
+++ b/core/watches.py
@@@ -476,9 -341,12 +476,14 @@@ class ManagedWatchStore
session_policy: Optional[str] = None,
message: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
+ expected_enabled_agent_id: Optional[str] = None,
+ expected_reference_agent_id: Optional[str] = None,
+ user_context: Any = None,
) -> ManagedWatch:
+ from core.vibe_agents import ensure_agent_name_access
+ from storage.resource_access_service import metadata_with_resource_user_context
+
+ ensure_agent_name_access(agent_name, user_context=user_context)
watch = ManagedWatch(
id=uuid4().hex[:12],
name=name,
@@@ -498,23 -366,11 +503,23 @@@
retry_delay_seconds=retry_delay_seconds,
post_to=post_to,
deliver_key=deliver_key,
- metadata=dict(metadata or {}),
+ metadata=metadata_with_resource_user_context(metadata, user_context),
)
- return self.upsert_watch(watch)
+ return self.upsert_watch(
+ watch,
+ expected_enabled_agent_id=expected_enabled_agent_id,
+ expected_reference_agent_id=expected_reference_agent_id,
+ )
def remove_watch(self, watch_id: str) -> bool:
+ """Delete a watch; the mirror rolls back with the delete (HFR-275).
+
+ The safer direction of the same class -- an entry dropped here reads as "gone"
+ and stops the watch -- but silently, and NOT self-healing: with the row still
+ there and unchanged, ``maybe_reload`` sees no external write, so the watch the
+ user was told could not be deleted just stops until the process restarts.
+ """
+
if watch_id not in self._watches:
return False
del self._watches[watch_id]
@@@ -569,13 -417,13 +574,18 @@@
session_policy: Optional[str] = None,
message: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
+ expected_enabled_agent_id: Optional[str] = None,
+ expected_reference_agent_id: Optional[str] = None,
+ user_context: Any = None,
) -> ManagedWatch:
+ from core.vibe_agents import ensure_agent_name_access
+ from storage.resource_access_service import metadata_with_resource_user_context
+
+ ensure_agent_name_access(agent_name, user_context=user_context)
watch = self._watches[watch_id]
+ # Captured before the first mutation: the state ``vibe watch update`` read and
+ # resolved its payload from.
+ expect = self._read_state(watch)
if mode != watch.mode:
# A mode change starts a new lifecycle. Completion and failure
# metadata from the old mode remains available in run history, but
@@@ -600,21 -448,15 +610,23 @@@
watch.retry_delay_seconds = retry_delay_seconds
watch.post_to = post_to
watch.deliver_key = deliver_key
- if metadata is not None:
- watch.metadata = dict(metadata)
+ watch.metadata = metadata_with_resource_user_context(
+ metadata if metadata is not None else watch.metadata,
+ user_context,
+ )
watch.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_watch(watch.to_dict())
- return watch
- self._save()
+ if not self._write_watch(
+ watch,
+ expect,
+ expected_enabled_agent_id=expected_enabled_agent_id,
+ expected_reference_agent_id=expected_reference_agent_id,
+ ):
+ # The edit did NOT land. ``cmd_watch_update`` turns this into a non-zero
+ # exit with an error payload instead of echoing an unwritten watch.
+ raise DefinitionWriteConflict(watch_id, definition_type="watch")
+ if expected_reference_agent_id is not None:
+ self.load()
+ return self._watches[watch_id]
return watch
@staticmethod
diff --cc core/web_push_notifications.py
index 737208b64,c9db7d675..afd3a3f62
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@@ -10,9 -10,10 +10,10 @@@ from typing import An
from sqlalchemy import or_, select
-from core.backend_failure import is_backend_failure_notification
from storage import messages_service, web_push_service
from storage.models import agent_sessions, messages
+from vibe.message_types import spec_for, types_with
+ from vibe.authorization import AuthorizationContext, context_from_session_payload
logger = logging.getLogger(__name__)
@@@ -64,26 -59,12 +66,25 @@@ def maybe_notify_inbox_message(message
return
if not _is_notifiable_message(message.get("type"), message.get("metadata")):
return
- if not message.get("session_id"):
- return
+
+ # ``session_id`` used to be a hard requirement, which made this the LAST rung of
+ # the failure-notification ladder to be empty rather than the one that always
+ # resolves. A definition created from a plain CLI invocation has no caller
+ # provenance at all (``_session_creation_metadata_from_caller`` returns ``{}``
+ # for a ``None`` caller), so it has no channel to fall back to and no user to DM;
+ # an unscoped ``create_per_run`` definition can have no delivery key either. For
+ # such a definition every earlier rung is empty, and a notice with nowhere to go
+ # is a notice that is never written — for exactly the runs nobody is watching.
+ #
+ # A workspace-addressed notice needs no session because it is addressed to the
+ # workspace. Where a session IS named the deep link still points at it.
+ session_id = message.get("session_id")
+ url = f"/chat/{session_id}" if session_id else "/harness"
+ tag = f"session:{session_id}" if session_id else "harness:failure"
- # ``badge_count`` is the app-icon badge number, which is a single global
- # value — not this one session's unread count. It is computed at send time
- # (see ``_send_to_enabled_subscriptions``) so it reflects the real total
- # after the debounce delay and matches the in-app Inbox badge.
+ # ``badge_count`` is computed per subscription owner at send time, not from
+ # this one session's unread count. That keeps it current after the debounce
+ # delay and aligned with the recipient's Project-filtered Inbox.
payload = {
"title": inbox_row.get("title") or inbox_row.get("project_name") or "avibe",
"body": (message.get("text") or inbox_row.get("preview_text") or "").strip()[:240],
diff --cc docs/plans/2026-07-27-agent-organization-onboarding.md
index 000000000,187b12fcf..da4549927
mode 000000,100644..100644
--- a/docs/plans/2026-07-27-agent-organization-onboarding.md
+++ b/docs/plans/2026-07-27-agent-organization-onboarding.md
@@@ -1,0 -1,52 +1,51 @@@
+ # Agent Organization Onboarding
+
+ ## Background
+
+ Organization Resource ACL publishes only resources that already have a local
+ policy. Agents created before an Instance became Organization-managed, including
+ built-in backend Agents, therefore remain absent from the hosted Resource Access
+ inventory. Missing policies fail closed for Organization members, but owners have
+ no explicit way to register those Agents for later group publication.
+
+ ## Goal
+
+ Give the signed Instance owner an explicit, safe, and repeatable onboarding path:
+
+ - inventory every custom and built-in/system Agent from `core/vibe_agents.py`;
+ - register every missing Agent as Organization-private;
+ - preserve every existing policy and revision unchanged;
+ - publish through the shared metadata-only Resource ACL sync path; and
+ - direct owners to the hosted Resource Access console to grant selected Agents
+ to Organization groups.
+
+ ## Design
+
+ `VibeAgentStore` owns the inventory and registration transaction because the
+ Agent table is the source of truth. The service requires owner-equivalent Agent
+ management access and an active signed Organization context before writing.
+ Registration uses `ensure_resource_policy()`, whose insert-only contract prevents
+ late onboarding from replacing an already-applied control-plane revision.
+
+ The local API returns only Agent identity and ACL state: id, safe name, backend,
+ source, enabled state, access level, group ids, and revisions. It never returns a
+ prompt, Agent metadata/configuration, credentials, source paths, or execution
+ output. Publication delegates to the shared Resource ACL descriptor builder so
+ the display-name and metadata-revision behavior owned by issue #1054 remains a
+ single contract.
+
+ The Agents page renders the inventory only when onboarding is available. One
+ owner action registers all missing Agents privately. Group selection stays in
+ the existing hosted Resource Access console, which owns desired ACL revisions.
+
+ ## Verification
+
+ - Upgrade path: legacy custom and built-in Agents become private, then an editor
+ sees only the Agents selected by a newer control-plane ACL intent.
+ - Fresh install: built-in Agents and a newly created private Organization Agent
+ produce the intended editor-visible set after publication.
+ - Idempotency: rerunning onboarding does not change existing access, groups, or
+ policy/control-plane revisions.
+ - Redaction: published descriptors contain only the shared safe metadata fields.
+ - Lifecycle: create-then-delete rename and deletion converge through the next
+ full resource-index snapshot.
-
diff --cc docs/plans/2026-08-04-org-to-master-integration.md
index 6a1976c83,000000000..42c0cdaeb
mode 100644,000000..100644
--- a/docs/plans/2026-08-04-org-to-master-integration.md
+++ b/docs/plans/2026-08-04-org-to-master-integration.md
@@@ -1,50 -1,0 +1,55 @@@
+# Organization Branch Integration Into Master
+
+## Background
+
+The `org` branch contains the Organization authorization, access-control,
+management, and remote-session work that must now ship on `master`. The two
+branches have continued independently since commit `452ebd43`, so a direct
+merge produces broad conflicts across runtime, storage, CLI, UI, tests, and
+documentation.
+
+## Goal
+
+Integrate `origin/org` into the latest `origin/master` without regressing the
+current `master` architecture or weakening Organization authorization.
+
+## Resolution Contract
+
+- Keep current `master` structure, runtime lifecycle, Model Hub UI, Workbench
+ state ownership, and CI/release behavior as the architectural baseline.
+- Port Organization authorization, instance/project/resource ACLs, remote
+ session revocation, Organization management routes, and compatibility
+ normalization from `org` into that baseline.
+- Preserve fail-closed behavior for remote callers and missing or stale
+ authorization state.
+- Do not restore components or contexts deleted by `master`; move required
+ Organization behavior to their current replacements.
+- Reconcile configuration, migrations, API contracts, i18n, lockfiles, tests,
+ and scenario metadata together rather than selecting one branch wholesale.
+- Keep the Organization navigation entry hidden while preserving direct
+ Organization routes and functionality.
+
+## Verification
+
+- Conflict markers and unmerged index entries are absent.
- - Changed Python files pass Ruff.
- - Focused authorization, session, remote-access, storage, watches, and CLI
- tests pass.
- - Frontend tests, lint, theme validation, and production build pass.
++- All 145 changed Python files pass Ruff; `uv lock --check` passes.
++- Focused authorization, session, remote-access, storage, watches, CLI, Memory,
++ Show Pages, Web Push, and scenario tests pass. The largest final groups were
++ 237 Show Pages, 329 Organization/Memory, 326 Harness/CLI/scenario, and 170
++ remote HTTP/Project ACL tests.
++- Frontend lint, theme validation, and production build pass. Vitest passes
++ 1476 of 1477 tests locally; the remaining macOS-only symlink cleanup failure
++ in `scripts/lintPolicy.test.mjs` is unchanged from `origin/master` and remains
++ covered by Linux CI.
+- Parser-backed scenario coverage remains aligned with auth/setup CLI examples.
+- GitHub PR CI passes on the integrated head and the current Codex review has
+ zero unresolved threads.
+
+## Todo
+
+- [x] Refresh `origin/master` and `origin/org` and record the live divergence.
- - [ ] Merge `origin/org` into the integration branch.
- - [ ] Resolve conflicts according to the resolution contract.
- - [ ] Run focused and broad validation.
++- [x] Merge `origin/org` into the integration branch.
++- [x] Resolve conflicts according to the resolution contract.
++- [x] Run focused and broad validation.
+- [ ] Push a ready PR targeting `master`.
+- [ ] Close CI and Codex review findings on the current PR head.
diff --cc modules/agents/opencode/agent.py
index 03ab624b5,a2c536f63..a7778ac49
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@@ -19,18 -16,13 +19,22 @@@ import aiohtt
from core.avibe_cloud import avibe_cloud_url_available
from core.backend_failure import emit_backend_failure
-from core.message_output import terminal_output_for
+from core.message_output import stop_output_for, terminal_output_for
+from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.resource_governance import governor_from_controller
+from core.services.agent_steering import (
+ ActiveSteerTarget,
+ SteerOutcome,
+ SteerReconcileRequest,
+ SteerRequest,
+ SteerResult,
+ result as steer_result,
+)
- from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
+ from core.system_prompt_injection import (
+ build_system_prompt_injection,
+ get_enabled_agents_for_prompt,
+ memory_cli_prompt_admitted,
+ )
from modules.agents.base import AgentRequest, BaseAgent
from modules.agents.model_hub import (
ModelHubLaunch,
diff --cc modules/im/slack.py
index aa3d22982,e31381dbb..2067932e0
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@@ -2000,9 -1976,9 +2003,10 @@@ class SlackBot(BaseIMClient)
"bot_user_id": bot_user_id,
"bot_mention": bot_mention,
"control_text": route_text,
+ "normalized_user_text": normalized_user_text,
},
files=file_attachments,
+ is_ordinary_text=is_ordinary_slack_text(event, file_attachments) and not has_shared_content,
)
if handled_bot_mention_in_message_event and self.settings_manager and thread_id:
@@@ -2097,9 -2070,9 +2103,10 @@@
"bot_user_id": bot_user_id,
"bot_mention": bot_mention,
"control_text": route_text,
+ "normalized_user_text": normalized_user_text,
},
files=file_attachments,
+ is_ordinary_text=is_ordinary_slack_text(event, file_attachments) and not bool(shared_text),
)
# Mark thread as active only when the mention carries actionable content.
diff --cc storage/alembic/versions/20260804_0046_merge_org_master.py
index 000000000,000000000..3fb9b82dc
new file mode 100644
--- /dev/null
+++ b/storage/alembic/versions/20260804_0046_merge_org_master.py
@@@ -1,0 -1,0 +1,22 @@@
++"""merge Organization schema into the master migration line
++
++Revision ID: 20260804_0046
++Revises: 20260725_0038, 20260802_0045
++Create Date: 2026-08-04
++"""
++
++from __future__ import annotations
++
++
++revision = "20260804_0046"
++down_revision = ("20260725_0038", "20260802_0045")
++branch_labels = None
++depends_on = None
++
++
++def upgrade() -> None:
++ pass
++
++
++def downgrade() -> None:
++ pass
diff --cc storage/message_deliveries.py
index c47722e79,000000000..876ebd2e8
mode 100644,000000..100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@@ -1,2008 -1,0 +1,2076 @@@
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Iterable
+
+from sqlalchemy import Select, and_, func, or_, select, update
+from sqlalchemy.engine import Connection
+
+from storage.delivery_states import (
+ CLAIMABLE_QUEUE_STATES,
+ FENCE_STATES,
+ RUN_CANCEL_RETIRE_STATES,
+ policy_for,
+)
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ message_deliveries,
+ messages,
+ session_turns,
+ show_session_events,
+)
+
+
+TURN_OWNER_STATES = ("starting", "active")
+WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"
+WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"
++WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA = "_web_push_authorization_contexts"
++MEMORY_USER_ID_METADATA = "_memory_user_id"
++MEMORY_ORDINARY_TEXT_METADATA = "_memory_ordinary_text"
++MEMORY_CLI_ADMITTED_METADATA = "_memory_cli_admitted"
+
+
+def utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def turn_now_iso() -> str:
+ """Preserve the true order of Turn lifecycle boundaries."""
+
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+
+
+def new_turn_id() -> str:
+ return f"trn_{uuid.uuid4().hex}"
+
+
+def new_delivery_id() -> str:
+ return f"msg_{int(time.time() * 1_000_000):015x}{uuid.uuid4().hex[:8]}"
+
+
+def new_attempt_id() -> str:
+ return f"atm_{uuid.uuid4().hex}"
+
+
+def _canonical_json(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
+
+
+def _sha256_text(value: str) -> str:
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
+
+
+def native_dedupe_key(
+ platform: str,
+ native_message_id: str | None,
+ *,
+ scope_id: str | None = None,
+) -> str | None:
+ """Return the canonical live dedupe identity for a native submission."""
+
+ native_id = str(native_message_id or "").strip()
+ if not native_id:
+ return None
+ native_scope = str(scope_id or "").strip()
+ if not native_scope:
+ return f"{platform}:{native_id}"
+ return f"{platform}:scope:{len(native_scope)}:{native_scope}:{native_id}"
+
+
+def _json_object(value: Any) -> dict[str, Any]:
+ if isinstance(value, dict):
+ return dict(value)
+ if not value:
+ return {}
+ try:
+ parsed = json.loads(str(value))
+ except (TypeError, ValueError):
+ return {}
+ return dict(parsed) if isinstance(parsed, dict) else {}
+
+
+def _history(value: Any) -> dict[str, Any]:
+ parsed = _json_object(value)
+ events = parsed.get("events")
+ return {
+ "version": 1,
+ "events": list(events) if isinstance(events, list) else [],
+ }
+
+
+def _append_history_value(value: Any, event: dict[str, Any]) -> str:
+ history = _history(value)
+ history["events"].append({"at": utc_now_iso(), **event})
+ return _canonical_json(history)
+
+
+def message_snapshot(
+ *,
+ scope_id: str | None,
+ session_id: str,
+ platform: str,
+ author: str,
+ source: str | None,
+ message_type: str | None = None,
+ text: str | None = None,
+ content: dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
+ author_id: str | None = None,
+ author_name: str | None = None,
+ native_message_id: str | None = None,
+ parent_native_message_id: str | None = None,
+ read_at: str | None = None,
+) -> dict[str, Any]:
+ """Build the immutable Message candidate held before native acceptance."""
+
+ body = dict(content or {})
+ if text is not None:
+ body.setdefault("text", text)
+ resolved_type = message_type or ("user" if author == "user" else "assistant")
+ if source == "harness" and author == "user" and resolved_type == "user":
+ author = "harness"
+ resolved_type = "harness"
+ return {
+ "scope_id": scope_id,
+ "session_id": session_id,
+ "platform": platform,
+ "author": author,
+ "type": resolved_type,
+ "author_id": author_id,
+ "author_name": author_name,
+ "source": source,
+ "native_message_id": native_message_id,
+ "parent_native_message_id": parent_native_message_id,
+ "content_text": text if text is not None else body.get("text") or None,
+ "content_json": _canonical_json(body),
+ "metadata_json": _canonical_json(metadata or {}),
+ "read_at": read_at,
+ }
+
+
+def _one(conn: Connection, query: Select[Any]) -> dict[str, Any] | None:
+ row = conn.execute(query).mappings().first()
+ return dict(row) if row else None
+
+
+def get_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ return _one(conn, select(session_turns).where(session_turns.c.id == turn_id))
+
+
+def get_delivery(conn: Connection, delivery_id: str) -> dict[str, Any] | None:
+ return _one(conn, select(message_deliveries).where(message_deliveries.c.id == delivery_id))
+
+
+def get_delivery_by_dedupe(conn: Connection, dedupe_key: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(message_deliveries).where(message_deliveries.c.dedupe_key == dedupe_key),
+ )
+
+
+def get_delivery_by_native_identity(
+ conn: Connection,
+ *,
+ platform: str,
+ native_message_id: str,
+ scope_id: str | None,
+ session_id: str | None = None,
+ normalize_legacy: bool = False,
+) -> dict[str, Any] | None:
+ """Resolve one native event, including the pre-0045 unscoped key."""
+
+ canonical_key = native_dedupe_key(
+ platform,
+ native_message_id,
+ scope_id=scope_id,
+ )
+ if canonical_key is None:
+ return None
+ delivery = get_delivery_by_dedupe(conn, canonical_key)
+ if delivery is not None or scope_id is None:
+ return delivery
+
+ legacy_key = native_dedupe_key(platform, native_message_id)
+ if legacy_key is None or legacy_key == canonical_key:
+ return None
+ delivery = get_delivery_by_dedupe(conn, legacy_key)
+ if delivery is None:
+ return None
+ if session_id is not None and delivery["session_id"] != session_id:
+ return None
+
+ delivery_scope = _json_object(delivery.get("snapshot_json")).get("scope_id")
+ if delivery_scope is None and delivery.get("message_id"):
+ delivery_scope = conn.execute(
+ select(messages.c.scope_id)
+ .where(messages.c.id == delivery["message_id"])
+ .limit(1)
+ ).scalar_one_or_none()
+ if delivery_scope != scope_id:
+ return None
+ if not normalize_legacy:
+ return delivery
+
+ result = conn.execute(
+ update(message_deliveries)
+ .where(message_deliveries.c.id == delivery["id"])
+ .where(message_deliveries.c.dedupe_key == legacy_key)
+ .values(dedupe_key=canonical_key)
+ )
+ if result.rowcount != 1:
+ return get_delivery_by_dedupe(conn, canonical_key)
+ delivery["dedupe_key"] = canonical_key
+ return delivery
+
+
+def delivery_admission_context(delivery: dict[str, Any]) -> dict[str, Any]:
+ """Return immutable operational context captured by the admission event."""
+
+ try:
+ history = json.loads(str(delivery.get("delivery_history_json") or "{}"))
+ except (TypeError, ValueError, json.JSONDecodeError):
+ return {}
+ events = history.get("events") if isinstance(history, dict) else None
+ for event in events or []:
+ if not isinstance(event, dict) or event.get("kind") != "admission":
+ continue
+ context = event.get("context")
+ return dict(context) if isinstance(context, dict) else {}
+ return {}
+
+
+def active_turn(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(session_turns)
+ .where(session_turns.c.session_id == session_id)
+ .where(session_turns.c.state.in_(TURN_OWNER_STATES))
+ .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
+ .limit(1),
+ )
+
+
+def ordering_head(
+ conn: Connection,
+ session_id: str,
+ *,
+ include_claimable: bool = True,
+) -> dict[str, Any] | None:
+ """Oldest eligible queued row or unresolved ordering fence."""
+
+ predicates = [message_deliveries.c.state.in_(FENCE_STATES)]
+ if include_claimable:
+ predicates.append(
+ and_(
+ message_deliveries.c.priority == "p3",
+ message_deliveries.c.state.in_(CLAIMABLE_QUEUE_STATES),
+ )
+ )
+
+ return _one(
+ conn,
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(or_(*predicates))
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ .limit(1),
+ )
+
+
+def claimable_fifo_head(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ head = ordering_head(conn, session_id)
+ return head if head is not None and head["state"] == "queued" else None
+
+
+def claimable_fifo_prefix(conn: Connection, session_id: str) -> list[dict[str, Any]]:
+ """Queued prefix before the first unresolved ordering fence."""
+
+ rows = conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(
+ or_(
+ and_(
+ message_deliveries.c.priority == "p3",
+ message_deliveries.c.state == "queued",
+ ),
+ message_deliveries.c.state.in_(FENCE_STATES),
+ )
+ )
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ prefix: list[dict[str, Any]] = []
+ for row in rows:
+ current = dict(row)
+ if current["state"] != "queued":
+ break
+ prefix.append(delivery_payload(current))
+ return prefix
+
+
+def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
+ rows = conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state == "queued")
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ return [delivery_payload(dict(row)) for row in rows]
+
+
+def delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
+ snapshot = _json_object(row.get("snapshot_json"))
+ content = _json_object(snapshot.get("content_json"))
+ metadata = _json_object(snapshot.get("metadata_json"))
+ return {
+ "id": row["id"],
+ "delivery_id": row["id"],
+ "message_id": row.get("message_id"),
+ "turn_id": row.get("turn_id"),
+ "turn_role": row.get("turn_role"),
+ "turn_position": row.get("turn_position"),
+ "session_id": row.get("session_id"),
+ "scope_id": snapshot.get("scope_id"),
+ "platform": snapshot.get("platform"),
+ "author": snapshot.get("author"),
+ "type": snapshot.get("type"),
+ "source": snapshot.get("source"),
+ "author_id": snapshot.get("author_id"),
+ "author_name": snapshot.get("author_name"),
+ "native_message_id": snapshot.get("native_message_id"),
+ "parent_native_message_id": snapshot.get("parent_native_message_id"),
+ "text": snapshot.get("content_text") or content.get("text") or "",
+ "content": content,
+ "metadata": metadata,
+ "dispatch_text": row.get("dispatch_text") or "",
+ "priority": row.get("priority"),
+ "state": row.get("state"),
+ "created_at": row.get("submitted_at"),
+ "submitted_at": row.get("submitted_at"),
+ "updated_at": row.get("updated_at"),
+ "retired_at": row.get("retired_at"),
+ "version": row.get("version"),
+ }
+
+
++def public_delivery_payload(row: dict[str, Any]) -> dict[str, Any]:
++ """Return a Delivery payload without server-owned identity metadata."""
++
++ payload = (
++ dict(row)
++ if "content" in row and "metadata" in row
++ else delivery_payload(row)
++ )
++ metadata = payload.get("metadata")
++ if isinstance(metadata, dict):
++ payload["metadata"] = {
++ key: value
++ for key, value in metadata.items()
++ if not str(key).startswith(("_web_push_", "_memory_"))
++ }
++ return payload
++
++
+_MESSAGE_MERGE_IDENTITY_FIELDS = (
+ "scope_id",
+ "platform",
+ "author",
+ "type",
+ "source",
+ "author_id",
+ "author_name",
+ "parent_native_message_id",
+)
+
+
+def message_merge_identity(value: dict[str, Any]) -> tuple[Any, ...]:
+ """Return the Message fields that must stay singular after batching."""
+
+ return tuple(value.get(field) for field in _MESSAGE_MERGE_IDENTITY_FIELDS)
+
+
+def has_substantive_input(
+ dispatch_text: str | None,
+ *,
+ has_attachments: bool = False,
+) -> bool:
+ """Whether an admission contains text or a previously resolved attachment."""
+
+ return bool(str(dispatch_text or "").strip()) or has_attachments
+
+
+def has_substantive_content(
+ delivery: dict[str, Any],
+ *,
+ has_attachments: bool = False,
+) -> bool:
+ """Whether a reserved Delivery can produce a meaningful backend input."""
+
+ return has_substantive_input(
+ delivery.get("dispatch_text"),
+ has_attachments=has_attachments,
+ )
+
+
+def list_queued_page(conn: Connection, session_id: str, *, page_request: Any) -> Any:
+ from storage.pagination import page_result_from_limit_plus_one
+
+ query = (
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state == "queued")
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ .limit(page_request.limit + 1)
+ .offset(page_request.offset)
+ )
+ return page_result_from_limit_plus_one(
+ [delivery_payload(dict(row)) for row in conn.execute(query).mappings()],
+ page_request,
+ )
+
+
+def insert_turn(
+ conn: Connection,
+ *,
+ turn_id: str,
+ session_id: str,
+ initial_delivery_id: str,
+ state: str,
+ backend: str,
+ start_attempt_id: str | None = None,
+ dispatch_text: str | None = None,
+ now: str | None = None,
+) -> dict[str, Any]:
+ timestamp = now or turn_now_iso()
+ has_started = state in {"starting", "active"}
+ resolved_attempt_id = start_attempt_id or new_attempt_id() if has_started else None
+ resolved_dispatch_text = dispatch_text if has_started else None
+ if has_started and resolved_dispatch_text is None:
+ initial = get_delivery(conn, initial_delivery_id)
+ resolved_dispatch_text = str((initial or {}).get("dispatch_text") or "")
+ values = {
+ "id": turn_id,
+ "session_id": session_id,
+ "initial_delivery_id": initial_delivery_id,
+ "state": state,
+ "backend": backend,
+ "runtime_key": None,
+ "runtime_turn_id": None,
+ "native_turn_id": None,
+ "start_attempt_id": resolved_attempt_id,
+ "start_receipt_outcome": "accepted" if state == "active" else None,
+ "start_receipt_json": (
+ _canonical_json({"kind": "seeded_active"}) if state == "active" else "{}"
+ ),
+ "dispatch_text": resolved_dispatch_text,
+ "dispatch_sha256": (
+ _sha256_text(resolved_dispatch_text or "") if has_started else None
+ ),
+ "terminal_outcome": None,
+ "settled_by": None,
+ "terminal_evidence_kind": None,
+ "terminal_evidence_json": "{}",
+ "control_state": None,
+ "control_mode": None,
+ "control_attempt_id": None,
+ "control_expected_native_turn_id": None,
+ "control_receipt_outcome": None,
+ "control_receipt_json": "{}",
+ "control_successor_delivery_id": None,
+ "control_successor_turn_id": None,
+ "version": 1,
+ "created_at": timestamp,
+ "updated_at": timestamp,
+ "started_at": timestamp if has_started else None,
+ "terminal_at": None,
+ }
+ conn.execute(session_turns.insert().values(**values))
+ return values
+
+
+def insert_delivery(
+ conn: Connection,
+ *,
+ delivery_id: str,
+ session_id: str,
+ priority: str,
+ state: str,
+ snapshot: dict[str, Any],
+ dispatch_text: str,
+ dedupe_key: str | None = None,
+ turn_id: str | None = None,
+ current_attempt_id: str | None = None,
+ current_attempt_kind: str | None = None,
+ current_target_turn_id: str | None = None,
+ current_expected_native_turn_id: str | None = None,
+ current_receipt_outcome: str | None = None,
+ current_receipt: dict[str, Any] | None = None,
+ history_event: dict[str, Any] | None = None,
+ now: str | None = None,
+) -> dict[str, Any]:
+ timestamp = now or utc_now_iso()
+ serialized_snapshot = _canonical_json(snapshot)
+ history = {"version": 1, "events": []}
+ if history_event:
+ history["events"].append({"at": timestamp, **history_event})
+ values = {
+ "id": delivery_id,
+ "session_id": session_id,
+ "message_id": None,
+ "priority": priority,
+ "state": state,
+ "snapshot_json": serialized_snapshot,
+ "snapshot_sha256": _sha256_text(serialized_snapshot),
+ "dispatch_text": dispatch_text,
+ "dispatch_sha256": _sha256_text(dispatch_text),
+ "dedupe_key": dedupe_key,
+ "turn_id": turn_id,
+ "turn_role": None,
+ "turn_position": None,
+ "current_attempt_id": current_attempt_id,
+ "current_attempt_kind": current_attempt_kind,
+ "current_target_turn_id": current_target_turn_id,
+ "current_expected_native_turn_id": current_expected_native_turn_id,
+ "current_receipt_outcome": current_receipt_outcome,
+ "current_receipt_json": _canonical_json(current_receipt or {}),
+ "current_attempt_opened_at": timestamp if current_attempt_id else None,
+ "delivery_history_json": _canonical_json(history),
+ "version": 1,
+ "submitted_at": timestamp,
+ "updated_at": timestamp,
+ "materialized_at": None,
+ "retired_at": None,
+ }
+ conn.execute(message_deliveries.insert().values(**values))
+ return values
+
+
+def enqueue_queued(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ session_id: str,
+ text: str,
+ dispatch_text: str | None = None,
+ platform: str = "avibe",
+ author: str = "user",
+ source: str | None = "user",
+ message_type: str | None = None,
+ author_id: str | None = None,
+ author_name: str | None = None,
+ native_message_id: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ now: str | None = None,
+) -> dict[str, Any]:
+ """Persist one P3 submission without creating a transcript Message."""
+
+ delivery_id = new_delivery_id()
+ row = insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="queued",
+ snapshot=message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform=platform,
+ author=author,
+ source=source,
+ message_type=message_type,
+ text=text,
+ metadata=metadata,
+ author_id=author_id,
+ author_name=author_name,
+ native_message_id=native_message_id,
+ ),
+ dispatch_text=text if dispatch_text is None else dispatch_text,
+ dedupe_key=native_dedupe_key(
+ platform,
+ native_message_id,
+ scope_id=scope_id,
+ ),
+ history_event={"kind": "submitted", "priority": "p3"},
+ now=now,
+ )
+ return delivery_payload(row)
+
+
+def cas_turn(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ expected_states: Iterable[str],
+ values: dict[str, Any],
+) -> dict[str, Any] | None:
+ next_values = {**values, "version": expected_version + 1, "updated_at": utc_now_iso()}
+ if next_values.get("state") == "starting" and "started_at" not in next_values:
+ next_values["started_at"] = turn_now_iso()
+ result = conn.execute(
+ update(session_turns)
+ .where(session_turns.c.id == turn_id)
+ .where(session_turns.c.version == expected_version)
+ .where(session_turns.c.state.in_(tuple(expected_states)))
+ .values(**next_values)
+ )
+ return get_turn(conn, turn_id) if result.rowcount == 1 else None
+
+
+def cas_delivery(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ expected_states: Iterable[str],
+ values: dict[str, Any],
+ history_event: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ current = get_delivery(conn, delivery_id)
+ if current is None or int(current["version"]) != expected_version:
+ return None
+ next_values = dict(values)
+ if history_event is not None:
+ next_values["delivery_history_json"] = _append_history_value(
+ current.get("delivery_history_json"),
+ history_event,
+ )
+ next_values.update(version=expected_version + 1, updated_at=utc_now_iso())
+ result = conn.execute(
+ update(message_deliveries)
+ .where(message_deliveries.c.id == delivery_id)
+ .where(message_deliveries.c.version == expected_version)
+ .where(message_deliveries.c.state.in_(tuple(expected_states)))
+ .values(**next_values)
+ )
+ return get_delivery(conn, delivery_id) if result.rowcount == 1 else None
+
+
+def open_start_attempt(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ turn_id: str,
+ attempt_id: str,
+) -> dict[str, Any] | None:
+ turn = get_turn(conn, turn_id)
+ delivery = get_delivery(conn, delivery_id)
+ if turn is None or delivery is None or turn["state"] != "starting":
+ return None
+ if turn.get("initial_delivery_id") != delivery_id:
+ return None
+ updated_turn = cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ expected_states=("starting",),
+ values={
+ "start_attempt_id": attempt_id,
+ "dispatch_text": str(delivery.get("dispatch_text") or ""),
+ "dispatch_sha256": _sha256_text(str(delivery.get("dispatch_text") or "")),
+ },
+ )
+ if updated_turn is None:
+ return None
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=("reserved", "queued", "interrupt_waiting"),
+ values={
+ "state": "claimed",
+ "turn_id": turn_id,
+ "turn_role": "initial",
+ "turn_position": 0,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": utc_now_iso(),
+ },
+ history_event={"kind": "start", "attempt_id": attempt_id, "turn_id": turn_id, "outcome": "opened"},
+ )
+
+
+def claim_start_batch(
+ conn: Connection,
+ *,
+ turn_id: str,
+ session_id: str,
+ backend: str,
+ deliveries: list[dict[str, Any]],
+ dispatch_text: str,
+ attempt_id: str | None = None,
+) -> dict[str, Any]:
+ """Claim one ordered Delivery segment for exactly one native start."""
+
+ if not deliveries:
+ raise ValueError("a Turn requires at least one Delivery")
+ resolved_attempt_id = attempt_id or new_attempt_id()
+ turn = insert_turn(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ initial_delivery_id=str(deliveries[0]["id"]),
+ state="starting",
+ backend=backend,
+ start_attempt_id=resolved_attempt_id,
+ dispatch_text=dispatch_text,
+ )
+ claimed: list[dict[str, Any]] = []
+ for position, delivery in enumerate(deliveries):
+ row = cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved", "queued", "interrupt_waiting"),
+ values={
+ "state": "claimed",
+ "turn_id": turn_id,
+ "turn_role": "initial",
+ "turn_position": position,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={
+ "kind": "start",
+ "attempt_id": resolved_attempt_id,
+ "turn_id": turn_id,
+ "position": position,
+ "outcome": "claimed",
+ },
+ )
+ if row is None:
+ raise RuntimeError("Delivery batch claim lost after writer reservation")
+ claimed.append(row)
+ return {"turn": turn, "deliveries": claimed}
+
+
+def activate_waiting_successor(
+ conn: Connection,
+ *,
+ turn: dict[str, Any],
+ delivery: dict[str, Any],
+) -> dict[str, Any] | None:
+ if (
+ turn.get("state") != "waiting"
+ or delivery.get("state") != "interrupt_waiting"
+ or delivery.get("turn_id") != turn.get("id")
+ ):
+ return None
+ attempt_id = new_attempt_id()
+ dispatch_text = str(delivery.get("dispatch_text") or "")
+ started = cas_turn(
+ conn,
+ str(turn["id"]),
+ expected_version=int(turn["version"]),
+ expected_states=("waiting",),
+ values={
+ "state": "starting",
+ "start_attempt_id": attempt_id,
+ "start_receipt_outcome": None,
+ "start_receipt_json": "{}",
+ "dispatch_text": dispatch_text,
+ "dispatch_sha256": _sha256_text(dispatch_text),
+ },
+ )
+ if started is None:
+ return None
+ claimed = cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("interrupt_waiting",),
+ values={"state": "claimed"},
+ history_event={
+ "kind": "start",
+ "attempt_id": attempt_id,
+ "turn_id": turn["id"],
+ "position": 0,
+ "outcome": "claimed_after_interrupt",
+ },
+ )
+ if claimed is None:
+ raise RuntimeError("waiting successor Delivery claim lost")
+ return started
+
+
+def open_steer_attempt(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ turn_id: str,
+ attempt_id: str,
+ expected_native_turn_id: str,
+) -> dict[str, Any] | None:
+ current = get_delivery(conn, delivery_id)
+ if (
+ current is not None
+ and current.get("state") == "pending_steer"
+ and current.get("current_attempt_id") != attempt_id
+ ):
+ return None
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=("reserved", "queued", "pending_steer"),
+ values={
+ "state": "steering",
+ "current_attempt_id": attempt_id,
+ "current_attempt_kind": "steer",
+ "current_target_turn_id": turn_id,
+ "current_expected_native_turn_id": expected_native_turn_id,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": utc_now_iso(),
+ },
+ history_event={
+ "kind": "steer",
+ "attempt_id": attempt_id,
+ "turn_id": turn_id,
+ "expected_native_turn_id": expected_native_turn_id,
+ "outcome": "opened",
+ },
+ )
+
+
+def open_steer_attempt_batch(
+ conn: Connection,
+ *,
+ deliveries: list[dict[str, Any]],
+ turn_id: str,
+ attempt_id: str,
+ expected_native_turn_id: str,
+) -> list[dict[str, Any]]:
+ """Claim one ordered queue segment for one native steer call."""
+
+ claimed: list[dict[str, Any]] = []
+ for delivery in deliveries:
+ saved = open_steer_attempt(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ turn_id=turn_id,
+ attempt_id=attempt_id,
+ expected_native_turn_id=expected_native_turn_id,
+ )
+ if saved is None:
+ raise RuntimeError("Delivery steer batch claim lost after writer reservation")
+ claimed.append(saved)
+ return claimed
+
+
+def open_pending_steer_batch(
+ conn: Connection,
+ *,
+ deliveries: list[dict[str, Any]],
+ turn_id: str,
+ attempt_id: str,
+) -> list[dict[str, Any]]:
+ pending: list[dict[str, Any]] = []
+ for delivery in deliveries:
+ saved = cas_delivery(
+ conn,
+ str(delivery["id"]),
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved", "queued"),
+ values={
+ "state": "pending_steer",
+ "current_attempt_id": attempt_id,
+ "current_attempt_kind": "steer",
+ "current_target_turn_id": turn_id,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": utc_now_iso(),
+ },
+ history_event={
+ "kind": "steer",
+ "attempt_id": attempt_id,
+ "turn_id": turn_id,
+ "outcome": "pending_native_identity",
+ },
+ )
+ if saved is None:
+ raise RuntimeError("Delivery pending-steer batch claim lost")
+ pending.append(saved)
+ return pending
+
+
+def bind_native_start(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ runtime_key: str | None,
+ runtime_turn_id: str | None,
+ native_turn_id: str | None,
+) -> dict[str, Any] | None:
+ turn = get_turn(conn, turn_id)
+ if turn is None:
+ return None
+ for column, observed in (
+ ("runtime_key", runtime_key),
+ ("runtime_turn_id", runtime_turn_id),
+ ("native_turn_id", native_turn_id),
+ ):
+ persisted = str(turn.get(column) or "").strip()
+ candidate = str(observed or "").strip()
+ if persisted and candidate and persisted != candidate:
+ return None
+ return cas_turn(
+ conn,
+ turn_id,
+ expected_version=expected_version,
+ expected_states=("starting", "active"),
+ values={
+ "state": "active",
+ "runtime_key": runtime_key or turn.get("runtime_key"),
+ "runtime_turn_id": runtime_turn_id or turn.get("runtime_turn_id"),
+ "native_turn_id": native_turn_id or turn.get("native_turn_id"),
+ "start_receipt_outcome": "accepted",
+ "start_receipt_json": _canonical_json({"kind": "native_start"}),
+ "started_at": turn.get("started_at") or turn_now_iso(),
+ },
+ )
+
+
+def rebind_restored_native_generation(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ expected_native_turn_id: str,
+ restored_native_turn_id: str,
+) -> dict[str, Any] | None:
+ """Rotate one restored runtime generation and every unresolved exact target."""
+
+ turn = get_turn(conn, turn_id)
+ if (
+ turn is None
+ or turn["state"] != "active"
+ or turn.get("start_receipt_outcome") != "accepted"
+ or int(turn["version"]) != expected_version
+ or str(turn.get("native_turn_id") or "") != expected_native_turn_id
+ or not restored_native_turn_id
+ or restored_native_turn_id == expected_native_turn_id
+ ):
+ return None
+ turn_values: dict[str, Any] = {"native_turn_id": restored_native_turn_id}
+ if (
+ turn.get("control_state")
+ in {"pending", "interrupting", "waiting_terminal", "reconciling"}
+ and str(turn.get("control_expected_native_turn_id") or "")
+ == expected_native_turn_id
+ ):
+ turn_values["control_expected_native_turn_id"] = restored_native_turn_id
+ rebound = cas_turn(
+ conn,
+ turn_id,
+ expected_version=expected_version,
+ expected_states=("active",),
+ values=turn_values,
+ )
+ if rebound is None:
+ return None
+
+ attempts = list(
+ conn.execute(
+ select(message_deliveries).where(
+ message_deliveries.c.current_target_turn_id == turn_id,
+ message_deliveries.c.state.in_(("steering", "reconciling_steer")),
+ message_deliveries.c.current_expected_native_turn_id
+ == expected_native_turn_id,
+ )
+ ).mappings()
+ )
+ for attempt in attempts:
+ saved = cas_delivery(
+ conn,
+ str(attempt["id"]),
+ expected_version=int(attempt["version"]),
+ expected_states=(str(attempt["state"]),),
+ values={
+ "current_expected_native_turn_id": restored_native_turn_id,
+ },
+ history_event={
+ "kind": "native_generation_rebind",
+ "attempt_id": attempt.get("current_attempt_id"),
+ "turn_id": turn_id,
+ "previous_native_turn_id": expected_native_turn_id,
+ "restored_native_turn_id": restored_native_turn_id,
+ },
+ )
+ if saved is None:
+ raise RuntimeError("restored native generation lost a Delivery attempt CAS")
+ return rebound
+
+
+def mark_start_unknown(
+ conn: Connection,
+ turn_id: str,
+ *,
+ expected_version: int,
+ receipt: dict[str, Any],
+) -> dict[str, Any] | None:
+ return cas_turn(
+ conn,
+ turn_id,
+ expected_version=expected_version,
+ expected_states=("starting",),
+ values={
+ "start_receipt_outcome": "unknown",
+ "start_receipt_json": _canonical_json(receipt),
+ },
+ )
+
+
+def _verified_snapshot(delivery: dict[str, Any]) -> dict[str, Any]:
+ snapshot_json = str(delivery.get("snapshot_json") or "")
+ if not snapshot_json or _sha256_text(snapshot_json) != delivery.get("snapshot_sha256"):
+ raise RuntimeError("Delivery snapshot integrity check failed")
+ snapshot = _json_object(snapshot_json)
+ required = {"session_id", "platform", "author", "type", "content_json", "metadata_json"}
+ if not required <= set(snapshot):
+ raise RuntimeError("Delivery snapshot is incomplete")
+ return snapshot
+
+
+def _insert_message(
+ conn: Connection,
+ *,
+ message_id: str,
+ snapshot: dict[str, Any],
+ accepted_at: str,
+) -> None:
+ existing = conn.execute(select(messages).where(messages.c.id == message_id)).mappings().first()
+ values = {
+ "id": message_id,
+ "scope_id": snapshot.get("scope_id"),
+ "session_id": snapshot["session_id"],
+ "platform": snapshot["platform"],
+ "author": snapshot["author"],
+ "type": snapshot["type"],
+ "author_id": snapshot.get("author_id"),
+ "author_name": snapshot.get("author_name"),
+ "source": snapshot.get("source"),
+ "native_message_id": snapshot.get("native_message_id"),
+ "parent_native_message_id": snapshot.get("parent_native_message_id"),
+ "content_text": snapshot.get("content_text"),
+ "content_json": snapshot["content_json"],
+ "metadata_json": snapshot["metadata_json"],
+ "created_at": snapshot.get("created_at") or accepted_at,
+ "updated_at": accepted_at,
+ "delivered_at": accepted_at,
+ "read_at": snapshot.get("read_at"),
+ }
+ if existing is None:
+ conn.execute(messages.insert().values(**values))
+ return
+ immutable = tuple(key for key in values if key not in {"updated_at", "delivered_at"})
+ if any(existing[key] != values[key] for key in immutable):
+ raise RuntimeError("Delivery Message identity collided with different content")
+
+
+def _merged_initial_snapshot(deliveries: list[dict[str, Any]]) -> dict[str, Any]:
+ snapshots = [_verified_snapshot(delivery) for delivery in deliveries]
+ expected_identity = message_merge_identity(snapshots[0])
+ if any(message_merge_identity(snapshot) != expected_identity for snapshot in snapshots[1:]):
+ raise RuntimeError("Delivery batch contains incompatible Message identities")
+ first = dict(snapshots[0])
+ first["created_at"] = deliveries[0]["submitted_at"]
+ contents = [_json_object(snapshot.get("content_json")) for snapshot in snapshots]
+ texts = [str(snapshot.get("content_text") or "") for snapshot in snapshots]
+ visible_text = "\n".join(text for text in texts if text)
+ attachments = [
+ attachment
+ for content in contents
+ for attachment in (content.get("attachments") or [])
+ ]
+ merged_content = dict(contents[0])
+ if visible_text:
+ merged_content["text"] = visible_text
+ elif "text" in merged_content:
+ merged_content.pop("text", None)
+ if attachments:
+ merged_content["attachments"] = attachments
+ metadata = _json_object(first.get("metadata_json"))
+ web_push_user_keys: list[str] = []
++ authorization_contexts: dict[str, dict[str, Any]] = {}
++ memory_user_ids: list[str] = []
++ memory_metadata_present = False
++ memory_ordinary_text = True
++ memory_cli_admitted = True
+ for snapshot in snapshots:
+ snapshot_metadata = _json_object(snapshot.get("metadata_json"))
++ memory_metadata_present = memory_metadata_present or any(
++ key in snapshot_metadata
++ for key in (
++ MEMORY_USER_ID_METADATA,
++ MEMORY_ORDINARY_TEXT_METADATA,
++ MEMORY_CLI_ADMITTED_METADATA,
++ )
++ )
++ memory_user_id = str(snapshot_metadata.get(MEMORY_USER_ID_METADATA) or "").strip()
++ if memory_user_id and memory_user_id not in memory_user_ids:
++ memory_user_ids.append(memory_user_id)
++ memory_ordinary_text = memory_ordinary_text and (
++ snapshot_metadata.get(MEMORY_ORDINARY_TEXT_METADATA) is True
++ )
++ memory_cli_admitted = memory_cli_admitted and (
++ snapshot_metadata.get(MEMORY_CLI_ADMITTED_METADATA) is True
++ )
+ values = [snapshot_metadata.get(WEB_PUSH_USER_KEY_METADATA)]
+ plural = snapshot_metadata.get(WEB_PUSH_USER_KEYS_METADATA)
+ if isinstance(plural, list):
+ values.extend(plural)
+ for value in values:
+ key = str(value or "").strip()
+ if key and key not in web_push_user_keys:
+ web_push_user_keys.append(key)
++ raw_contexts = snapshot_metadata.get(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA)
++ if isinstance(raw_contexts, list):
++ for raw_context in raw_contexts:
++ if not isinstance(raw_context, dict):
++ continue
++ user_key = str(raw_context.get("user_key") or "").strip()
++ if user_key:
++ authorization_contexts[user_key] = raw_context
+ metadata.pop(WEB_PUSH_USER_KEY_METADATA, None)
+ metadata.pop(WEB_PUSH_USER_KEYS_METADATA, None)
+ if len(web_push_user_keys) == 1:
+ metadata[WEB_PUSH_USER_KEY_METADATA] = web_push_user_keys[0]
+ elif web_push_user_keys:
+ metadata[WEB_PUSH_USER_KEYS_METADATA] = web_push_user_keys
++ if memory_metadata_present:
++ metadata[MEMORY_ORDINARY_TEXT_METADATA] = memory_ordinary_text
++ metadata[MEMORY_CLI_ADMITTED_METADATA] = memory_cli_admitted
++ if len(memory_user_ids) == 1:
++ metadata[MEMORY_USER_ID_METADATA] = memory_user_ids[0]
++ else:
++ metadata.pop(MEMORY_USER_ID_METADATA, None)
++ filtered_contexts = [
++ context
++ for user_key, context in authorization_contexts.items()
++ if user_key in web_push_user_keys
++ ]
++ if filtered_contexts:
++ metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = filtered_contexts
++ else:
++ metadata.pop(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA, None)
+ if len(deliveries) > 1:
+ metadata["merged_delivery_ids"] = [str(delivery["id"]) for delivery in deliveries]
+ native_ids = [
+ str(snapshot.get("native_message_id") or "")
+ for snapshot in snapshots
+ if str(snapshot.get("native_message_id") or "")
+ ]
+ if native_ids:
+ metadata["merged_native_message_ids"] = native_ids
+ first["content_text"] = visible_text or None
+ first["content_json"] = _canonical_json(merged_content)
+ first["metadata_json"] = _canonical_json(metadata)
+ return first
+
+
+def materialize_start_acceptance(
+ conn: Connection,
+ *,
+ turn_id: str,
+ evidence: dict[str, Any],
+) -> list[dict[str, Any]]:
+ turn = get_turn(conn, turn_id)
+ if turn is None or turn["state"] not in {"starting", "active", "terminal"}:
+ return []
+ if turn.get("start_receipt_outcome") != "accepted":
+ return []
+ rows = [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.turn_id == turn_id)
+ .where(message_deliveries.c.turn_role == "initial")
+ .order_by(message_deliveries.c.turn_position, message_deliveries.c.id)
+ ).mappings()
+ ]
+ if not rows:
+ raise RuntimeError("active Turn has no initial Delivery batch")
+ if all(row["state"] == "accepted" for row in rows):
+ return rows
+ if any(row["state"] != "claimed" for row in rows):
+ raise RuntimeError("initial Delivery batch is only partially materialized")
+ message_id = str(turn["initial_delivery_id"])
+ accepted_at = turn_now_iso()
+ snapshot = _merged_initial_snapshot(rows)
+ _insert_message(
+ conn,
+ message_id=message_id,
+ snapshot=snapshot,
+ accepted_at=accepted_at,
+ )
+ accepted: list[dict[str, Any]] = []
+ for row in rows:
+ saved = cas_delivery(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=("claimed",),
+ values={
+ "state": "accepted",
+ "message_id": message_id,
+ "snapshot_json": None,
+ "dispatch_text": None,
+ "materialized_at": accepted_at,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={
+ "kind": "start",
+ "attempt_id": turn.get("start_attempt_id"),
+ "turn_id": turn_id,
+ "outcome": "accepted",
+ "evidence": evidence,
+ },
+ )
+ if saved is None:
+ raise RuntimeError("initial Delivery materialization CAS lost")
+ accepted.append(saved)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.delivery_id == str(row["id"]))
+ .where(show_session_events.c.message_id.is_(None))
+ .values(message_id=message_id)
+ )
+ return accepted
+
+
+def materialize_acceptance(
+ conn: Connection,
+ *,
+ delivery_id: str,
+ expected_attempt_id: str | None,
+ turn_id: str,
+ evidence: dict[str, Any],
+) -> dict[str, Any] | None:
+ delivery = get_delivery(conn, delivery_id)
+ if delivery is None:
+ return None
+ if delivery["state"] == "accepted":
+ if delivery.get("message_id") == delivery_id and delivery.get("turn_id") == turn_id:
+ if conn.execute(select(messages.c.id).where(messages.c.id == delivery_id)).scalar_one_or_none() is None:
+ raise RuntimeError("accepted Delivery is missing its Message")
+ return delivery
+ return None
+ if expected_attempt_id is not None and delivery.get("current_attempt_id") != expected_attempt_id:
+ return None
+ target_turn_id = str(delivery.get("current_target_turn_id") or "")
+ if target_turn_id != turn_id:
+ return None
+ target_turn = get_turn(conn, turn_id)
+ if (
+ target_turn is None
+ or target_turn["session_id"] != delivery["session_id"]
+ ):
+ return None
+ snapshot = _verified_snapshot(delivery)
+ now = turn_now_iso()
+ position = int(
+ conn.execute(
+ select(func.coalesce(func.max(message_deliveries.c.turn_position), -1)).where(
+ message_deliveries.c.turn_id == turn_id
+ )
+ ).scalar_one()
+ ) + 1
+ values = {
+ "state": "accepted",
+ "message_id": delivery_id,
+ "turn_id": turn_id,
+ "turn_role": "steer",
+ "turn_position": position,
+ "snapshot_json": None,
+ "dispatch_text": None,
+ "materialized_at": now,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ }
+ accepted = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=(str(delivery["state"]),),
+ values=values,
+ history_event={
+ "kind": str(delivery.get("current_attempt_kind") or evidence.get("kind") or "start"),
+ "attempt_id": delivery.get("current_attempt_id"),
+ "turn_id": turn_id,
+ "outcome": "accepted",
+ "evidence": evidence,
+ },
+ )
+ if accepted is None:
+ return None
+
+ _insert_message(conn, message_id=delivery_id, snapshot=snapshot, accepted_at=now)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.delivery_id == delivery_id)
+ .where(show_session_events.c.message_id.is_(None))
+ .values(message_id=delivery_id)
+ )
+ return accepted
+
+
+def attempt_deliveries(conn: Connection, attempt_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.current_attempt_id == attempt_id)
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ ]
+
+
+def materialize_steer_acceptance(
+ conn: Connection,
+ *,
+ leader_delivery_id: str,
+ expected_attempt_id: str,
+ turn_id: str,
+ evidence: dict[str, Any],
+) -> list[dict[str, Any]]:
+ leader = get_delivery(conn, leader_delivery_id)
+ if leader is None or leader.get("current_attempt_id") != expected_attempt_id:
+ return []
+ rows = attempt_deliveries(conn, expected_attempt_id)
+ if not rows or any(
+ row["state"] not in {"steering", "reconciling_steer"}
+ or row.get("current_target_turn_id") != turn_id
+ for row in rows
+ ):
+ return []
+ target_turn = get_turn(conn, turn_id)
+ if target_turn is None or any(row["session_id"] != target_turn["session_id"] for row in rows):
+ return []
+ now = turn_now_iso()
+ message_id = str(rows[0]["id"])
+ snapshot = _merged_initial_snapshot(rows)
+ first_position = int(
+ conn.execute(
+ select(func.coalesce(func.max(message_deliveries.c.turn_position), -1)).where(
+ message_deliveries.c.turn_id == turn_id
+ )
+ ).scalar_one()
+ ) + 1
+ accepted: list[dict[str, Any]] = []
+ for offset, row in enumerate(rows):
+ saved = cas_delivery(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=(str(row["state"]),),
+ values={
+ "state": "accepted",
+ "message_id": message_id,
+ "turn_id": turn_id,
+ "turn_role": "steer",
+ "turn_position": first_position + offset,
+ "snapshot_json": None,
+ "dispatch_text": None,
+ "materialized_at": now,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={
+ "kind": "steer",
+ "attempt_id": expected_attempt_id,
+ "turn_id": turn_id,
+ "outcome": "accepted",
+ "evidence": evidence,
+ },
+ )
+ if saved is None:
+ raise RuntimeError("steer Delivery batch materialization CAS lost")
+ accepted.append(saved)
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.delivery_id == str(row["id"]))
+ .where(show_session_events.c.message_id.is_(None))
+ .values(message_id=message_id)
+ )
+ _insert_message(conn, message_id=message_id, snapshot=snapshot, accepted_at=now)
+ return accepted
+
+
+def mark_attempt_unknown(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ receipt: dict[str, Any],
+) -> dict[str, Any] | None:
+ delivery = get_delivery(conn, delivery_id)
+ if delivery is None:
+ return None
+ kind = str(delivery.get("current_attempt_kind") or "")
+ if kind != "steer":
+ return None
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=("steering",),
+ values={
+ "state": "reconciling_steer",
+ "current_receipt_outcome": "unknown",
+ "current_receipt_json": _canonical_json(receipt),
+ },
+ history_event={
+ "kind": kind or "attempt",
+ "attempt_id": delivery.get("current_attempt_id"),
+ "turn_id": delivery.get("current_target_turn_id"),
+ "outcome": "unknown",
+ "receipt": receipt,
+ },
+ )
+
+
+def record_definitive_attempt(
+ conn: Connection,
+ delivery_id: str,
+ *,
+ expected_version: int,
+ expected_states: Iterable[str],
+ outcome: str,
+ next_state: str,
+ next_priority: str | None = None,
+ next_turn_id: str | None = None,
+ receipt: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ delivery = get_delivery(conn, delivery_id)
+ if delivery is None:
+ return None
+ values: dict[str, Any] = {
+ "state": next_state,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": next_turn_id,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ }
+ if next_priority:
+ values["priority"] = next_priority
+ if next_state in {"queued", "reserved", "retired"}:
+ values.update(turn_id=None, turn_role=None, turn_position=None)
+ if next_state == "retired":
+ values["retired_at"] = utc_now_iso()
+ history_kind = str(delivery.get("current_attempt_kind") or "")
+ if not history_kind:
+ if delivery.get("state") == "claimed":
+ history_kind = "start"
+ elif delivery.get("state") == "pending_steer":
+ history_kind = "steer"
+ else:
+ history_kind = "interrupt_join"
+ return cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=expected_version,
+ expected_states=expected_states,
+ values=values,
+ history_event={
+ "kind": history_kind,
+ "attempt_id": delivery.get("current_attempt_id"),
+ "turn_id": delivery.get("current_target_turn_id"),
+ "outcome": outcome,
+ "receipt": receipt or {},
+ },
+ )
+
+
+def terminalize_turn(
+ conn: Connection,
+ turn_id: str,
+ *,
+ outcome: str,
+ settled_by: str | None,
+ evidence_kind: str,
+ evidence: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ turn = get_turn(conn, turn_id)
+ if turn is None or turn["state"] == "terminal":
+ return {"changed": False, "turn": turn}
+ values = {
+ "state": "terminal",
+ "terminal_outcome": outcome,
+ "settled_by": settled_by,
+ "terminal_evidence_kind": evidence_kind,
+ "terminal_evidence_json": _canonical_json(evidence or {}),
+ "terminal_at": turn_now_iso(),
+ }
+ if outcome == "not_written" and turn.get("start_attempt_id"):
+ if turn.get("start_receipt_outcome") == "accepted":
+ return {"changed": False, "turn": turn}
+ values.update(
+ {
+ "start_receipt_outcome": "not_written",
+ "start_receipt_json": _canonical_json(
+ {"kind": evidence_kind, **(evidence or {})}
+ ),
+ }
+ )
+ settled = cas_turn(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ expected_states=(str(turn["state"]),),
+ values=values,
+ )
+ return {"changed": settled is not None, "turn": settled or turn}
+
+
+def recovery_turns(conn: Connection, session_id: str | None = None) -> list[dict[str, Any]]:
+ query = select(session_turns).where(session_turns.c.state.in_(("waiting",) + TURN_OWNER_STATES))
+ if session_id:
+ query = query.where(session_turns.c.session_id == session_id)
+ return [dict(row) for row in conn.execute(query.order_by(session_turns.c.created_at, session_turns.c.id)).mappings()]
+
+
+def unresolved_deliveries(conn: Connection, session_id: str | None = None) -> list[dict[str, Any]]:
+ query = select(message_deliveries).where(
+ message_deliveries.c.state.in_(FENCE_STATES + ("claimed",))
+ )
+ if session_id:
+ query = query.where(message_deliveries.c.session_id == session_id)
+ return [dict(row) for row in conn.execute(query.order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)).mappings()]
+
+
+def recoverable_reservations(
+ conn: Connection,
+ session_id: str | None = None,
+) -> list[dict[str, Any]]:
+ """Pre-write producer reservations safe to re-enter through admission."""
+
+ query = select(message_deliveries).where(message_deliveries.c.state == "reserved")
+ if session_id:
+ query = query.where(message_deliveries.c.session_id == session_id)
+ return [
+ dict(row)
+ for row in conn.execute(
+ query.order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ ).mappings()
+ ]
+
+
+def session_ids_with_live_turns(conn: Connection) -> set[str]:
+ return {
+ str(value)
+ for value in conn.execute(
+ select(session_turns.c.session_id).where(session_turns.c.state.in_(TURN_OWNER_STATES)).distinct()
+ ).scalars()
+ }
+
+
+def session_ids_with_turn_history(conn: Connection) -> set[str]:
+ return {str(value) for value in conn.execute(select(session_turns.c.session_id).distinct()).scalars()}
+
+
+def active_runtime_session_ids_for_backend(conn: Connection, backend: str) -> set[str]:
+ return {
+ str(value)
+ for value in conn.execute(
+ select(session_turns.c.session_id)
+ .where(session_turns.c.backend == backend)
+ .where(session_turns.c.state == "active")
+ .distinct()
+ ).scalars()
+ }
+
+
+def live_turns_for_backend_sessions(
+ conn: Connection,
+ backend: str,
+ session_ids: set[str],
+) -> list[dict[str, Any]]:
+ if not session_ids:
+ return []
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(session_turns)
+ .where(session_turns.c.backend == backend)
+ .where(session_turns.c.session_id.in_(session_ids))
+ .where(session_turns.c.state.in_(TURN_OWNER_STATES))
+ ).mappings()
+ ]
+
+
+def delivery_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ turn = get_turn(conn, turn_id)
+ return get_delivery(conn, str((turn or {}).get("initial_delivery_id") or ""))
+
+
+def initial_deliveries_for_turn(conn: Connection, turn_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.turn_id == turn_id)
+ .where(message_deliveries.c.turn_role == "initial")
+ .order_by(message_deliveries.c.turn_position, message_deliveries.c.id)
+ ).mappings()
+ ]
+
+
+def message_for_delivery(conn: Connection, delivery: dict[str, Any]) -> dict[str, Any] | None:
+ message_id = str(delivery.get("message_id") or "")
+ return _one(conn, select(messages).where(messages.c.id == message_id)) if message_id else None
+
+
+def queued_session_ids_without_live_turns(
+ conn: Connection,
+ session_id: str | None = None,
+ *,
+ include_held: bool = False,
+) -> list[str]:
+ live = select(session_turns.c.id).where(
+ session_turns.c.session_id == message_deliveries.c.session_id,
+ session_turns.c.state.in_(TURN_OWNER_STATES),
+ ).exists()
+ query = (
+ select(message_deliveries.c.session_id)
+ .join(agent_sessions, agent_sessions.c.id == message_deliveries.c.session_id)
+ .where(message_deliveries.c.state == "queued")
+ .where(agent_sessions.c.status == "active")
+ .where(~live)
+ )
+ if not include_held:
+ query = query.where(agent_sessions.c.queue_hold_state == "open")
+ if session_id:
+ query = query.where(message_deliveries.c.session_id == session_id)
+ return [str(value) for value in conn.execute(query.distinct()).scalars()]
+
+
+def retire_queued(conn: Connection, session_id: str, delivery_id: str) -> bool:
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "queued"
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("queued",),
+ values={"state": "retired", "retired_at": utc_now_iso()},
+ history_event={"kind": "retire", "reason": "queue_remove"},
+ )
+ return updated is not None
+
+
+def retire_queued_for_resubmission(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+ *,
+ expected_dedupe_key: str,
+) -> bool:
+ """Retire a recovered primary row and release its native dedupe claim."""
+
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "queued"
+ or delivery.get("dedupe_key") != expected_dedupe_key
+ or delivery.get("current_attempt_id") is not None
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("queued",),
+ values={
+ "state": "retired",
+ "retired_at": utc_now_iso(),
+ "dedupe_key": None,
+ },
+ history_event={
+ "kind": "retire",
+ "reason": "agent_run_recovery_resubmit",
+ "released_dedupe_key": expected_dedupe_key,
+ },
+ )
+ return updated is not None
+
+
+def agent_run_ids_for_delivery(
+ conn: Connection,
+ delivery: dict[str, Any],
+) -> list[str]:
+ """Return the Agent Runs operationally represented by one Delivery."""
+
+ delivery_id = str(delivery.get("id") or "").strip()
+ if not delivery_id:
+ return []
+ return [
+ str(run_id)
+ for run_id in conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.delivery_id == delivery_id)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ ).scalars()
+ ]
+
+
+def accepted_agent_run_ids_for_turn(conn: Connection, turn_id: str) -> list[str]:
+ """Return every accepted Agent Run participant owned by an exact Turn."""
+
+ run_ids: list[str] = []
+ for delivery in deliveries_for_turn(conn, turn_id):
+ if (
+ delivery.get("state") != "accepted"
+ or delivery.get("turn_id") != turn_id
+ ):
+ continue
+ for run_id in agent_run_ids_for_delivery(conn, delivery):
+ if run_id not in run_ids:
+ run_ids.append(run_id)
+ return run_ids
+
+
+def retire_queued_with_run(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+) -> bool:
+ """Retire an exact queued Delivery and its held Agent Run atomically."""
+
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "queued"
+ ):
+ return False
+ run_ids = agent_run_ids_for_delivery(conn, delivery)
+ if run_ids:
+ from storage.background import (
+ cancel_queued_agent_run_delivery_in_connection,
+ )
+ if len(run_ids) != 1:
+ return False
+ if not cancel_queued_agent_run_delivery_in_connection(
+ conn,
+ run_ids[0],
+ session_id=session_id,
+ delivery_id=delivery_id,
+ ):
+ return False
+ return retire_queued(conn, session_id, delivery_id)
+
+
+def terminal_turn_agent_run_owners(
+ conn: Connection,
+ session_id: str | None = None,
+) -> list[tuple[dict[str, Any], list[str]]]:
+ """Return terminal Turns and their accepted Agent Run participants."""
+
+ query = (
+ select(
+ session_turns.c.id.label("turn_id"),
+ session_turns.c.terminal_outcome,
+ session_turns.c.settled_by,
+ session_turns.c.terminal_evidence_kind,
+ session_turns.c.terminal_evidence_json,
+ session_turns.c.terminal_at,
+ agent_runs.c.id.label("run_id"),
+ )
+ .join(
+ message_deliveries,
+ message_deliveries.c.turn_id == session_turns.c.id,
+ )
+ .join(agent_runs, agent_runs.c.delivery_id == message_deliveries.c.id)
+ .where(session_turns.c.state == "terminal")
+ .where(message_deliveries.c.state == "accepted")
+ )
+ if session_id:
+ query = query.where(session_turns.c.session_id == session_id)
+ owners: dict[str, tuple[dict[str, Any], list[str]]] = {}
+ rows = conn.execute(
+ query.order_by(session_turns.c.terminal_at, session_turns.c.id)
+ ).mappings()
+ for row in rows:
+ turn_id = str(row["turn_id"])
+ run_id = str(row["run_id"])
+ owner = owners.setdefault(
+ turn_id,
+ (
+ {
+ "id": turn_id,
+ "terminal_outcome": row["terminal_outcome"],
+ "settled_by": row["settled_by"],
+ "terminal_evidence_kind": row["terminal_evidence_kind"],
+ "terminal_evidence_json": row["terminal_evidence_json"],
+ },
+ [],
+ ),
+ )
+ if run_id not in owner[1]:
+ owner[1].append(run_id)
+ return list(owners.values())
+
+
+def retire_reserved(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+ *,
+ reason: str,
+) -> bool:
+ """Retire only a producer reservation that no executor has claimed."""
+
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or delivery["state"] != "reserved"
+ or delivery.get("current_attempt_id")
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=("reserved",),
+ values={"state": "retired", "retired_at": utc_now_iso()},
+ history_event={"kind": "retire", "reason": reason},
+ )
+ return updated is not None
+
+
+def retire_not_written(conn: Connection, session_id: str, delivery_id: str, *, reason: str) -> bool:
+ delivery = get_delivery(conn, delivery_id)
+ if (
+ delivery is None
+ or delivery["session_id"] != session_id
+ or policy_for(str(delivery["state"])).run_cancel != "retire"
+ ):
+ return False
+ updated = cas_delivery(
+ conn,
+ delivery_id,
+ expected_version=int(delivery["version"]),
+ expected_states=(str(delivery["state"]),),
+ values={
+ "state": "retired",
+ "retired_at": utc_now_iso(),
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={"kind": "retire", "reason": reason},
+ )
+ return updated is not None
+
+
+def retire_for_run_cancellation(
+ conn: Connection,
+ session_id: str,
+ delivery_id: str,
+) -> bool:
+ """Retire an exact Run input only when its state proves no native side effect."""
+
+ return retire_not_written(
+ conn,
+ session_id,
+ delivery_id,
+ reason="agent_run_canceled_before_native_write",
+ )
+
+
+def retire_for_archive(conn: Connection, session_id: str) -> dict[str, Any]:
+ """Retire only states proven not written; ambiguity remains reconcilable."""
+
+ rows = [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(message_deliveries.c.session_id == session_id)
+ .where(message_deliveries.c.state.in_(RUN_CANCEL_RETIRE_STATES))
+ ).mappings()
+ ]
+ retired = 0
+ retired_delivery_ids: list[str] = []
+ for row in rows:
+ if cas_delivery(
+ conn,
+ str(row["id"]),
+ expected_version=int(row["version"]),
+ expected_states=(str(row["state"]),),
+ values={
+ "state": "retired",
+ "retired_at": utc_now_iso(),
+ "turn_id": None,
+ "turn_role": None,
+ "turn_position": None,
+ "current_attempt_id": None,
+ "current_attempt_kind": None,
+ "current_target_turn_id": None,
+ "current_expected_native_turn_id": None,
+ "current_receipt_outcome": None,
+ "current_receipt_json": "{}",
+ "current_attempt_opened_at": None,
+ },
+ history_event={"kind": "retire", "reason": "session_archive"},
+ ) is not None:
+ retired += 1
+ retired_delivery_ids.append(str(row["id"]))
+ return {
+ "retired": retired,
+ "delivery_ids": retired_delivery_ids,
+ }
+
+
+def set_queue_hold(conn: Connection, session_id: str, *, held: bool) -> bool:
+ row = conn.execute(
+ select(agent_sessions.c.queue_hold_version).where(agent_sessions.c.id == session_id)
+ ).first()
+ if row is None:
+ return False
+ version = int(row[0])
+ result = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.queue_hold_version == version)
+ .values(
+ queue_hold_state="held" if held else "open",
+ queue_hold_version=version + 1,
+ queue_held_at=utc_now_iso() if held else None,
+ )
+ )
+ return result.rowcount == 1
+
+
+def queue_is_held(conn: Connection, session_id: str) -> bool:
+ value = conn.execute(
+ select(agent_sessions.c.queue_hold_state).where(agent_sessions.c.id == session_id)
+ ).scalar_one_or_none()
+ return value == "held"
+
+
+def set_draft(conn: Connection, session_id: str, text: str | None) -> bool:
+ now = utc_now_iso()
+ result = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(
+ composer_draft_text=text if text and text.strip() else None,
+ composer_draft_updated_at=now if text and text.strip() else None,
+ updated_at=now,
+ )
+ )
+ return result.rowcount == 1
+
+
+def get_draft(conn: Connection, session_id: str) -> dict[str, Any] | None:
+ row = conn.execute(
+ select(
+ agent_sessions.c.composer_draft_text,
+ agent_sessions.c.composer_draft_updated_at,
+ ).where(agent_sessions.c.id == session_id)
+ ).first()
+ if row is None or not row[0]:
+ return None
+ return {"text": str(row[0]), "updated_at": row[1]}
+
+
+def pending_control_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(session_turns)
+ .where(session_turns.c.id == turn_id)
+ .where(
+ session_turns.c.control_state.in_(
+ ("pending", "interrupting", "waiting_terminal", "reconciling")
+ )
+ ),
+ )
+
+
+def pending_steer_for_turn(conn: Connection, turn_id: str) -> dict[str, Any] | None:
+ return _one(
+ conn,
+ select(message_deliveries)
+ .where(message_deliveries.c.current_target_turn_id == turn_id)
+ .where(message_deliveries.c.state == "pending_steer")
+ .order_by(message_deliveries.c.submitted_at, message_deliveries.c.id)
+ .limit(1),
+ )
+
+
+def turn_has_delivery_owner(conn: Connection, turn_id: str) -> bool:
+ turn = get_turn(conn, turn_id)
+ return bool(turn and get_delivery(conn, str(turn["initial_delivery_id"])))
+
+
+def deliveries_for_turn(conn: Connection, turn_id: str) -> list[dict[str, Any]]:
+ return [
+ dict(row)
+ for row in conn.execute(
+ select(message_deliveries)
+ .where(
+ or_(
+ message_deliveries.c.turn_id == turn_id,
+ message_deliveries.c.current_target_turn_id == turn_id,
+ )
+ )
+ .order_by(
+ message_deliveries.c.turn_position,
+ message_deliveries.c.submitted_at,
+ message_deliveries.c.id,
+ )
+ ).mappings()
+ ]
diff --cc storage/messages_service.py
index 198eb9b9a,926c9d098..415ab9af3
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@@ -273,7 -239,7 +288,8 @@@ def search_messages
platform: str = "avibe",
types: Optional[Iterable[str]] = None,
limit: int = 50,
+ include_archived: bool = False,
+ scope_ids: Optional[Iterable[str]] = None,
) -> dict[str, Any]:
"""Global message-content search, grouped by session.
@@@ -310,13 -267,13 +326,16 @@@
cleaned = (query or "").strip()
if not cleaned:
return {"sessions": [], "total": 0, "session_count": 0}
+ allowed_scope_ids = list(dict.fromkeys(scope_ids)) if scope_ids is not None else None
+ if allowed_scope_ids == []:
+ return {"sessions": [], "total": 0, "session_count": 0}
like = escape_sql_like(cleaned)
- type_list = list(types if types is not None else ("user", HARNESS_TYPE, "result"))
+ type_list = list(types if types is not None else types_with("searchable"))
effective_limit = min(max(int(limit), 1), 200)
+ # Applied in place below so the default (opt-out) statement keeps exactly the
+ # predicates — and the predicate order — it had before the flag existed.
+ archived_session_filters = () if include_archived else (agent_sessions.c.status != "archived",)
stmt = (
select(
@@@ -593,6 -493,7 +614,7 @@@ def list_session_messages
around_id: Optional[str] = None,
limit: int = 50,
types: Optional[Iterable[str]] = None,
- include_metadata_sources: Iterable[str] = (),
++ include_private_metadata: bool = False,
tail: bool = False,
) -> dict[str, Any]:
"""Return messages for one session in chronological order with cursor pagination.
@@@ -647,13 -561,13 +669,20 @@@
.order_by(messages.c.created_at.desc(), messages.c.id.desc())
.limit(effective_limit + 1)
)
-- older = [_row_to_payload(dict(row)) for row in conn.execute(older_q).mappings().all()]
++ older = [
++ _row_to_payload(
++ dict(row), include_private_metadata=include_private_metadata
++ )
++ for row in conn.execute(older_q).mappings().all()
++ ]
has_older = len(older) > effective_limit
older = older[:effective_limit]
older.reverse()
anchor_rows = [
-- _row_to_payload(dict(row))
++ _row_to_payload(
++ dict(row), include_private_metadata=include_private_metadata
++ )
for row in conn.execute(query.where(messages.c.id == around_id)).mappings().all()
]
@@@ -667,7 -581,7 +696,12 @@@
.order_by(messages.c.created_at.asc(), messages.c.id.asc())
.limit(effective_limit + 1)
)
-- newer = [_row_to_payload(dict(row)) for row in conn.execute(newer_q).mappings().all()]
++ newer = [
++ _row_to_payload(
++ dict(row), include_private_metadata=include_private_metadata
++ )
++ for row in conn.execute(newer_q).mappings().all()
++ ]
has_newer = len(newer) > effective_limit
newer = newer[:effective_limit]
@@@ -681,7 -595,7 +715,13 @@@
# Newest ``limit`` rows, then flip back to chronological for the caller.
query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)
rows = _attach_agent_run_provenance(
-- conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
++ conn,
++ [
++ _row_to_payload(
++ dict(row), include_private_metadata=include_private_metadata
++ )
++ for row in conn.execute(query).mappings().all()
++ ],
)
has_older = len(rows) > effective_limit
rows = rows[:effective_limit]
@@@ -704,7 -618,7 +744,13 @@@
)
query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)
rows = _attach_agent_run_provenance(
-- conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
++ conn,
++ [
++ _row_to_payload(
++ dict(row), include_private_metadata=include_private_metadata
++ )
++ for row in conn.execute(query).mappings().all()
++ ],
)
has_older = len(rows) > effective_limit
rows = rows[:effective_limit]
@@@ -727,7 -641,7 +773,13 @@@
)
query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(effective_limit + 1)
rows = _attach_agent_run_provenance(
-- conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
++ conn,
++ [
++ _row_to_payload(
++ dict(row), include_private_metadata=include_private_metadata
++ )
++ for row in conn.execute(query).mappings().all()
++ ],
)
# Probe one extra row against the clamped page size: a full page alone does
# not prove there is another page, but the extra row does.
@@@ -869,8 -1032,13 +941,13 @@@ def unread_counts_by_session
return {session_id: int(count) for session_id, count in conn.execute(query).all()}
- def total_unread(conn: Connection, *, platform: Optional[str] = None) -> int:
+ def total_unread(
+ conn: Connection,
+ *,
+ platform: Optional[str] = None,
+ scope_ids: Optional[Iterable[str]] = None,
+ ) -> int:
- """Unread agent-``result`` count across the caller's visible sessions.
+ """Global unread agent-``result`` count across all non-archived sessions.
This is the sum of :func:`unread_counts_by_session`, i.e. the exact number
the Inbox nav badge shows (``ui_server`` returns it as ``unread_total``). It
diff --cc storage/migrations.py
index aacc72694,d986c7c95..fe4b6dd20
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@@ -112,35 -110,15 +118,42 @@@ PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMN
"cancel_requested_at",
},
}
+HEAD_REQUIRED_COLUMNS = PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS | {
+ "agent_sessions": PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS["agent_sessions"]
+ | {
+ "queue_hold_state",
+ "queue_hold_version",
+ "queue_held_at",
+ "composer_draft_text",
+ "composer_draft_updated_at",
+ },
+ "message_deliveries": {
+ "message_id",
+ "priority",
+ "state",
+ "dispatch_text",
+ "delivery_history_json",
+ "version",
+ },
+ "session_turns": {
+ "initial_delivery_id",
+ "state",
+ "native_turn_id",
+ "control_state",
+ "terminal_outcome",
+ "settled_by",
+ "version",
+ },
+}
HEAD_ONLY_REQUIRED_COLUMNS = {
"web_push_subscriptions": {"device_id"},
+ "remote_access_authorizations": {
+ "instance_id",
+ "subject",
+ "claims_json",
+ "expires_at",
+ "created_at",
+ },
"vault_requests": {"callback_status"},
"vault_grants": {"agent_ready", "agent_ready_at"},
"vault_auth_factors": {"credential_id", "public_key", "alg", "sign_count"},
diff --cc storage/projects_service.py
index cb963b929,599016394..5b2f64b2c
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@@ -21,8 -21,9 +21,10 @@@ from typing import Any, Mapping, Option
from sqlalchemy import select, update
from sqlalchemy.engine import Connection
+from storage.agent_session_rows import reserve_write_lock
+ from storage import project_access_service
from storage.models import agents, scope_settings, scopes
+ from vibe.authorization import AuthorizationContext, require_instance_role
PROJECT_PLATFORM = "avibe"
@@@ -344,7 -354,7 +390,8 @@@ def update_project
by sending ``None``s. Empty strings normalize to ``None`` so an empty pick
clears too.
"""
+ context = require_instance_role(authorization_context, "owner")
+ reserve_write_lock(conn)
scope_id = _make_scope_id(project_id)
existing = conn.execute(select(scopes.c.id).where(scopes.c.id == scope_id)).scalar_one_or_none()
if existing is None:
diff --cc storage/workbench_sessions_service.py
index 0acadb3a7,c903d1437..91c7ace71
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@@ -24,20 -24,14 +24,22 @@@ from sqlalchemy import and_, func, or_
from sqlalchemy.engine import Connection
from config import paths
+ from storage import project_access_service
+ from vibe.authorization import AuthorizationContext, require_instance_role
from storage.agent_session_rows import (
- SESSION_VISIBILITIES,
+ ASSIGNABLE_SESSION_VISIBILITIES,
+ WORKSPACE_NOTICE_SESSION_ID,
create_agent_session_row,
new_session_id,
+ reserve_write_lock,
)
from storage.db import escape_sql_like
+from storage.session_reclaim import (
+ RECLAIM_DELETE,
+ reclaim_bound_definitions,
+ reconcile_explicit_overrides,
+ retire_session_delivery_owners,
+)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.models import (
agent_runs,
@@@ -144,15 -148,20 +160,26 @@@ def list_sessions
``title_query`` powers the chat composer ``#``-mention global search: a
case-insensitive title LIKE match (LIKE metacharacters escaped).
+
+ The visibility predicate is POSITIVE (``== 'foreground'``), which is why the runtime's
+ ``system`` sessions need no exclusion of their own here: an ordinary session list
+ shows ordinary sessions, and anything the runtime owns has to opt IN to a surface
+ rather than be remembered as an exception. ``tests/test_workspace_system_session.py``
+ pins that, so it stays a property rather than an assumption.
"""
+ context = require_instance_role(authorization_context, "viewer")
query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")
+ if not context.is_instance_owner:
+ accessible_scope_ids = {
+ project_access_service.project_scope_id(project_id)
+ for project_id in project_access_service.accessible_project_ids(conn, context)
+ }
+ if scope_id is not None and scope_id not in accessible_scope_ids:
+ return {"sessions": [], "next_before_id": None}
+ if not accessible_scope_ids:
+ return {"sessions": [], "next_before_id": None}
+ query = query.where(agent_sessions.c.scope_id.in_(accessible_scope_ids))
if scope_id is not None:
query = query.where(agent_sessions.c.scope_id == scope_id)
if status is not None and status != "all":
@@@ -391,33 -454,9 +482,33 @@@ def create_session
metadata=metadata_payload,
now=now,
)
- return get_session(conn, session_id)
+ return get_session(conn, session_id, authorization_context=authorization)
+class ReservedSessionError(PermissionError):
+ """Raised when a caller tries to tear down or edit a session the runtime reserves.
+
+ ``PermissionError`` by inheritance, deliberately: the session routes in
+ ``vibe/ui_server.py`` already map that to a refusal response, so a route that has
+ not learned this class yet answers a refusal rather than 500. ``code`` is the
+ machine half; the user-visible sentence is rendered at the HTTP boundary from
+ ``vibe/i18n``, because this layer has no way to know the caller's language (the
+ configured language lives in ``core.services.settings``, and importing core from
+ storage would invert the layering).
+
+ Raised from ``archive_session`` (teardown) and ``update_session`` (edit), both on
+ identity rather than row state — see each for why.
+ """
+
+ code = "reserved_session"
+
+ def __init__(self, session_id: str):
+ self.session_id = session_id
+ super().__init__(
+ f"Session {session_id} is reserved by the runtime and cannot be archived or modified"
+ )
+
+
class SessionBackendLockedError(Exception):
"""Raised when a caller tries to switch the backend of a session that already
has a native conversation (pinned for life: the native can only be resumed by
@@@ -469,26 -490,10 +560,29 @@@ def update_session
visibility: Any = _UNSET,
pinned: Any = _UNSET,
scope_id: Any = _UNSET,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+ user_context: Any = None,
) -> dict[str, Any]:
+ """Apply a caller's edits to one session row.
+
+ THE RESERVED WORKSPACE-NOTICE SESSION IS REFUSED HERE TOO, for the same reason
+ ``archive_session`` refuses it and on the same IDENTITY test (so the answer does not
+ depend on whether the lazily-created row exists yet). That row is D5 rung (5)'s home
+ and its ``system`` visibility IS the projection: hidden from ordinary session lists,
+ admitted to the inbox. An unguarded write could move it off that value — ``visibility
+ = 'background'`` mutes the notice outright, ``foreground`` re-materializes a
+ machine-owned chat in every user's session list — and also ``scope_id``, which would
+ mint a fake project row and put the session inside a scoped clear's reach. Each of
+ those is silent until the next notice's heal, so an ack could be earned against a
+ surface showing nothing in between.
+
+ ``system`` itself is not assignable in the other direction either: see the
+ ``visibility`` branch below.
+ """
+ authorization = require_instance_role(authorization_context, "editor")
+ if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
+ raise ReservedSessionError(str(session_id))
+ reserve_write_lock(conn)
existing = conn.execute(
select(
agent_sessions.c.id,
@@@ -502,20 -506,70 +596,79 @@@
).first()
if existing is None:
raise LookupError(f"Session not found: {session_id}")
+ # THIS READ IS A FAST PATH, NOT THE GUARD. It reserves nothing — pysqlite
+ # opens no transaction for a bare SELECT, so SQLite only takes the write lock
+ # at the UPDATE below — meaning an archive can commit after it and before the
+ # write. The ``status != 'archived'`` predicate ON the UPDATE is what makes
+ # the terminal archive hold; this read only spares an already-lost caller the
+ # rest of the work (and answers the common case before the metadata/scope
+ # reads). Same split as ``sessions_service.bind_agent_session_by_id``.
+ if existing.status == "archived":
+ raise SessionArchivedError(session_id)
+ if not authorization.is_instance_owner:
+ project_id = project_access_service.project_id_from_scope_id(existing.scope_id)
+ if project_id is None or not project_access_service.can_chat_project(
+ conn, authorization, project_id
+ ):
+ raise LookupError(f"Session not found: {session_id}")
+ if scope_id is not _UNSET:
+ target_project_id = project_access_service.project_id_from_scope_id(scope_id)
+ if target_project_id is None or not project_access_service.can_chat_project(
+ conn, authorization, target_project_id
+ ):
+ raise LookupError(f"Session not found: {session_id}")
derived_backend = False
- if agent_name is not _UNSET and agent_backend is _UNSET:
- agent_backend = _backend_for_agent_name(conn, str(agent_name or "")) if agent_name else None
- derived_backend = True
+ from core.vibe_agents import (
+ VibeAgentAccessError,
+ ensure_agent_selection_access,
+ ensure_default_agent_access,
+ resolve_resource_access_context,
+ )
+
+ resource_context = resolve_resource_access_context(user_context)
+ selector_changed = agent_name is not _UNSET or agent_id is not _UNSET
+ selected_agent = None
+ if selector_changed:
+ selected_agent = ensure_agent_selection_access(
+ conn,
+ agent_name=None if agent_name is _UNSET else agent_name,
+ agent_id=None if agent_id is _UNSET else agent_id,
+ user_context=resource_context,
+ )
+ if selected_agent is None and resource_context.is_remote:
+ selected_agent = ensure_default_agent_access(
+ conn,
+ user_context=resource_context,
+ missing_is_error=True,
+ )
+ if selected_agent is not None:
+ requested_backend = str(agent_backend or "").strip() if agent_backend is not _UNSET else ""
+ if requested_backend and requested_backend != selected_agent.backend:
+ raise ValueError("Agent backend does not match selected Agent")
+ agent_id = selected_agent.id
+ agent_name = selected_agent.name
+ if not requested_backend:
+ agent_backend = selected_agent.backend
+ derived_backend = True
+ else:
+ # Preserve legacy local names/ids that predate the Agent catalog,
+ # but clear the omitted half so it cannot remain stale.
+ requested_name = "" if agent_name is _UNSET else str(agent_name or "").strip()
+ requested_id = "" if agent_id is _UNSET else str(agent_id or "").strip()
+ agent_name = requested_name or None
+ agent_id = requested_id or None
+ if agent_backend is _UNSET and requested_name:
+ agent_backend = _backend_for_agent_name(conn, requested_name)
+ derived_backend = True
+
+ if (
+ resource_context.is_remote
+ and agent_backend is not _UNSET
+ and bool(str(agent_backend or "").strip())
+ and selected_agent is None
+ ):
+ raise VibeAgentAccessError("Agent access is not permitted.")
# Backend is pinned once a NATIVE conversation exists: the native can only
# be resumed by the backend that created it, so switching (or clearing) the
@@@ -1101,26 -1076,8 +1260,27 @@@ def archive_session
Returns the archived session payload plus a ``reclaimed`` summary
(``{tasks, watches, runs}``) for the confirm-dialog / post-archive notice.
+
+ THE RESERVED WORKSPACE-NOTICE SESSION IS REFUSED, and the refusal is on IDENTITY
+ rather than on row state, so a race that removes the row cannot turn it into a
+ 404-and-then-archive. That row is D5 rung (5)'s home (see
+ ``storage.agent_session_rows.resolve_workspace_notice_session``); it is ``system``,
+ so it is NOT one click from a session list any more — but it is still one ``DELETE
+ /api/sessions/ses-workspace-notices`` from anyone holding the id (the inbox card
+ carries it), and archiving it fails SILENTLY. Everything downstream disagrees about
+ what archived means: ``_session_row`` has no status filter so a later notice still
+ persists and still earns its receipt — the notice is stamped ``sent`` — while
+ ``list_inbox_sessions`` excludes archived sessions, so no card, no realtime event and
+ no push. Every subsequent caller-less failure would be recorded as delivered into a
+ surface nothing displays. Hiding the row from the lists narrows the blast radius; it
+ does not replace this guard, which is why both exist.
+
+ Checked BEFORE the existence lookup so the answer is the same on every install,
+ whether or not the lazily-created row exists yet.
"""
+ if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
+ raise ReservedSessionError(str(session_id))
+ context = require_instance_role(authorization_context, "editor")
existing = conn.execute(
select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)
).scalar_one_or_none()
@@@ -1260,3 -1220,21 +1434,14 @@@ def set_agent_status(conn: Connection,
update(agent_sessions).where(agent_sessions.c.id == session_id).values(agent_status=status)
)
return True
+
+
+ def reset_running_agent_status(conn: Connection) -> int:
- """Reset every ``running`` session to ``idle`` (startup crash recovery).
-
- No turn survives a controller restart, so a ``running`` left in the table
- is stale. Returns the number of rows reset. The browser reconciles the reset
- by refetching sessions when its inbox-event stream (re)connects, NOT from a
- broadcast — this runs in ``Controller.__init__`` before any event subscriber
- exists, so a broadcast here would be dropped.
- """
++ """Reset legacy ``running`` projections to ``idle`` during recovery."""
+
+ result = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.agent_status == "running")
+ .values(agent_status="idle")
+ )
+ return result.rowcount or 0
diff --cc tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index f1da014af,fad9b0036..5b18fa989
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@@ -9,16 -8,13 +9,21 @@@ from unittest.mock import AsyncMock, pa
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
+from config.v2_config import (
+ ModelHubModelConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+)
+from core.handlers.model_hub.service import ModelHubError
+from modules.agents.codex.agent import CodexAgent
from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
+from tests.scenario_harness.model_hub_native_oauth import NativeOAuthScenarioHarness
+ from tests.scenario_harness.organization_management import (
+ REMOTE_ORIGIN,
+ OrganizationManagementScenarioHarness,
+ )
+ from vibe import cloud_management
class _FakeNextTurnRuntime:
@@@ -50,15 -46,265 +55,274 @@@ class _FakeCodexNextTurnRuntime
return "turn-ok"
+class _CodexProviderBindingSessions:
+ def get_agent_session_id(self, *_args, **_kwargs):
+ return "thread-existing"
+
+ def ensure_agent_session_id(self, *_args, **_kwargs):
+ return "ses-provider"
+
+ def bind_agent_session(self, *_args, **_kwargs):
+ return "ses-provider"
+ class OrganizationManagementAuthScenarioTests(unittest.TestCase):
+ def setUp(self):
+ self.harness = OrganizationManagementScenarioHarness()
+ self.addCleanup(self.harness.close)
+
+ def test_explicit_management_sign_in_starts_interactive_handoff(self):
+ """Scenario: AUTH-SETUP-301"""
+ client = self.harness.remote_client()
+ with patch.object(
+ cloud_management,
+ "begin_authorization",
+ return_value=("https://avibe.bot/oauth/management/authorize?state=state-1", "state-1"),
+ ) as begin:
+ response = client.post(
+ "/api/cloud-management/session/start",
+ json={"mode": "interactive", "next": "/admin/organization/members"},
+ headers=self.harness.csrf(client),
+ base_url=REMOTE_ORIGIN,
+ )
+
+ self.assertEqual(response.status_code, 202)
+ self.assertEqual(response.get_json()["mode"], "interactive")
+ begin.assert_called_once()
+ self.assertFalse(begin.call_args.kwargs["silent"])
+ self.assertEqual(begin.call_args.kwargs["remote_subject"], "user-1")
+
+ def test_silent_reauthorization_stops_after_login_required(self):
+ """Scenarios: AUTH-SETUP-302, AUTH-SETUP-306"""
+ client = self.harness.remote_client()
+ with patch.object(
+ cloud_management,
+ "begin_authorization",
+ return_value=("https://avibe.bot/oauth/management/authorize?prompt=none", "state-1"),
+ ) as begin:
+ first = client.post(
+ "/api/cloud-management/session/start",
+ json={"mode": "silent", "next": "/admin/organization/overview"},
+ headers=self.harness.csrf(client),
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(first.status_code, 202)
+ self.assertTrue(begin.call_args.kwargs["silent"])
+
+ with patch.object(
+ cloud_management,
+ "fail_handshake",
+ return_value="/admin/organization/overview",
+ ):
+ callback = client.get(
+ "/auth/organization/callback?error=login_required&state=state-1",
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(callback.status_code, 302)
+ self.assertIn("cloud_management_error=login_required", callback.headers["location"])
+
+ second = client.post(
+ "/api/cloud-management/session/start",
+ json={"mode": "silent", "next": "/admin/organization/overview"},
+ headers=self.harness.csrf(client),
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(second.status_code, 401)
+
+ def test_logout_suppresses_silent_reauthorization(self):
+ """Scenario: AUTH-SETUP-303"""
+ client = self.harness.remote_client()
+ client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")
+ client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")
+ logout = client.delete(
+ "/api/cloud-management/session",
+ headers=self.harness.csrf(client),
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(logout.status_code, 200)
+ session = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)
+ self.assertEqual(session.status_code, 200)
+ self.assertFalse(session.get_json()["can_silent_reauthorize"])
+
+ def test_subject_mismatch_is_terminal(self):
+ """Scenario: AUTH-SETUP-304"""
+ client = self.harness.remote_client()
+ client.set_cookie(cloud_management.HANDLE_COOKIE_NAME, "grant-1", domain="alex.avibe.bot")
+ client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")
+ with patch.object(
+ cloud_management,
+ "resolve_grant",
+ return_value=(None, "cloud_management_subject_mismatch"),
+ ):
+ response = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)
+ self.assertEqual(response.status_code, 409)
+ self.assertEqual(response.get_json()["state"], "subject_mismatch")
+
+ def test_invalid_callback_token_requires_manual_sign_in(self):
+ """Scenario: AUTH-SETUP-305"""
+ client = self.harness.remote_client()
+ client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")
+ with patch.object(
+ cloud_management,
+ "complete_authorization",
+ side_effect=cloud_management.CloudManagementError(
+ "invalid_cloud_management_token",
+ status=400,
+ ),
+ ):
+ response = client.get(
+ "/auth/organization/callback?code=bad-code&state=bad-state",
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(response.status_code, 302)
+ self.assertIn("cloud_management_error=invalid_cloud_management_token", response.headers["location"])
+ session = client.get("/api/cloud-management/session", base_url=REMOTE_ORIGIN)
+ self.assertFalse(session.get_json()["can_silent_reauthorize"])
+
+ def test_remote_callback_keeps_the_bound_subject(self):
+ """Scenario: AUTH-SETUP-307"""
+ backend = SimpleNamespace(base_url="https://avibe.bot")
+ with patch.object(cloud_management, "_validated_backend", return_value=backend):
+ _, state = cloud_management.begin_authorization(
+ self.harness.config,
+ browser_id="browser-1",
+ remote_subject="user-1",
+ callback_origin=REMOTE_ORIGIN,
+ next_path="/admin/organization/overview",
+ silent=False,
+ )
+ client = self.harness.remote_client(subject="user-2")
+ client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")
+ token_payload = {
+ "access_token": "not-exposed",
+ "token_type": "Bearer",
+ "subject": "user-2",
+ "vibe_instance_id": "inst_123",
+ }
+ token_claims = {
+ "sub": "user-2",
+ "email": "[email protected]",
+ "vibe_instance_id": "inst_123",
+ "exp": 4_102_444_800,
+ }
+ with (
+ patch.object(cloud_management, "_backend_request", return_value=(200, token_payload)),
+ patch.object(cloud_management, "_validate_management_token", return_value=token_claims),
+ ):
+ response = client.get(
+ f"/auth/organization/callback?code=code-1&state={state}",
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(response.status_code, 302)
+ self.assertIn("cloud_management_error=cloud_management_subject_mismatch", response.headers["location"])
+ self.assertNotIn("not-exposed", response.text)
+
+ def test_trusted_loopback_flow_can_establish_the_first_subject(self):
+ """Scenario: AUTH-SETUP-308"""
+ client = self.harness.unbound_remote_client()
+ client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")
+ grant = cloud_management.ManagementGrant(
+ handle="grant-1",
+ browser_id="browser-1",
+ subject="first-user",
+ token="not-exposed",
+ expires_at=4_102_444_800,
+ )
+ with patch.object(
+ cloud_management,
+ "complete_authorization",
+ return_value=(grant, "/admin/organization/overview"),
+ ) as complete:
+ response = client.get(
+ "/auth/organization/callback?code=code-1&state=state-1",
+ base_url=REMOTE_ORIGIN,
+ )
+ self.assertEqual(response.status_code, 302)
+ self.assertIsNone(complete.call_args.kwargs["remote_subject"])
+
+ def test_unbound_loopback_requires_interactive_sign_in(self):
+ """Scenario: AUTH-SETUP-309"""
+ client = self.harness.unbound_remote_client()
+ loopback_origin = "http://127.0.0.1:15131"
+
+ session = client.get("/api/cloud-management/session", base_url=loopback_origin)
+ silent = client.post(
+ "/api/cloud-management/session/start",
+ json={"mode": "silent", "next": "/admin/organization/overview"},
+ headers=self.harness.csrf(client, loopback_origin),
+ base_url=loopback_origin,
+ )
+
+ self.assertEqual(session.status_code, 200)
+ self.assertFalse(session.get_json()["can_silent_reauthorize"])
+ self.assertEqual(silent.status_code, 401)
+ self.assertEqual(
+ silent.get_json(),
+ {
+ "error": "cloud_management_authorization_required",
+ "retryable": False,
+ },
+ )
+
+ def test_subject_mismatch_can_reenter_with_clean_return_path(self):
+ """Scenario: AUTH-SETUP-310"""
+ client = self.harness.remote_client()
+ client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")
+ with patch.object(
+ cloud_management,
+ "complete_authorization",
+ side_effect=cloud_management.CloudManagementError(
+ "cloud_management_subject_mismatch",
+ status=409,
+ ),
+ ):
+ mismatch = client.get(
+ "/auth/organization/callback?code=wrong-user&state=state-1",
+ base_url=REMOTE_ORIGIN,
+ )
+
+ self.assertEqual(mismatch.status_code, 302)
+ self.assertIn(
+ "cloud_management_error=cloud_management_subject_mismatch",
+ mismatch.headers["location"],
+ )
+
+ clean_next = "/admin/organization/overview"
+ with patch.object(
+ cloud_management,
+ "begin_authorization",
+ return_value=("https://avibe.bot/oauth/management/authorize?state=state-2", "state-2"),
+ ) as begin:
+ reentry = client.post(
+ "/api/cloud-management/session/start",
+ json={"mode": "interactive", "next": clean_next},
+ headers=self.harness.csrf(client),
+ base_url=REMOTE_ORIGIN,
+ )
+
+ self.assertEqual(reentry.status_code, 202)
+ self.assertEqual(begin.call_args.kwargs["next_path"], clean_next)
+
+ grant = cloud_management.ManagementGrant(
+ handle="grant-2",
+ browser_id="browser-1",
+ subject="user-1",
+ token="not-exposed",
+ expires_at=4_102_444_800,
+ )
+ with patch.object(
+ cloud_management,
+ "complete_authorization",
+ return_value=(grant, clean_next),
+ ):
+ success = client.get(
+ "/auth/organization/callback?code=right-user&state=state-2",
+ base_url=REMOTE_ORIGIN,
+ )
+
+ self.assertEqual(success.status_code, 302)
+ self.assertEqual(success.headers["location"], clean_next)
+ self.assertNotIn("cloud_management_error", success.headers["location"])
class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
diff --cc tests/test_controller_dispatch_loop.py
index cf6c7032c,85b24d169..8df3501f9
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@@ -423,27 -422,86 +424,110 @@@ def test_terminal_checkpoint_runs_after
assert order == ["checkpoint-start", "delivered", "checkpoint-end"]
+def test_terminal_delivery_failure_keeps_turn_owner_live() -> None:
+ controller = Controller.__new__(Controller)
+ completed: list[MessageContext] = []
+
+ class _Dispatcher:
+ @staticmethod
+ async def emit_agent_message(**_kwargs):
+ raise RuntimeError("Workbench run output was not durably persisted")
+
+ controller.message_dispatcher = _Dispatcher()
+ controller.session_turns = SimpleNamespace(
+ on_terminal_delivery_complete=lambda context: completed.append(context)
+ )
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"turn_token": "turn-live"},
+ )
+
+ with pytest.raises(RuntimeError, match="not durably persisted"):
+ asyncio.run(controller.emit_agent_message(context, "result", "done"))
+
+ assert completed == []
+ def test_cleanup_sync_settles_the_internal_server_task(tmp_path, monkeypatch) -> None:
+ """Shutdown must cancel the task, not just abandon it.
+
+ Leaving it pending meant the done callback that records "stopped" never
+ ran, so ``internal-server.json`` kept "ready" and ``vibe status`` reported a
+ ready internal server against a service that no longer existed.
+ """
+
+ from config import paths
+ from core import internal_server
+
+ status_path = tmp_path / "runtime" / "internal-server.json"
+ monkeypatch.setattr(paths, "get_internal_server_status_path", lambda: status_path)
+
+ controller = Controller.__new__(Controller)
+ loop = asyncio.new_event_loop()
+ controller._loop = loop
+
+ class _Stopper:
+ async def stop(self) -> None:
+ return None
+
+ controller.scheduled_task_service = _Stopper()
+ controller.watch_service = _Stopper()
+ controller.runtime_command_watcher = _Stopper()
+ controller.update_checker = type("UpdateChecker", (), {"stop": lambda self: None})()
+ controller.receiver_tasks = {}
+ controller.im_client = None
+ controller._im_thread = None
+
+ async def never_returns() -> None:
+ await asyncio.Event().wait()
+
+ task = loop.create_task(never_returns())
+ controller._internal_server_task = task
+
+ try:
+ controller.cleanup_sync()
+ finally:
+ loop.close()
+
+ assert task.cancelled()
+ assert controller._internal_server_task is None
+ assert json.loads(status_path.read_text(encoding="utf-8"))["state"] == "stopped"
+
+
+ def test_cleanup_sync_cancels_memory_reconcile_before_closing_runtime() -> None:
+ controller = Controller.__new__(Controller)
+ loop = asyncio.new_event_loop()
+ controller._loop = loop
+ controller.cleanup_task = None
+
+ class _Stopper:
+ async def stop(self) -> None:
+ return None
+
+ controller.scheduled_task_service = _Stopper()
+ controller.watch_service = _Stopper()
+ controller.runtime_command_watcher = _Stopper()
+ controller.update_checker = type("UpdateChecker", (), {"stop": lambda self: None})()
+ controller.receiver_tasks = {}
+ controller.im_client = None
+ controller._im_thread = None
+
+ async def never_returns() -> None:
+ await asyncio.Event().wait()
+
+ reconcile_task = loop.create_task(never_returns())
+ controller._memory_reconcile_task = reconcile_task
+
+ class _MemoryRuntime:
+ async def close(self) -> None:
+ assert reconcile_task.cancelled()
+
+ controller.memory_runtime = _MemoryRuntime()
+
+ try:
+ controller.cleanup_sync()
+ finally:
+ loop.close()
+
+ assert reconcile_task.cancelled()
+ assert controller._memory_reconcile_task is None
diff --cc tests/test_core_services_sessions.py
index 862c475fc,56b1bef6c..be584f6e5
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@@ -84,20 -85,12 +85,22 @@@ def test_public_surface_is_stable()
"reserve_standalone_agent_session",
# Backend-pin guard raised by update_session on a cross-backend switch:
"SessionBackendLockedError",
+ # Terminal-archive guard raised by update_session on an archived row:
+ "SessionArchivedError",
+ # Localized user-facing copy for that guard's 409 body:
+ "session_archived_message",
+ # Reserved-row guard raised by archive_session for the workspace-notifications
+ # session (D5 rung (5)'s home): archive is terminal, and archiving that row
+ # would silently swallow every later caller-less failure notice.
+ "ReservedSessionError",
+ # Stable authorization denial translated by API callers:
+ "ProjectAccessDeniedError",
}
- assert set(sessions_service.__all__) == expected
+ assert set(sessions_service.__all__) == expected | {"SESSION_ARCHIVED_I18N_KEY"}
for name in expected:
assert callable(getattr(sessions_service, name))
+ # The one non-callable member: the i18n key constant the parity guard pins.
+ assert isinstance(sessions_service.SESSION_ARCHIVED_I18N_KEY, str)
def test_each_workbench_function_delegates_to_storage():
@@@ -762,121 -746,3 +766,137 @@@ def test_update_session_legacy_blank_ba
# Now pinned: a different backend is rejected.
with pytest.raises(sessions_service.SessionBackendLockedError):
sessions_service.update_session(conn, sid, agent_backend="claude", agent_name="claude")
+
+
+# --- HFR-247: the override marker must not outlive the columns it describes ----
+
+
+def test_workbench_default_action_drops_the_explicit_override_marker(isolated_state, tmp_path):
+ """HFR-247 — the Chat header's "Default" must actually restore the defaults.
+
+ ``agent_sessions.metadata_json.explicit_setting_overrides`` tells dispatch
+ that this session's NULL ``model`` / ``reasoning_effort`` are a deliberate pin
+ ("inherit nothing"), not the ordinary "inherit from the Agent". Only the
+ ``create_once`` rebind wrote it -- but any writer of those columns replaces
+ what the marker describes. ``update_session`` only rewrote ``metadata_json``
+ on a title change or a scope move, so the Workbench "Default" action (present
+ nulls for the whole route) left the marker in place: the session then showed a
+ cleared route, and every turn still ran with NO model and NO reasoning effort
+ while claiming to run as the default Agent. The control looked like it worked
+ and routed nothing.
+ """
+
+ import asyncio
+
+ from config import paths
+ from core.handlers.message_handler import MessageHandler
+ from core.internal_server import _build_session_context
+ from core.vibe_agents import VibeAgentStore
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+ from tests.test_scheduled_tasks import _DispatchController, _DispatchSessionHandler
+
+ workdir = tmp_path / "workdir"
+ workdir.mkdir()
+
+ agent_store = VibeAgentStore()
+ try:
+ agent_store.ensure_builtin_default_agents(["codex"])
+ agent_store.set_default_agent_name("codex")
+ # The Agent the cleared session must fall back to. Distinctive values so
+ # "inherited the Agent's defaults" cannot pass on a None == None compare.
+ default_agent = agent_store.update(
+ "codex", model="gpt-5.5-default", reasoning_effort="xhigh"
+ )
+ finally:
+ agent_store.close()
+ assert default_agent.model == "gpt-5.5-default"
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn, workdir=str(workdir))
+ # A session that pins NOTHING on purpose -- the shape a preserved
+ # ``create_once`` rebind reserves (D3) and the user then opens in Chat.
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+ sid = session["id"]
+
+ # An UNRELATED edit must not touch a marker entry it knows nothing about.
+ renamed = sessions_service.update_session(conn, sid, title="Nightly digest")
+ assert renamed["metadata"][SESSION_SETTINGS_OVERRIDE_KEY] == [
+ "model",
+ "reasoning_effort",
+ ], "a title-only edit dropped an override marker it never wrote"
+
+ # The Chat header's "Default" item: present nulls for the whole route.
+ cleared = sessions_service.update_session(
+ conn,
+ sid,
+ agent_id=None,
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ )
+
+ assert cleared["model"] is None
+ assert cleared["reasoning_effort"] is None
+ assert SESSION_SETTINGS_OVERRIDE_KEY not in cleared["metadata"], (
+ "'Default' replaced model/reasoning_effort but left the explicit-override "
+ "marker, so dispatch keeps honouring a pin the user just removed"
+ )
+ # The title metadata the earlier edit wrote is still there: reconciling the
+ # marker must compose with the other metadata writers, not replace them.
+ assert cleared["metadata"]["title_source"] == "user"
+
+ # The deliverable is the turn, not the row. Build the REAL workbench dispatch
+ # context from the stored row and run the REAL MessageHandler.
+ context = _build_session_context(sid, message_id="m1")
+ controller = _DispatchController(paths.get_sqlite_state_path(), workdir)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_DispatchSessionHandler(str(workdir)))
+ controller.message_handler = handler
+ controller.session_handler = handler.session_handler
+ try:
+ asyncio.run(handler.handle_user_message(context, "hello"))
+ finally:
+ controller.sessions.close()
+ controller.vibe_agent_store.close()
+
+ assert len(controller.agent_service.dispatched) == 1
+ backend_name, request = controller.agent_service.dispatched[0]
+ assert backend_name == default_agent.backend
+ assert request.vibe_agent_name == default_agent.name
+ assert request.vibe_agent_model == "gpt-5.5-default", (
+ f"dispatch handed the backend model={request.vibe_agent_model!r}: the stale "
+ "marker still forces the cleared session's NULL, so 'Default' changed the "
+ "stored row and nothing else"
+ )
+ assert request.vibe_agent_reasoning_effort == "xhigh", (
+ f"dispatch handed the backend reasoning_effort="
+ f"{request.vibe_agent_reasoning_effort!r} instead of the default Agent's"
+ )
++
++
++def test_reset_running_agent_status_clears_only_running(isolated_state):
++ """Startup recovery: stale ``running`` → ``idle``; failed/idle untouched."""
++ engine = create_sqlite_engine()
++ with engine.begin() as conn:
++ scope_id = _seed_avibe_scope(conn)
++ running = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]
++ failed = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]
++ sessions_service.set_agent_status(conn, running, "running")
++ sessions_service.set_agent_status(conn, failed, "failed")
++ reset = sessions_service.reset_running_agent_status(conn)
++ assert reset == 1
++ with engine.connect() as conn:
++ assert sessions_service.get_session(conn, running)["agent_status"] == "idle"
++ assert sessions_service.get_session(conn, failed)["agent_status"] == "failed"
diff --cc tests/test_internal_client.py
index 888ff99c8,03ac1223f..7cc5df798
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@@ -100,31 -120,7 +120,30 @@@ def test_dispatch_async_missing_socket_
asyncio.run(internal_client.dispatch_async({"session_id": "s", "text": "x"}, socket_path=sock))
- def test_dispatch_async_read_timeout_reports_acceptance_unknown(tmp_path):
- sock = tmp_path / "dispatch.sock"
- sock.touch()
-def test_reconcile_platforms_round_trip(tmp_path, socket_path):
++def test_dispatch_async_read_timeout_reports_acceptance_unknown(socket_path):
++ sock = socket_path
+
+ class TimingOutClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def post(self, _path, json):
+ raise httpx.ReadTimeout("response deadline elapsed")
+
+ with patch("vibe.internal_client.httpx.AsyncClient", return_value=TimingOutClient()):
+ with pytest.raises(internal_client.InternalServerTimeout):
+ asyncio.run(
+ internal_client.dispatch_async(
+ {"session_id": "s", "text": "x"},
+ socket_path=sock,
+ )
+ )
+
+
- def test_reconcile_platforms_round_trip(tmp_path):
++def test_reconcile_platforms_round_trip(socket_path):
app = FastAPI()
calls: list[bool] = []
diff --cc tests/test_internal_server.py
index df5ea87bb,6a392d68c..c5f9cc3b2
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@@ -16,8 -16,11 +16,12 @@@ We exercise three layers
from __future__ import annotations
import asyncio
+import contextlib
+ import errno
+ import json
+ import os
import socket
+ import stat
import sys
import tempfile
import types
@@@ -31,16 -32,10 +35,17 @@@ from sqlalchemy import selec
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+ from config import paths
from core import internal_server, session_turns
-from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from core.services.dispatch import (
+ SOURCE_HUMAN,
+ SOURCE_SCHEDULED,
+ TurnDispatchOutcome,
+ dispatch_turn,
+)
from modules.im import MessageContext
+from storage import message_deliveries
# ---------------------------------------------------------------------
@@@ -334,11 -343,495 +516,451 @@@ def test_create_app_exposes_minimal_end
assert ("/internal/reconcile-agent-backends", ("POST",)) in routes
assert ("/internal/model-hub", ("POST",)) in routes
assert ("/internal/cancel/{session_id}", ("POST",)) in routes
- assert ("/internal/dispatch", ("POST",)) in routes
+ assert ("/internal/dispatch", ("POST",)) not in routes
assert ("/internal/events", ("GET",)) in routes
assert ("/internal/events", ("POST",)) in routes
+ assert ("/internal/reconcile-memory", ("POST",)) in routes
+ assert ("/internal/memory/install-runtime", ("POST",)) in routes
+ assert ("/internal/memory/status", ("GET",)) in routes
+ assert ("/internal/memory/failures", ("GET",)) in routes
+ assert ("/internal/memory/profile", ("GET",)) in routes
+ assert ("/internal/memory/search", ("POST",)) in routes
+ assert ("/internal/memory/remember", ("POST",)) in routes
+ assert ("/internal/memory/clear", ("POST",)) in routes
+
+
+ def test_memory_internal_routes_only_accept_typed_operations(monkeypatch):
+ from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof
+
+ controller = _build_controller_double()
+ calls: list[tuple[str, object]] = []
+ capture_finished = asyncio.Event()
+
+ class _Module:
+ async def capture(self, request):
+ calls.append(("capture", request))
+ capture_finished.set()
+ return types.SimpleNamespace(status="accepted")
+
+ class _Runtime:
+ def __init__(self):
+ self.module = _Module()
+
+ async def status_payload(self):
+ calls.append(("status", None))
+ return {"state": "ready", "data_exists": True}
+
+ async def failure_log_payload(self):
+ calls.append(("failures", None))
+ return {"items": [], "retention_days": 90}
+
+ def principal_for_user_key(self, user_key):
+ assert user_key == "avibe:local"
+ return "u-11111111111111111111111111111111"
+
+ async def profile_payload(self, principal_id):
+ calls.append(("profile", principal_id))
+ return {"status": "ok", "items": []}
+
+ async def search_payload(self, query, limit, principal_id):
+ calls.append(("search", (query, limit, principal_id)))
+ return {"status": "ok", "items": []}
+
+ async def clear(self):
+ calls.append(("clear", None))
+ return {"status": "completed", "epoch": 2}
+
+ async def install_artifact(self):
+ calls.append(("install", None))
+ return {"ok": False, "reason": "memory_runtime_unpublished", "download_error": None}
+
+ async def reconcile_memory(config):
+ calls.append(("reconcile", config))
+ return {"ok": True, "state": "ready"}
+
+ controller.memory_runtime = _Runtime()
+ _set_memory_cli_sessions(
+ controller,
+ {"session-1": "u-11111111111111111111111111111111"},
+ )
+ controller.reconcile_memory = reconcile_memory
+ monkeypatch.setattr("config.v2_config.V2Config.load", lambda: types.SimpleNamespace(memory="configured-memory"))
+ memory_ui_secret = "test-ui-controller-secret"
+ app = internal_server.create_app(controller, memory_ui_secret=memory_ui_secret)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ user_headers = {
+ "X-Avibe-Memory-User-Key": "avibe:local",
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ memory_ui_secret,
+ method="GET",
+ path="/internal/memory/profile",
+ user_key="avibe:local",
+ ),
+ }
+ search_headers = {
+ "X-Avibe-Memory-User-Key": "avibe:local",
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ memory_ui_secret,
+ method="POST",
+ path="/internal/memory/search",
+ user_key="avibe:local",
+ ),
+ }
+ session_headers = {"X-Avibe-Caller-Session": "session-1"}
+ clear_headers = {
+ "X-Avibe-Memory-User-Key": "avibe:local",
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ memory_ui_secret,
+ method="POST",
+ path="/internal/memory/clear",
+ user_key="avibe:local",
+ ),
+ }
+ responses = (
+ await client.get("/internal/memory/status"),
+ await client.get("/internal/memory/failures"),
+ await client.get("/internal/memory/profile", headers=user_headers),
+ await client.post(
+ "/internal/memory/search",
+ json={"query": "safe query", "limit": 3},
+ headers=search_headers,
+ ),
+ await client.post(
+ "/internal/memory/remember",
+ json={"text": "ordinary text"},
+ headers=session_headers,
+ ),
+ await client.post(
+ "/internal/memory/clear",
+ json={"confirm": True},
+ headers=clear_headers,
+ ),
+ await client.post("/internal/memory/install-runtime"),
+ await client.post("/internal/reconcile-memory"),
+ await client.post("/internal/memory/search", json=[], headers=search_headers),
+ await client.post(
+ "/internal/memory/remember",
+ json={"text": ""},
+ headers=session_headers,
+ ),
+ )
+ await asyncio.wait_for(capture_finished.wait(), timeout=1)
+ return responses
+
+ status, failures, profile, search, capture, clear, install, reconcile, invalid, invalid_capture = asyncio.run(_go())
+
+ assert status.json() == {"state": "ready", "data_exists": True}
+ assert failures.json() == {"items": [], "retention_days": 90}
+ assert profile.json() == {"status": "ok", "items": []}
+ assert search.json() == {"status": "ok", "items": []}
+ assert capture.json() == {"status": "accepted"}
+ assert clear.json() == {"status": "completed", "epoch": 2}
+ assert install.json() == {"ok": False, "reason": "memory_runtime_unpublished", "download_error": None}
+ assert reconcile.json() == {"ok": True, "state": "ready"}
+ assert invalid.status_code == 400
+ assert invalid_capture.status_code == 400
+ assert [name for name, _value in calls if name != "capture"] == [
+ "status",
+ "failures",
+ "profile",
+ "search",
+ "clear",
+ "install",
+ "reconcile",
+ ]
+ captured_request = next(value for name, value in calls if name == "capture")
+ assert captured_request.source_message_id.startswith(
+ "agent:u-11111111111111111111111111111111:session-1:"
+ )
+ assert captured_request.session_id == "session-1"
+ assert captured_request.principal_id == "u-11111111111111111111111111111111"
+ assert captured_request.provenance == "agent"
+
+
+ def test_memory_remember_idempotency_is_scoped_to_the_principal():
+ controller = _build_controller_double()
+ captures = []
+
+ class _Module:
+ async def capture(self, request):
+ captures.append(request)
+ return types.SimpleNamespace(status="accepted")
+
+ controller.memory_runtime = types.SimpleNamespace(module=_Module())
+ first_principal = "u-11111111111111111111111111111111"
+ second_principal = "u-22222222222222222222222222222222"
+ principals = {"shared-session": first_principal}
+ _set_memory_cli_sessions(controller, principals)
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ first = await client.post(
+ "/internal/memory/remember",
+ json={"text": "same text"},
+ headers={"X-Avibe-Caller-Session": "shared-session"},
+ )
+ principals["shared-session"] = second_principal
+ second = await client.post(
+ "/internal/memory/remember",
+ json={"text": "same text"},
+ headers={"X-Avibe-Caller-Session": "shared-session"},
+ )
+ return first, second
+
+ first, second = asyncio.run(_go())
+
+ assert first.status_code == second.status_code == 200
+ assert [request.principal_id for request in captures] == [first_principal, second_principal]
+ assert captures[0].source_message_id != captures[1].source_message_id
+
+
+ def test_memory_clear_accepts_only_a_clear_scoped_ui_proof() -> None:
+ from core.memory.http_headers import CALLER_SESSION_HEADER, MEMORY_USER_KEY_HEADER
+ from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof
+
+ controller = _build_controller_double()
+ controller.memory_runtime = types.SimpleNamespace(
+ clear=AsyncMock(return_value={"status": "completed", "epoch": 2}),
+ )
+ _set_memory_cli_sessions(
+ controller,
+ {"session-1": "u-11111111111111111111111111111111"},
+ )
+ secret = "test-ui-controller-secret"
+ app = internal_server.create_app(controller, memory_ui_secret=secret)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ no_proof = await client.post("/internal/memory/clear", json={"confirm": True})
+ agent_session = await client.post(
+ "/internal/memory/clear",
+ json={"confirm": True},
+ headers={CALLER_SESSION_HEADER: "session-1"},
+ )
+ profile_proof = await client.post(
+ "/internal/memory/clear",
+ json={"confirm": True},
+ headers={
+ MEMORY_USER_KEY_HEADER: "avibe:local",
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ secret,
+ method="GET",
+ path="/internal/memory/profile",
+ user_key="avibe:local",
+ ),
+ },
+ )
+ clear_proof = await client.post(
+ "/internal/memory/clear",
+ json={"confirm": True},
+ headers={
+ MEMORY_USER_KEY_HEADER: "avibe:local",
+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(
+ secret,
+ method="POST",
+ path="/internal/memory/clear",
+ user_key="avibe:local",
+ ),
+ },
+ )
+ return no_proof, agent_session, profile_proof, clear_proof
+
+ no_proof, agent_session, profile_proof, clear_proof = asyncio.run(_go())
+
+ assert [no_proof.status_code, agent_session.status_code, profile_proof.status_code] == [403, 403, 403]
+ assert clear_proof.status_code == 200
+ controller.memory_runtime.clear.assert_awaited_once_with()
+
+
+ def test_memory_internal_reads_reject_an_unassociated_agent_session():
+ controller = _build_controller_double()
+ calls: list[str] = []
+
+ class _Runtime:
+ async def profile_payload(self, principal_id):
+ calls.append("profile")
+ return {"status": "ok", "items": []}
+
+ controller.memory_runtime = _Runtime()
+ _set_memory_cli_sessions(controller, {})
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.get(
+ "/internal/memory/profile",
+ headers={
+ "X-Avibe-Caller-Session": "ses-non-admin",
+ },
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 403
+ assert response.json() == {"status": "failed", "error": "memory_access_denied"}
+ assert calls == []
+
+
+ def test_memory_internal_reads_accept_an_associated_agent_session():
+ from core.memory.http_headers import CALLER_SESSION_HEADER
+
+ controller = _build_controller_double()
+ controller.memory_runtime = types.SimpleNamespace(
+ profile_payload=AsyncMock(return_value={"status": "ok", "items": []})
+ )
+ principal_id = "u-11111111111111111111111111111111"
+ _set_memory_cli_sessions(controller, {"ses-admin": principal_id})
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.get(
+ "/internal/memory/profile",
+ headers={CALLER_SESSION_HEADER: "ses-admin"},
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 200
+ assert response.json() == {"status": "ok", "items": []}
+ controller.memory_runtime.profile_payload.assert_awaited_once_with(principal_id)
+
+
+ def test_memory_internal_read_rejects_agent_session_with_forged_local_owner_header():
+ from core.memory.http_headers import (
+ CALLER_SESSION_HEADER,
+ MEMORY_USER_KEY_HEADER,
+ )
+
+ controller = _build_controller_double()
+ controller.memory_runtime = types.SimpleNamespace(
+ principal_for_user_key=Mock(return_value="u-11111111111111111111111111111111"),
+ profile_payload=AsyncMock(return_value={"status": "ok", "items": []}),
+ )
+ _set_memory_cli_sessions(
+ controller,
+ {"ses-user-b": "u-22222222222222222222222222222222"},
+ )
+ app = internal_server.create_app(
+ controller,
+ memory_ui_secret="test-ui-controller-secret",
+ )
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.get(
+ "/internal/memory/profile",
+ headers={
+ CALLER_SESSION_HEADER: "ses-user-b",
+ MEMORY_USER_KEY_HEADER: "avibe:local",
+ },
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 403
+ controller.memory_runtime.principal_for_user_key.assert_not_called()
+ controller.memory_runtime.profile_payload.assert_not_awaited()
+
+
+ def test_memory_internal_reads_keep_two_session_principals_isolated():
+ from core.memory.http_headers import CALLER_SESSION_HEADER
+
+ first_principal = "u-11111111111111111111111111111111"
+ second_principal = "u-22222222222222222222222222222222"
+ calls: list[tuple[str, str]] = []
+
+ class _Runtime:
+ async def profile_payload(self, principal_id):
+ calls.append(("profile", principal_id))
+ return {"status": "ok", "items": [{"kind": "profile", "text": principal_id}]}
+
+ async def search_payload(self, _query, _limit, principal_id):
+ calls.append(("search", principal_id))
+ return {"status": "ok", "items": [{"kind": "fact", "text": principal_id}]}
+
+ controller = _build_controller_double()
+ controller.memory_runtime = _Runtime()
+ _set_memory_cli_sessions(
+ controller,
+ {"session-1": first_principal, "session-2": second_principal},
+ )
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ first_headers = {CALLER_SESSION_HEADER: "session-1"}
+ second_headers = {CALLER_SESSION_HEADER: "session-2"}
+ return (
+ await client.get("/internal/memory/profile", headers=first_headers),
+ await client.post(
+ "/internal/memory/search",
+ json={"query": "mine", "limit": 3},
+ headers=second_headers,
+ ),
+ await client.get("/internal/memory/profile"),
+ await client.post("/internal/memory/search", json={"query": "none", "limit": 3}),
+ )
+
+ first, second, unscoped_profile, unscoped_search = asyncio.run(_go())
+
+ assert first.json()["items"][0]["text"] == first_principal
+ assert second.json()["items"][0]["text"] == second_principal
+ assert unscoped_profile.status_code == 403
+ assert unscoped_search.status_code == 403
+ assert calls == [("profile", first_principal), ("search", second_principal)]
+
+
+ def test_memory_remember_endpoint_returns_after_durable_capture_handoff():
+ controller = _build_controller_double()
+ capture_started = asyncio.Event()
+ release_capture = asyncio.Event()
+
+ class _Module:
+ async def capture(self, request):
+ capture_started.set()
+ await release_capture.wait()
+ return types.SimpleNamespace(status="accepted")
+
+ controller.memory_runtime = types.SimpleNamespace(module=_Module())
+ _set_memory_cli_sessions(
+ controller,
+ {"session-1": "u-11111111111111111111111111111111"},
+ )
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response_task = asyncio.create_task(
+ client.post(
+ "/internal/memory/remember",
+ json={"text": "ordinary text"},
+ headers={
+ "X-Avibe-Caller-Session": "session-1",
+ },
+ )
+ )
+ await asyncio.wait_for(capture_started.wait(), timeout=1)
+ assert response_task.done() is False
+ release_capture.set()
+ response = await asyncio.wait_for(response_task, timeout=1)
+ assert response.status_code == 200
+ assert response.json() == {"status": "accepted"}
+
+ asyncio.run(_go())
-def test_streaming_dispatch_publishes_single_bus_lifecycle(monkeypatch):
- """The Show-page stream owns one bus lifecycle because it bypasses the FSM."""
- from core import inbox_events
-
- context = MessageContext(user_id="workbench", channel_id="ses_show", platform="avibe")
-
- async def _build_payload(_payload):
- return "edit the show page", context
-
- async def _dispatch_turn(_controller, _context, _text, *, on_chunk=None):
- assert on_chunk is not None
- await on_chunk({"kind": "result", "text": "done"})
-
- monkeypatch.setattr(internal_server, "_build_dispatch_payload", _build_payload)
- monkeypatch.setattr(internal_server, "dispatch_turn", _dispatch_turn)
- controller = _build_controller_double()
- app = internal_server.create_app(controller)
- transport = httpx.ASGITransport(app=app)
- lifecycle = []
-
- async def _go():
- subscription_id = inbox_events.bus.subscribe_callback(
- lambda event_type, data: lifecycle.append((event_type, data))
- if event_type in {"turn.start", "turn.end"}
- else None
- )
- try:
- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- return await client.post(
- "/internal/dispatch",
- json={"session_id": "ses_show", "text": "edit the show page"},
- )
- finally:
- inbox_events.bus.unsubscribe(subscription_id)
-
- response = asyncio.run(_go())
-
- assert response.status_code == 200
- assert lifecycle == [
- ("turn.start", {"session_id": "ses_show"}),
- ("turn.end", {"session_id": "ses_show"}),
- ]
-
-
# ---------------------------------------------------------------------
# ASGI round-trips
# ---------------------------------------------------------------------
@@@ -576,6 -1028,16 +1198,34 @@@ def test_dispatch_rejects_missing_sessi
assert "session_id" in resp.json()["error"]
+ def test_workbench_memory_cli_admission_is_explicit_internal_turn_provenance(monkeypatch):
++ from core import scheduled_tasks
++
++ target = scheduled_tasks.ResolvedSessionIdTarget(
++ session_id="s1",
++ session_key=scheduled_tasks.ParsedSessionKey(
++ platform="avibe",
++ scope_type="channel",
++ scope_id="s1",
++ ),
++ agent_backend="codex",
++ agent_variant="default",
++ native_session_id="",
++ )
++ monkeypatch.setattr(
++ scheduled_tasks,
++ "resolve_session_id_target",
++ lambda _session_id: target,
++ )
+ monkeypatch.setattr(internal_server, "_lookup_session", lambda _session_id: None)
+
+ admitted = internal_server._build_session_context("s1", memory_cli_admitted=True)
+ denied = internal_server._build_session_context("s1")
+
+ assert admitted.platform_specific["memory_cli_admitted"] is True
+ assert "memory_cli_admitted" not in denied.platform_specific
+
+
def test_register_turn_sink_ignores_duplicate_and_pop_is_identity_guarded():
"""Streaming turns are serialized per session (dispatch_turn rejects a
concurrent one). As defense in depth, register_turn_sink must NOT clobber
@@@ -1774,1381 -1537,52 +2424,1393 @@@ def test_idle_show_admission_starts_its
transport = httpx.ASGITransport(app=app)
async def _go():
- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- idle = (await client.get("/internal/turn-state/ses_ts")).json()
- # Simulate an in-flight turn.
- task = asyncio.create_task(asyncio.sleep(60))
- app.state.in_flight_dispatches["ses_ts"] = session_turns.Turn(
- task=task,
- context=MessageContext(
- user_id="U",
- channel_id="C",
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session["id"],
+ "text": annotation["delivery"]["dispatch_text"],
+ "user_message_id": annotation["delivery_id"],
+ "show_event_id": annotation["id"],
+ },
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 202
+ assert response.json()["queued"] is False
+ assert response.json().get("drained") is None
+ assert len(runs) == 1
+ assert runs[0][1] == annotation["delivery"]["dispatch_text"]
+ with engine.connect() as conn:
+ queued = message_deliveries.list_queued(conn, session["id"])
+ linked_message_id = conn.execute(
+ select(show_session_events.c.message_id).where(
+ show_session_events.c.id == annotation["id"]
+ )
+ ).scalar_one()
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session["id"],
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
+ )["messages"]
+ assert [row["id"] for row in queued] == [older["id"]]
+ assert linked_message_id == annotation["delivery_id"]
+ assert [row["text"] for row in visible] == [annotation["transcript_text"]]
+ assert visible[0]["id"] == annotation["delivery_id"]
+ assert visible[0]["type"] == messages_service.ANNOTATION_TYPE
+ assert visible[0]["author_name"] == "show_annotation"
+ assert visible[0]["native_message_id"] == f"show:{annotation['id']}"
+ assert asyncio.run(manager.flush_queue(session["id"])) is False
+
+
+def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(
+ message_deliveries,
+ "new_delivery_id",
+ lambda: "msg_000000000000200aaaaaaaa",
+ )
+ session_id = _seed_avibe_session_with_queue([("queued follow-up", None)])
+
+ from sqlalchemy import update
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.models import message_deliveries as delivery_rows, messages
+
+ with create_sqlite_engine().begin() as conn:
+ queued = message_deliveries.list_queued(conn, session_id)[0]
+ queued_id = queued["id"]
+ conn.execute(
+ update(delivery_rows)
+ .where(delivery_rows.c.id == queued["id"])
+ .values(submitted_at="2026-06-22T00:00:37Z")
+ )
+ generated_ids = iter(
+ (
+ "msg_000000000000100aaaaaaaa",
+ "msg_000000000000300aaaaaaaa",
+ )
+ )
+ monkeypatch.setattr(messages_service, "_new_message_id", lambda: next(generated_ids))
+ monkeypatch.setattr(messages_service, "_utc_now_iso", lambda: "2026-06-22T00:00:37Z")
+ result = messages_service.append(
+ conn,
+ scope_id=queued["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="preceding result",
+ )
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == result["id"])
+ .values(
+ created_at="2026-06-22T00:00:37Z",
+ updated_at="2026-06-22T00:00:37Z",
+ )
+ )
+
+ manager, _runs = _manager_capturing_runs()
+ from core.inbox_events import bus
+
+ published = []
+ monkeypatch.setattr(
+ bus,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+
+ async def append_fast_result(
+ sid,
+ context,
+ text,
+ *,
+ source=SOURCE_HUMAN,
+ logical_turn_id=None,
+ delivery_id=None,
+ **_kwargs,
+ ):
+ _bind_test_native_start(create_sqlite_engine(), context)
+ with create_sqlite_engine().begin() as conn:
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=logical_turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ assert accepted
+ messages_service.append(
+ conn,
+ scope_id=context.platform_specific.get("scope_id"),
+ session_id=sid,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="fast queued result",
+ )
+ manager._publish_materialized_delivery(delivery_id)
+
+ async def fail_if_sleeping(_delay):
+ pytest.fail("queue promotion must not wait for wall-clock time")
+
+ monkeypatch.setattr(session_turns.asyncio, "sleep", fail_if_sleeping)
+ manager._run = append_fast_result
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+
+ with create_sqlite_engine().connect() as conn:
+ transcript = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user", "result"),
+ )
+ assert [(row["type"], row["text"]) for row in transcript["messages"]] == [
+ ("result", "preceding result"),
+ ("user", "queued follow-up"),
+ ("result", "fast queued result"),
+ ]
+ assert [row["created_at"] for row in transcript["messages"]] == [
+ "2026-06-22T00:00:37Z",
+ "2026-06-22T00:00:37Z",
+ "2026-06-22T00:00:37Z",
+ ]
+ assert [row["id"] for row in transcript["messages"]] == [
+ "msg_000000000000100aaaaaaaa",
+ "msg_000000000000200aaaaaaaa",
+ "msg_000000000000300aaaaaaaa",
+ ]
+ assert queued_id == "msg_000000000000200aaaaaaaa"
+ assert [
+ (event_type, data.get("id"))
+ for event_type, data in published
+ if event_type == "message.new"
+ ] == [("message.new", "msg_000000000000200aaaaaaaa")]
+ assert not hasattr(session_turns, "_timestamp_after_latest_session_message")
+ assert not hasattr(session_turns, "_wait_until_message_timestamp")
+
+
+def test_flush_materializes_exact_head_and_links_delivery_dependencies(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ session_id = _seed_avibe_session_with_queue(
+ [
+ ("canonical queued message", None),
+ ("merged queued message", None),
+ ]
+ )
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.models import show_session_events
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ queued = message_deliveries.list_queued(conn, session_id)
+ head_id = queued[0]["id"]
+ second_id = queued[1]["id"]
+ for index, delivery_id in enumerate((head_id, second_id), start=1):
+ conn.execute(
+ show_session_events.insert().values(
+ id=f"show_evt_repoint_{index}",
+ session_id=session_id,
+ event_type="human.annotation.created",
+ actor="human",
+ scope="page",
+ anchor_json="{}",
+ payload_json="{}",
+ transcript_text=f"annotation {index}",
+ message_id=None,
+ delivery_id=delivery_id,
+ created_at=f"2026-06-22T00:00:0{index}Z",
+ )
+ )
+
+ manager, _runs = _manager_accepting_runs()
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+
+ with engine.connect() as conn:
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user",),
+ )["messages"]
+ event_message_ids = conn.execute(
+ select(show_session_events.c.message_id).order_by(
+ show_session_events.c.id
+ )
+ ).scalars().all()
+ queued_ids = [row["id"] for row in message_deliveries.list_queued(conn, session_id)]
+
+ assert len(visible) == 1
+ assert visible[0]["id"] == head_id
+ assert event_message_ids == [head_id, head_id]
+ assert queued_ids == []
+
+
+def test_flush_claims_compatible_user_rows_as_one_turn_and_one_message(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ session_id = _seed_avibe_session_with_queue(
+ [
+ ("first show annotation", None),
+ ("second show annotation", None),
+ ]
+ )
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.models import show_session_events
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ queued = message_deliveries.list_queued(conn, session_id)
+ for index, row in enumerate(queued, start=1):
+ event_id = f"show_evt_identity_{index}"
+ conn.execute(
+ show_session_events.insert().values(
+ id=event_id,
+ session_id=session_id,
+ event_type="human.annotation.created",
+ actor="human",
+ scope="default",
+ anchor_json="{}",
+ payload_json="{}",
+ transcript_text=row["text"],
+ message_id=None,
+ delivery_id=row["id"],
+ created_at=f"2026-06-22T00:00:0{index}Z",
+ )
+ )
+
+ manager, runs = _manager_accepting_runs()
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+
+ with engine.connect() as conn:
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user",),
+ )["messages"]
+ event_links = conn.execute(
+ select(show_session_events.c.id, show_session_events.c.message_id).order_by(
+ show_session_events.c.id
+ )
+ ).all()
+
+ assert [text for text, _source, _context in runs] == [
+ "first show annotation\nsecond show annotation"
+ ]
+ assert len(visible) == 1
+ assert event_links == [
+ ("show_evt_identity_1", visible[0]["id"]),
+ ("show_evt_identity_2", visible[0]["id"]),
+ ]
+
+
+def test_async_dispatch_flushes_one_compatible_queue_segment_on_turn_end(monkeypatch, tmp_path):
+ """Natural settlement combines the compatible FIFO segment into one Turn."""
+ 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_flush", now="2026-05-31T00:00:00Z"
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ first = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="first turn",
+ )
+ session_id = session["id"]
+
+ seen_texts: list[str] = []
+
+ async def handler(ctx, text):
+ seen_texts.append(text)
+ # Simulate the user queueing two messages WHILE the first turn runs (the
+ # real flow — queued rows only exist during an active turn).
+ if text == "first turn":
+ with engine.begin() as conn:
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
platform="avibe",
- platform_specific={"agent_session_target": {"agent_backend": "opencode"}},
- ),
+ author="user",
+ source="user",
+ text="q1",
+ author_id="remote:user-a",
- metadata={"_web_push_user_key": "remote:user-a"},
++ metadata={
++ "_web_push_user_key": "remote:user-a",
++ "_memory_user_id": "remote:user-a",
++ "_memory_ordinary_text": True,
++ },
+ )
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="q2",
+ author_id="remote:user-a",
++ metadata={
++ "_memory_user_id": "remote:user-a",
++ "_memory_ordinary_text": True,
++ },
+ )
+ controller.mark_turn_complete(ctx) # release each turn immediately
+ return None
+
+ controller = _build_controller_double(handler=handler)
+ 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:
+ await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "first turn",
+ "user_message_id": first["id"],
+ },
)
- busy = (await client.get("/internal/turn-state/ses_ts")).json()
- task.cancel()
- return idle, busy
+ # Wait for the first turn AND the flush turn to both drain the queue.
+ for _ in range(200):
+ if len(seen_texts) >= 2 and session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+
+ asyncio.run(_go())
+ assert seen_texts == ["first turn", "q1\nq2"]
+ with engine.connect() as conn:
+ assert message_deliveries.list_queued(conn, session_id) == []
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert [m["text"] for m in transcript["messages"]] == ["first turn", "q1\nq2"]
+ assert transcript["messages"][1]["author_id"] == "remote:user-a"
- assert transcript["messages"][1]["metadata"]["_web_push_user_key"] == "remote:user-a"
++ assert not any(
++ key.startswith("_web_push_")
++ for key in transcript["messages"][1]["metadata"]
++ )
++ assert transcript["messages"][1]["metadata"]["_memory_user_id"] == "remote:user-a"
+
+
+def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
+ """A user Stop interrupts the turn but must NOT flush the queue — the user
+ asked to keep queued messages on stop ('不清空队列'). The queued rows survive
+ the cancellation; only a natural turn end (or send-now) runs them."""
+ 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_noflush", now="2026-05-31T00:00:00Z"
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ first = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="first",
+ )
+ session_id = session["id"]
+
+ started = asyncio.Event()
+
+ async def long_handler(ctx, text):
+ _bind_test_native_start(engine, ctx)
+ started.set()
+ await asyncio.sleep(5) # held until the test cancels it
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ controller = _build_controller_double(handler=long_handler)
+ 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:
+ await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "first",
+ "user_message_id": first["id"],
+ },
+ )
+ await asyncio.wait_for(started.wait(), timeout=3)
+ # Queue a message while the turn runs, then Stop.
+ with engine.begin() as conn:
+ message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")
+ await client.post(f"/internal/cancel/{session_id}")
+ for _ in range(200):
+ if session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+
+ asyncio.run(_go())
+ with engine.connect() as conn:
+ queued = message_deliveries.list_queued(conn, session_id)
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert [q["text"] for q in queued] == ["q1"], "Stop must keep the queue intact"
+ assert [row["text"] for row in transcript["messages"]] == ["first"]
+
+
+def test_turn_state_reflects_in_flight():
+ """``/internal/turn-state`` reports whether a turn is running, so a freshly
+ loaded / reconnected Chat page can restore its Stop state."""
+ controller = _build_controller_double()
+ controller.agent_service.runtime_turn_started.return_value = True
+ 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:
+ idle = (await client.get("/internal/turn-state/ses_ts")).json()
+ # Simulate an in-flight turn.
+ task = asyncio.create_task(asyncio.sleep(60))
+ app.state.in_flight_dispatches["ses_ts"] = session_turns.Turn(
+ task=task,
+ context=MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_target": {"agent_backend": "opencode"}},
+ ),
+ )
+ busy = (await client.get("/internal/turn-state/ses_ts")).json()
+ task.cancel()
+ return idle, busy
+
+ idle, busy = asyncio.run(_go())
+ assert idle["in_flight"] is False
+ assert busy["in_flight"] is True
+ assert busy["native_turn_started"] is True
+ assert busy["backend"] == "opencode"
+
+
+def test_turn_state_projects_a_restored_durable_owner_without_in_flight(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="restored-turn-state",
+ backend="opencode",
+ )
+ app = internal_server.create_app(_build_controller_double())
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return (await client.get(f"/internal/turn-state/{session['id']}")).json()
+
+ state = asyncio.run(_go())
+ assert state["in_flight"] is True
+ assert state["foreground"] == "running"
+ assert state["native_turn_started"] is True
+ assert state["backend"] == "opencode"
+ assert state["owner"]["runtime_key"] == f"runtime:{session['id']}"
+ assert state["owner"]["native_turn_started"] is True
+ assert turn_id
+
+
+def test_cancel_returns_404_when_session_not_in_flight(tmp_path, monkeypatch):
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ app = internal_server.create_app(_build_controller_double())
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post("/internal/cancel/ses_unknown")
+
+ resp = asyncio.run(_go())
+ assert resp.status_code == 404
+ body = resp.json()
+ assert body["ok"] is False
+ assert body["code"] == "not_in_flight"
+
+
+def test_cancel_releases_stale_turn_when_backend_not_active(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_stale_cancel",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ statuses = []
+ notices = []
+ controller.set_agent_status = lambda session_id, status: statuses.append((session_id, status))
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": session_id},
+ )
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+
+ async def _not_active(_context):
+ notices.append(_context.platform_specific.get("suppress_stop_no_active_notice"))
+ _context.platform_specific["stop_failure_reason"] = "not_active"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.post(f"/internal/cancel/{session_id}")
+ for _ in range(200):
+ if session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+ return resp, task
+
+ resp, task = asyncio.run(_go())
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "stale_released"
+ assert body["reason"] == "not_active"
+ assert task.cancelled()
+ assert session_id not in app.state.in_flight_dispatches
+ assert statuses == []
+ from storage.models import agent_sessions
+
+ with engine.connect() as conn:
+ status = conn.execute(
+ select(agent_sessions.c.agent_status).where(agent_sessions.c.id == session_id)
+ ).scalar_one()
+ assert status == "idle"
+ assert notices == [True]
+
+
+def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_stale_cleanup",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ controller.set_agent_status = lambda session_id, status: None
+
+ async def _go():
+ done_event = asyncio.Event()
+ cleanup_started = asyncio.Event()
+ allow_cleanup = asyncio.Event()
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": session_id},
+ )
+
+ async def _stale_dispatch():
+ controller.register_turn_sink(
+ controller._get_session_key(context),
+ on_chunk=AsyncMock(),
+ done_event=done_event,
+ turn_token="old-turn",
+ )
+ try:
+ await asyncio.sleep(60)
+ finally:
+ cleanup_started.set()
+ await allow_cleanup.wait()
+ controller.pop_turn_sink(controller._get_session_key(context), done_event)
+
+ task = asyncio.create_task(_stale_dispatch())
+ for _ in range(200):
+ if controller.get_turn_sink("avibe::C") is not None:
+ break
+ await asyncio.sleep(0.01)
+ assert controller.get_turn_sink("avibe::C") is not None
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+
+ async def _not_active(_context):
+ _context.platform_specific["stop_failure_reason"] = "not_active"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ cancel_task = asyncio.create_task(client.post(f"/internal/cancel/{session_id}"))
+ await asyncio.wait_for(cleanup_started.wait(), timeout=1)
+ await asyncio.sleep(0.02)
+ assert not cancel_task.done()
+ assert session_id in app.state.in_flight_dispatches
+ allow_cleanup.set()
+ resp = await cancel_task
+ return resp, task
+
+ resp, task = asyncio.run(_go())
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "stale_released"
+ assert task.cancelled()
+ assert controller.get_turn_sink("avibe::C") is None
+
+
+def test_cancel_keeps_turn_when_backend_interrupt_failed(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_failed_stop",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": session_id},
+ )
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+
+ async def _interrupt_failed(_context):
+ _context.platform_specific["stop_failure_reason"] = "interrupt_failed"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_interrupt_failed)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.post(f"/internal/cancel/{session_id}")
+ held = session_id in app.state.in_flight_dispatches and not task.done()
+ task.cancel()
+ return resp, held
+
+ resp, held = asyncio.run(_go())
+ assert resp.status_code == 409
+ body = resp.json()
+ assert body["ok"] is False
+ assert body["code"] == "stop_unknown"
+ assert body["reason"] == "stop_unknown"
+ assert held is True
+
+
+def test_release_for_backend_refresh_cancels_matching_turn_and_sets_idle():
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ statuses = []
+ controller.set_agent_status = lambda session_id, status: statuses.append((session_id, status))
+
+ async def _go():
+ async def _busy():
+ await asyncio.sleep(60)
+
+ task = asyncio.create_task(_busy())
+ ctx = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
+ ctx.platform_specific = {
+ "agent_session_id": "ses_codex",
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+ manager.in_flight["ses_codex"] = session_turns.Turn(task=task, context=ctx)
+ manager.begin_backend_drain("codex")
+
+ released = await manager.release_for_backend_refresh(
+ backend="codex",
+ base_session_ids={"ses_codex"},
+ )
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ return released, task.cancelled()
+
+ released, cancelled = asyncio.run(_go())
+
+ assert released == 1
+ assert cancelled is True
+ assert statuses == [("ses_codex", "idle")]
+ assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}
+
+
+def test_release_for_backend_refresh_leaves_other_backend_turn_running():
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ statuses = []
+ controller.set_agent_status = lambda session_id, status: statuses.append((session_id, status))
+
+ async def _go():
+ async def _busy():
+ await asyncio.sleep(60)
+
+ task = asyncio.create_task(_busy())
+ ctx = MessageContext(user_id="U", channel_id="ses_claude", platform="avibe")
+ ctx.platform_specific = {
+ "agent_session_id": "ses_claude",
+ "agent_session_target": {"agent_backend": "claude"},
+ }
+ manager.in_flight["ses_claude"] = session_turns.Turn(task=task, context=ctx)
+ try:
+ released = await manager.release_for_backend_refresh(
+ backend="codex",
+ base_session_ids={"ses_claude"},
+ )
+ return released, task.done()
+ finally:
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ released, done = asyncio.run(_go())
+
+ assert released == 0
+ assert done is False
+ assert statuses == []
+
+
+def test_backend_drain_queues_idle_session_without_dispatching(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain",
+ backend="codex",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+
+ async def _go():
+ manager.begin_backend_drain("codex")
+ return await manager.submit(session_id, context, "next")
+
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ )
+ with engine.connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["next"]
+ assert manager.is_in_flight(session_id) is False
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
+
+
+def test_backend_drain_queues_pre_reserved_idle_submission_before_resume(
+ tmp_path,
+ monkeypatch,
+):
+ """A Web-reserved Delivery becomes claimable before the backend drain ends."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain_reserved",
+ backend="codex",
+ )
+ session_id = session["id"]
+ with engine.begin() as conn:
+ reserved = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="reserved during refresh",
+ )
+
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ manager._start_persisted_turn = AsyncMock(return_value=None)
+ context = MessageContext(
+ user_id="U",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
+ "delivery_id": reserved["id"],
+ "agent_session_target": {"agent_backend": "codex"},
+ },
+ )
+
+ async def _go():
+ manager.begin_backend_drain("codex")
+ admitted = await manager.submit(
+ session_id,
+ context,
+ "reserved during refresh",
+ )
+ with engine.connect() as conn:
+ queued = message_deliveries.get_delivery(conn, reserved["id"])
+ await manager.end_backend_drain("codex")
+ return admitted, queued
+
+ admitted, queued = asyncio.run(_go())
+
+ assert admitted == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ )
+ assert queued is not None and queued["state"] == "queued"
+ manager._start_persisted_turn.assert_awaited_once()
+
+
+def test_backend_drain_exposes_failed_queue_persistence(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain_failure",
+ backend="codex",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+ monkeypatch.setattr(
+ manager,
+ "_insert_delivery",
+ Mock(side_effect=RuntimeError("queue persistence failed")),
+ )
+
+ async def _go():
+ manager.begin_backend_drain("codex")
+ return await manager.submit(session_id, context, "next")
+
+ with pytest.raises(RuntimeError, match="queue persistence failed"):
+ asyncio.run(_go())
+ assert manager.is_in_flight(session_id) is False
+
+
+def test_backend_drain_resolves_inherited_default_agent_backend(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_backend_drain_default",
+ backend="codex",
+ )
+ session_id = session["id"]
+ controller = _build_controller_double()
+ controller.resolve_agent_for_context = Mock(return_value="codex")
+ manager = session_turns.SessionTurnManager(controller)
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": session_id,
+ "scope_id": session["scope_id"],
+ "agent_session_target": {"agent_name": None, "agent_backend": None},
+ }
+
+ async def _go():
+ manager.begin_backend_drain("codex")
+ return await manager.submit(session_id, context, "next")
+
+ assert asyncio.run(_go()) == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ )
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
+
+
+def test_backend_drain_flushes_deferred_session_after_cutover():
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ manager.flush_queue = AsyncMock(return_value=True)
+ manager.begin_backend_drain("codex")
+ manager._deferred_restart_sessions["codex"].add("ses_codex")
+
+ asyncio.run(manager.end_backend_drain("codex"))
+
+ manager.flush_queue.assert_awaited_once_with("ses_codex")
+ assert "codex" not in manager._draining_backends
+
+
+def test_backend_drain_blocks_direct_queue_flush(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_direct_drain",
+ backend="codex",
+ )
+ session_id = session["id"]
+ with engine.begin() as conn:
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="queued",
+ )
+ controller = _build_controller_double()
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": session_id,
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+ manager = session_turns.SessionTurnManager(controller, build_context=lambda _session_id: context)
+ manager._run = AsyncMock() # type: ignore[method-assign]
+ manager.begin_backend_drain("codex")
+
+ assert asyncio.run(manager.flush_queue(session_id)) is False
+ manager._run.assert_not_awaited()
+ with engine.connect() as conn:
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["queued"]
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
+
+
+def test_stop_during_backend_drain_keeps_existing_queue_parked(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_stop_drain",
+ backend="codex",
+ )
+ session_id = session["id"]
+ with engine.begin() as conn:
+ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="queued",
+ )
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ context = MessageContext(user_id="U", channel_id=session_id, platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": session_id,
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ manager.in_flight[session_id] = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id=turn_id,
+ )
+ manager.begin_backend_drain("codex")
+ manager._deferred_restart_sessions["codex"].add(session_id)
+ result = await manager.cancel(session_id)
+ held = not task.done()
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ return result, held
+
+ result, held = asyncio.run(_go())
+
+ assert result["status"] == "cancel_requested"
+ assert held is True
+ with engine.connect() as conn:
+ assert message_deliveries.queue_is_held(conn, session_id) is True
+ assert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["queued"]
+ assert manager._deferred_restart_sessions == {"codex": {session_id}}
+
+
+# ---------------------------------------------------------------------
+# Dispatcher hook contract
+# ---------------------------------------------------------------------
+
+
+def test_dispatch_turn_registers_sink_for_dispatcher_hook():
+ """Locks the contract between ``dispatch_turn`` and the dispatcher's
+ ``_stream_chunk`` helper: the streaming ``on_chunk`` is registered as a
+ per-session turn sink (resolvable by session key while the turn runs)
+ and cleaned up afterward — not stashed on the per-turn context.
+ """
+
+ async def on_chunk(envelope):
+ pass
+
+ seen: dict = {}
+
+ async def capture(ctx, text):
+ sink = controller.get_turn_sink(controller._get_session_key(ctx))
+ seen["on_chunk"] = sink["on_chunk"] if sink else None
+ # Release the dispatch the way a real result emit would.
+ if sink:
+ sink["done_event"].set()
+
+ controller = _build_controller_double(handler=capture)
+ ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")
+ asyncio.run(dispatch_turn(controller, ctx, "ping", on_chunk=on_chunk))
+ assert seen["on_chunk"] is on_chunk
+ assert controller.get_turn_sink("avibe::C") is None, "sink cleaned up after the turn"
+
+
+# ---------------------------------------------------------------------
+# Scheduled / watch turn gate (controller.session_turn_gate)
+# ---------------------------------------------------------------------
+
+
+def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
+ """An IDLE scheduled run goes through ``_run_turn`` like a Chat turn: it
+ registers ``in_flight`` + publishes ``turn.start`` / ``turn.end`` on the bus
+ (so the Chat page shows the working indicator + Stop works) and calls
+ ``dispatch_turn`` with ``source=SOURCE_SCHEDULED`` and the no-op chunk sink —
+ NOT ``on_chunk=None``. The sink isn't about the browser (chunks are discarded;
+ avibe renders from ``message.new``); it makes ``dispatch_turn`` HOLD the turn
+ open until the backend's terminal result, which keeps ``in_flight`` populated
+ for the scheduled turn's whole lifetime so a Chat send can't preempt a
+ still-running scheduled turn (Codex P2)."""
+ from core import inbox_events
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_scheduled_idle",
+ )
+ session_id = session["id"]
+
+ captured: dict = {}
+ started = asyncio.Event()
+
+ async def _fake_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ captured["source"] = source
+ captured["on_chunk"] = on_chunk
+ captured["text"] = text
+ captured["in_flight_while_running"] = session_id in app.state.in_flight_dispatches
+ started.set()
+ # The manager now branches on the outcome to settle a run whose turn ended
+ # without a terminal result, so a double has to return one.
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _fake_dispatch_turn)
+
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": session_id,
+ "agent_session_target": {"agent_backend": "claude"},
+ },
+ )
+
+ async def _go():
+ sub_id, queue = inbox_events.bus.subscribe()
+ events: list[str] = []
+ try:
+ await controller.session_turn_gate.submit_scheduled(session_id, ctx, "digest please")
+ await asyncio.wait_for(started.wait(), timeout=3)
+ for _ in range(100):
+ if session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+ for _ in range(2):
+ try:
+ evt, _data = await asyncio.wait_for(queue.get(), timeout=1.0)
+ events.append(evt)
+ except asyncio.TimeoutError:
+ break
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+ return events
+
+ events = asyncio.run(_go())
+ assert captured["source"] == SOURCE_SCHEDULED, "scheduled run dispatches on the scheduler path"
+ # A scheduled run passes the no-op chunk SINK (callable, NOT None) so dispatch_turn
+ # HOLDS the turn open to its terminal result — same as a Chat turn — instead of an
+ # async backend returning at prompt-submit and freeing the slot (Codex P2). The sink
+ # discards chunks; the reply still surfaces over ``message.new``, not a live stream.
+ assert captured["on_chunk"] is not None, "scheduled run holds the turn open via the no-op sink"
+ assert callable(captured["on_chunk"]), "the held-open sink is the no-op chunk callable"
+ assert captured["text"] == "digest please"
+ assert captured["in_flight_while_running"] is True, "registered in_flight (Stop works) while running"
+ assert events == ["turn.start", "turn.end"], "publishes the session turn lifecycle on the bus"
+ assert session_id not in app.state.in_flight_dispatches, "slot released after the turn"
+
+
+def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch, tmp_path):
+ """A scheduled run for a session that already has a turn in flight ENQUEUES a
+ harness-attributed ``queued`` row (so it runs AFTER the active turn via the
+ existing flush) instead of preempting it — and it never starts a competing
+ turn nor disturbs the in-flight Chat task (Codex P2)."""
+ from core.inbox_events import bus
+ from storage import messages_service
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, owner_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_sched_busy",
+ )
+ scope_id = session["scope_id"]
+ session_id = session["id"]
+
+ # A scheduled run must NEVER reach dispatch_turn while busy — a call here fails
+ # the test loudly.
+ async def _explode_dispatch_turn(*args, **kwargs):
+ raise AssertionError("a busy scheduled run must enqueue, not dispatch a turn")
+
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _explode_dispatch_turn)
+ published: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ bus,
+ "publish",
+ lambda event, payload: published.append((event, payload)),
+ )
+
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ ctx = MessageContext(user_id="workbench", channel_id=session_id, platform="avibe")
+
+ async def _go():
+ async def _busy():
+ await asyncio.sleep(60)
+
+ chat_task = asyncio.create_task(_busy())
+ chat_ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")
+ app.state.in_flight_dispatches[session_id] = session_turns.Turn(
+ task=chat_task,
+ context=chat_ctx,
+ logical_turn_id=owner_turn_id,
+ )
+ try:
+ await controller.session_turn_gate.submit_scheduled(session_id, ctx, "scheduled while busy")
+ finally:
+ entry = app.state.in_flight_dispatches.get(session_id)
+ # The in-flight Chat turn is undisturbed: same task object, not cancelled.
+ assert entry is not None and entry.task is chat_task and not chat_task.done()
+ chat_task.cancel()
+ return chat_ctx
+
+ chat_ctx = asyncio.run(_go())
+ controller.message_handler.handle_user_message.assert_not_awaited()
+ with engine.connect() as conn:
+ queued = message_deliveries.list_queued(conn, session_id)
+ # The queued row is drainable + carries the session's scope and harness
+ # attribution; it stays OUT of the user transcript.
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert [q["text"] for q in queued] == ["scheduled while busy"]
+ assert queued[0]["scope_id"] == scope_id
+ assert queued[0]["author"] == "harness"
+ assert [row["text"] for row in transcript["messages"]] == ["active owner"]
+ assert ("queue.updated", {"session_id": session_id}) in published
+
+
+def test_agent_run_send_now_interrupts_then_dispatches_the_fifo_head(monkeypatch, tmp_path):
+ """HFR-430 — Agent-to-Agent send-now reuses the Workbench turn transition.
+
+ The Agent Run row and queued message must exist before Stop is attempted. The
+ active turn is then canceled once, and the durable successor claim starts
+ the durable Agent Run as a new scheduled turn.
+ """
+ from core.scheduled_tasks import TaskExecutionStore
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_agent_send_now",
+ 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"]
+ original = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ text="original work",
+ )
- idle, busy = asyncio.run(_go())
- assert idle["in_flight"] is False
- assert busy["in_flight"] is True
- assert busy["native_turn_started"] is True
- assert busy["backend"] == "opencode"
+ 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":
+ _bind_test_native_start(engine, ctx)
+ 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)
-def test_cancel_returns_404_when_session_not_in_flight():
- app = internal_server.create_app(_build_controller_double())
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
+ async def _stop_original(_context):
+ active = app.state.in_flight_dispatches.get(session_id)
+ assert active is not None
+ active.task.cancel()
+ return True
+
+ controller.command_handler.handle_stop.side_effect = _stop_original
+
async def _go():
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- return await client.post("/internal/cancel/ses_unknown")
+ response = await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": "original work",
+ "user_message_id": original["id"],
+ },
+ )
+ 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
- resp = asyncio.run(_go())
- assert resp.status_code == 404
- body = resp.json()
- assert body["ok"] is False
- assert body["code"] == "not_in_flight"
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ target_was_busy=True,
+ delivery_status="waiting_terminal",
+ delivery_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 message_deliveries.list_queued(conn, session_id) == []
+ stored = request_store.get_run(request.id)
+ assert stored is not None
+ assert stored["metadata"]["delivery_outcome"] == {
+ "intent": "send_now",
+ "status": "waiting_terminal",
+ "target_was_busy": True,
+ }
-def test_cancel_releases_stale_turn_when_backend_not_active():
+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
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session, owner_turn_id = _create_active_test_turn(
+ tmp_path,
+ native_id="proj_agent_send_now_refused",
+ )
+ session_id = session["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()
+
+ async def _refuse_stop(context):
+ context.platform_specific["stop_failure_reason"] = "refused"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_refuse_stop)
app = internal_server.create_app(controller)
- transport = httpx.ASGITransport(app=app)
- statuses = []
- notices = []
- controller.set_agent_status = lambda session_id, status: statuses.append((session_id, status))
async def _go():
task = asyncio.create_task(asyncio.sleep(60))
@@@ -4420,27 -2221,18 +5082,34 @@@ def _seed_avibe_session_with_queue(queu
platform="avibe",
author=("harness" if prov is not None else "user"),
source=("harness" if prov is not None else "user"),
- message_type=messages_service.QUEUED_TYPE,
+ message_type=("harness" if prov is not None else "user"),
text=text,
- metadata=({session_turns.SCHEDULED_PROVENANCE_KEY: prov} if prov is not None else None),
+ metadata=(
+ {session_turns.SCHEDULED_PROVENANCE_KEY: prov}
+ if prov is not None
+ else {
+ session_turns.MEMORY_USER_ID_METADATA: "local",
+ session_turns.MEMORY_ORDINARY_TEXT_METADATA: True,
+ }
+ ),
native_message_id=(prov or {}).get("message_id") if prov is not None else None,
)
+ spec = (prov or {}).get("platform_specific") or {}
+ run_id = str(spec.get("task_execution_id") or "").strip()
+ if run_id and conn.execute(
+ select(agent_runs.c.id).where(agent_runs.c.id == run_id)
+ ).scalar_one_or_none():
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(session_id=session["id"])
+ )
+ assert attach_agent_run_delivery_in_connection(
+ conn,
+ run_id,
+ session_id=session["id"],
+ delivery_id=str(delivery["id"]),
+ )
return session["id"]
@@@ -5331,148 -3482,306 +6000,297 @@@ def test_flush_does_not_mark_native_ids
assert asyncio.run(mgr.flush_queue(session_id)) is False
with create_sqlite_engine().begin() as conn:
- from sqlalchemy import select
+ queued = message_deliveries.list_queued(conn, session_id)
+ assert [row["native_message_id"] for row in queued] == ["watch:def-watch:run-1"]
- from storage.models import messages
- rows = conn.execute(select(messages).where(messages.c.session_id == session_id)).mappings().all()
- assert [row for row in rows if row["type"] == messages_service.HARNESS_DEDUPE_TYPE] == []
+def test_capture_scheduled_provenance_keeps_delivery_drops_routing():
+ """capture_scheduled_provenance keeps the delivery / attribution keys — notably
+ delivery_override, the redirect MessageDispatcher._get_target_context uses — and
+ DROPS the routing keys the flush rebuilds, so a queued scheduled run keeps its
+ delivery target (#84 / Codex P1 #3338692433)."""
+ override = {"channel_id": "slack-9", "platform": "slack"}
+ ctx = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ message_id="scheduled:exec-9",
+ platform_specific={
+ "platform": "avibe",
+ "is_dm": False,
+ "agent_session_id": "ses1",
+ "agent_session_target": {"id": "ses1", "agent_name": "worker"},
+ "delivery_override": override,
+ "suppress_delivery": True,
+ "turn_source": "scheduled",
+ "task_trigger_kind": "task",
+ },
+ )
+ prov = session_turns.capture_scheduled_provenance(ctx)
+ # The stable native id is captured for dedup (Codex P2).
+ assert prov["message_id"] == "scheduled:exec-9"
+ spec = prov["platform_specific"]
+ # Delivery / attribution provenance kept.
+ assert spec["delivery_override"] == override
+ assert spec["suppress_delivery"] is True
+ assert spec["turn_source"] == "scheduled"
+ assert spec["task_trigger_kind"] == "task"
+ assert spec[session_turns.SCHEDULED_TARGET_AGENT_KEY] == "worker"
+ # Routing keys the flush rebuilds are NOT carried.
+ for routing in ("platform", "is_dm", "agent_session_id", "agent_session_target"):
+ assert routing not in spec
-def test_flush_continues_after_dropping_duplicate_scheduled_segment(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- session_id = _seed_avibe_session_with_queue(
- [
- (
- "duplicate callback",
- {
- "message_id": "watch:def-watch:run-2",
- "platform_specific": {
- "task_execution_id": "run-2",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- },
- ),
- ("queued user follow-up", None),
- ]
+def test_boot_queue_recovery_stops_when_durable_owner_recovery_fails(
+ monkeypatch,
+ tmp_path,
+):
+ import uvicorn
+
+ calls: list[str] = []
+
+ async def fail_delivery_recovery(*, service_restart=False):
+ assert service_restart is True
+ calls.append("delivery")
+ raise RuntimeError("owner recovery failed")
+
+ async def recover_queue():
+ calls.append("queue")
+ return []
+
+ manager = SimpleNamespace(
+ recover_durable_delivery_state=fail_delivery_recovery,
+ recover_persisted_agent_run_queue=recover_queue,
)
+ controller = SimpleNamespace(session_turns=manager)
- from storage import messages_service
- from storage.db import create_sqlite_engine
+ class _Server:
+ def __init__(self, _config):
+ pass
- with create_sqlite_engine().begin() as conn:
- from sqlalchemy import update
+ async def serve(self, *, sockets):
+ assert len(sockets) == 1
+ calls.append("serve")
- from storage.models import messages
+ listener = SimpleNamespace(close=lambda: calls.append("close"))
+ monkeypatch.setattr(internal_server, "create_app", lambda _controller: object())
+ monkeypatch.setattr(
+ internal_server,
+ "_bind_socket",
+ lambda _path: (listener, tmp_path / "internal.sock"),
+ )
+ monkeypatch.setattr(uvicorn, "Config", lambda *_args, **_kwargs: object())
+ monkeypatch.setattr(uvicorn, "Server", _Server)
- queued = messages_service.list_queued(conn, session_id)
- messages_service.delete_queued(conn, [queued[0]["id"]])
- messages_service.append(
- conn,
- scope_id=queued[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.HARNESS_DEDUPE_TYPE,
- text="",
- metadata={"coalesced_from": "older-row"},
- native_message_id="watch:def-watch:run-2",
- )
- messages_service.append(
- conn,
- scope_id=queued[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text="duplicate callback",
- metadata={
- session_turns.SCHEDULED_PROVENANCE_KEY: {
- "message_id": "watch:def-watch:run-2",
- "platform_specific": {
- "task_execution_id": "run-2",
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
- },
- native_message_id=None,
- )
- queued = messages_service.list_queued(conn, session_id)
- for row in queued:
- created_at = "2026-06-22T00:00:00Z" if row["text"] == "duplicate callback" else "2026-06-22T00:01:00Z"
- conn.execute(update(messages).where(messages.c.id == row["id"]).values(created_at=created_at))
+ asyncio.run(internal_server.serve(controller))
- mgr, runs = _manager_capturing_runs()
+ assert calls == ["delivery", "serve", "close"]
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert [(text, source) for text, source, _ in runs] == [("queued user follow-up", SOURCE_HUMAN)]
- with create_sqlite_engine().begin() as conn:
- assert messages_service.list_queued(conn, session_id) == []
+def test_boot_waits_for_backend_restore_before_delivery_recovery(
+ monkeypatch,
+ tmp_path,
+):
+ import uvicorn
-def test_flush_does_not_coalesce_scheduled_callbacks_outside_window(tmp_path, monkeypatch):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ calls: list[str] = []
+ restore_barrier = asyncio.Event()
+ recovery_complete = asyncio.Event()
- def prov(execution_id: str) -> dict:
- return {
- "message_id": f"watch:def-watch:{execution_id}",
- "platform_specific": {
- "task_execution_id": execution_id,
- "task_trigger_kind": "watch",
- "task_definition_id": "def-watch",
- },
- }
+ async def recover_deliveries(*, service_restart=False):
+ assert service_restart is True
+ calls.append("delivery")
+ return []
- session_id = _seed_avibe_session_with_queue(
- [
- ("first callback", prov("run-1")),
- ("late callback", prov("run-2")),
- ]
+ async def recover_queue():
+ calls.append("queue")
+ return []
+
+ manager = SimpleNamespace(
+ recover_durable_delivery_state=recover_deliveries,
+ recover_persisted_agent_run_queue=recover_queue,
+ )
+ controller = SimpleNamespace(
+ session_turns=manager,
+ _delivery_recovery_barrier=restore_barrier,
+ _delivery_recovery_complete=recovery_complete,
)
- from sqlalchemy import update
+ class _Server:
+ def __init__(self, _config):
+ pass
- from storage import messages_service
- from storage.db import create_sqlite_engine
- from storage.models import messages
+ async def serve(self, *, sockets):
+ assert len(sockets) == 1
+ assert recovery_complete.is_set()
+ calls.append("serve")
+
+ listener = SimpleNamespace(close=lambda: calls.append("close"))
+ monkeypatch.setattr(internal_server, "create_app", lambda _controller: object())
+ monkeypatch.setattr(
+ internal_server,
+ "_bind_socket",
+ lambda _path: (listener, tmp_path / "internal.sock"),
+ )
+ monkeypatch.setattr(uvicorn, "Config", lambda *_args, **_kwargs: object())
+ monkeypatch.setattr(uvicorn, "Server", _Server)
- with create_sqlite_engine().begin() as conn:
- rows = messages_service.list_queued(conn, session_id)
- conn.execute(update(messages).where(messages.c.id == rows[0]["id"]).values(created_at="2026-06-22T00:00:00Z"))
- conn.execute(update(messages).where(messages.c.id == rows[1]["id"]).values(created_at="2026-06-22T00:02:01Z"))
+ async def _run() -> None:
+ serving = asyncio.create_task(internal_server.serve(controller))
+ await asyncio.sleep(0)
+ assert calls == []
+ restore_barrier.set()
+ await serving
- mgr, runs = _manager_capturing_runs()
+ asyncio.run(_run())
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert [(text, source) for text, source, _ in runs] == [("first callback", SOURCE_SCHEDULED)]
- with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
- assert [row["text"] for row in remaining] == ["late callback"]
+ assert calls == ["delivery", "queue", "serve", "close"]
+
++# ---------------------------------------------------------------------
++# ASGI round-trips
++# ---------------------------------------------------------------------
+
-def test_flush_segments_user_then_scheduled_in_order(tmp_path, monkeypatch):
- """A mixed queue drains one segment per flush, in order: leading user rows merge
- into one user turn; the scheduled row then runs separately with its provenance.
- The completion-reflush handles the next segment, so one flush runs only the first
- segment and leaves the rest (#84)."""
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- session_id = _seed_avibe_session_with_queue(
- [
- ("u1", None),
- ("u2", None),
- ("sched", {"message_id": "scheduled:x", "platform_specific": {"suppress_delivery": True}}),
- ]
- )
- mgr, runs = _manager_capturing_runs()
+
- from storage import messages_service
++def test_flush_restores_memory_cli_admission_only_when_every_queued_turn_was_local(tmp_path, monkeypatch):
++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
++ session_id = _seed_avibe_session_with_queue([("first", None), ("second", None)])
++ from storage import message_deliveries
+ from storage.db import create_sqlite_engine
+
- # First flush: leading user rows merge into one user turn; the scheduled row stays.
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert [(t, s) for t, s, _ in runs] == [("u1\nu2", SOURCE_HUMAN)]
- assert "suppress_delivery" not in (runs[0][2].platform_specific or {})
+ with create_sqlite_engine().begin() as conn:
- remaining = messages_service.list_queued(conn, session_id)
- assert [r["text"] for r in remaining] == ["sched"]
-
- # Second flush (what the turn completion triggers): the scheduled row runs as
- # SOURCE_SCHEDULED with its provenance.
- assert asyncio.run(mgr.flush_queue(session_id)) is True
- assert (runs[-1][0], runs[-1][1]) == ("sched", SOURCE_SCHEDULED)
- assert runs[-1][2].platform_specific["suppress_delivery"] is True
++ rows = message_deliveries.list_queued(conn, session_id)
++ for row in rows:
++ delivery = message_deliveries.get_delivery(conn, row["id"])
++ assert delivery is not None
++ snapshot = json.loads(delivery["snapshot_json"])
++ metadata = json.loads(snapshot["metadata_json"])
++ metadata["_memory_cli_admitted"] = True
++ snapshot["metadata_json"] = json.dumps(metadata)
++ assert message_deliveries.cas_delivery(
++ conn,
++ row["id"],
++ expected_version=delivery["version"],
++ expected_states=("queued",),
++ values={"snapshot_json": json.dumps(snapshot)},
++ )
++ manager, runs = _manager_capturing_runs()
++ assert asyncio.run(manager.flush_queue(session_id)) is True
++ assert runs[0][2].platform_specific["memory_cli_admitted"] is True
+
+
+ def test_flush_mixed_owner_user_rows_never_merge(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ from core.services import sessions as sessions_service
- from storage import messages_service
++ from storage import message_deliveries, messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
++ delivery_ids: list[str] = []
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_mixed_owner", now="2026-05-31T00:00:00Z"
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ for text, owner in (("u1", "remote:user-a"), ("u2", "remote:user-b")):
- messages_service.append(
++ delivery = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ platform="avibe",
+ author="user",
+ source="user",
- message_type=messages_service.QUEUED_TYPE,
+ text=text,
+ author_id=owner,
+ metadata={
+ "_web_push_user_key": owner,
+ "_memory_user_id": owner,
+ "_web_push_authorization_contexts": [
+ {
+ "user_key": owner,
+ "sub": owner.removeprefix("remote:"),
+ "email": f"{owner.removeprefix('remote:')}@example.com",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_group_ids": [],
+ }
+ ],
+ },
+ )
++ delivery_ids.append(delivery["id"])
+
- mgr, runs = _manager_capturing_runs()
++ mgr, runs = _manager_accepting_runs()
+
+ assert asyncio.run(mgr.flush_queue(session["id"])) is True
+ assert [(t, s) for t, s, _ in runs] == [("u1", SOURCE_HUMAN)]
+ assert runs[0][2].user_id == "remote:user-a"
+ with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session["id"])
- assert [row["text"] for row in queued] == ["u2"]
- with engine.connect() as conn:
++ first_delivery = message_deliveries.get_delivery(conn, delivery_ids[0])
++ second_delivery = message_deliveries.get_delivery(conn, delivery_ids[1])
++ assert first_delivery is not None
++ assert second_delivery is not None
++ assert first_delivery["state"] == "accepted"
++ assert second_delivery["state"] == "claimed"
++ assert first_delivery["turn_id"] != second_delivery["turn_id"]
++ assert second_delivery["message_id"] is None
+ transcript = messages_service.list_session_messages(conn, session_id=session["id"], types=("user",))
+ from storage.models import messages
+
+ metadata_json = conn.execute(
+ select(messages.c.metadata_json).where(
+ messages.c.id == transcript["messages"][0]["id"]
+ )
+ ).scalar_one()
+ assert transcript["messages"][0]["author_id"] == "remote:user-a"
+ assert not any(
+ key.startswith("_web_push_")
+ for key in transcript["messages"][0]["metadata"]
+ )
+ assert transcript["messages"][0]["metadata"]["_memory_user_id"] == "remote:user-a"
+ persisted_metadata = json.loads(metadata_json)
+ assert persisted_metadata["_web_push_user_key"] == "remote:user-a"
+ assert [
+ record["user_key"]
+ for record in persisted_metadata["_web_push_authorization_contexts"]
+ ] == ["remote:user-a"]
+
+
-def test_capture_scheduled_provenance_keeps_delivery_drops_routing():
- """capture_scheduled_provenance keeps the delivery / attribution keys — notably
- delivery_override, the redirect MessageDispatcher._get_target_context uses — and
- DROPS the routing keys the flush rebuilds, so a queued scheduled run keeps its
- delivery target (#84 / Codex P1 #3338692433)."""
- override = {"channel_id": "slack-9", "platform": "slack"}
- ctx = MessageContext(
- user_id="U",
- channel_id="C",
- platform="avibe",
- message_id="scheduled:exec-9",
- platform_specific={
- "platform": "avibe",
- "is_dm": False,
- "agent_session_id": "ses1",
- "agent_session_target": {"id": "ses1", "agent_name": "worker"},
- "delivery_override": override,
- "suppress_delivery": True,
- "turn_source": "scheduled",
- "task_trigger_kind": "task",
- },
- )
- prov = session_turns.capture_scheduled_provenance(ctx)
- # The stable native id is captured for dedup (Codex P2).
- assert prov["message_id"] == "scheduled:exec-9"
- spec = prov["platform_specific"]
- # Delivery / attribution provenance kept.
- assert spec["delivery_override"] == override
- assert spec["suppress_delivery"] is True
- assert spec["turn_source"] == "scheduled"
- assert spec["task_trigger_kind"] == "task"
- assert spec[session_turns.SCHEDULED_TARGET_AGENT_KEY] == "worker"
- # Routing keys the flush rebuilds are NOT carried.
- for routing in ("platform", "is_dm", "agent_session_id", "agent_session_target"):
- assert routing not in spec
-
-
+ def test_shutdown_records_stopped_even_if_the_done_callback_never_runs(monkeypatch, tmp_path) -> None:
+ """``start``'s done callback is scheduled with ``call_soon``.
+
+ A shutdown that cancels the task and then closes the loop can finish before
+ that callback runs, which is why ``internal-server.json`` kept saying
+ "ready" after a normal stop. ``note_stopped`` makes the write deterministic.
+ """
+
+ status_path = tmp_path / "runtime" / "internal-server.json"
+ monkeypatch.setattr(paths, "get_internal_server_status_path", lambda: status_path)
+
+ async def never_returns(*_args, **_kwargs) -> None:
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(internal_server, "serve", never_returns)
+
+ async def run() -> asyncio.Task:
+ task = internal_server.start(object())
+ await asyncio.sleep(0)
+ assert json.loads(status_path.read_text(encoding="utf-8"))["state"] == "starting"
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ # Deliberately do NOT yield to the loop here: that is what lets the
+ # done callback slip past a closing loop in the real shutdown path.
+ internal_server.note_stopped()
+ return task
+
+ asyncio.run(run())
+
+ assert json.loads(status_path.read_text(encoding="utf-8"))["state"] == "stopped"
diff --cc tests/test_message_handler_auth_setup.py
index c74c22f17,d12ee09eb..bc484c60d
--- a/tests/test_message_handler_auth_setup.py
+++ b/tests/test_message_handler_auth_setup.py
@@@ -167,73 -171,51 +167,116 @@@ class MessageHandlerAuthSetupTests(unit
context,
"auth-code#oauth-state",
)
- self.assertEqual(controller.settings_manager.sessions.recorded, [("C1", "m1", "m1")])
+ self.assertEqual(controller.settings_manager.sessions.recorded, [("im:slack:C1", "im:slack:m1", "im:slack:m1")])
+
+ async def test_platform_qualified_dedup_keeps_colliding_native_ids_distinct(self):
+ controller = _StubController()
+ controller.agent_auth_service.maybe_consume_setup_reply = AsyncMock(return_value=True)
+ handler = MessageHandler(controller)
+
+ slack = MessageContext(user_id="U1", channel_id="C1", platform="slack", message_id="m1")
+ duplicate_slack = MessageContext(user_id="U1", channel_id="C1", platform="slack", message_id="m1")
+ discord = MessageContext(user_id="U1", channel_id="C1", platform="discord", message_id="m1")
+
+ await handler.handle_user_message(slack, "first")
+ await handler.handle_user_message(duplicate_slack, "duplicate")
+ await handler.handle_user_message(discord, "second platform")
+
+ self.assertEqual(
+ controller.settings_manager.sessions.recorded,
+ [
+ ("im:slack:C1", "im:slack:m1", "im:slack:m1"),
+ ("im:discord:C1", "im:discord:m1", "im:discord:m1"),
+ ],
+ )
+ self.assertEqual(controller.agent_auth_service.maybe_consume_setup_reply.await_count, 2)
+
+ async def test_legacy_unprefixed_dedup_row_blocks_post_upgrade_redelivery(self):
+ controller = _StubController()
+ controller.agent_auth_service.maybe_consume_setup_reply = AsyncMock(return_value=True)
+ handler = MessageHandler(controller)
+ sessions = controller.settings_manager.sessions
+ # A previous version claimed this Slack event with raw native ids.
+ sessions.seed_legacy_claim("C1", "m1", "m1")
+
+ redelivered = MessageContext(user_id="U1", channel_id="C1", platform="slack", message_id="m1")
+ await handler.handle_user_message(redelivered, "redelivered after upgrade")
+
+ self.assertEqual(sessions.recorded, [])
+ controller.agent_auth_service.maybe_consume_setup_reply.assert_not_awaited()
+
+ # The legacy row must not suppress any other event in the same channel.
+ fresh = MessageContext(user_id="U1", channel_id="C1", platform="slack", message_id="m2")
+ await handler.handle_user_message(fresh, "a new message")
+
+ self.assertEqual(sessions.recorded, [("im:slack:C1", "im:slack:m2", "im:slack:m2")])
+ controller.agent_auth_service.maybe_consume_setup_reply.assert_awaited_once()
+ async def test_durable_setup_reply_claims_native_event_before_consuming(self):
+ controller = _StubController()
+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())
+ consumed = []
+ flow_active = True
+
+ async def consume_once(context, message, *, claim_native_event):
+ nonlocal flow_active
+ if not flow_active:
+ return False
+ if not claim_native_event():
+ return True
+ consumed.append(message)
+ flow_active = False
+ return True
+
+ controller.agent_auth_service.maybe_consume_setup_reply = AsyncMock(
+ side_effect=consume_once
+ )
+ handler = MessageHandler(controller)
+ handler._is_duplicate_human_delivery = Mock(
+ side_effect=lambda context: controller.settings_manager.sessions.is_message_already_processed(
+ context.channel_id,
+ context.thread_id or context.message_id,
+ context.message_id,
+ )
+ )
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ message_id="m-setup",
+ )
+
+ await handler.handle_user_message(context, "sk-opencode-secret")
+ await handler.handle_user_message(context, "sk-opencode-secret")
+
+ self.assertEqual(consumed, ["sk-opencode-secret"])
+ self.assertEqual(
+ controller.settings_manager.sessions.recorded,
+ [("C1", "m-setup", "m-setup")],
+ )
+ self.assertEqual(
+ controller.agent_auth_service.maybe_consume_setup_reply.await_count,
+ 1,
+ )
+ controller.session_turns.deliver.assert_not_awaited()
+
+ async def test_consumed_control_fence_precedes_delivery_lookup(self):
+ controller = _StubController()
+ handler = MessageHandler(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="telegram",
+ message_id="1",
+ )
+ assert handler._claim_native_human_event(context)
+
+ with patch(
+ "storage.db.get_cached_sqlite_engine",
+ side_effect=AssertionError("Delivery lookup must not run"),
+ ):
+ assert handler._is_duplicate_human_delivery(context)
+
if __name__ == "__main__":
unittest.main()
diff --cc tests/test_remote_access_vibe_cloud.py
index 0a2734d6a,0f59ce7d5..84978cb30
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@@ -803,36 -1134,16 +1134,46 @@@ def test_ra_tq_007_runtime_status_paylo
assert payload["tunnel_quality"]["grade"] == "good"
+def test_ra_tq_014_runtime_status_payload_includes_v2_request_path(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.save()
+ monkeypatch.setattr(remote_access, "_local_ui_healthy", lambda cfg: True)
+ monkeypatch.setattr(remote_access, "_observed_cloudflared_origin_service", lambda: "http://127.0.0.1:5123")
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda cfg=None: {
+ "ok": True,
+ "running": True,
+ "binary_found": True,
+ "tunnel_quality": {
+ "schema_version": 2,
+ "state": "degraded",
+ "grade": "critical",
+ "sampled_at": "2026-08-03T12:45:00Z",
+ "request_path": {
+ "confidence": "high",
+ "latency_ms": {"p50": 202, "p95": 1100, "p99": 2300, "max": 2700},
+ },
+ },
+ },
+ )
+
+ payload = remote_access.runtime_status_payload(config, event="tunnel_quality")
+
+ assert payload["tunnel_quality"]["schema_version"] == 2
+ assert payload["tunnel_quality"]["request_path"]["latency_ms"]["p95"] == 1100
+ def test_runtime_status_payload_omits_unknown_observed_origin(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ monkeypatch.setattr(remote_access, "_local_ui_healthy", lambda cfg: True)
+ monkeypatch.setattr(remote_access, "status", lambda cfg: {"running": True, "binary_found": True})
+ monkeypatch.setattr(remote_access, "_observed_cloudflared_origin_service", lambda: None)
+
+ payload = remote_access.runtime_status_payload(config, event="heartbeat")
+
+ assert "observed_origin_service" not in payload
def test_observed_cloudflared_origin_service_reads_only_log_tail(monkeypatch, tmp_path) -> None:
diff --cc tests/test_reply_enhancer_platform.py
index 4d3ec9545,c34c94fd7..a0b40d5c5
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@@ -7,12 -7,11 +7,13 @@@ from unittest.mock import AsyncMock, pa
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from core.message_dispatcher import ConsolidatedMessageDispatcher
+import core.reply_enhancer as reply_enhancer
+ from core.controller import Controller
-from core.reply_enhancer import process_reply
+from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.reply_enhancer import process_reply, strip_silent_blocks
- from core.system_prompt_injection import build_system_prompt_injection
+ from core.system_prompt_injection import build_system_prompt_injection, memory_cli_prompt_admitted
from config import paths
+from modules.agents.base import AgentRequest, BaseAgent
from modules.im import MessageContext
diff --cc tests/test_sqlite_state_migration.py
index 6d0d3a25c,16a10c6eb..637aed8a4
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@@ -20,29 -13,13 +20,29 @@@ from config import path
from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStore
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state
-from storage import migrations
+from storage import message_deliveries, messages_service, migrations
+from storage.background import SQLiteBackgroundTaskStore
from storage.migrations import UnsafeDefaultStateMigrationError, background_tables_ready, run_migrations
from storage.models import metadata
-from storage.settings_service import SQLiteSettingsService
-
-
-HEAD_REVISION = "20260725_0038"
+from storage.settings_service import SQLiteSettingsService, upsert_scope
+from vibe.message_types import build_partial_index_predicate
+
+
- HEAD_REVISION = "20260802_0045"
++HEAD_REVISION = "20260804_0046"
+MESSAGE_PARTIAL_INDEX_PREDICATES = {
+ "ix_messages_inbox_activity": (
+ "session_id is not null and type in "
+ "('user', 'harness', 'annotation', 'result', 'notify', 'error', 'assistant')"
+ ),
+ "ix_messages_inbox_agent_reply": (
+ "session_id is not null and type in ('result', 'notify', 'error')"
+ ),
+ "ix_messages_inbox_user_send": (
+ "session_id is not null and ((author = 'user' and type = 'user') "
+ "or (author = 'harness' and type = 'harness') "
+ "or (author = 'harness' and type = 'annotation'))"
+ ),
+}
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@@ -51,1131 -28,6 +51,1134 @@@
return str(row[0] or "")
+ ("index_name", "expected_predicate"),
+ tuple(MESSAGE_PARTIAL_INDEX_PREDICATES.items()),
+)
+def test_message_partial_index_ddl_matches_catalog_contract(
+ index_name: str,
+ expected_predicate: str,
+) -> None:
+ index = next(index for index in metadata.tables["messages"].indexes if index.name == index_name)
+
+ catalog_predicate = build_partial_index_predicate(index_name)
+ ddl = str(CreateIndex(index).compile(dialect=sqlite_dialect()))
+
+ assert catalog_predicate == expected_predicate
+ assert ddl == (
+ f"CREATE INDEX {index_name} ON messages "
+ f"(platform, session_id, created_at desc, id desc) WHERE {expected_predicate}"
+ )
+
+
+def test_show_annotation_migration_predicate_matches_catalog() -> None:
+ migration = import_module(
+ "storage.alembic.versions.20260727_0038_show_annotation_type"
+ )
+
+ assert migration.UPGRADE_USER_SEND_PREDICATE == build_partial_index_predicate(
+ "ix_messages_inbox_user_send"
+ )
+
+
+class _Pre335Cursor(sqlite3.Cursor):
+ def execute(self, sql, parameters=()):
+ normalized = " ".join(str(sql).upper().split())
+ if " DROP COLUMN " in f" {normalized} ":
+ raise sqlite3.OperationalError("near \"DROP\": syntax error")
+ return super().execute(sql, parameters)
+
+
+class _Pre335Connection(sqlite3.Connection):
+ def cursor(self, factory=None):
+ return super().cursor(factory or _Pre335Cursor)
+
+
+def test_alembic_script_directory_has_exactly_one_head() -> None:
+ heads = ScriptDirectory.from_config(migrations.alembic_config()).get_heads()
+
+ assert len(heads) == 1
+ assert heads[0] == HEAD_REVISION
+
+
+def test_scoped_native_message_identity_upgrade_and_safe_downgrade(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260801_0044")
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ now = messages_service._utc_now_iso()
+ first_scope = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="chat-1",
+ now=now,
+ )
+ messages_service.append(
+ conn,
+ scope_id=first_scope,
+ session_id=None,
+ platform="telegram",
+ author="user",
+ text="first",
+ native_message_id="1",
+ )
+
+ command.upgrade(migrations.alembic_config(db_path), "head")
+
+ with engine.begin() as conn:
+ now = messages_service._utc_now_iso()
+ second_scope = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="chat-2",
+ now=now,
+ )
+ messages_service.append(
+ conn,
+ scope_id=second_scope,
+ session_id=None,
+ platform="telegram",
+ author="user",
+ text="second",
+ native_message_id="1",
+ )
+ indexes = {
+ row[1]
+ for row in conn.exec_driver_sql("pragma index_list(messages)")
+ }
+ assert "uq_messages_platform_scope_native" in indexes
+ assert "uq_messages_platform_native_unscoped" in indexes
+
+ with pytest.raises(IntegrityError), engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=second_scope,
+ session_id=None,
+ platform="telegram",
+ author="user",
+ text="duplicate",
+ native_message_id="1",
+ )
+
+ with pytest.raises(
+ RuntimeError,
+ match="conversation-scoped Message identities would collide",
+ ):
+ command.downgrade(migrations.alembic_config(db_path), "20260801_0044")
+
+
+def test_scoped_native_message_identity_upgrade_preserves_accepted_delivery(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260801_0044")
+ engine = create_sqlite_engine(db_path)
+ now = "2026-08-02T00:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="telegram",
+ scope_type="channel",
+ native_id="chat-accepted",
+ now=now,
+ )
+ conn.exec_driver_sql(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_name, agent_backend, agent_variant,
+ session_anchor, workdir, native_session_id, status, visibility,
+ pinned, agent_status, metadata_json, created_at, updated_at,
+ last_active_at
+ ) values (
+ 'ses_accepted', ?, 'codex', 'codex', 'codex', 'accepted',
+ '/tmp', '', 'active', 'foreground', 0, 'idle', '{}', ?, ?, ?
+ )
+ """,
+ (scope_id, now, now, now),
+ )
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_accepted_delivery",
+ session_id="ses_accepted",
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id="ses_accepted",
+ platform="telegram",
+ author="user",
+ source="user",
+ message_type="user",
+ text="accepted",
+ native_message_id="1",
+ ),
+ dispatch_text="accepted",
+ dedupe_key="telegram:1",
+ now=now,
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id="turn_accepted_delivery",
+ session_id="ses_accepted",
+ backend="codex",
+ deliveries=[delivery],
+ dispatch_text="accepted",
+ )
+ turn = message_deliveries.bind_native_start(
+ conn,
+ "turn_accepted_delivery",
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key="runtime",
+ runtime_turn_id="runtime-turn",
+ native_turn_id="native-turn",
+ )
+ assert turn is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id="turn_accepted_delivery",
+ evidence={"kind": "test"},
+ )
+
+ command.upgrade(migrations.alembic_config(db_path), "head")
+
+ with engine.connect() as conn:
+ accepted = conn.exec_driver_sql(
+ "select message_id, dedupe_key from message_deliveries "
+ "where id='msg_accepted_delivery'"
+ ).one()
+ message = conn.exec_driver_sql(
+ "select scope_id, native_message_id from messages "
+ "where id='msg_accepted_delivery'"
+ ).one()
+ foreign_key_errors = conn.exec_driver_sql("pragma foreign_key_check").all()
+ assert accepted == (
+ "msg_accepted_delivery",
+ message_deliveries.native_dedupe_key(
+ "telegram",
+ "1",
+ scope_id=scope_id,
+ ),
+ )
+ assert message == (scope_id, "1")
+ assert foreign_key_errors == []
+
+ command.downgrade(migrations.alembic_config(db_path), "20260801_0044")
+ with engine.connect() as conn:
+ assert conn.exec_driver_sql(
+ "select message_id, dedupe_key from message_deliveries "
+ "where id='msg_accepted_delivery'"
+ ).one() == ("msg_accepted_delivery", "telegram:1")
+ assert conn.exec_driver_sql("pragma foreign_key_check").all() == []
+
+
+def test_session_delivery_fsm_upgrade_and_downgrade_preserve_existing_rows(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_id, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, session_anchor, workdir, native_session_id,
+ title, status, visibility, pinned, agent_status, created_at,
+ updated_at, last_active_at, metadata_json
+ ) values (
+ 'ses_fsm', null, null, 'codex', 'codex', 'codex', null, null,
+ 'ses_fsm', '/tmp', '', null, 'active', 'foreground', 0, 'idle',
+ ?, ?, ?, '{}'
+ )
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm', null, 'ses_fsm', 'avibe', 'user', 'queued', null,
+ null, 'user', null, null, 'hello', '{"text":"hello"}', '{}',
+ ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm_agent_run', null, 'ses_fsm', 'avibe', 'harness',
+ 'queued', null, null, 'harness', 'agent_run:run-legacy',
+ null, 'run prompt', '{"text":"run prompt"}', '{}', ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm_dedupe', null, 'ses_fsm', 'avibe', 'harness',
+ 'harness_dedupe', null, null, 'harness', 'watch:legacy:run-1',
+ null, '', '{}', '{}', ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ 'msg_fsm_draft', null, 'ses_fsm', 'avibe', 'user', 'draft', null,
+ null, 'user', null, null, 'unfinished thought',
+ '{"text":"unfinished thought"}', '{}', ?, ?, null, null
+ )
+ """,
+ (now, now),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+ with sqlite3.connect(db_path) as conn:
+ tables = {
+ row[0]
+ for row in conn.execute("select name from sqlite_master where type = 'table'")
+ }
+ turn_columns = {
+ row[1] for row in conn.execute("pragma table_info(session_turns)")
+ }
+ delivery_columns = {
+ row[1] for row in conn.execute("pragma table_info(message_deliveries)")
+ }
+ existing = conn.execute(
+ "select content_text, type from messages where id = 'msg_fsm'"
+ ).fetchone()
+ delivery = conn.execute(
+ "select state, dispatch_text, snapshot_json from message_deliveries where id = 'msg_fsm'"
+ ).fetchone()
+ migrated_dedupe = conn.execute(
+ "select state, dedupe_key, snapshot_json from message_deliveries "
+ "where id = 'msg_fsm_dedupe'"
+ ).fetchone()
+ migrated_agent_run = conn.execute(
+ "select state, dedupe_key, snapshot_json from message_deliveries "
+ "where id = 'msg_fsm_agent_run'"
+ ).fetchone()
+ hold_state = conn.execute(
+ "select queue_hold_state from agent_sessions where id = 'ses_fsm'"
+ ).fetchone()
+ draft_state = conn.execute(
+ "select composer_draft_text, composer_draft_updated_at "
+ "from agent_sessions where id = 'ses_fsm'"
+ ).fetchone()
+ message_session_fk = next(
+ row
+ for row in conn.execute("pragma foreign_key_list(messages)")
+ if row[2] == "agent_sessions" and row[3] == "session_id"
+ )
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ assert {"session_turns", "message_deliveries"}.issubset(tables)
+ assert {
+ "initial_delivery_id",
+ "runtime_turn_id",
+ "native_turn_id",
+ "terminal_outcome",
+ "version",
+ }.issubset(turn_columns)
+ assert {
+ "message_id",
+ "dispatch_text",
+ "priority",
+ "current_target_turn_id",
+ "current_attempt_id",
+ "current_expected_native_turn_id",
+ "current_receipt_outcome",
+ "delivery_history_json",
+ "version",
+ }.issubset(delivery_columns)
+ assert existing is None
+ assert delivery[0:2] == ("queued", "hello")
+ assert json.loads(delivery[2])["content_text"] == "hello"
+ assert migrated_dedupe[0:2] == ("retired", "avibe:watch:legacy:run-1")
+ assert json.loads(migrated_dedupe[2])["type"] == "harness"
+ assert migrated_agent_run[0:2] == ("queued", "avibe:agent_run:run-legacy")
+ assert json.loads(migrated_agent_run[2])["type"] == "harness"
+ assert hold_state == ("held",)
+ assert draft_state == ("unfinished thought", now)
+ assert message_session_fk[6] == "NO ACTION"
+ assert version == (HEAD_REVISION,)
+
+ from storage import message_deliveries
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ assert message_deliveries.queued_session_ids_without_live_turns(conn) == []
+ assert message_deliveries.queued_session_ids_without_live_turns(
+ conn,
+ include_held=True,
+ ) == ["ses_fsm"]
+ finally:
+ engine.dispose()
+
+ command.downgrade(migrations.alembic_config(db_path), "20260729_0042")
+ with sqlite3.connect(db_path) as conn:
+ tables = {
+ row[0]
+ for row in conn.execute("select name from sqlite_master where type = 'table'")
+ }
+ existing = conn.execute(
+ "select content_text, type, session_id from messages where id = 'msg_fsm'"
+ ).fetchone()
+ restored_draft = conn.execute(
+ "select content_text, type from messages "
+ "where session_id = 'ses_fsm' and type = 'draft'"
+ ).fetchone()
+ restored_dedupe = conn.execute(
+ "select type, native_message_id from messages where id = 'msg_fsm_dedupe'"
+ ).fetchone()
+ restored_agent_run = conn.execute(
+ "select type, native_message_id from messages "
+ "where id = 'msg_fsm_agent_run'"
+ ).fetchone()
+ message_session_fk = next(
+ row
+ for row in conn.execute("pragma foreign_key_list(messages)")
+ if row[2] == "agent_sessions" and row[3] == "session_id"
+ )
- version = conn.execute("select version_num from alembic_version").fetchone()
++ versions = {
++ row[0]
++ for row in conn.execute("select version_num from alembic_version")
++ }
+ assert "session_turns" not in tables
+ assert "message_deliveries" not in tables
+ assert existing == ("hello", "queued", "ses_fsm")
+ assert restored_draft == ("unfinished thought", "draft")
+ assert restored_dedupe == ("harness_dedupe", "watch:legacy:run-1")
+ assert restored_agent_run == ("queued", "agent_run:run-legacy")
+ assert message_session_fk[6] == "SET NULL"
- assert version == ("20260729_0042",)
++ assert versions == {"20260725_0038", "20260729_0042"}
+
+
+def test_session_delivery_migration_uses_live_dedupe_for_harness_provenance(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ cases = [
+ (
+ "human",
+ "user",
+ "user",
+ None,
+ "human:1",
+ "user",
+ "legacy:avibe:human:1",
+ ),
+ (
+ "task",
+ "harness",
+ "harness",
+ None,
+ "task:1",
+ "harness",
+ "avibe:task:1",
+ ),
+ (
+ "watch",
+ "harness",
+ "harness",
+ None,
+ "watch:1",
+ "harness",
+ "avibe:watch:1",
+ ),
+ (
+ "webhook",
+ "harness",
+ "harness",
+ None,
+ "webhook:1",
+ "harness",
+ "avibe:webhook:1",
+ ),
+ (
+ "show",
+ "harness",
+ "harness",
+ "show_annotation",
+ "show:1",
+ "annotation",
+ "avibe:show:1",
+ ),
+ ]
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_id, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, session_anchor, workdir, native_session_id,
+ title, status, visibility, pinned, agent_status, created_at,
+ updated_at, last_active_at, metadata_json
+ ) values (
+ 'ses_dedupe_classifier', null, null, 'codex', 'codex', 'codex',
+ null, null, 'ses_dedupe_classifier', '/tmp', '', null, 'active',
+ 'foreground', 0, 'idle', ?, ?, ?, '{}'
+ )
+ """,
+ (now, now, now),
+ )
+ for name, author, source, author_name, native_id, _type, _dedupe in cases:
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ ?, null, 'ses_dedupe_classifier', 'avibe', ?, 'queued', null,
+ ?, ?, ?, null, ?, json_object('text', ?), '{}', ?, ?, null, null
+ )
+ """,
+ (
+ f"msg_{name}",
+ author,
+ author_name,
+ source,
+ native_id,
+ name,
+ name,
+ now,
+ now,
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ migrated = conn.execute(
+ "select id, dedupe_key, snapshot_json from message_deliveries "
+ "where session_id = 'ses_dedupe_classifier' order by id"
+ ).fetchall()
+ by_id = {
+ row_id: (dedupe_key, json.loads(snapshot_json)["type"])
+ for row_id, dedupe_key, snapshot_json in migrated
+ }
+ assert by_id == {
+ f"msg_{name}": (expected_dedupe, expected_type)
+ for (
+ name,
+ _author,
+ _source,
+ _author_name,
+ _native_id,
+ expected_type,
+ expected_dedupe,
+ ) in cases
+ }
+
+
+def test_session_delivery_migration_binds_each_live_scheduled_run(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ cases = (
+ ("task", "scheduled", "queued"),
+ ("watch", "watch", "pending"),
+ ("webhook", "hook", "processing"),
+ )
+ with sqlite3.connect(db_path) as conn:
+ for name, trigger_kind, run_status in cases:
+ session_id = f"ses_{name}_migration"
+ run_id = f"run_{name}_migration"
+ message_id = f"msg_{name}_migration"
+ native_id = f"{name}:migration"
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_id, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, session_anchor, workdir, native_session_id,
+ title, status, visibility, pinned, agent_status, created_at,
+ updated_at, last_active_at, metadata_json
+ ) values (
+ ?, null, null, 'codex', 'codex', 'codex', null, null,
+ ?, '/tmp', '', null, 'active', 'foreground', 0, 'idle',
+ ?, ?, ?, '{}'
+ )
+ """,
+ (session_id, session_id, now, now, now),
+ )
+ conn.execute(
+ """
+ insert into agent_runs (
+ id, run_type, status, session_id, cancel_requested,
+ created_at, updated_at, metadata_json
+ ) values (?, ?, ?, ?, 0, ?, ?, '{}')
+ """,
+ (run_id, name, run_status, session_id, now, now),
+ )
+ metadata_json = json.dumps(
+ {
+ "scheduled_provenance": {
+ "platform_specific": {
+ "task_execution_id": run_id,
+ "task_trigger_kind": trigger_kind,
+ }
+ }
+ }
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_id,
+ author_name, source, native_message_id, parent_native_message_id,
+ content_text, content_json, metadata_json, created_at, updated_at,
+ delivered_at, read_at
+ ) values (
+ ?, null, ?, 'avibe', 'harness', 'queued', null, ?, 'harness',
+ ?, null, ?, json_object('text', ?), ?, ?, ?, null, null
+ )
+ """,
+ (
+ message_id,
+ session_id,
+ name,
+ native_id,
+ name,
+ name,
+ metadata_json,
+ now,
+ now,
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ migrated = conn.execute(
+ """
+ select r.id, r.delivery_id, d.state, d.dedupe_key,
+ s.queue_hold_state
+ from agent_runs r
+ join message_deliveries d on d.id = r.delivery_id
+ join agent_sessions s on s.id = r.session_id
+ where r.id like 'run_%_migration'
+ order by r.id
+ """
+ ).fetchall()
+ assert migrated == [
+ (
+ f"run_{name}_migration",
+ f"msg_{name}_migration",
+ "queued",
+ f"avibe:{name}:migration",
+ "open",
+ )
+ for name, _trigger_kind, _run_status in sorted(cases)
+ ]
+
+
+def test_session_delivery_migration_dedupes_and_avoids_legacy_event_id_collisions(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ tool_message_id = "msg_tool_collision"
+ silent_message_id = "msg_silent_existing"
+ tool_event_id = (
+ "evt_legacy_"
+ + hashlib.sha256(f"tool_call:{tool_message_id}".encode()).hexdigest()[:24]
+ )
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into scopes (
+ id, platform, scope_type, native_id, is_private, supports_threads,
+ metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values ('scope_fsm_trace', 'avibe', 'project', 'trace', 0, 0,
+ '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_name, agent_backend, agent_variant,
+ session_anchor, workdir, native_session_id, status, visibility,
+ pinned, agent_status, metadata_json, created_at, updated_at,
+ last_active_at
+ ) values ('ses_fsm_trace', 'scope_fsm_trace', 'codex', 'codex',
+ 'codex', 'trace', '/tmp', '', 'active', 'foreground', 0,
+ 'idle', '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.executemany(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, content_text,
+ content_json, metadata_json, created_at, updated_at
+ ) values (?, 'scope_fsm_trace', 'ses_fsm_trace', 'avibe', 'agent',
+ ?, ?, '{}', '{}', ?, ?)
+ """,
+ (
+ (tool_message_id, "tool_call", "tool trace", now, now),
+ (silent_message_id, "silent", "silent trace", now, now),
+ ),
+ )
+ conn.executemany(
+ """
+ insert into agent_events (
+ id, scope_id, session_id, platform, event_type, visibility,
+ content_json, metadata_json, created_at, updated_at
+ ) values (?, 'scope_fsm_trace', 'ses_fsm_trace', 'avibe', ?,
+ 'trace', '{}', ?, ?, ?)
+ """,
+ (
+ (tool_event_id, "unrelated", "{}", now, now),
+ (
+ "evt_existing_silent",
+ "silent_terminal",
+ json.dumps({"legacy_message_id": silent_message_id}),
+ now,
+ now,
+ ),
+ ),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, content_text,
+ content_json, metadata_json, created_at, updated_at
+ ) values ('msg_accepted_ref', 'scope_fsm_trace', 'ses_fsm_trace',
+ 'avibe', 'agent', 'result', 'accepted', '{}', '{}', ?, ?)
+ """,
+ (now, now),
+ )
+ conn.execute(
+ """
+ insert into show_session_events (
+ id, session_id, event_type, actor, scope, anchor_json,
+ payload_json, message_id, created_at
+ ) values ('show_accepted_ref', 'ses_fsm_trace', 'annotation',
+ 'agent', 'session', '{}', '{}', 'msg_accepted_ref', ?)
+ """,
+ (now,),
+ )
+ conn.execute(
+ """
+ insert into media_objects (
+ token, scope_id, session_id, message_id, kind, source,
+ local_path, created_at
+ ) values ('media_accepted_ref', 'scope_fsm_trace', 'ses_fsm_trace',
+ 'msg_accepted_ref', 'file', 'agent', '/tmp/accepted.txt', ?)
+ """,
+ (now,),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ pseudo_count = conn.execute(
+ "select count(*) from messages where id in (?, ?)",
+ (tool_message_id, silent_message_id),
+ ).fetchone()[0]
+ tool_events = conn.execute(
+ "select id from agent_events where event_type = 'tool_call' "
+ "and json_extract(metadata_json, '$.legacy_message_id') = ?",
+ (tool_message_id,),
+ ).fetchall()
+ silent_events = conn.execute(
+ "select id from agent_events where event_type = 'silent_terminal' "
+ "and json_extract(metadata_json, '$.legacy_message_id') = ?",
+ (silent_message_id,),
+ ).fetchall()
+ collision = conn.execute(
+ "select event_type from agent_events where id = ?",
+ (tool_event_id,),
+ ).fetchone()
+ accepted_refs = (
+ conn.execute(
+ "select message_id from show_session_events "
+ "where id = 'show_accepted_ref'"
+ ).fetchone(),
+ conn.execute(
+ "select message_id from media_objects "
+ "where token = 'media_accepted_ref'"
+ ).fetchone(),
+ )
+ assert pseudo_count == 0
+ assert tool_events == [(f"{tool_event_id}_1",)]
+ assert silent_events == [("evt_existing_silent",)]
+ assert collision == ("unrelated",)
+ assert accepted_refs == (("msg_accepted_ref",), ("msg_accepted_ref",))
+
+ from storage import agent_activity_service
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(
+ conn,
+ session_id="ses_fsm_trace",
+ )["groups"]
+ finally:
+ engine.dispose()
+ assert [group["status"] for group in groups] == ["done"]
+ assert groups[0]["steps"] == 1
+
+ command.downgrade(migrations.alembic_config(db_path), "20260729_0042")
+ with sqlite3.connect(db_path) as conn:
+ restored_trace = conn.execute(
+ "select id, type, content_text from messages "
+ "where id in (?, ?) order by id",
+ (tool_message_id, silent_message_id),
+ ).fetchall()
+ remaining_events = conn.execute(
+ "select id, metadata_json from agent_events order by id"
+ ).fetchall()
+ downgraded_refs = (
+ conn.execute(
+ "select message_id from show_session_events "
+ "where id = 'show_accepted_ref'"
+ ).fetchone(),
+ conn.execute(
+ "select message_id from media_objects "
+ "where token = 'media_accepted_ref'"
+ ).fetchone(),
+ )
+ assert restored_trace == [
+ (silent_message_id, "silent", "silent trace"),
+ (tool_message_id, "tool_call", "tool trace"),
+ ]
+ assert {row[0] for row in remaining_events} == {
+ tool_event_id,
+ "evt_existing_silent",
+ }
+ metadata_by_id = {row[0]: json.loads(row[1]) for row in remaining_events}
+ assert metadata_by_id["evt_existing_silent"] == {
+ "legacy_message_id": silent_message_id
+ }
+ assert downgraded_refs == (("msg_accepted_ref",), ("msg_accepted_ref",))
+
+
+def test_session_delivery_migration_refuses_preexisting_operational_tables(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260731_0043")
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("create table message_deliveries (id text primary key)")
+ conn.execute("create table session_turns (id text primary key)")
+ conn.commit()
+
+ with pytest.raises(RuntimeError, match="interrupted 0044 migration"):
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ assert conn.execute("select version_num from alembic_version").fetchone() == (
+ "20260731_0043",
+ )
+
+
+def test_session_delivery_migration_completes_precreated_operational_tables(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260731_0043")
+ now = "2026-07-31T00:00:00Z"
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_name, agent_backend, agent_variant,
+ session_anchor, workdir, native_session_id, status, visibility,
+ pinned, agent_status, metadata_json, created_at, updated_at,
+ last_active_at
+ ) values ('ses_interrupted', null, 'codex', 'codex', 'codex',
+ 'interrupted', '/tmp', '', 'active', 'foreground', 0,
+ 'idle', '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.execute(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, source,
+ content_text, content_json, metadata_json, created_at, updated_at
+ ) values (
+ 'msg_interrupted', null, 'ses_interrupted', 'avibe', 'user',
+ 'queued', 'user', 'resume me', '{"text":"resume me"}', '{}', ?, ?
+ )
+ """,
+ (now, now),
+ )
+ conn.commit()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(
+ engine,
+ tables=[
+ metadata.tables["message_deliveries"],
+ metadata.tables["session_turns"],
+ ],
+ )
+ finally:
+ engine.dispose()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ assert conn.execute(
+ "select 1 from messages where id = 'msg_interrupted'"
+ ).fetchone() is None
+ assert conn.execute(
+ "select state, session_id from message_deliveries "
+ "where id = 'msg_interrupted'"
+ ).fetchone() == ("queued", "ses_interrupted")
+ assert conn.execute(
+ "select 1 from pragma_table_info('agent_runs') where name = 'delivery_id'"
+ ).fetchone() == (1,)
+ assert conn.execute(
+ "select 1 from pragma_index_list('agent_runs') "
+ "where name = 'uq_agent_runs_delivery'"
+ ).fetchone() == (1,)
+
+
+def test_session_delivery_migration_resolves_legacy_pending_by_its_real_owner(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260729_0042")
+ now = "2026-07-31T00:00:00Z"
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_name, agent_backend, agent_variant,
+ session_anchor, workdir, native_session_id, status, visibility,
+ pinned, agent_status, metadata_json, created_at, updated_at,
+ last_active_at
+ ) values ('ses_pending', null, 'codex', 'codex', 'codex',
+ 'pending', '/tmp', '', 'active', 'foreground', 0,
+ 'idle', '{}', ?, ?, ?)
+ """,
+ (now, now, now),
+ )
+ conn.executemany(
+ """
+ insert into messages (
+ id, scope_id, session_id, platform, author, type, author_name,
+ source, content_text, content_json, metadata_json, created_at,
+ updated_at
+ ) values (?, null, 'ses_pending', 'avibe', ?, 'pending', ?, ?, ?,
+ json_object('text', ?), '{}', ?, ?)
+ """,
+ (
+ ("msg_pending_human", "user", None, "user", "human", "human", now, now),
+ (
+ "msg_pending_harness",
+ "harness",
+ "watch",
+ "harness",
+ "scheduled",
+ "scheduled",
+ now,
+ now,
+ ),
+ (
+ "msg_pending_annotation",
+ "harness",
+ "show_annotation",
+ "harness",
+ "annotation",
+ "annotation",
+ now,
+ now,
+ ),
+ ),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ remaining_messages = conn.execute(
+ "select id from messages where id in "
+ "('msg_pending_human', 'msg_pending_harness', 'msg_pending_annotation')"
+ ).fetchall()
+ deliveries = conn.execute(
+ "select id, state, current_attempt_kind, current_receipt_outcome, "
+ "snapshot_json from message_deliveries where id in "
+ "('msg_pending_human', 'msg_pending_harness', 'msg_pending_annotation') "
+ "order by id"
+ ).fetchall()
+ assert remaining_messages == []
+ assert [(row[0], row[1], row[2], row[3]) for row in deliveries] == [
+ ("msg_pending_annotation", "retired", None, None),
+ ("msg_pending_harness", "retired", None, None),
+ ("msg_pending_human", "retired", None, None),
+ ]
+ snapshots = {row[0]: json.loads(row[4]) for row in deliveries}
+ assert snapshots["msg_pending_annotation"]["type"] == "annotation"
+ assert snapshots["msg_pending_annotation"]["author"] == "harness"
+ assert snapshots["msg_pending_harness"]["type"] == "harness"
+ assert snapshots["msg_pending_harness"]["author"] == "harness"
+ assert snapshots["msg_pending_harness"]["author_name"] == "watch"
+ assert snapshots["msg_pending_harness"]["source"] == "harness"
+ assert snapshots["msg_pending_human"]["type"] == "user"
+ assert snapshots["msg_pending_human"]["author"] == "user"
+ assert snapshots["msg_pending_human"]["source"] == "user"
+ from storage import message_deliveries
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ assert message_deliveries.recoverable_reservations(conn, "ses_pending") == []
+ assert message_deliveries.ordering_head(conn, "ses_pending") is None
+ finally:
+ engine.dispose()
+
+ command.downgrade(migrations.alembic_config(db_path), "20260729_0042")
+ with sqlite3.connect(db_path) as conn:
+ restored = conn.execute(
+ "select id, type, author from messages where id in "
+ "('msg_pending_human', 'msg_pending_harness', 'msg_pending_annotation') "
+ "order by id"
+ ).fetchall()
+ assert restored == [
+ ("msg_pending_annotation", "pending", "harness"),
+ ("msg_pending_harness", "pending", "harness"),
+ ("msg_pending_human", "pending", "user"),
+ ]
+
+
+def test_upgrade_keeps_historical_conflated_callback_rows_sent(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260726_0037")
+ now = "2026-07-30T00:00:00Z"
+
+ with sqlite3.connect(db_path) as conn:
+ def insert_run(
+ run_id: str,
+ *,
+ source_kind: str,
+ parent_run_id: str | None = None,
+ session_id: str | None = None,
+ callback_session_id: str | None = None,
+ callback_status: str | None = None,
+ callback_run_id: str | None = None,
+ ) -> None:
+ conn.execute(
+ """
+ insert into agent_runs (
+ id, run_type, status, source_kind, parent_run_id, session_id,
+ callback_session_id, callback_status, callback_error,
+ callback_run_id, callback_completed_at, cancel_requested,
+ created_at, completed_at, updated_at, metadata_json
+ ) values (
+ ?, 'agent_run', 'succeeded', ?, ?, ?, ?, ?, 'legacy error',
+ ?, ?, 0, ?, ?, ?, '{}'
+ )
+ """,
+ (
+ run_id,
+ source_kind,
+ parent_run_id,
+ session_id,
+ callback_session_id,
+ callback_status,
+ callback_run_id,
+ now if callback_status else None,
+ now,
+ now if callback_status else None,
+ now,
+ ),
+ )
+
+ insert_run(
+ "historical_parent",
+ source_kind="agent",
+ callback_session_id="ses_caller",
+ callback_status="sent",
+ callback_run_id="directed_child",
+ )
+ insert_run(
+ "directed_child",
+ source_kind="agent",
+ parent_run_id="historical_parent",
+ session_id="ses_caller",
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ parent = conn.execute(
+ """
+ select callback_status, callback_error, callback_run_id,
+ callback_completed_at
+ from agent_runs
+ where id = 'historical_parent'
+ """
+ ).fetchone()
+ child = conn.execute(
+ """
+ select source_kind, parent_run_id, session_id
+ from agent_runs
+ where id = 'directed_child'
+ """
+ ).fetchone()
+ callback_count = conn.execute(
+ "select count(*) from agent_runs where source_kind = 'callback'"
+ ).fetchone()
+ version = conn.execute(
+ "select version_num from alembic_version"
+ ).fetchone()
+
+ assert parent == (
+ "sent",
+ "legacy error",
+ "directed_child",
+ now,
+ )
+ assert child == ("agent", "historical_parent", "ses_caller")
+ assert callback_count == (0,)
+ assert version == (HEAD_REVISION,)
+
+
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
@@@ -1644,33 -249,7 +1647,36 @@@ def test_show_annotation_migration_chan
run_migrations(db_path)
- assert background_tables_ready(db_path) is True
+ with sqlite3.connect(db_path) as conn:
+ upgraded_rows = conn.execute(
+ "select * from messages order by id"
+ ).fetchall()
+ user_send_index = _index_sql(conn, "ix_messages_inbox_user_send")
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert upgraded_rows == original_rows
+ assert user_send_index.endswith(
+ MESSAGE_PARTIAL_INDEX_PREDICATES["ix_messages_inbox_user_send"]
+ )
+ assert "(platform, session_id, created_at desc, id desc)" in user_send_index
+ assert version == (HEAD_REVISION,)
+
+ command.downgrade(migrations.alembic_config(db_path), "20260726_0037")
+
+ with sqlite3.connect(db_path) as conn:
+ downgraded_rows = conn.execute(
+ "select * from messages order by id"
+ ).fetchall()
+ user_send_index = _index_sql(conn, "ix_messages_inbox_user_send")
- version = conn.execute("select version_num from alembic_version").fetchone()
++ versions = {
++ row[0]
++ for row in conn.execute("select version_num from alembic_version")
++ }
+
+ assert downgraded_rows == original_rows
+ assert user_send_index.endswith(migration.DOWNGRADE_USER_SEND_PREDICATE)
+ assert "(platform, session_id, created_at desc, id desc)" in user_send_index
- assert version == ("20260726_0037",)
++ assert versions == {"20260725_0038", "20260726_0037"}
def test_session_pinning_migration_preserves_existing_sessions_as_unpinned(tmp_path: Path) -> None:
@@@ -4940,3 -3181,3 +4946,126 @@@ def _write_discovered_chats(path: Path
),
encoding="utf-8",
)
++
++
++def test_media_reference_migration_backfills_legacy_cross_session_tokens(tmp_path: Path) -> None:
++ db_path = tmp_path / "vibe.sqlite"
++ run_migrations(db_path, revision="20260725_0035")
++ now = "2026-07-25T00:00:00Z"
++
++ with sqlite3.connect(db_path) as conn:
++ conn.execute(
++ """
++ insert into scopes (
++ id, platform, scope_type, native_id, native_type, is_private,
++ supports_threads, metadata_json, first_seen_at, last_seen_at, updated_at
++ ) values (
++ 'avibe::project::proj_media', 'avibe', 'project', 'proj_media', null,
++ 1, 1, '{}', ?, ?, ?
++ )
++ """,
++ (now, now, now),
++ )
++ for session_id in ("ses_media_original", "ses_media_reuse"):
++ conn.execute(
++ """
++ insert into agent_sessions (
++ id, scope_id, agent_backend, agent_variant, session_anchor,
++ native_session_id, status, visibility, metadata_json,
++ created_at, updated_at, last_active_at
++ ) values (?, 'avibe::project::proj_media', 'codex', 'codex', ?, '',
++ 'active', 'foreground', '{}', ?, ?, ?)
++ """,
++ (session_id, session_id, now, now, now),
++ )
++ conn.execute(
++ """
++ insert into media_objects (
++ token, scope_id, session_id, kind, source, local_path, created_at
++ ) values (
++ 'legacy-shared-token', 'avibe::project::proj_media',
++ 'ses_media_original', 'file', 'agent_reply', '/tmp/legacy.txt', ?
++ )
++ """,
++ (now,),
++ )
++ conn.execute(
++ """
++ insert into messages (
++ id, scope_id, session_id, platform, author, type, source,
++ content_text, content_json, metadata_json, created_at, updated_at
++ ) values (
++ 'msg_legacy_media', 'avibe::project::proj_media', 'ses_media_reuse',
++ 'avibe', 'agent', 'result', 'agent',
++ 'See [attachment](/api/media/legacy-shared-token)', '{}', '{}', ?, ?
++ )
++ """,
++ (now, now),
++ )
++ conn.commit()
++
++ run_migrations(db_path)
++
++ with sqlite3.connect(db_path) as conn:
++ references = set(
++ conn.execute(
++ "select token, session_id from media_object_references"
++ )
++ )
++ version = conn.execute("select version_num from alembic_version").fetchone()
++
++ assert references == {
++ ("legacy-shared-token", "ses_media_original"),
++ ("legacy-shared-token", "ses_media_reuse"),
++ }
++ assert version == (HEAD_REVISION,)
++
++
++def test_background_tables_ready_requires_project_acl_and_media_references(tmp_path: Path) -> None:
++ db_path = tmp_path / "vibe.sqlite"
++ run_migrations(db_path, revision="20260725_0035")
++
++ assert background_tables_ready(db_path) is False
++
++ run_migrations(db_path)
++
++ assert background_tables_ready(db_path) is True
++
++
++def test_run_migrations_upgrades_released_0030_to_acl_head(tmp_path: Path) -> None:
++ db_path = tmp_path / "vibe.sqlite"
++
++ run_migrations(db_path, revision="20260707_0029")
++ with sqlite3.connect(db_path) as conn:
++ conn.execute(
++ "update messages set author = 'harness', type = 'harness' "
++ "where source = 'harness' and author = 'user' and type = 'user'"
++ )
++ conn.execute("drop index if exists ix_messages_inbox_user_send")
++ conn.execute(
++ "create index ix_messages_inbox_user_send "
++ "on messages (platform, session_id, created_at desc, id desc) "
++ "where session_id is not null and "
++ "((author = 'user' and type = 'user') or "
++ "(author = 'harness' and type = 'harness'))"
++ )
++ conn.execute(
++ "update alembic_version set version_num = '20260716_0030'"
++ )
++ conn.commit()
++
++ run_migrations(db_path)
++
++ with sqlite3.connect(db_path) as conn:
++ version = conn.execute("select version_num from alembic_version").fetchone()
++ tables = {
++ row[0]
++ for row in conn.execute("select name from sqlite_master where type = 'table'")
++ }
++ assert version == (HEAD_REVISION,)
++ assert build_partial_index_predicate("ix_messages_inbox_activity") in _index_sql(
++ conn,
++ "ix_messages_inbox_activity",
++ )
++ assert "resource_access_policies" in tables
++ assert "resource_access_groups" in tables
diff --cc tests/test_ui_project_access.py
index 000000000,30b84240e..4b9c916fa
mode 000000,100644..100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@@ -1,0 -1,663 +1,657 @@@
+ from __future__ import annotations
+
+ import json
+ from types import SimpleNamespace
+
+ from sqlalchemy import select
+
+ from config.v2_config import (
+ AgentsConfig,
+ PlatformsConfig,
+ RemoteAccessConfig,
+ RuntimeConfig,
+ SlackConfig,
+ UiConfig,
+ V2Config,
+ )
+ from core.vibe_agents import VibeAgentStore
+ from storage import (
+ media_service,
++ message_deliveries,
+ messages_service,
+ project_access_service,
+ projects_service,
+ resource_access_service,
+ )
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import media_object_references, media_objects, messages, scopes
+ from storage.workbench_sessions_service import create_session, update_session
+ from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
++from tests.test_ui_session_stream import _settle_reserved_delivery
+ from vibe import api, internal_client, remote_access, ui_server
+ from vibe.authorization import AuthorizationContext
+ from vibe.sse_broker import broker
+ from vibe.ui_server import app
+
+
+ REMOTE_ORIGIN = "https://alex.avibe.bot"
+ REMOTE_PEER = {"REMOTE_ADDR": "203.0.113.10"}
+
+
+ def _save_config() -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="slack",
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.public_url = REMOTE_ORIGIN
+ cloud.client_id = "vr_client_123"
+ cloud.instance_id = "inst_123"
+ cloud.session_secret = "session-secret"
+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
+ cloud.redirect_uri = f"{REMOTE_ORIGIN}/auth/callback"
+ config.save()
+ return config
+
+
+ def _intent(project_id: str, email: str, role: str = "editor") -> dict:
+ return {
+ "project_id": project_id,
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": email,
+ "access_role": role,
+ }
+ ],
+ }
+
+
+ def _group_intent(project_id: str, group_id: str, role: str = "editor") -> dict:
+ return {
+ "project_id": project_id,
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "organization_group",
+ "principal_value": group_id,
+ "access_role": role,
+ }
+ ],
+ }
+
+
+ def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:
+ config = _save_config()
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_a_dir = tmp_path / "project-a"
+ project_b_dir = tmp_path / "project-b"
+ project_a_dir.mkdir()
+ project_b_dir.mkdir()
+ shared_media = tmp_path / "shared.txt"
+ shared_media.write_text("shared media", encoding="utf-8")
+ with engine.begin() as conn:
+ project_a = projects_service.create_project(conn, str(project_a_dir), display_name="A")
+ project_b = projects_service.create_project(conn, str(project_b_dir), display_name="B")
+ session_a = create_session(conn, scope_id=project_a["scope_id"], agent_backend="codex")
+ session_b = create_session(conn, scope_id=project_b["scope_id"], agent_backend="codex")
+ unscoped = create_session(conn, scope_id=None, agent_backend="codex")
+ for project, session in ((project_a, session_a), (project_b, session_b)):
+ messages_service.append(
+ conn,
+ scope_id=project["scope_id"],
+ session_id=session["id"],
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="shared needle",
+ )
+ media_a_token = media_service.register(
+ conn,
+ scope_id=project_a["scope_id"],
+ session_id=session_a["id"],
+ kind="file",
+ source="agent_reply",
+ local_path=str(shared_media.resolve()),
+ )
+ media_b_token = media_service.register(
+ conn,
+ scope_id=project_b["scope_id"],
+ session_id=session_b["id"],
+ kind="file",
+ source="agent_reply",
+ local_path=str(shared_media.resolve()),
+ )
+ assert media_a_token != media_b_token
+ project_access_service.apply_project_access_intent(
+ conn,
+ _intent(project_a["id"], "[email protected]"),
+ )
+ project_access_service.apply_project_access_intent(
+ conn,
+ _group_intent(project_b["id"], "grp_beta"),
+ )
+ engine.dispose()
+ return config, {
+ "project_a": project_a["id"],
+ "project_b": project_b["id"],
+ "session_a": session_a["id"],
+ "session_b": session_b["id"],
+ "unscoped": unscoped["id"],
+ "media_a": media_a_token,
+ "media_b": media_b_token,
+ }
+
+
+ def _remote_client(config: V2Config, *, role: str, email: str):
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, email, f"user-{role}-{email}", role=role),
+ domain="alex.avibe.bot",
+ )
+ return client
+
+
+ def _get(client, path: str):
+ return client.get(path, base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER)
+
+
+ def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ conn.execute(
+ scopes.update()
+ .where(scopes.c.native_id == ids["project_a"])
+ .values(metadata_json=json.dumps({"host_path_hint": "/private/host"}))
+ )
+ client = _remote_client(config, role="editor", email="[email protected]")
+ monkeypatch.setattr(
+ api,
+ "list_show_pages",
+ lambda: {
+ "ok": True,
+ "count": 3,
+ "pages": [
+ {"session_id": ids["session_a"]},
+ {"session_id": ids["session_b"]},
+ {"session_id": ids["unscoped"]},
+ ],
+ },
+ )
+
+ project_rows = _get(client, "/api/projects").get_json()["projects"]
+ assert [row["id"] for row in project_rows] == [ids["project_a"]]
+ assert project_rows[0]["folder_path"] == ""
+ assert project_rows[0]["metadata"] == {}
+ assert project_rows[0]["capabilities"] == {"can_chat": True}
+ sessions = _get(client, "/api/sessions?status=active").get_json()["sessions"]
+ assert {row["id"] for row in sessions} == {ids["session_a"]}
+ assert sessions[0]["workdir"] is None
+ assert sessions[0]["metadata"] == {}
+ assert _get(client, f"/api/projects/{ids['project_a']}").status_code == 200
+ assert _get(client, f"/api/projects/{ids['project_b']}").status_code == 404
+ session = _get(client, f"/api/sessions/{ids['session_a']}").get_json()
+ assert session["workdir"] is None
+ assert session["metadata"] == {}
+ assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 200
+ assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 404
+ assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 404
+
+ search = _get(client, "/api/search/messages?q=needle").get_json()
+ assert [row["session_id"] for row in search["sessions"]] == [ids["session_a"]]
+ inbox = _get(client, "/api/inbox").get_json()
+ assert [row["session_id"] for row in inbox["sessions"]] == [ids["session_a"]]
+ assert set(inbox["unread_by_session"]) == {ids["session_a"]}
+ assert _get(client, f"/api/media/{ids['media_a']}").status_code == 200
+ assert _get(client, f"/api/media/{ids['media_b']}").status_code == 404
+ show_pages = _get(client, "/api/show-pages").get_json()
+ assert show_pages["pages"] == [{"session_id": ids["session_a"]}]
+ assert show_pages["count"] == 1
+
+ published = []
+ monkeypatch.setattr(broker, "publish", lambda event_type, data: published.append((event_type, data)))
+ headers = csrf_headers(client, REMOTE_ORIGIN)
+ mark_read = client.post(
+ f"/api/sessions/{ids['session_a']}/mark-read",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ assert mark_read.status_code == 200
+ assert mark_read.get_json()["unread_counts"] == {}
+ assert mark_read.get_json()["unread_by_session"] == {}
+ event_type, event_data = published[-1]
+ assert event_type == "inbox.unread.changed"
+ raw_payload = json.dumps({"type": event_type, "data": event_data})
+ alice_context = AuthorizationContext(
+ instance_role="editor",
+ is_remote=True,
+ )
+ alice_payload = json.loads(
+ ui_server._workbench_event_payload_for_context(
+ alice_context,
+ event_type,
+ raw_payload,
+ )
+ )
+ assert alice_payload["data"]["unread_counts"] == {}
+ assert alice_payload["data"]["unread_by_session"] == {}
+
+ owner_payload = json.loads(
+ ui_server._workbench_event_payload_for_context(None, event_type, raw_payload)
+ )
+ assert owner_payload["data"]["unread_counts"] == {
+ project_access_service.project_scope_id(ids["project_b"]): 1,
+ }
+ assert owner_payload["data"]["unread_by_session"] == {ids["session_b"]: 1}
+ filtered_owner_payload = json.loads(
+ ui_server._workbench_event_payload_for_context(
+ alice_context,
+ event_type,
+ json.dumps(owner_payload),
+ )
+ )
+ assert filtered_owner_payload["data"]["unread_counts"] == {}
+ assert filtered_owner_payload["data"]["unread_by_session"] == {}
+
+ allowed_action = client.post(
+ f"/api/sessions/{ids['session_a']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ hidden_action = client.post(
+ f"/api/sessions/{ids['session_b']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ assert allowed_action.status_code == 400
+ assert hidden_action.status_code == 404
+
+
+ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ **_intent(ids["project_a"], "[email protected]", role="viewer"),
+ "revision": 2,
+ },
+ )
+ scope_id = project_access_service.project_scope_id(ids["project_a"])
- messages_service.enqueue_queued(
++ message_deliveries.enqueue_queued(
+ conn,
+ scope_id=scope_id,
+ session_id=ids["session_a"],
+ text="editor-only queued prompt",
+ )
- messages_service.set_draft(
++ message_deliveries.set_draft(
+ conn,
- scope_id=scope_id,
- session_id=ids["session_a"],
- text="editor-only draft",
++ ids["session_a"],
++ "editor-only draft",
+ )
+
+ monkeypatch.setattr(
+ api,
+ "get_vibe_agents",
+ lambda **kwargs: {
+ "agents": [{"name": "editor-agent", "backend": "codex", "enabled": True}],
+ "default_agent_name": "editor-agent",
+ },
+ )
+ client = _remote_client(config, role="editor", email="[email protected]")
+
+ viewer_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()
+ assert viewer_project["capabilities"] == {"can_chat": False}
+
+ viewer_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")
+
+ assert viewer_bootstrap.status_code == 200
+ viewer_payload = viewer_bootstrap.get_json()
+ assert viewer_payload["capabilities"] == {"can_chat": False}
+ assert viewer_payload["agents"] == []
+ assert viewer_payload["default_agent_name"] is None
+ assert viewer_payload["queued"] == []
+ assert viewer_payload["draft"] == {"text": ""}
+ assert [message["text"] for message in viewer_payload["messages"]] == ["shared needle"]
+ assert viewer_payload["session"]["workdir"] is None
+ assert viewer_payload["session"]["metadata"] == {}
+
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ **_intent(ids["project_a"], "[email protected]"),
+ "revision": 3,
+ },
+ )
+
+ editor_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")
+
+ assert editor_bootstrap.status_code == 200
+ editor_payload = editor_bootstrap.get_json()
+ assert editor_payload["capabilities"] == {"can_chat": True}
+ assert editor_payload["agents"][0]["name"] == "editor-agent"
+ assert editor_payload["default_agent_name"] == "editor-agent"
+ assert editor_payload["queued"][0]["text"] == "editor-only queued prompt"
+ assert editor_payload["draft"] == {"text": "editor-only draft"}
+ editor_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()
+ assert editor_project["capabilities"] == {"can_chat": True}
+
+
+ def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ published = []
+ monkeypatch.setattr(
+ broker,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ owner = _remote_client(config, role="owner", email="[email protected]")
+ archive = owner.delete(
+ f"/api/projects/{ids['project_a']}",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=csrf_headers(owner, REMOTE_ORIGIN),
+ )
+ assert archive.status_code == 200
+ assert (
+ "authorization.changed",
+ {"project_ids": [ids["project_a"]]},
+ ) in published
+
+ monkeypatch.setattr(
+ api,
+ "list_show_pages",
+ lambda: {
+ "ok": True,
+ "count": 1,
+ "pages": [{"session_id": ids["session_a"]}],
+ },
+ )
+ client = _remote_client(config, role="editor", email="[email protected]")
+
+ assert _get(client, "/api/projects").get_json()["projects"] == []
+ assert _get(client, f"/api/projects/{ids['project_a']}").status_code == 404
+ assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 404
+ assert _get(client, f"/api/media/{ids['media_a']}").status_code == 404
+ assert _get(client, "/api/show-pages").get_json()["pages"] == []
+
+ response = client.post(
+ f"/api/sessions/{ids['session_a']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=csrf_headers(client, REMOTE_ORIGIN),
+ json={},
+ )
+ assert response.status_code == 404
+
+
+ def test_legacy_media_token_uses_all_migrated_session_references(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ engine = create_sqlite_engine()
+ token = "legacy-shared-token"
+ with engine.begin() as conn:
+ original = media_service.get_by_token(conn, ids["media_a"])
+ assert original is not None
+ conn.execute(media_objects.insert().values(**{**original, "token": token}))
+ conn.execute(
+ media_object_references.insert(),
+ [
+ {
+ "token": token,
+ "session_id": ids["session_a"],
+ "created_at": original["created_at"],
+ },
+ {
+ "token": token,
+ "session_id": ids["session_b"],
+ "created_at": original["created_at"],
+ },
+ ],
+ )
+
+ alice = _remote_client(config, role="editor", email="[email protected]")
+ beta = _remote_client(config, role="editor", email="[email protected]")
+ beta.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "user-beta",
+ role="editor",
+ organization_id="org_beta",
+ organization_member_id="member_beta",
+ organization_role="member",
+ group_ids=["grp_beta"],
+ ),
+ domain="alex.avibe.bot",
+ )
+
+ assert _get(alice, f"/api/media/{token}").status_code == 200
+ assert _get(beta, f"/api/media/{token}").status_code == 200
+
+
+ def test_remote_message_persists_trusted_web_push_authorization_context(
+ monkeypatch,
+ tmp_path,
+ ) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ engine = create_sqlite_engine()
+ agent_store = VibeAgentStore()
+ try:
+ agent = agent_store.create(name="project-access-agent", backend="codex")
+ finally:
+ agent_store.close()
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="agent",
+ resource_id=agent.id,
+ organization_id=None,
+ owner_user_id="[email protected]",
+ access_level="private",
+ )
+ update_session(
+ conn,
+ ids["session_a"],
+ agent_id=agent.id,
+ agent_name=agent.name,
+ agent_backend=agent.backend,
+ )
+ client = _remote_client(config, role="editor", email="[email protected]")
- published = []
+
- async def dispatch_async(_payload):
- return {"status_code": 202, "body": {"ok": True}}
++ async def dispatch_async(payload):
++ settled = _settle_reserved_delivery(payload, state="accepted")
++ return {
++ "status_code": 202,
++ "body": {
++ "ok": True,
++ "delivery_state": settled["state"],
++ "message_id": settled["message_id"],
++ },
++ }
+
+ monkeypatch.setattr(internal_client, "dispatch_async", dispatch_async)
- monkeypatch.setattr(
- broker,
- "publish",
- lambda event_type, data: published.append((event_type, data)),
- )
+ response = client.post(
+ f"/api/sessions/{ids['session_a']}/messages",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=csrf_headers(client, REMOTE_ORIGIN),
+ json={
+ "text": "Run it",
+ "metadata": {
+ "_web_push_authorization_contexts": [
+ {"user_key": "remote:spoofed", "email": "[email protected]"}
+ ]
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ payload = response.get_json()
+ assert not any(key.startswith("_web_push_") for key in payload["metadata"])
- published_message = next(
- data
- for event_type, data in published
- if event_type == "message.new"
- )
- assert not any(
- key.startswith("_web_push_")
- for key in published_message["metadata"]
- )
+
+ with engine.connect() as conn:
+ metadata_json = conn.execute(
+ select(messages.c.metadata_json).where(messages.c.id == payload["id"])
+ ).scalar_one()
+ persisted_metadata = json.loads(metadata_json)
+ assert persisted_metadata["_web_push_user_key"].startswith("remote:")
+ records = persisted_metadata["_web_push_authorization_contexts"]
+ claims_issued_at = records[0].pop("claims_issued_at")
+ assert isinstance(claims_issued_at, int) and claims_issued_at > 0
+ assert records == [
+ {
+ "email": "[email protected]",
+ "sub": persisted_metadata["_web_push_user_key"].removeprefix("remote:"),
+ "user_key": persisted_metadata["_web_push_user_key"],
+ "vibe_group_ids": [],
+ "vibe_instance_access_source": "owner",
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "editor",
+ }
+ ]
+ transcript = _get(client, f"/api/sessions/{ids['session_a']}/messages").get_json()
+ stored_payload = next(row for row in transcript["messages"] if row["id"] == payload["id"])
+ assert not any(key.startswith("_web_push_") for key in stored_payload["metadata"])
+
+
+ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+
+ viewer = _remote_client(config, role="viewer", email="[email protected]")
+ assert _get(viewer, f"/api/sessions/{ids['session_a']}").status_code == 200
+ assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 404
+ headers = csrf_headers(viewer, REMOTE_ORIGIN)
+ assert viewer.post(
+ "/api/sessions",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"project_id": ids["project_a"]},
+ ).status_code == 403
+
+ no_match = _remote_client(config, role="editor", email="[email protected]")
+ assert _get(no_match, "/api/projects").get_json()["projects"] == []
+ assert _get(no_match, "/api/sessions").get_json()["sessions"] == []
+ assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 404
+ no_match_headers = csrf_headers(no_match, REMOTE_ORIGIN)
+ denied = no_match.post(
+ "/api/sessions",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers={**no_match_headers, "Accept-Language": "zh-CN,zh;q=0.9"},
+ json={"project_id": ids["project_a"]},
+ )
+ assert denied.status_code == 403
+ assert denied.get_json() == {
+ "ok": False,
+ "error": {
+ "code": "project_access_denied",
+ "message": "你没有权限在这个项目中创建会话。",
+ },
+ "code": "project_access_denied",
+ "message": "你没有权限在这个项目中创建会话。",
+ }
+
+ organization_member = app.test_client()
+ organization_member.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "user-org-member",
+ role="editor",
+ access_source="organization_group",
+ organization_id="org_beta",
+ organization_member_id="member_beta",
+ organization_role="member",
+ group_ids=["grp_beta"],
+ ),
+ domain="alex.avibe.bot",
+ )
+ assert [
+ row["id"] for row in _get(organization_member, "/api/projects").get_json()["projects"]
+ ] == [ids["project_b"]]
+ assert _get(organization_member, f"/api/sessions/{ids['session_b']}").status_code == 200
+ assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 404
+ assert _get(organization_member, f"/api/media/{ids['media_b']}").status_code == 200
+ assert _get(organization_member, f"/api/media/{ids['media_a']}").status_code == 404
+
+ owner = _remote_client(config, role="owner", email="[email protected]")
+ assert {row["id"] for row in _get(owner, "/api/projects").get_json()["projects"]} == {
+ ids["project_a"],
+ ids["project_b"],
+ }
+ assert _get(owner, f"/api/sessions/{ids['unscoped']}").status_code == 200
+
+ local = app.test_client()
+ local_projects = local.get("/api/projects", base_url="http://localhost").get_json()["projects"]
+ assert {row["id"] for row in local_projects} == {ids["project_a"], ids["project_b"]}
+ assert local.get(f"/api/sessions/{ids['unscoped']}", base_url="http://localhost").status_code == 200
+
+
+ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ context = AuthorizationContext(
+ instance_role="editor",
+ is_remote=True,
+ )
+ visible_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_a"]}})
+ hidden_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_b"]}})
+ assert ui_server._workbench_event_visible_to_context(context, "session.status", visible_payload) is True
+ assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is False
+ assert ui_server._workbench_event_visible_to_context(
+ context,
+ "authorization.changed",
+ json.dumps({"type": "authorization.changed", "data": {"project_ids": []}}),
+ ) is True
+
+ cookie = remote_session_cookie(config, "[email protected]", "user-editor", role="editor")
+ websocket = SimpleNamespace(
+ client=SimpleNamespace(host="203.0.113.10"),
+ headers={"host": "alex.avibe.bot"},
+ cookies={remote_access.SESSION_COOKIE_NAME: cookie},
+ url=SimpleNamespace(scheme="wss"),
+ )
+ assert ui_server._show_runtime_websocket_authorized(
+ websocket,
+ minimum_role="viewer",
+ project_session_id=ids["session_a"],
+ ) is True
+ assert ui_server._show_runtime_websocket_authorized(
+ websocket,
+ minimum_role="viewer",
+ project_session_id=ids["session_b"],
+ ) is False
diff --cc tests/test_ui_remote_access_auth.py
index 37b98ca5e,33c763d8a..86b3b121f
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@@ -634,6 -814,129 +814,130 @@@ def test_remote_session_info_includes_a
}
+ def test_remote_viewer_can_read_but_cannot_use_management_api(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "user-viewer",
+ role="viewer",
+ access_source="owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+
+ read_response = client.get("/api/version", base_url="https://alex.avibe.bot")
+ manage_response = client.get("/api/remote-access/status", base_url="https://alex.avibe.bot")
+ session_response = client.get("/api/session", base_url="https://alex.avibe.bot")
+
+ assert read_response.status_code == 200
+ assert manage_response.status_code == 403
+ assert manage_response.get_json()["error"] == "instance_access_forbidden"
+ session_payload = session_response.get_json()
+ assert session_payload["instance_role"] == "viewer"
+ assert session_payload["capabilities"]["can_read_instance"] is True
+ assert session_payload["capabilities"]["can_chat"] is False
+ assert session_payload["capabilities"]["is_instance_owner"] is False
+
+
+ @pytest.mark.parametrize(
+ (
+ "role",
+ "agents_status",
+ "skills_status",
+ "vault_status",
+ "show_pages_status",
+ "conversation_status",
+ "project_status",
+ ),
+ [
+ ("viewer", 403, 403, 403, 200, 403, 403),
+ ("editor", 200, 200, 200, 200, 400, 403),
+ ("owner", 200, 200, 200, 200, 400, 400),
+ ],
+ )
+ def test_remote_instance_role_route_matrix(
+ monkeypatch,
+ tmp_path,
+ role,
+ agents_status,
+ skills_status,
+ vault_status,
+ show_pages_status,
+ conversation_status,
+ project_status,
+ ):
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ ensure_sqlite_state()
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, f"{role}@example.com", f"user-{role}", role=role),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, "https://alex.avibe.bot")
+
+ read_response = client.get("/api/projects", base_url="https://alex.avibe.bot")
+ agents_response = client.get("/api/agents", base_url="https://alex.avibe.bot")
+ skills_response = client.get("/api/skills", base_url="https://alex.avibe.bot")
+ vault_response = client.get("/api/vault/secrets", base_url="https://alex.avibe.bot")
+ show_pages_response = client.get("/api/show-pages", base_url="https://alex.avibe.bot")
+ config_response = client.get("/api/config", base_url="https://alex.avibe.bot")
+ prefs_read_response = client.get("/api/workbench/prefs", base_url="https://alex.avibe.bot")
+ prefs_write_response = client.put(
+ "/api/workbench/prefs",
+ base_url="https://alex.avibe.bot",
+ headers=headers,
+ json={"background_work_banner_enabled": False},
+ )
+ conversation_response = client.post(
+ "/api/sessions",
+ base_url="https://alex.avibe.bot",
+ headers=headers,
+ json={},
+ )
+ project_response = client.post(
+ "/api/projects",
+ base_url="https://alex.avibe.bot",
+ headers=headers,
+ json={},
+ )
+
+ assert read_response.status_code == 200
+ assert agents_response.status_code == agents_status
+ assert skills_response.status_code == skills_status
+ assert vault_response.status_code == vault_status
+ assert show_pages_response.status_code == show_pages_status
+ assert config_response.status_code == 200
+ assert prefs_read_response.status_code == 200
+ assert prefs_read_response.get_json()["background_work_banner_enabled"] is True
+ assert prefs_write_response.status_code == (200 if role == "owner" else 403)
+ if role == "owner":
+ assert "runtime" in config_response.get_json()
+ else:
+ assert set(config_response.get_json()) == {
++ "capabilities",
+ "language",
+ "mode",
+ "setup_state",
+ "ui",
+ "version",
+ }
+ assert conversation_response.status_code == conversation_status
+ assert project_response.status_code == project_status
+ if role == "viewer":
+ assert conversation_response.get_json()["error"] == "instance_access_forbidden"
+ if role != "owner":
+ assert project_response.get_json()["error"] == "instance_access_forbidden"
+
+
def _forged_session_cookie(config: V2Config, exp: int, *, email: str = "[email protected]", subject: str = "user-1") -> str:
import json
import urllib.parse
diff --cc tests/test_ui_server_fastapi.py
index 3f004d5fb,32b953f7f..8baf7cab1
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@@ -1,6 -1,6 +1,7 @@@
+ import asyncio
import gzip
import json
+from types import SimpleNamespace
import pytest
diff --cc tests/test_ui_session_stream.py
index fb4940a39,dcbb666b9..45bafbfaa
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@@ -217,97 -135,145 +219,234 @@@ def test_route_fire_and_forgets_dispatc
sent = dispatch_mock.await_args.args[0]
assert sent["session_id"] == session_id
assert sent["text"] == "no stream"
+ assert sent["memory_cli_admitted"] is False
+ assert sent["is_ordinary_text"] is True
+
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ {"text": "Yes", "metadata": {"quick_reply_for": "agent-message-1"}},
+ {"text": "forwarded text", "metadata": {"forwarded": True}},
+ ],
+ )
+ def test_workbench_side_actions_are_not_marked_as_ordinary_memory_input(
+ isolated_state,
+ tmp_path,
+ payload,
+ ):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ dispatch = AsyncMock(
+ return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
+ )
+ with patch("vibe.internal_client.dispatch_async", dispatch):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json=payload,
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 201
+ assert dispatch.await_args.args[0]["is_ordinary_text"] is False
+
+
+
+ def test_workbench_memory_text_is_persisted_and_dispatched_as_ordinary_input(
+ isolated_state,
+ tmp_path,
+ ):
+ from storage import messages_service
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ dispatch = AsyncMock(
+ return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
+ )
+ client = app.test_client()
+ headers = csrf_headers(client, "http://127.0.0.1:15131")
+
+ with (
+ patch("vibe.internal_client.dispatch_async", dispatch),
+ patch.object(messages_service, "append", wraps=messages_service.append) as append,
+ ):
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={"text": "/memory status"},
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ environ_base={"REMOTE_ADDR": "127.0.0.1"},
+ )
+
+ assert response.status_code == 201
+ append.assert_called_once()
+ payload = dispatch.await_args.args[0]
+ assert payload["text"] == "/memory status"
+ assert payload["user_id"] == "local"
+ assert payload["message_id"] == response.get_json()["id"]
+ assert payload["memory_cli_admitted"] is True
+
+
+ @pytest.mark.parametrize(
+ "session_payload,expected",
+ [
+ ({"sub": "user-a"}, "remote:user-a"),
+ ({}, None),
+ (None, None),
+ ],
+ )
+ def test_remote_workbench_memory_identity_requires_a_stable_subject(session_payload, expected):
+ from vibe import remote_access
+ from vibe.ui_server import app, _workbench_memory_user_id
+
+ with (
+ app.test_request_context("/chat/session", headers={"Cookie": "avibe_remote_session=session"}),
+ patch("vibe.ui_server.is_direct_loopback_memory_request", return_value=False),
+ patch("vibe.ui_server._load_remote_access_config", return_value=object()),
+ patch.object(remote_access, "parse_session_cookie", return_value=session_payload),
+ ):
+ assert _workbench_memory_user_id() == expected
+
+
+ def test_workbench_dispatch_propagates_attachment_and_resolved_identity(
+ isolated_state,
+ tmp_path,
+ ):
+ import base64
+
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ dispatch = AsyncMock(
+ return_value={"status_code": 202, "body": {"ok": True, "session_id": session_id}}
+ )
+ client = app.test_client()
+ headers = csrf_headers(client, "http://127.0.0.1:15131")
+ upload = client.post(
+ f"/api/sessions/{session_id}/attachments",
+ json={
+ "name": "diagram.png",
+ "mime": "image/png",
+ "data": base64.b64encode(b"attachment-bytes").decode("ascii"),
+ },
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ )
+
+ with patch("vibe.internal_client.dispatch_async", dispatch):
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={
+ "content": {
+ "text": "remember this diagram",
+ "attachments": [{"token": upload.get_json()["token"]}],
+ }
+ },
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ environ_base={"REMOTE_ADDR": "127.0.0.1"},
+ )
+
+ assert response.status_code == 201
+ payload = dispatch.await_args.args[0]
+ assert payload["user_id"] == "local"
+ assert payload["message_id"] == response.get_json()["id"]
+ assert len(payload["files"]) == 1
+ assert payload["files"][0]["name"] == "diagram.png"
+ assert Path(payload["files"][0]["path"]).read_bytes() == b"attachment-bytes"
+def test_route_reads_the_materialized_message_id_for_a_merged_batch(
+ isolated_state,
+ tmp_path,
+) -> None:
+ from vibe.ui_server import app
+
+ scope_id, session_id = _make_session(tmp_path)
+ older_delivery_id = "msg_merged_segment_head"
+
+ async def dispatch(payload):
+ with create_sqlite_engine().begin() as conn:
+ current = message_deliveries.get_delivery(conn, payload["user_message_id"])
+ assert current is not None and current["state"] == "reserved"
+ older = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=older_delivery_id,
+ session_id=session_id,
+ priority="p3",
+ state="queued",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="older queued input",
+ metadata={"_web_push_user_key": "remote:user-a"},
+ author_id="remote:user-a",
+ ),
+ dispatch_text="older queued input",
+ now="2026-01-01T00:00:00Z",
+ )
+ turn_id = message_deliveries.new_turn_id()
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="claude",
+ deliveries=[older, current],
+ dispatch_text="older queued input\nnew input",
+ )
+ turn = claimed["turn"]
+ assert message_deliveries.bind_native_start(
+ conn,
+ turn_id,
+ expected_version=int(turn["version"]),
+ runtime_key=f"runtime:{turn_id}",
+ runtime_turn_id=f"runtime-turn:{turn_id}",
+ native_turn_id=f"native:{turn_id}",
+ ) is not None
+ accepted = message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id=turn_id,
+ evidence={"kind": "test_native_acceptance"},
+ )
+ current_after = message_deliveries.get_delivery(
+ conn,
+ payload["user_message_id"],
+ )
+ assert accepted and current_after is not None
+ return {
+ "status_code": 202,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "delivery_id": payload["user_message_id"],
+ "message_id": accepted[0]["message_id"],
+ "delivery_state": current_after["state"],
+ },
+ }
+
+ with (
+ patch("vibe.internal_client.dispatch_async", AsyncMock(side_effect=dispatch)),
+ patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),
+ ):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={"text": "new input"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 201
+ body = response.get_json()
+ assert body["id"] == older_delivery_id
+ assert body["message_id"] == older_delivery_id
+ assert body["delivery_id"] != older_delivery_id
+
+
def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
"""When the controller reports a turn already running (202 {queued}), the
route persists the user row, hands its id to the controller to re-type as
diff --cc tests/test_ui_show_pages.py
index 7d044936a,823098a8c..ff18f7177
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@@ -33,11 -32,11 +33,12 @@@ from core.show_runtime import
_safe_extract_tar,
set_show_runtime_manager_for_tests,
)
+ from storage import resource_access_service
from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _save_config
- from tests.ui_server_test_helpers import csrf_headers
+ from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
from vibe import remote_access, ui_server
from vibe.ui_server import app
+from storage import message_deliveries
class _FakeShowRuntimeManager:
@@@ -6009,3 -5808,3 +6496,14 @@@ def test_public_show_page_passes_runtim
# Public pages receive read/auth config but never the private write token.
assert "globalThis.__AVIBE_SHOW__=Object.assign" in text
assert '"writeToken"' not in text
++
++
++def test_show_runtime_manager_defaults_to_manifest_when_package_manifest_exists(monkeypatch, tmp_path):
++ monkeypatch.setattr("core.show_runtime._packaged_runtime_manifest_exists", lambda: True)
++
++ manager = ShowRuntimeManager(
++ workspace_root=tmp_path / "show",
++ runtime_dir=tmp_path / "runtime",
++ )
++
++ assert manager.runtime_source == "manifest-cache"
diff --cc tests/test_web_push_notifications.py
index 0c7bf86bb,ce3a8ec5a..626a4e67d
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@@ -1,7 -1,7 +1,7 @@@
from __future__ import annotations
from core import web_push_notifications
- from storage import message_deliveries, messages_service, web_push_service
-from storage import messages_service, project_access_service, web_push_service
++from storage import message_deliveries, messages_service, project_access_service, web_push_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions
diff --cc ui/eslint-baseline.json
index c9d861644,000000000..35666b912
mode 100644,000000..100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@@ -1,267 -1,0 +1,264 @@@
+{
+ "$comment": "Explicit ledger of the lint violations that predate the UI lint cleanup and are not fixed by it. `npm run lint` fails on anything not recorded here, on a recorded entry that grows, and on a recorded entry that shrinks without being re-recorded. See scripts/lint-baseline.mjs. Regenerate with `npm run lint:baseline`; raising a count needs a reviewer to agree in the PR.",
+ "rationale": {
+ "@typescript-eslint/no-explicit-any": "The untyped edge of the Python API. Each one is a response body, an SSE event payload or a third-party callback that reaches the UI as `any`. Typing them is a per-endpoint contract change against the backend, not a lint fix, and doing it as one sweep would produce a diff nobody can review. The ratchet's job here is to stop a NEW endpoint from landing untyped; the recorded ones come down endpoint by endpoint.",
+ "react-hooks/set-state-in-effect": "Legitimate-looking `reset derived state when the subject changes` and prop-mirroring effects in components with no test coverage. Each rewrite changes when a render happens, so each needs its own regression test first; batching them behind a lint deadline is how a subtle render-order bug ships.",
+ "react-hooks/preserve-manual-memoization": "Advice for adopting the React Compiler, not a defect. `babel-plugin-react-compiler` is not in this project's Vite plugin list, so no shipped behaviour depends on these; they become actionable in the change that turns the compiler on.",
+ "react-refresh/only-export-components": "`src/context/ApiContext.tsx` only. Every other context module in the UI now splits its handle from its provider, but this one is 3142 lines with ~78 consumers, and the split means relocating the ~1200-line provider in the single most contended file in the repository (36 unmerged branches currently modify it). The cost is a merge conflict for everyone else, and the benefit is hot-reload for one file \u2014 so it belongs in a change that owns ApiContext, not in a lint cleanup.",
+ "react-hooks/exhaustive-deps": "Inline `eslint-disable` comments predating this cleanup. Each one also opts its component out of the compiler-backed hook analysis, so the suppressed count is a direct measure of the UI the other react-hooks rules cannot see: removing all 43 raises the error count rather than lowering it. Frozen here so that area cannot grow while it is retired component by component.",
+ "react-hooks/refs": "Inline suppressions of the render-phase ref rule, in the same unanalysable area as the exhaustive-deps ones above. Frozen so no new render-phase ref access can be hidden behind a comment."
+ },
+ "violations": {
+ "src/components/AppShell.tsx": {
+ "@typescript-eslint/no-explicit-any": 2,
+ "react-hooks/set-state-in-effect": 2
+ },
+ "src/components/Dashboard.tsx": {
+ "@typescript-eslint/no-explicit-any": 9
+ },
+ "src/components/InstallHint.tsx": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/Wizard.tsx": {
+ "@typescript-eslint/no-explicit-any": 9
+ },
+ "src/components/settings/SettingsBackendsPage.tsx": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/settings/SettingsMessagingPage.tsx": {
+ "@typescript-eslint/no-explicit-any": 3,
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/settings/SettingsPlatformsPage.tsx": {
+ "@typescript-eslint/no-explicit-any": 10
+ },
+ "src/components/settings/SettingsServicePage.tsx": {
+ "@typescript-eslint/no-explicit-any": 4
+ },
+ "src/components/settings/models/modelsApi.ts": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/settings/providers/ClaudeProviderConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/settings/providers/CodexProviderConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/settings/shared/useBackendRuntime.ts": {
+ "@typescript-eslint/no-explicit-any": 2
+ },
+ "src/components/settings/shared/useOAuthFlowLock.ts": {
+ "react-hooks/preserve-manual-memoization": 1
+ },
+ "src/components/shared/RoutingConfigPanel.tsx": {
+ "@typescript-eslint/no-explicit-any": 3,
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/steps/AgentDetection.tsx": {
+ "@typescript-eslint/no-explicit-any": 3
+ },
+ "src/components/steps/ChannelList.tsx": {
+ "@typescript-eslint/no-explicit-any": 29
+ },
+ "src/components/steps/DiscordConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 6
+ },
+ "src/components/steps/DoctorPanel.tsx": {
+ "@typescript-eslint/no-explicit-any": 4
+ },
+ "src/components/steps/LarkConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 6
+ },
+ "src/components/steps/ModeSelection.tsx": {
+ "@typescript-eslint/no-explicit-any": 2
+ },
+ "src/components/steps/PlatformSelection.tsx": {
+ "@typescript-eslint/no-explicit-any": 7
+ },
+ "src/components/steps/SlackConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 4
+ },
+ "src/components/steps/Summary.tsx": {
+ "@typescript-eslint/no-explicit-any": 9
+ },
+ "src/components/steps/TelegramConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 4
+ },
+ "src/components/steps/UserList.tsx": {
+ "@typescript-eslint/no-explicit-any": 6
+ },
+ "src/components/steps/WeChatConfig.tsx": {
+ "@typescript-eslint/no-explicit-any": 4
+ },
+ "src/components/steps/Welcome.tsx": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/ui/secret-request-card.tsx": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/ui/vault-chat-requests.tsx": {
+ "react-hooks/set-state-in-effect": 1
+ },
- "src/components/workbench/AgentsPage.tsx": {
- "@typescript-eslint/no-explicit-any": 1
- },
+ "src/components/workbench/AppsEditorPage.tsx": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/workbench/ChatPage.tsx": {
+ "@typescript-eslint/no-explicit-any": 1,
+ "react-hooks/preserve-manual-memoization": 2,
+ "react-hooks/set-state-in-effect": 3
+ },
+ "src/components/workbench/FileTree.tsx": {
+ "react-hooks/set-state-in-effect": 2
+ },
+ "src/components/workbench/HarnessPage.tsx": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/workbench/TerminalView.tsx": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/workbench/VaultsPage.tsx": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/workbench/harnessLifecycle.test.ts": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/components/workbench/harnessLifecycle.ts": {
+ "@typescript-eslint/no-explicit-any": 5
+ },
+ "src/context/ApiContext.tsx": {
+ "@typescript-eslint/no-explicit-any": 52,
+ "react-refresh/only-export-components": 1
+ },
+ "src/context/DockProvider.tsx": {
+ "react-hooks/preserve-manual-memoization": 5
+ },
+ "src/context/StatusContext.ts": {
+ "@typescript-eslint/no-explicit-any": 3
+ },
+ "src/context/StatusProvider.tsx": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/context/apiErrorParse.ts": {
+ "@typescript-eslint/no-explicit-any": 1
+ },
+ "src/lib/platforms.ts": {
+ "@typescript-eslint/no-explicit-any": 12
+ },
+ "src/lib/secretFields.ts": {
+ "@typescript-eslint/no-explicit-any": 4
+ },
+ "src/lib/useMessageSearch.ts": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/lib/useNewSession.ts": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/lib/usePendingVaultRequests.ts": {
+ "react-hooks/preserve-manual-memoization": 1
+ }
+ },
+ "suppressions": {
+ "src/App.tsx": {
+ "react-hooks/refs": 1
+ },
+ "src/components/apps/AppWindow.tsx": {
+ "react-hooks/exhaustive-deps": 2
+ },
+ "src/components/settings/SettingsBackendsPage.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/settings/models/SourceOrderDrawer.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/settings/models/menus/AddCustomModelDialog.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/settings/models/menus/OpenCodeMenuDrawer.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/settings/providers/OpencodeProviderConfig.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/settings/shared/useBackendRuntime.ts": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/settings/shared/useOpencodePermission.ts": {
+ "react-hooks/set-state-in-effect": 1
+ },
+ "src/components/steps/AgentDetection.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/steps/ChannelList.tsx": {
+ "react-hooks/exhaustive-deps": 3
+ },
+ "src/components/steps/DoctorPanel.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/steps/LarkConfig.tsx": {
+ "react-hooks/exhaustive-deps": 3
+ },
+ "src/components/steps/LogsPanel.tsx": {
+ "react-hooks/exhaustive-deps": 2
+ },
+ "src/components/steps/SlackConfig.tsx": {
+ "react-hooks/exhaustive-deps": 3
+ },
+ "src/components/ui/directory-browser.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/ui/editor-dialog.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/ui/vault-approval-card.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/ui/vault-secret-form.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/workbench/AgentsPage.tsx": {
+ "react-hooks/exhaustive-deps": 2
+ },
+ "src/components/workbench/AppsFileBrowserPage.tsx": {
+ "react-hooks/exhaustive-deps": 2
+ },
+ "src/components/workbench/EditorApp.tsx": {
+ "react-hooks/exhaustive-deps": 2
+ },
+ "src/components/workbench/FilePicker.tsx": {
+ "react-hooks/exhaustive-deps": 3
+ },
+ "src/components/workbench/FileTree.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/workbench/GlobalPromptsDialog.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/workbench/InboxPage.tsx": {
+ "react-hooks/exhaustive-deps": 2
+ },
+ "src/components/workbench/MentionEditor.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/workbench/MonacoEditor.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/workbench/ProjectAgentsMdDialog.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/components/workbench/WebPushControl.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/context/ApiContext.tsx": {
+ "react-hooks/exhaustive-deps": 1
+ },
+ "src/context/WindowManagerProvider.tsx": {
+ "react-hooks/refs": 1
+ },
+ "src/lib/useLatestRef.ts": {
+ "react-hooks/refs": 1
+ },
+ "src/lib/vaultTags.test.ts": {
+ "@typescript-eslint/no-explicit-any": 1
+ }
+ }
+}
diff --cc ui/src/App.tsx
index abcbbaf14,8777bc87f..eef335e16
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@@ -34,15 -35,17 +35,17 @@@ import { SettingsLogsPage } from './com
import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';
import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPage';
import { SettingsServicePage } from './components/settings/SettingsServicePage';
-import { StatusProvider } from './context/StatusContext';
+import { StatusProvider } from './context/StatusProvider';
import { ApiProvider, useApi, ApiError } from './context/ApiContext';
+ import type { SessionInfo } from './context/ApiContext';
-import { InstanceAuthorizationProvider } from './context/InstanceAuthorizationContext';
++import { InstanceAuthorizationProvider } from './context/InstanceAuthorizationProvider';
import { useWindowManager } from './context/WindowManagerContext';
-import { ToastProvider } from './context/ToastContext';
-import { ThemeProvider } from './context/ThemeContext';
+import { ToastProvider } from './context/ToastProvider';
+import { ThemeProvider } from './context/ThemeProvider';
import { VaultSandboxAppearanceBridge } from './components/VaultSandboxAppearanceBridge';
-import { WorkbenchInboxProvider } from './context/WorkbenchInboxContext';
-import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';
-import { ComposerBridgeProvider } from './context/ComposerBridgeContext';
+import { WorkbenchInboxProvider } from './context/WorkbenchInboxProvider';
+import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsProvider';
+import { ComposerBridgeProvider } from './context/ComposerBridgeProvider';
import { UnsavedChangesProvider } from './context/UnsavedChangesProvider';
import { AgentationToggle } from './components/AgentationToggle';
import { PwaLoopbackLinkGuard } from './components/PwaLoopbackLinkGuard';
@@@ -634,8 -658,9 +670,9 @@@ const router = createBrowserRouter
<Route path="/settings/backends/opencode" element={<Navigate to="/admin/settings/backends/opencode" replace />} />
<Route path="/settings/backends/claude" element={<Navigate to="/admin/settings/backends/claude" replace />} />
<Route path="/settings/backends/codex" element={<Navigate to="/admin/settings/backends/codex" replace />} />
- <Route path="/settings/models" element={<Navigate to="/admin/settings/models" replace />} />
+ <Route path="/settings/models" element={<LegacyModelHubRoute />} />
<Route path="/settings/dependencies" element={<Navigate to="/admin/settings/dependencies" replace />} />
+ <Route path="/settings/memory" element={<Navigate to="/admin/settings/memory" replace />} />
<Route path="/settings/messaging" element={<Navigate to="/admin/settings/messaging" replace />} />
<Route path="/settings/diagnostics" element={<Navigate to="/admin/settings/diagnostics" replace />} />
<Route path="/settings/logs" element={<Navigate to="/admin/settings/logs" replace />} />
diff --cc ui/src/components/AppShell.tsx
index 47f795a2c,20a8882c2..67cb2c93b
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@@ -4,7 -4,8 +4,8 @@@ import { ArrowLeft, Bot, Brain, Buildin
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { MODEL_HUB_NAV_ENABLED } from './settings/models/featureFlags';
+import { modelHubEnabledFromConfig } from './settings/models/featureFlags';
+ import { memoryNavShouldBeVisible } from '../lib/memorySettings';
import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';
@@@ -263,10 -283,34 +284,35 @@@ export const AppShell: React.FC = () =
setAppsDrawerOpen(false);
}, [location.pathname]);
+ if (location.pathname.startsWith('/admin/organization')) {
+ return <OrganizationShell />;
+ }
+
const hasChannelPlatforms = enabledPlatforms.some((platform) => platformSupportsChannels(config, platform));
+ const modelHubEnabled = modelHubEnabledFromConfig(config);
const isRunning = status.state === 'running';
+ const ownerOnlyPath =
+ location.pathname === '/setup' ||
+ (location.pathname.startsWith('/admin') && !location.pathname.startsWith('/admin/organization')) ||
+ ['/agents', '/harness', '/apps/library'].some(
+ (path) => location.pathname === path || location.pathname.startsWith(`${path}/`),
+ );
+ const resourceUseDenied =
+ (location.pathname.startsWith('/skills') && !capabilities.can_use_skills) ||
+ (location.pathname.startsWith('/vaults') && !capabilities.can_use_vault_secrets);
+ const fileOnlyPath =
+ location.pathname.startsWith('/apps/files') || location.pathname.startsWith('/apps/editor');
+ const terminalOnlyPath = location.pathname.startsWith('/apps/terminal');
+ if (
+ (ownerOnlyPath && !capabilities.can_manage_instance) ||
+ resourceUseDenied ||
+ (fileOnlyPath && !capabilities.can_use_files) ||
+ (terminalOnlyPath && !capabilities.can_use_terminal)
+ ) {
+ return <Navigate to="/" replace />;
+ }
+
if (location.pathname === '/setup') {
return <Outlet />;
}
@@@ -402,8 -456,7 +456,8 @@@
// pans the locked page to lift the focused composer above the keyboard.
// Desktop: normal document flow.
<WindowManagerProvider>
- <DockProvider>
+ <DockProvider enabled={capabilities.can_use_system}>
+ <ShowPageDragProvider>
<div className="flex h-[var(--app-shell-h)] flex-col overflow-hidden bg-background text-foreground md:block md:h-auto md:min-h-screen md:overflow-visible">
{/* The sidebar forms its own stacking context BELOW the window layer (aside z-10 < window
layer z-20), so a maximized window covers the WHOLE sidebar — including the Apps launcher.
@@@ -632,9 -717,8 +718,9 @@@
second launcher on top in full-screen anymore (product: avoid the fullscreen floating
button; a Dock redesign comes later). Un-maximize via the window traffic-lights to reach
the sidebar launcher. */}
- <WindowLayer />
+ {capabilities.can_use_system && <WindowLayer />}
</div>
+ </ShowPageDragProvider>
</DockProvider>
</WindowManagerProvider>
);
diff --cc ui/src/components/workbench/AgentsPage.tsx
index 4253a5c77,8fc6d3be8..16c44f664
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@@ -22,7 -25,8 +25,13 @@@ import
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
- import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';
-import type { VibeAgentBrief, VibeAgentFull, VibeAgentOnboardingResult } from '../../context/ApiContext';
++import type {
++ VibeAgentBrief,
++ VibeAgentFull,
++ VibeAgentOnboardingResult,
++ VibeAgentUpdatePayload,
++} from '../../context/ApiContext';
+ import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { AgentGraphTab } from './AgentGraphTab';
import { useToast } from '../../context/ToastContext';
import { NewAgentDialog } from './NewAgentDialog';
@@@ -261,10 -291,10 +293,10 @@@ export const AgentsPage: React.FC = ()
};
-- const updateField = async (patch: Partial<VibeAgentFull>) => {
++ const updateField = async (patch: VibeAgentUpdatePayload) => {
if (!selected) return;
try {
-- const result = await api.updateVibeAgent(selected.name, patch as any);
++ const result = await api.updateVibeAgent(selected.name, patch);
if (result.ok) {
setSelected(result.agent);
refresh();
@@@ -299,6 -330,9 +332,7 @@@
if (result.ok) {
setSelected(null);
refresh();
+ void refreshOnboarding();
- } else if (result.code === 'agent_in_use') {
- setError(t('agents.deleteInUse', { name: selected.name }));
} else if (result.message) {
setError(result.message);
}
@@@ -338,6 -373,25 +373,25 @@@
}
};
+ const onOnboardAgents = async () => {
+ if (onboardingSubmitting) return;
+ setOnboardingSubmitting(true);
+ try {
+ const result = await api.onboardVibeAgents();
+ setOnboardingInventory(result);
+ showToast(
+ result.sync?.ok === false
+ ? t('agents.onboarding.savedPending')
+ : t('agents.onboarding.saved', { count: result.created ?? 0 }),
+ result.sync?.ok === false ? 'warning' : 'success',
+ );
- } catch (err: any) {
- showToast(t('agents.onboarding.failed', { error: err?.message ?? String(err) }), 'error');
++ } catch (err) {
++ showToast(t('agents.onboarding.failed', { error: errorMessage(err) ?? String(err) }), 'error');
+ } finally {
+ setOnboardingSubmitting(false);
+ }
+ };
+
const totalShown = filtered.length;
const noMatches = totalShown === 0 && agents.length > 0;
@@@ -644,7 -836,7 +836,7 @@@ const ImportMenu: React.FC<ImportMenuPr
interface DetailProps {
agent: VibeAgentFull;
isDefault: boolean;
-- onChange: (patch: Partial<VibeAgentFull>) => void;
++ onChange: (patch: VibeAgentUpdatePayload) => void;
onSetDefault: () => Promise<void>;
onRenamed: (newName: string) => void;
onDelete: () => void;
diff --cc ui/src/components/workbench/ChatPage.tsx
index 82dcdcf23,deb5650ff..31a57c7a9
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@@ -6,29 -6,18 +6,30 @@@ import type { LucideIcon } from 'lucide
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
+import { selectApiErrorFields } from '../../context/apiErrorParse';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
+ import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';
+import { useWindowManager } from '../../context/WindowManagerContext';
import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { apiFetch } from '../../lib/apiFetch';
+import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
-import { isNotifyMessageType, isTerminalAgentMessage } from '../../lib/chatMessageTypes';
+import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';
+import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessageTypes';
+import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
+import { isVaultApprovalRequest, placeVaultProvisionRequests } from '../../lib/vaultRequestPlacement';
import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
+import { showPageEmbeddedPath } from '../../apps/showPageAvatar';
+import { downloadFile, fileMeta } from '../../lib/filesApi';
+import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/filePreview';
+import { recentPathLabel } from '../../lib/editorRecents';
+import type { LocalFileLinkTarget } from '../../lib/localFileLinks';
import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';
+import { resultFooterParts } from '../../lib/resultFooter';
import {
activityItemKind,
activityKindI18nKey,
@@@ -171,24 -163,6 +176,25 @@@ export const ChatPage: React.FC = () =
const chatSurfaceRef = useRef<HTMLDivElement>(null);
useIosKeyboardInset(chatSurfaceRef);
+ // Loaded session (null while bootstrapping — ChatPage renders a loader until
+ // it's set). Lifted above the composer bridge + show-page logic that gate on it.
+ const [session, setSession] = useState<WorkbenchSession | null>(null);
+ // Archive is terminal: an archived transcript stays fully readable (search's
+ // "include archived" opt-in links straight here) but every mutation is refused
+ // server-side, so the chat renders read-only — no composer, no rename, no
+ // re-route, no transcript control that would write to the session, and no Show
+ // Page controls (archive takes the page offline and refuses to create one, so
+ // Visualize and Share could only fail; see showPageControlActions).
+ //
+ // A ``visibility === 'system'`` session is read-only for a DIFFERENT reason and to
+ // the same depth: the runtime owns the row (the workspace-notifications session the
+ // Inbox links to) and the messages POST answers 403 ``reserved_session``. The reason
+ // is carried alongside because only the COPY differs — nothing here may call such a
+ // session archived.
+ const readOnlyReason = sessionReadOnlyReason(session);
+ const readOnly = isSessionReadOnly(session);
++ const writable = canChat && !readOnly;
+
// Chat-page-wide drag-and-drop: dropping files anywhere over the chat surface
// (not just the input row) stages them on the composer via its imperative
// handle. Desktop-only in practice — touch fires no drag events — and disabled
@@@ -197,9 -170,13 +203,9 @@@
const composerRef = useRef<ComposerHandle>(null);
const { dragging: fileDragging, handlers: fileDropHandlers } = useFileDrop(
(files) => composerRef.current?.addFiles(files),
- { disabled: !sessionId || readOnly },
- { disabled: !sessionId || !canChat },
++ { disabled: !sessionId || !writable },
);
- // Loaded session (null while bootstrapping — ChatPage renders a loader until
- // it's set). Lifted above the composer bridge + show-page logic that gate on it.
- const [session, setSession] = useState<WorkbenchSession | null>(null);
-
// Show Page toggle: swap the chat surface (transcript + composer, NOT the
// header bar) for this session's Show Page in an iframe, and back. Declared
// before the composer bridge target, which depends on showPageMode.
@@@ -321,15 -265,10 +327,15 @@@
// mounted + insertable: a chat is open (sessionId), its session has loaded
// (before that ChatPage shows a loader — the composer isn't rendered yet), and
// the Show Page iframe hasn't replaced the composer. Otherwise an insert would
- // silently no-op against a null composerRef.
+ // silently no-op against a null composerRef. An archived (read-only) chat is
+ // also not insertable — its composer is disabled, so the insert would land in a
+ // box that can never be sent.
const composerTarget = useMemo<ComposerInsertTarget | null>(
- () => (canChat && sessionId && session != null && !showPageMode ? { sessionId, insertSessionReference } : null),
- [canChat, sessionId, session, showPageMode, insertSessionReference],
+ () =>
- sessionId && session != null && !showPageActive && !readOnly
++ sessionId && session != null && !showPageActive && writable
+ ? { sessionId, insertSessionReference }
+ : null,
- [sessionId, session, showPageActive, readOnly, insertSessionReference],
++ [sessionId, session, showPageActive, writable, insertSessionReference],
);
useRegisterComposerTarget(composerTarget);
@@@ -1287,6 -1181,7 +1305,7 @@@
metadata?: Record<string, unknown>,
references?: MentionReference[],
) => {
- if (!canChat) return false;
++ if (!writable) return false;
// NB: no ``working`` guard — sending WHILE a turn runs is the queue
// feature; the backend enqueues it (202) instead of refusing.
const ready = (attachments ?? []).filter((a) => a.status === 'ready');
@@@ -1399,24 -1267,26 +1419,24 @@@
if (historicalWindowRef.current) {
const caughtUp = await reloadLatestMessages();
if (sessionId === sessionIdRef.current) {
- if (caughtUp) setJumpTarget((body as WorkbenchMessage).id);
- else appendMessage(body as WorkbenchMessage);
+ if (caughtUp) setJumpTarget(message.id);
+ else appendMessage(message);
}
} else {
- appendMessage(body as WorkbenchMessage);
+ appendMessage(message);
}
}
- } catch (err: any) {
+ } catch (err) {
if (sessionId === sessionIdRef.current) {
- // The request may have raced a turn owned by another tab or source.
- // Reconcile rather than clearing that turn's Stop state optimistically.
- void syncTurnStateRef.current?.();
- setError(err?.message ?? String(err));
+ setWorking(false);
+ setError(errorMessage(err) ?? String(err));
// Signal the composer the send didn't start so it restores the text +
// uploaded chips — the user can retry without re-uploading (Codex r5).
return false;
}
}
},
- [sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages, convergeSessionArchived, t],
- [canChat, sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages],
++ [sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages, convergeSessionArchived, t, writable],
);
// @ mention source: all enabled Agents, filtered client-side (the set is small
@@@ -1454,71 -1324,9 +1474,72 @@@
[api, sessionId],
);
- // Toggle the chat surface ↔ the session's Show Page (iframe). The first open
- // ensures the page exists; if it was just created, ask the agent to build the
- // visualization. Errors surface via the apiFetch toast layer.
+ // One action path serves inline view changes and external launches. Every
+ // target first ensures the page and sends the same first-build prompt; only
+ // the inline target changes this chat's remembered surface.
+ const performShowPageAction = useCallback(
+ async (sid: string, target: 'inline' | 'prepare'): Promise<boolean> => {
++ if (!canManageShowPage || readOnly) return false;
+ const request = ++showPageRequestRef.current;
+ setShowPageBusy(true);
+ try {
+ const res = await api.ensureShowPage(sid);
+ // Bail if the user switched chats or explicitly selected Chat while ensure
+ // was in flight. The request id closes the same-session ?view=chat race.
+ if (sessionIdRef.current !== sid || showPageRequestRef.current !== request) return false;
+ if (res?.ok) {
+ if (target === 'inline') {
+ // Public pages are served under /p/<share_id>/; private under /show/<id>/.
+ setShowPageUrl(
+ showPageEmbeddedPath(
+ res.visibility === 'public' && res.share_id
+ ? `/p/${encodeURIComponent(res.share_id)}/`
+ : `/show/${encodeURIComponent(sid)}/`,
+ ),
+ );
+ setShowPageMode(true);
+ writeChatViewMode(sid, 'show-page');
+ }
+ // First open (or a prior prompt that failed to send) asks the agent to
+ // build the visualization. sendMessage returns false on a failed send;
+ // track it so the NEXT toggle retries — the page row exists after this,
+ // so `existed` alone would never re-prompt a created-but-unprompted page.
+ // Never on a read-only (archived) session: the store refuses to CREATE a
+ // page there, but a session archived after a failed prompt is still in the
+ // retry set, and re-prompting it would only 409. The header no longer
+ // offers the toggle at all once the session reads archived, so this is the
+ // callback-level backstop for an invocation that raced that render.
+ if (!readOnly && (res.existed === false || showPagePromptRetryRef.current.has(sid))) {
+ void sendMessage(t('chat.showPage.prompt')).then((sent) => {
+ if (sent === false) showPagePromptRetryRef.current.add(sid);
+ else showPagePromptRetryRef.current.delete(sid);
+ });
+ }
+ return true;
+ }
+ return false;
+ } catch {
+ // apiFetch already surfaced a toast; stay in chat view.
+ return false;
+ } finally {
+ if (sessionIdRef.current === sid && showPageRequestRef.current === request) {
+ setShowPageBusy(false);
+ }
+ }
+ },
- [readOnly, api, sendMessage, t],
++ [canManageShowPage, readOnly, api, sendMessage, t],
+ );
+
+ const openShowPage = useCallback(
+ (sid: string) => performShowPageAction(sid, 'inline'),
+ [performShowPageAction],
+ );
+
+ const prepareShowPageLaunch = useCallback(
+ (sid: string) => performShowPageAction(sid, 'prepare'),
+ [performShowPageAction],
+ );
+
const toggleShowPage = useCallback(async () => {
const sid = sessionId;
if (!sid) return;
@@@ -2003,12 -1821,6 +2024,12 @@@
// ``h-16`` header occupies 4rem at the top, so subtract that instead.
<ImageViewerProvider images={sessionImages}>
<FileViewerProvider>
+ <VaultProvisionDialogProvider
+ key={sessionId ?? 'no-session'}
+ requests={vaultRequests}
+ onResolved={refreshVaultRequests}
- disabled={readOnly}
++ disabled={!writable}
+ >
{/* Mobile: a FIXED full-screen flex column (the AppShell brand header is
hidden on chat) so the composer has NO scrollable ancestor — that is what
let iOS fling it off the top. useIosKeyboardInset then sizes this surface
@@@ -2047,10 -1858,11 +2068,12 @@@
onShareOpenChange={setShareOpen}
annotation={annotation}
onAnnotateOpenChange={setAnnotateOpen}
- readOnly={!canChat}
+ readOnlyReason={readOnlyReason}
++ writable={writable}
+ canManageShowPage={canManageShowPage}
/>
- {showPageMode && showPageUrl && (
+ {showPageActive && showPageUrl && (
// The session's Show Page (same-origin /show/<id>/ private or /p/<share>/
// public; URL resolved from ensureShowPage) fills the chat area while the
// header bar stays. The chat surface below is kept mounted but hidden.
@@@ -2102,12 -1912,10 +2124,12 @@@
onJumpHandled={() => setJumpTarget(null)}
highlightedId={highlightedId}
messageFontSize={messageFontSize}
- onQuickReply={canChat ? handleQuickReply : undefined}
+ onQuickReply={handleQuickReply}
+ provisionRequestsByMessage={provisionPlacement.byMessageId}
+ onVaultRequestResolved={refreshVaultRequests}
onQuoteSelection={quoteSelectionToComposer}
- onAskInNewSession={canChat ? askInNewSession : undefined}
- writable={canChat}
+ onAskInNewSession={askInNewSession}
- readOnly={readOnly}
++ readOnly={!writable}
followingTailRef={followingTailRef}
activity={{
enabled: showAgentActivity,
@@@ -2127,15 -1935,9 +2149,15 @@@
onToggleTools: toggleToolCalls,
}}
footer={
- sessionId && capabilities.can_manage_instance ? (
+ // Archive expires every pending vault request for the session in the
+ // same transaction that flips the status, so these cards are already
+ // empty for a freshly-loaded archived chat. A tab that loaded them
+ // BEFORE the archive still holds them in state, though — the same
+ // stale-tab case that reaches the archived 409 — and their
+ // approve/deny buttons would write to a session that can't accept it.
- sessionId && !readOnly ? (
++ sessionId && !readOnly && canManageShowPage ? (
<VaultChatRequests
- requests={vaultRequests}
+ requests={transcriptTailVaultRequests}
onResolved={refreshVaultRequests}
onOffscreenApprovalsChange={setOffscreenApprovals}
/>
@@@ -2147,34 -1949,30 +2169,34 @@@
sessionId={sessionId ?? ''}
enabled={bannerEnabled === true}
/>
- {canChat && (
+ {/* Archive reclaims all unsent input (queued rows, pending rows, draft),
+ so an archived chat loads with an empty queue. A stale tab can still be
+ holding pre-archive rows, and every button here writes: Send now POSTs
+ the flush, Recall appends into the disabled composer. */}
- {!readOnly && (
++ {writable && (
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
)}
- {sessionId && !readOnly && pendingApprovals.length > 0 ? (
- {sessionId && capabilities.can_manage_instance && pendingApprovals.length > 0 ? (
++ {sessionId && !readOnly && canManageShowPage && pendingApprovals.length > 0 ? (
<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
) : null}
{/* key by session so the composer remounts per session — its draft-seeding
+ local value reset, instead of carrying across sessions (Codex P2). */}
- <Compose
- {canChat && (
- <Compose
- key={sessionId}
- composerRef={composerRef}
- onSend={(text, attachments, references) => sendMessage(text, attachments, undefined, references)}
- onStop={stopMessage}
- busy={working}
- sessionId={sessionId ?? ''}
- initialDraft={initialDraft}
- onDraftChange={onDraftChange}
- onSearchAgents={searchAgents}
- onSearchSessions={searchSessions}
- />
- )}
++ {(writable || readOnlyReason !== null) && <Compose
+ key={sessionId}
+ composerRef={composerRef}
+ onSend={(text, attachments, references) => sendMessage(text, attachments, undefined, references)}
+ onStop={stopMessage}
+ busy={working}
+ sessionId={sessionId ?? ''}
+ initialDraft={initialDraft}
+ onDraftChange={onDraftChange}
+ onSearchAgents={searchAgents}
+ onSearchSessions={searchSessions}
+ readOnlyReason={readOnlyReason}
- />
++ />}
</div>
</div>
+ </VaultProvisionDialogProvider>
</FileViewerProvider>
</ImageViewerProvider>
);
@@@ -2608,23 -2337,13 +2630,26 @@@ interface ChatHeaderBarProps
onShareOpenChange?: (open: boolean) => void;
annotation: AnnotationBridge;
onAnnotateOpenChange?: (open: boolean) => void;
- readOnly: boolean;
- canManageShowPage: boolean;
+ // Read-only session: the title and the agent route render as static text — the
+ // server refuses both edits (409 archived / 403 reserved) — and the Show Page action
+ // cluster is withdrawn entirely (see showPageControlActions). The REASON, not a
+ // boolean, because it also picks the badge: a runtime-owned row is not "Archived".
+ readOnlyReason: SessionReadOnlyReason | null;
++ writable?: boolean;
++ canManageShowPage?: boolean;
}
-const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnly, canManageShowPage }) => {
+// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),
+// which renders the header alone rather than mounting the whole page. Note the
+// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the
+// read-only rendering is reachable without an ApiProvider.
- export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason }) => {
++export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, canManageShowPage = true }) => {
const { t } = useTranslation();
- const readOnly = readOnlyReason !== null;
- const showPageActions = showPageControlActions(readOnly, showPageMode);
++ const readOnly = !writable;
++ const sessionReadOnly = readOnlyReason !== null;
++ const showPageActions = showPageControlActions(sessionReadOnly, showPageMode);
const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;
+ const sessionAgentLabel = sessionAgentDisplayName(session, agents);
// Backend locks once a NATIVE conversation exists — a native can only be
// resumed by the backend that created it — or while a turn is RUNNING (the
// in-flight turn binds its native on the current route any moment); mirrors
@@@ -2678,24 -2397,7 +2703,26 @@@
<ArrowLeft className="size-3.5" />
</Button>
<TitleField key={session.id} title={session.title} onCommit={(title) => onPatch({ title })} readOnly={readOnly} />
- {/* Hidden while the Show Page is open so the view gets the full width. */}
+ {/* Hidden while the Show Page is open so the view gets the full width.
+ On a read-only session the route is frozen, so show it as static text
+ plus a badge naming WHY instead of an interactive picker. A runtime-owned
+ row has no backend at all (``agent_backend`` is empty by design), so the
+ agent name — which would fall back to the default agent's, naming a route
+ this session will never run — is omitted there rather than invented. */}
+ {!showPageMode && readOnly && (
+ <div className="flex min-w-0 shrink-0 items-center gap-1.5">
- {readOnlyReason === 'archived' && (
++ {readOnlyReason !== 'system' && (
+ <span className="truncate text-[12px] font-medium text-muted">
+ {sessionAgentLabel || (defaultAgent ? defaultAgent.name : t('newSession.defaultAgent'))}
+ </span>
+ )}
- <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px] font-bold">
- {readOnlyReason === 'system' ? t('common.systemSession') : t('common.archived')}
- </Badge>
++ {readOnlyReason && (
++ <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px] font-bold">
++ {readOnlyReason === 'system' ? t('common.systemSession') : t('common.archived')}
++ </Badge>
++ )}
+ </div>
+ )}
{!showPageMode && !readOnly && (
<AgentRoutePicker
value={session}
@@@ -2727,41 -2429,45 +2754,41 @@@
{/* In Show Page mode the order is: annotation control · back-to-chat ·
Share. The annotation control sits immediately left of back-to-chat;
the Share control stays rightmost. In chat mode only the Visualize
- toggle shows. */}
- {(showPageMode || canManageShowPage) && <div className="ml-auto flex items-center gap-1.5">
- {showPageMode && !readOnly && (
- <ShowPageAnnotateControl
- state={annotation.state}
- onEnable={annotation.enable}
- onDisable={annotation.disable}
- onSetMode={annotation.setMode}
- onPopoverOpenChange={onAnnotateOpenChange}
- />
- )}
- <Button
- type="button"
- variant={showPageMode ? 'secondary' : 'ghost'}
- onClick={onToggleShowPage}
- disabled={showPageBusy}
- aria-label={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
- title={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
- className="h-7 shrink-0 gap-1.5 px-2"
- >
- {showPageBusy ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : showPageMode ? (
- <MessageSquare className="size-3.5" />
- ) : (
- <Presentation className="size-3.5" />
+ toggle shows.
+
+ The whole cluster is withdrawn on an archived session — archive takes
+ its Show Page offline and refuses to create a missing one, so none of
+ the three can do anything but 409 or frame a dead page. There is no
+ read-only page-serving path to offer instead; see
+ showPageControlActions for the per-control reasoning. */}
- {showPageActions.visualize && (
++ {showPageActions.visualize && (showPageMode || canManageShowPage) && (
+ <div className="ml-auto flex items-center gap-1.5">
- {showPageActions.annotate && (
++ {showPageActions.annotate && writable && (
+ <ShowPageAnnotateControl
+ state={annotation.state}
+ onEnable={annotation.enable}
+ onDisable={annotation.disable}
+ onSetMode={annotation.setMode}
+ onPopoverOpenChange={onAnnotateOpenChange}
+ />
)}
- <span className="hidden text-xs font-medium md:inline">
- {showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
- </span>
- </Button>
- {showPageMode && canManageShowPage && (
- <ShowPageShareControl
+ <ShowPageLaunchControl
sessionId={session.id}
- onPayloadChange={onShowPageVisibilityChange}
- onOpenChange={onShareOpenChange}
+ title={session.title}
+ showPageMode={showPageMode}
+ busy={showPageBusy}
+ onToggle={onToggleShowPage}
+ onPrepareLaunch={onPrepareShowPageLaunch}
/>
- {showPageActions.share && (
- )}
- </div>}
++ {showPageActions.share && canManageShowPage && (
+ <ShowPageShareControl
+ sessionId={session.id}
+ onPayloadChange={onShowPageVisibilityChange}
+ onOpenChange={onShareOpenChange}
+ />
+ )}
+ </div>
+ )}
</div>
</div>
);
@@@ -2788,15 -2493,10 +2815,18 @@@ const TitleField: React.FC<TitleFieldPr
if (editing) inputRef.current?.focus();
}, [editing]);
+ if (readOnly) {
+ return (
+ <span className="min-w-0 flex-1 truncate text-[16px] font-bold text-foreground">
+ {title || t('chat.untitled')}
+ </span>
+ );
+ }
+
if (!editing) {
+ if (readOnly) {
+ return <span className="min-w-0 flex-1 truncate text-[16px] font-bold text-foreground">{title || t('chat.untitled')}</span>;
+ }
return (
<button
type="button"
@@@ -3300,15 -2952,13 +3330,17 @@@ const Transcript: React.FC<TranscriptPr
}
return (
<div className="relative flex min-h-0 flex-1 flex-col">
- <SelectionQuoteToolbar
- {writable && <SelectionQuoteToolbar
-- containerRef={scrollRef}
- // Both write actions are omitted rather than offered just to fail —
- // see transcriptSelectionActions. On an archived session that leaves only
- // the touch Copy fallback, and on desktop the toolbar renders nothing.
- onQuote={selectionActions.quote ? onQuoteSelection : undefined}
- // Forking needs a bound native session (mirrors the sidebar's fork gate).
- onAskInNew={selectionActions.askInNew ? onAskInNewSession : undefined}
- />
- onQuote={onQuoteSelection}
- // Forking needs a bound native session (mirrors the sidebar's fork gate);
- // omit the action otherwise so it isn't offered just to 409.
- onAskInNew={session.native_session_id ? onAskInNewSession : undefined}
- />}
++ {!readOnly && (
++ <SelectionQuoteToolbar
++ containerRef={scrollRef}
++ // Both write actions are omitted rather than offered just to fail —
++ // see transcriptSelectionActions. On an archived session that leaves only
++ // the touch Copy fallback, and on desktop the toolbar renders nothing.
++ onQuote={selectionActions.quote ? onQuoteSelection : undefined}
++ // Forking needs a bound native session (mirrors the sidebar's fork gate).
++ onAskInNew={selectionActions.askInNew ? onAskInNewSession : undefined}
++ />
++ )}
<div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
{forkSourceBanner}
diff --cc ui/src/components/workbench/ProjectsPage.tsx
index f8f8d8f4d,c2b17b999..87e1a26ee
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@@ -25,12 -24,11 +25,14 @@@ import clsx from 'clsx'
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+ import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+ import { SessionPinAction } from './SessionPinAction';
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
+import { useApi } from '../../context/ApiContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
+import { useToast } from '../../context/ToastContext';
import { formatRelativeTime } from '../../lib/relativeTime';
+import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
@@@ -250,11 -256,10 +260,12 @@@ const MobileSessionRow: React.FC<
projectId: string;
session: WorkbenchSession;
unread: number;
+ canChat: boolean;
onOpen: () => void;
- }> = ({ projectId, session, unread, onOpen }) => {
+ }> = ({ projectId, session, unread, canChat, onOpen }) => {
const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
const { renameSession, setSessionPinned, archiveSession, forkSession } = useWorkbenchProjectsTree();
const navigate = useNavigate();
const [menuOpen, setMenuOpen] = useState(false);
diff --cc ui/src/components/workbench/SkillsPage.tsx
index 0891ad1cd,f3dfc7aec..e9a2d4019
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@@ -17,7 -17,7 +17,8 @@@ import { SkillDetailPanel } from './ski
import { ProjectPicker } from './skills/ProjectPicker';
import { AddSkillDialog } from './skills/AddSkillDialog';
import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';
+import { errorMessage } from '@/lib/errorMessage';
+ import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
const skillKey = (s: SkillBrief) => `${s.scope}:${s.name}`;
diff --cc ui/src/context/ApiContext.tsx
index 683d0232f,ddbdf8af7..9a4c9033a
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@@ -5,14 -6,16 +6,17 @@@ import { isAuthorizationSensitiveReadPa
import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';
import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';
++import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
import {
WorkbenchEventReconnectLoop,
type WorkbenchEventConnectionState,
} from '../lib/workbenchEventConnection';
-import type { DockDoc } from './DockContext';
-import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';
+import type { DockDoc } from './dockDoc';
+import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';
+ export type { InstanceCapabilities, SessionInfo };
+
// The workbench Dock API response shape ({ ok, dock }); the Dock document type
// itself lives with the DockProvider that owns reconciliation.
export type DockResponse = { ok: boolean; dock: DockDoc };
@@@ -658,12 -627,9 +670,14 @@@ export type ApiContextType =
setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;
listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; onlySession?: string; cache?: boolean; handleError?: boolean }) => Promise<InboxFeedResult>;
connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
- listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;
+ listVibeAgents: (params?: {
+ backend?: string;
+ includeDisabled?: boolean;
+ includeArchived?: boolean;
+ cache?: boolean;
+ }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;
+ getVibeAgentOnboarding: () => Promise<VibeAgentOnboardingResult>;
+ onboardVibeAgents: () => Promise<VibeAgentOnboardingResult>;
getVibeAgent: (name: string) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;
createVibeAgent: (payload: VibeAgentCreatePayload) => Promise<{ ok: boolean; agent: VibeAgentFull }>;
updateVibeAgent: (name: string, payload: VibeAgentUpdatePayload) => Promise<{ ok: boolean; agent: VibeAgentFull }>;
@@@ -2905,11 -2900,11 +3112,13 @@@ export const ApiProvider: React.FC<{ ch
const search = new URLSearchParams();
if (params?.backend) search.set('backend', params.backend);
if (params?.includeDisabled) search.set('include_disabled', '1');
+ if (params?.includeArchived) search.set('include_archived', '1');
const qs = search.toString();
- return getCachedJson(qs ? `/api/agents?${qs}` : '/api/agents', 5_000);
+ const path = qs ? `/api/agents?${qs}` : '/api/agents';
+ return params?.cache === false ? getJson(path) : getCachedJson(path, 5_000);
},
+ getVibeAgentOnboarding: () => getJson('/api/agent-onboarding'),
+ onboardVibeAgents: () => postJson('/api/agent-onboarding', {}),
getVibeAgent: (name) => getCachedJson(`/api/agents/${encodeURIComponent(name)}`, 5_000),
createVibeAgent: (payload) => postJson('/api/agents', payload),
updateVibeAgent: async (name, payload) => {
diff --cc ui/src/context/DockProvider.tsx
index db90813be,b4c7660dd..bf9fdccc5
--- a/ui/src/context/DockProvider.tsx
+++ b/ui/src/context/DockProvider.tsx
@@@ -19,8 -135,11 +19,32 @@@ import { useLatestRef } from '@/lib/use
// immediately (no flicker) before the server document loads. Matches the
// server's fresh-instance seed; reconcileDock takes over once the GET resolves.
const DEFAULT_DOC: DockDoc = seedDefaultDock();
++const DISABLED_DOCK_VALUE: DockValue = {
++ order: DEFAULT_DOC.order,
++ pins: [],
++ isPinned: () => false,
++ isDocked: (dockId) => DEFAULT_DOC.order.includes(dockId),
++ pinFor: () => null,
++ pin: () => Promise.resolve(),
++ unpin: () => Promise.resolve(),
++ dock: () => Promise.resolve(),
++ undock: () => Promise.resolve(),
++ setOrder: () => Promise.resolve(),
++};
- export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ export const DockProvider: React.FC<{ children: React.ReactNode; enabled?: boolean }> = ({
+ children,
+ enabled = true,
+ }) => {
++ if (!enabled) {
++ return (
++ <DockContext.Provider value={DISABLED_DOCK_VALUE}>{children}</DockContext.Provider>
++ );
++ }
++ return <EnabledDockProvider>{children}</EnabledDockProvider>;
++};
++
++const EnabledDockProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const api = useApi();
const [doc, setDoc] = useState<DockDoc>(DEFAULT_DOC);
// Latest committed doc for the async actions' rollback (avoids stale closures).
diff --cc ui/src/context/InstanceAuthorizationContext.ts
index 000000000,000000000..28a077055
new file mode 100644
--- /dev/null
+++ b/ui/src/context/InstanceAuthorizationContext.ts
@@@ -1,0 -1,0 +1,18 @@@
++import { createContext, useContext } from 'react';
++
++import type { InstanceCapabilities } from './ApiContext';
++import { DENIED_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';
++
++export interface InstanceAuthorizationValue {
++ remote: boolean;
++ instanceRole: 'owner' | 'editor' | 'viewer' | null;
++ capabilities: InstanceCapabilities;
++}
++
++export const InstanceAuthorizationContext = createContext<InstanceAuthorizationValue>({
++ remote: false,
++ instanceRole: null,
++ capabilities: DENIED_INSTANCE_CAPABILITIES,
++});
++
++export const useInstanceAuthorization = () => useContext(InstanceAuthorizationContext);
diff --cc ui/src/context/InstanceAuthorizationProvider.tsx
index 000000000,33671adaa..2eeeb6937
mode 000000,100644..100644
--- a/ui/src/context/InstanceAuthorizationProvider.tsx
+++ b/ui/src/context/InstanceAuthorizationProvider.tsx
@@@ -1,0 -1,54 +1,43 @@@
-/* eslint-disable react-refresh/only-export-components */
-import { createContext, useContext, useMemo, type ReactNode } from 'react';
++import { useMemo, type ReactNode } from 'react';
+
-import type { InstanceCapabilities, SessionInfo } from './ApiContext';
++import type { SessionInfo } from './ApiContext';
++import {
++ InstanceAuthorizationContext,
++ type InstanceAuthorizationValue,
++} from './InstanceAuthorizationContext';
+ import {
+ DENIED_INSTANCE_CAPABILITIES,
+ OWNER_INSTANCE_CAPABILITIES,
+ } from '../lib/sessionInfo';
+
-interface InstanceAuthorizationValue {
- remote: boolean;
- instanceRole: 'owner' | 'editor' | 'viewer' | null;
- capabilities: InstanceCapabilities;
-}
-
-const InstanceAuthorizationContext = createContext<InstanceAuthorizationValue>({
- remote: false,
- instanceRole: null,
- capabilities: DENIED_INSTANCE_CAPABILITIES,
-});
-
+ export const InstanceAuthorizationProvider = ({
+ session,
+ children,
+ }: {
+ session: SessionInfo;
+ children: ReactNode;
+ }) => {
+ const value = useMemo<InstanceAuthorizationValue>(() => {
+ if (!session.remote) {
+ return {
+ remote: false,
+ instanceRole: session.instance_role ?? 'owner',
+ capabilities: session.capabilities ?? OWNER_INSTANCE_CAPABILITIES,
+ };
+ }
+ if (!session.authenticated) {
+ return { remote: true, instanceRole: null, capabilities: DENIED_INSTANCE_CAPABILITIES };
+ }
+ return {
+ remote: true,
+ instanceRole: session.instance_role,
+ capabilities: session.capabilities,
+ };
+ }, [session]);
+
+ return (
+ <InstanceAuthorizationContext.Provider value={value}>
+ {children}
+ </InstanceAuthorizationContext.Provider>
+ );
+ };
-
-export const useInstanceAuthorization = () => useContext(InstanceAuthorizationContext);
diff --cc ui/src/context/WorkbenchProjectsProvider.tsx
index 001eafa2d,cc5f638e9..43065dd3f
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@@ -153,15 -216,15 +169,15 @@@ export const WorkbenchProjectsProvider
const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
try {
const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
- setProjects(result.projects);
+ applyProjectsSnapshot(result.projects);
applyBootstrapSessions(result.sessions ?? {});
setProjectsError(null);
- } catch (err: any) {
+ } catch (err) {
// Don't strand consumers on an empty-state for a transient failure — keep
// any list we had and surface the error (mobile shows a retry).
- setProjectsError(err?.message ?? String(err));
+ setProjectsError(errorMessage(err) ?? String(err));
}
- }, [api, applyBootstrapSessions]);
+ }, [api, applyBootstrapSessions, applyProjectsSnapshot]);
useEffect(() => {
void fetchProjects();
diff --cc ui/src/features/organization/OrganizationProvider.tsx
index 000000000,3f743ff16..32795534d
mode 000000,100644..100644
--- a/ui/src/features/organization/OrganizationProvider.tsx
+++ b/ui/src/features/organization/OrganizationProvider.tsx
@@@ -1,0 -1,293 +1,260 @@@
-/* eslint-disable react-refresh/only-export-components */
+ import React, {
- createContext,
+ useCallback,
- useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ } from 'react';
+
+ import { OrganizationApiError, organizationRequest } from './api/client';
+ import type {
+ CloudManagementSession,
+ Organization,
+ OrganizationDetail,
+ } from './api/types';
++import {
++ OrganizationContext,
++ type GateState,
++ type OrganizationContextValue,
++} from './context';
+ import { organizationAuthorizationReturnPath } from './policy';
-
-type GateState =
- | 'loading'
- | 'cloud_not_connected'
- | 'authorization_required'
- | 'reauthorizing'
- | 'subject_mismatch'
- | 'unreachable'
- | 'revoked'
- | 'connected'
- | 'error';
-
-type OrganizationContextValue = {
- gate: GateState;
- session: Extract<CloudManagementSession, { connected: true }> | null;
- organizations: Organization[];
- selectedOrganizationId: string | null;
- detail: OrganizationDetail | null;
- dataVersion: number;
- signIn: () => Promise<void>;
- signOut: () => Promise<void>;
- retry: () => Promise<void>;
- selectOrganization: (organizationId: string) => Promise<void>;
- refreshOrganization: () => Promise<void>;
- invalidate: () => void;
- request: <T>(path: string, init?: RequestInit) => Promise<T>;
-};
-
-const OrganizationContext = createContext<OrganizationContextValue | null>(null);
+ const SELECTED_ORG_KEY = 'avibe.organization.selected';
+
+ function callbackError(): string | null {
+ const params = new URLSearchParams(window.location.search);
+ const error = params.get('cloud_management_error');
+ if (error) {
+ const next = organizationAuthorizationReturnPath(
+ window.location.pathname,
+ window.location.search,
+ );
+ window.history.replaceState(null, '', `${next}${window.location.hash}`);
+ }
+ return error;
+ }
+
+ function gateForOrganizationError(
+ error: unknown,
+ unauthorizedGate: Extract<GateState, 'authorization_required' | 'revoked'>,
+ ): GateState {
+ if (!(error instanceof OrganizationApiError)) return 'unreachable';
+ if (error.code === 'cloud_management_subject_mismatch') return 'subject_mismatch';
+ if (error.status === 401) return unauthorizedGate;
+ if (error.status === 409) return 'cloud_not_connected';
+ if (error.retryable || error.status >= 500) return 'unreachable';
+ return 'error';
+ }
+
+ export function OrganizationProvider({ children }: { children: React.ReactNode }) {
+ const [gate, setGate] = useState<GateState>('loading');
+ const [session, setSession] = useState<Extract<CloudManagementSession, { connected: true }> | null>(null);
+ const [organizations, setOrganizations] = useState<Organization[]>([]);
+ const [selectedOrganizationId, setSelectedOrganizationId] = useState<string | null>(null);
+ const [detail, setDetail] = useState<OrganizationDetail | null>(null);
+ const [dataVersion, setDataVersion] = useState(0);
+ const silentAttempted = useRef(false);
+ const operationGeneration = useRef(0);
+
+ const startAuthorization = useCallback(async (mode: 'interactive' | 'silent') => {
+ operationGeneration.current += 1;
+ setGate('reauthorizing');
+ try {
+ const result = await organizationRequest<{ authorize_url: string }>(
+ '/api/cloud-management/session/start',
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ mode,
+ next: organizationAuthorizationReturnPath(
+ window.location.pathname,
+ window.location.search,
+ ),
+ }),
+ },
+ );
+ window.location.assign(result.authorize_url);
+ } catch (error) {
+ setGate(gateForOrganizationError(error, 'authorization_required'));
+ }
+ }, []);
+
+ const loadOrganizationAtGeneration = useCallback(async (
+ organizationId: string,
+ generation: number,
+ ): Promise<boolean> => {
+ let result: OrganizationDetail;
+ try {
+ result = await organizationRequest<OrganizationDetail>(
+ `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}`,
+ );
+ } catch (error) {
+ if (generation !== operationGeneration.current) return false;
+ throw error;
+ }
+ if (generation !== operationGeneration.current) return false;
+ setSelectedOrganizationId(organizationId);
+ setDetail(result);
+ sessionStorage.setItem(SELECTED_ORG_KEY, organizationId);
+ return true;
+ }, []);
+
+ const selectOrganization = useCallback(async (organizationId: string) => {
+ const generation = ++operationGeneration.current;
+ try {
+ await loadOrganizationAtGeneration(organizationId, generation);
+ } catch (error) {
+ if (generation !== operationGeneration.current) return;
+ setGate(gateForOrganizationError(error, 'revoked'));
+ }
+ }, [loadOrganizationAtGeneration]);
+
+ const loadOrganizations = useCallback(async (generation: number) => {
+ const result = await organizationRequest<{ organizations: Organization[] }>(
+ '/api/cloud-management/organizations',
+ );
+ if (generation !== operationGeneration.current) return;
+ setOrganizations(result.organizations);
+ if (result.organizations.length === 0) {
+ setSelectedOrganizationId(null);
+ setDetail(null);
+ setGate('connected');
+ return;
+ }
+ const remembered = sessionStorage.getItem(SELECTED_ORG_KEY);
+ const selected = result.organizations.some((item) => item.id === remembered)
+ ? remembered!
+ : result.organizations[0].id;
+ if (await loadOrganizationAtGeneration(selected, generation)) {
+ setGate('connected');
+ }
+ }, [loadOrganizationAtGeneration]);
+
+ const probe = useCallback(async () => {
+ const generation = ++operationGeneration.current;
+ const returnedError = callbackError();
+ if (returnedError === 'cloud_management_subject_mismatch') {
+ setGate('subject_mismatch');
+ return;
+ }
+ setGate('loading');
+ try {
+ const result = await organizationRequest<CloudManagementSession>(
+ '/api/cloud-management/session',
+ );
+ if (generation !== operationGeneration.current) return;
+ if (!result.connected) {
+ setSession(null);
+ setOrganizations([]);
+ setDetail(null);
+ if (result.state === 'cloud_not_connected') {
+ setGate('cloud_not_connected');
+ } else if (result.state === 'subject_mismatch') {
+ setGate('subject_mismatch');
+ } else if (
+ result.can_silent_reauthorize
+ && !silentAttempted.current
+ && returnedError === null
+ ) {
+ silentAttempted.current = true;
+ await startAuthorization('silent');
+ } else {
+ setGate('authorization_required');
+ }
+ return;
+ }
+ setSession(result);
+ silentAttempted.current = false;
+ await loadOrganizations(generation);
+ } catch (error) {
+ if (generation !== operationGeneration.current) return;
+ setGate(gateForOrganizationError(
+ error,
+ returnedError ? 'authorization_required' : 'revoked',
+ ));
+ }
+ }, [loadOrganizations, startAuthorization]);
+
+ useEffect(() => {
+ void probe();
+ }, [probe]);
+
+ const request = useCallback(async <T,>(path: string, init: RequestInit = {}): Promise<T> => {
+ try {
+ return await organizationRequest<T>(path, init);
+ } catch (error) {
+ if (error instanceof OrganizationApiError) {
+ if (error.code === 'cloud_management_subject_mismatch') {
+ operationGeneration.current += 1;
+ setGate('subject_mismatch');
+ } else if (error.status === 401) {
+ if (error.canSilentReauthorize && !silentAttempted.current) {
+ silentAttempted.current = true;
+ await startAuthorization('silent');
+ } else {
+ operationGeneration.current += 1;
+ setGate('revoked');
+ }
+ } else if (error.status >= 500 && error.retryable) {
+ setGate('unreachable');
+ }
+ }
+ throw error;
+ }
+ }, [startAuthorization]);
+
+ const signOut = useCallback(async () => {
+ operationGeneration.current += 1;
+ try {
+ await organizationRequest('/api/cloud-management/session', { method: 'DELETE' });
+ } finally {
+ operationGeneration.current += 1;
+ setSession(null);
+ setOrganizations([]);
+ setDetail(null);
+ setGate('authorization_required');
+ silentAttempted.current = true;
+ }
+ }, []);
+
+ const refreshOrganization = useCallback(async () => {
+ if (!selectedOrganizationId) return;
+ const generation = ++operationGeneration.current;
+ try {
+ await loadOrganizationAtGeneration(selectedOrganizationId, generation);
+ } catch (error) {
+ if (generation !== operationGeneration.current) return;
+ setGate(gateForOrganizationError(error, 'revoked'));
+ }
+ }, [loadOrganizationAtGeneration, selectedOrganizationId]);
+
+ const value = useMemo<OrganizationContextValue>(() => ({
+ gate,
+ session,
+ organizations,
+ selectedOrganizationId,
+ detail,
+ dataVersion,
+ signIn: () => startAuthorization('interactive'),
+ signOut,
+ retry: probe,
+ selectOrganization,
+ refreshOrganization,
+ invalidate: () => setDataVersion((version) => version + 1),
+ request,
+ }), [
+ dataVersion,
+ detail,
+ gate,
+ organizations,
+ probe,
+ refreshOrganization,
+ request,
+ selectedOrganizationId,
+ session,
+ selectOrganization,
+ signOut,
+ startAuthorization,
+ ]);
+
+ return <OrganizationContext.Provider value={value}>{children}</OrganizationContext.Provider>;
+ }
-
-export function useOrganization(): OrganizationContextValue {
- const value = useContext(OrganizationContext);
- if (!value) throw new Error('useOrganization must be used within OrganizationProvider');
- return value;
-}
diff --cc ui/src/features/organization/OrganizationShell.tsx
index 000000000,56ce0b775..893d9a6e1
mode 000000,100644..100644
--- a/ui/src/features/organization/OrganizationShell.tsx
+++ b/ui/src/features/organization/OrganizationShell.tsx
@@@ -1,0 -1,268 +1,269 @@@
+ import { useState } from 'react';
+ import {
+ ArrowLeft,
+ Boxes,
+ Building2,
+ Cloud,
+ CloudOff,
+ Grid2x2,
+ LoaderCircle,
+ LogOut,
+ Menu,
+ Server,
+ ShieldAlert,
+ Users,
+ WifiOff,
+ X,
+ } from 'lucide-react';
+ import { useTranslation } from 'react-i18next';
+ import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';
+ import clsx from 'clsx';
+
+ import { Button } from '@/components/ui/button';
+ import { Select } from '@/components/ui/select';
+
-import { OrganizationProvider, useOrganization } from './context';
++import { useOrganization } from './context';
++import { OrganizationProvider } from './OrganizationProvider';
+ import { EmptyState, InitialsAvatar } from './components';
+ import { organizationSwitchDestination } from './policy';
+
+ const NAV = [
+ { path: '/admin/organization/overview', key: 'overview', icon: Grid2x2 },
+ { path: '/admin/organization/instances', key: 'instances', icon: Server },
+ { path: '/admin/organization/members', key: 'members', icon: Users },
+ { path: '/admin/organization/groups', key: 'groups', icon: Boxes },
+ { path: '/admin/organization/resources', key: 'resources', icon: Building2 },
+ ] as const;
+
+ function GateState() {
+ const { t } = useTranslation();
+ const { gate, signIn, retry } = useOrganization();
+ if (gate === 'loading' || gate === 'reauthorizing') {
+ return (
+ <div className="grid min-h-[100dvh] place-items-center bg-background p-6 text-center">
+ <div>
+ <LoaderCircle className="mx-auto size-8 animate-spin text-mint" />
+ <h1 className="mt-4 text-lg font-semibold">
+ {t(gate === 'reauthorizing' ? 'organization.states.reauthorizingTitle' : 'organization.states.loadingTitle')}
+ </h1>
+ <p className="mt-1 text-[13px] text-muted">
+ {t(gate === 'reauthorizing' ? 'organization.states.reauthorizingBody' : 'organization.states.loadingBody')}
+ </p>
+ </div>
+ </div>
+ );
+ }
+ const config = {
+ cloud_not_connected: {
+ icon: CloudOff,
+ title: t('organization.states.notConnectedTitle'),
+ body: t('organization.states.notConnectedBody'),
+ action: <Button asChild variant="brand"><Link to="/admin/remote-access">{t('organization.actions.openRemoteAccess')}</Link></Button>,
+ },
+ authorization_required: {
+ icon: Cloud,
+ title: t('organization.states.signInTitle'),
+ body: t('organization.states.signInBody'),
+ action: <Button variant="brand" onClick={() => void signIn()}>{t('organization.actions.signIn')}</Button>,
+ },
+ subject_mismatch: {
+ icon: ShieldAlert,
+ title: t('organization.states.mismatchTitle'),
+ body: t('organization.states.mismatchBody'),
+ action: <Button variant="brand" onClick={() => void signIn()}>{t('organization.actions.signInAgain')}</Button>,
+ },
+ unreachable: {
+ icon: WifiOff,
+ title: t('organization.states.unreachableTitle'),
+ body: t('organization.states.unreachableBody'),
+ action: <Button variant="outline" onClick={() => void retry()}>{t('common.retry')}</Button>,
+ },
+ revoked: {
+ icon: ShieldAlert,
+ title: t('organization.states.revokedTitle'),
+ body: t('organization.states.revokedBody'),
+ action: <Button variant="brand" onClick={() => void signIn()}>{t('organization.actions.signIn')}</Button>,
+ },
+ error: {
+ icon: ShieldAlert,
+ title: t('organization.states.errorTitle'),
+ body: t('organization.errors.generic'),
+ action: <Button variant="outline" onClick={() => void retry()}>{t('common.retry')}</Button>,
+ },
+ } as const;
+ const state = config[gate as keyof typeof config] ?? config.error;
+ const Icon = state.icon;
+ return (
+ <div className="min-h-[100dvh] bg-background p-4 md:p-8">
+ <Link to="/admin/dashboard" className="inline-flex items-center gap-2 text-[13px] text-muted hover:text-foreground">
+ <ArrowLeft className="size-4" />
+ {t('organization.actions.backToControlPanel')}
+ </Link>
+ <div className="mx-auto mt-20 max-w-xl">
+ <EmptyState
+ title={state.title}
+ body={state.body}
+ action={state.action}
+ />
+ <Icon className="sr-only" />
+ </div>
+ </div>
+ );
+ }
+
+ function OrganizationSidebar({ mobile = false, onNavigate }: { mobile?: boolean; onNavigate?: () => void }) {
+ const { t } = useTranslation();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const {
+ organizations,
+ selectedOrganizationId,
+ selectOrganization,
+ detail,
+ session,
+ signOut,
+ } = useOrganization();
+ const switchOrganization = async (organizationId: string) => {
+ const destination = organizationSwitchDestination(location.pathname);
+ if (destination) navigate(destination, { replace: true });
+ await selectOrganization(organizationId);
+ onNavigate?.();
+ };
+ return (
+ <div className="flex h-full flex-col bg-surface px-4 py-5">
+ <Link to="/admin/dashboard" className="flex items-center gap-2 text-[13px] text-muted hover:text-foreground" onClick={onNavigate}>
+ <ArrowLeft className="size-4" />
+ {t('organization.actions.backToControlPanel')}
+ </Link>
+ <div className="mt-6 rounded-lg border border-border bg-card p-3">
+ <div className="flex items-center gap-3">
+ <InitialsAvatar value={detail?.organization.name ?? ''} tone="violet" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-semibold">{detail?.organization.name}</div>
+ <div className="mt-0.5 text-[11px] text-muted">
+ {t(`organization.roles.${detail?.membership.role ?? 'member'}`)}
+ {organizations.length > 1 ? ` · ${t('organization.sidebar.organizationCount', { count: organizations.length })}` : ''}
+ </div>
+ </div>
+ </div>
+ {organizations.length > 1 ? (
+ <Select
+ className="mt-3"
+ value={selectedOrganizationId ?? ''}
+ aria-label={t('organization.sidebar.switchOrganization')}
+ onChange={(event) => void switchOrganization(event.target.value)}
+ >
+ {organizations.map((organization) => (
+ <option key={organization.id} value={organization.id}>{organization.name}</option>
+ ))}
+ </Select>
+ ) : null}
+ </div>
+ <div className="mt-5 px-1 font-mono text-[10px] font-bold uppercase text-muted">
+ {t('organization.sidebar.section')}
+ </div>
+ <nav className="mt-3 flex flex-col gap-1">
+ {NAV.map((item) => {
+ const Icon = item.icon;
+ return (
+ <NavLink
+ key={item.path}
+ to={item.path}
+ onClick={onNavigate}
+ className={({ isActive }) => clsx(
+ 'flex items-center gap-3 rounded-lg border px-3 py-2.5 text-[13px] font-medium transition-colors',
+ isActive
+ ? 'border-mint/30 bg-mint/10 text-foreground'
+ : 'border-transparent text-muted hover:bg-foreground/[0.04] hover:text-foreground',
+ )}
+ >
+ <Icon className="size-4" />
+ {t(`organization.nav.${item.key}`)}
+ </NavLink>
+ );
+ })}
+ </nav>
+ <div className="mt-auto pt-6">
+ <div className="rounded-lg border border-mint/30 bg-mint/10 p-3">
+ <div className="flex items-center gap-2 text-[12px] font-semibold">
+ <span className="size-2 rounded-full bg-mint shadow-[0_0_8px_rgba(91,255,160,0.8)]" />
+ {t('organization.sidebar.cloudConnected')}
+ </div>
+ <div className="mt-1 font-mono text-[10px] text-muted">
+ {t('organization.sidebar.sessionRemaining', { minutes: Math.max(1, Math.ceil((session?.expires_in ?? 0) / 60)) })}
+ </div>
+ </div>
+ <div className="mt-3 flex items-center gap-2">
+ <InitialsAvatar value={session?.user.email ?? ''} className="size-8 rounded-full" />
+ <div className="min-w-0 flex-1 truncate text-[11px] text-muted">{session?.user.email}</div>
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t('organization.actions.signOut')}
+ onClick={() => void signOut()}
+ >
+ <LogOut className="size-4" />
+ </Button>
+ </div>
+ </div>
+ {mobile ? <div className="h-[env(safe-area-inset-bottom)]" /> : null}
+ </div>
+ );
+ }
+
+ function ConnectedShell() {
+ const { t } = useTranslation();
+ const location = useLocation();
+ const { organizations, detail } = useOrganization();
+ const [drawerOpen, setDrawerOpen] = useState(false);
+ if (organizations.length === 0 || !detail) {
+ return (
+ <div className="min-h-[100dvh] bg-background p-6">
+ <EmptyState title={t('organization.states.emptyTitle')} body={t('organization.states.emptyBody')} />
+ </div>
+ );
+ }
+ return (
+ <div className="h-[100dvh] overflow-y-auto bg-background text-foreground md:grid md:grid-cols-[260px_minmax(0,1fr)] md:overflow-hidden">
+ <aside className="sticky top-0 hidden h-[100dvh] border-r border-border md:block">
+ <OrganizationSidebar />
+ </aside>
+ <div className="min-w-0 md:h-[100dvh] md:overflow-y-auto">
+ <header className="sticky top-0 z-30 flex h-14 items-center justify-between border-b border-border bg-background/95 px-4 backdrop-blur md:hidden">
+ <Button variant="ghost" size="icon" aria-label={t('organization.sidebar.openMenu')} onClick={() => setDrawerOpen(true)}>
+ <Menu className="size-5" />
+ </Button>
+ <div className="truncate text-[13px] font-semibold">{detail.organization.name}</div>
+ <div className="size-9" />
+ </header>
+ <main key={location.pathname} className="mx-auto w-full max-w-[1560px] px-4 py-5 md:px-8 md:py-7">
+ <Outlet />
+ </main>
+ </div>
+ {drawerOpen ? (
+ <div className="fixed inset-0 z-50 md:hidden" role="dialog" aria-modal="true">
+ <button className="absolute inset-0 bg-background/70 backdrop-blur-sm" aria-label={t('common.close')} onClick={() => setDrawerOpen(false)} />
+ <aside className="absolute inset-y-0 left-0 w-[min(86vw,300px)] border-r border-border shadow-2xl">
+ <Button variant="ghost" size="icon" className="absolute right-3 top-3 z-10" aria-label={t('common.close')} onClick={() => setDrawerOpen(false)}>
+ <X className="size-4" />
+ </Button>
+ <OrganizationSidebar mobile onNavigate={() => setDrawerOpen(false)} />
+ </aside>
+ </div>
+ ) : null}
+ </div>
+ );
+ }
+
+ function OrganizationShellInner() {
+ const { gate } = useOrganization();
+ return gate === 'connected' ? <ConnectedShell /> : <GateState />;
+ }
+
+ export function OrganizationShell() {
+ return (
+ <OrganizationProvider>
+ <OrganizationShellInner />
+ </OrganizationProvider>
+ );
+ }
diff --cc ui/src/features/organization/context.ts
index 000000000,000000000..0294a0e66
new file mode 100644
--- /dev/null
+++ b/ui/src/features/organization/context.ts
@@@ -1,0 -1,0 +1,42 @@@
++import { createContext, useContext } from 'react';
++
++import type {
++ CloudManagementSession,
++ Organization,
++ OrganizationDetail,
++} from './api/types';
++
++export type GateState =
++ | 'loading'
++ | 'cloud_not_connected'
++ | 'authorization_required'
++ | 'reauthorizing'
++ | 'subject_mismatch'
++ | 'unreachable'
++ | 'revoked'
++ | 'connected'
++ | 'error';
++
++export type OrganizationContextValue = {
++ gate: GateState;
++ session: Extract<CloudManagementSession, { connected: true }> | null;
++ organizations: Organization[];
++ selectedOrganizationId: string | null;
++ detail: OrganizationDetail | null;
++ dataVersion: number;
++ signIn: () => Promise<void>;
++ signOut: () => Promise<void>;
++ retry: () => Promise<void>;
++ selectOrganization: (organizationId: string) => Promise<void>;
++ refreshOrganization: () => Promise<void>;
++ invalidate: () => void;
++ request: <T>(path: string, init?: RequestInit) => Promise<T>;
++};
++
++export const OrganizationContext = createContext<OrganizationContextValue | null>(null);
++
++export function useOrganization(): OrganizationContextValue {
++ const value = useContext(OrganizationContext);
++ if (!value) throw new Error('useOrganization must be used within OrganizationProvider');
++ return value;
++}
diff --cc ui/src/i18n/en.json
index 541f58f0d,bb9c2c889..a4e1cf40b
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@@ -107,12 -106,7 +106,15 @@@
"proxyUrl": "Proxy URL (optional)",
"proxyUrlHint": "SOCKS5, SOCKS4, HTTP or HTTPS proxy. Leave empty to fall back to system SOCKS proxy detection or direct connection.",
"proxyUrlCollapsedHint": "(blank → system proxy if set, else direct)",
- "locked": "Locked"
++ "locked": "Locked",
++ "archived": "Archived",
++ "systemSession": "System",
+ "duration": {
+ "seconds": "s",
+ "minutes": "m",
+ "hours": "h",
+ "days": "d"
+ }
},
"nav": {
"dashboard": "Dashboard",
@@@ -1125,56 -977,9 +1134,16 @@@
"qualityUnknown": "Measuring",
"qualityRecovering": "Optimizing",
"qualityDegraded": "Degraded",
+ "optimizeRoute": "Optimize route",
+ "optimizingRoute": "Optimizing...",
- "optimizeStarted": "A second Connector is evaluating a better route"
++ "optimizeStarted": "A second Connector is evaluating a better route",
+ "protocolAutomatic": "{{protocol}} (Auto)",
+ "protocolUnknown": "Detecting",
+ "connectorPath": "Connector · {{protocol}} · {{connections}}/4 · RTT {{rtt}}",
+ "rttUnavailable": "Unavailable",
+ "requestPath": "Requests · P95 {{p95}} · P99 {{p99}} · {{slow}}% > 1 s",
+ "requestPathUnavailable": "Requests unavailable · {{success}}/{{count}} succeeded",
- "requestPathMeasuring": "Measuring requests · {{count}} samples",
- "optimizeRoute": "Optimize route",
- "optimizingRoute": "Optimizing...",
- "optimizeStarted": "A second Connector is evaluating a better route"
- },
- "models": {
- "eligibility": {
- "subscription_wrong_client": "{{vendor}} subscriptions only work in {{backend}}",
- "opencode_api_key_only": "OpenCode can only be supplied by API-key sources",
- "consent_required": "Needs your consent for experimental hub supply first"
- },
- "oauth": {
- "upstream_failed": "The vendor didn't complete this sign-in, please retry",
- "engine_unavailable": "The Hub isn't responding, please retry",
- "submission_failed": "Couldn't submit what you pasted, please retry",
- "ambiguous_engine_binding": "Couldn't tell which account signed in — do one at a time, then retry",
- "binding_failed": "That account is already used by another source",
- "expired": "Authorization timed out, please reconnect"
- },
- "probe": {
- "native_cli_unavailable": "Can't use the CLI's sign-in",
- "no_candidate": {
- "waiting": "Every source is cooling down",
- "interrupted": "No source can serve this model right now"
- }
- },
- "source": {
- "cooldown": {
- "network": "Network unreachable",
- "timeout": "Repeated timeouts",
- "rate_limited": "Rate limited",
- "quota_exhausted": "Cycle quota used up",
- "server_error": "Upstream server error"
- },
- "needs_action": {
- "oauth_expired": "Needs a new sign-in",
- "balance_exhausted": "Out of balance — top it up",
- "credential_revoked": "Credential revoked — enter a new one",
- "account_banned": "Account is restricted"
- },
- "error": {
- "unclassified": "Unknown error — temporarily unavailable"
- }
- }
++ "requestPathMeasuring": "Measuring requests · {{count}} samples"
},
"accessBlocked": {
"title": "Can't open the control panel here",
@@@ -1221,7 -1025,25 +1189,27 @@@
"remote_access_not_running": "Start Remote Access before optimizing its route.",
"route_optimization_unavailable": "A route optimization is already running or cooling down.",
"route_optimization_start_failed": "Avibe could not start route optimization. Check the remote access runtime logs.",
- "bind_code_limit_reached": "Too many active bind codes. Revoke an unused code before creating another."
+ "bind_code_limit_reached": "Too many active bind codes. Revoke an unused code before creating another.",
+ "memory_disabled": "Memory is disabled, or this connection can't reach it.",
+ "memory_invalid_input": "That Memory request wasn't valid.",
+ "memory_input_too_large": "That input is too large for Memory.",
+ "memory_queue_full": "The Memory queue is full right now.",
+ "memory_low_disk_space": "There isn't enough free disk space for Memory right now.",
+ "memory_store_unavailable": "The Memory store is unavailable right now.",
+ "memory_runtime_missing": "The memory-runtime dependency isn't installed yet.",
+ "memory_runtime_unsupported": "The memory-runtime dependency isn't supported on this platform.",
+ "memory_runtime_install_failed": "The memory-runtime dependency failed to install.",
+ "memory_sidecar_unavailable": "The Memory sidecar isn't reachable right now.",
+ "memory_provider_timeout": "The Memory request timed out.",
+ "memory_provider_response_invalid": "Memory returned an invalid response.",
+ "memory_processing_failed": "Memory processing failed.",
+ "memory_clear_failed": "Clearing Memory data failed.",
+ "memory_runtime_unpublished": "This Avibe version hasn't published a memory runtime yet.",
+ "memory_runtime_manifest_missing": "The memory runtime manifest is missing.",
+ "memory_runtime_manifest_unavailable": "The memory runtime manifest couldn't be downloaded.",
- "memory_runtime_archive_unavailable": "The memory runtime download isn't available right now."
++ "memory_runtime_archive_unavailable": "The memory runtime download isn't available right now.",
++ "session_agent_unavailable": "The source session's Agent is no longer available. Choose an enabled Agent to fork this session.",
++ "reserved_session": "Avibe owns this session — it only receives workspace notifications."
},
"apps": {
"title": "Apps",
@@@ -1599,7 -1420,7 +1586,8 @@@
"kbdOpen": "Open",
"kbdClose": "Close",
"footerNote": "Apps and message content · all sessions",
-- "scopeAll": "all sessions"
++ "scopeAll": "all sessions",
++ "includeArchived": "Include archived"
},
"inbox": {
"eyebrow": "Inbox",
@@@ -2582,6 -2403,6 +2571,28 @@@
"movedForeground": "Moved to foreground",
"movedBackground": "Moved to background",
"endGone": "This session is no longer live."
++ },
++ "triggerDetail": {
++ "taskType": "Task",
++ "watchType": "Watch",
++ "enabled": "Enabled",
++ "disabled": "Disabled",
++ "schedule": "Schedule",
++ "nextRun": "Next run",
++ "command": "Command",
++ "runtime": "Runtime",
++ "running": "Running",
++ "runningPid": "Running · pid {{pid}}",
++ "notRunning": "Not running",
++ "firedSessions": "Triggered sessions",
++ "noFiredSessions": "No sessions triggered in this window.",
++ "runsTitle": "Recent runs",
++ "taskActiveLabel": "Enabled",
++ "watchActiveLabel": "Watching",
++ "enabledToast": "Enabled",
++ "disabledToast": "Disabled",
++ "openInHarness": "Open in Harness",
++ "toggleFailed": "Couldn't update — try again."
}
},
"showDisabled": "Show disabled",
@@@ -2604,7 -2426,8 +2616,8 @@@
"empty": "No agents yet. Create one to start a conversation.",
"selectPrompt": "Select an agent to view its configuration.",
"makeDefault": "Make default",
- "deleteConfirm": "Delete agent \"{{name}}\"? This cannot be undone.",
+ "deleteConfirm": "Archive agent \"{{name}}\"? It will disappear from Agents, while existing sessions and automations keep their saved configuration.",
+ "deleteInUse": "Agent \"{{name}}\" is currently in use by one or more channels and cannot be deleted.",
"detail": {
"enabled": "Enabled",
"enabledHint": "Disabling keeps the agent in the registry but excludes it from new sessions; running sessions are unaffected.",
@@@ -2792,41 -2616,15 +2806,20 @@@
},
"harness": {
"title": "Harness",
- "subtitle": "Scheduled tasks, watches, webhooks, and the run history of all three.",
+ "subtitle": "Scheduled tasks, watches, and the run history of both.",
+ "soon": "soon",
"create": "Create",
"searchPlaceholder": "Search…",
- "searchRunsPlaceholder": "Search runs…",
"statusFilter": {
"all": "All",
+ "enabled": "Enabled only",
- "disabled": "Disabled only"
++ "disabled": "Disabled only",
+ "active": "Live",
+ "waiting": "Waiting",
+ "running": "Running",
+ "paused": "Paused",
+ "finished": "Finished"
},
- "runStatus": {
- "all": "All",
- "queued": "Queued",
- "running": "Running",
- "succeeded": "Succeeded",
- "failed": "Failed",
- "canceled": "Canceled"
- },
- "runType": {
- "agent_run": "Agent run",
- "watch": "Watch check",
- "scheduled": "Scheduled task",
- "task_run": "Task run",
- "hook_send": "Message delivery",
- "webhook": "Webhook trigger",
- "watch_runtime": "Watcher heartbeat",
- "unknown": "Run"
- },
- "runTypeFilter": {
- "label": "Run type",
- "default": "Default (no heartbeats)",
- "all": "All types"
- },
"filtered": "{{shown}}/{{total}}",
"bannerToggle": {
"title": "Background task banner",
@@@ -2877,23 -2686,8 +2881,17 @@@
"source": "Source",
"parentRun": "Parent run",
"callback": "Callback",
- "effort": "effort {{value}}"
+ "effort": "effort {{value}}",
++ "triggeredBy": "Triggered by",
++ "sessionDeleted": "Session deleted",
+ "waitingSince": "Waiting since",
+ "onFailure": "On failure",
+ "timeout": "Timeout",
+ "timeoutSeconds": "{{seconds}}s",
+ "timeoutNone": "No timeout",
+ "timeoutDefault": "{{duration}} (default)",
+ "lastExitCode": "Last exit code"
},
- "taskKind": {
- "command": "Command"
- },
- "onFailure": {
- "none": "Notice only (no Agent)",
- "agent": "Escalate to an Agent"
- },
"sessionPolicy": {
"createPerRun": "New session each run",
"createOnce": "Create once, then reuse",
@@@ -2935,51 -2719,6 +2933,85 @@@
"kindWatch": "Watch",
"promptTask": "Help me create a scheduled task. What I want: [describe here, e.g. \"every weekday at 9:30am summarize yesterday's PR comments\"]. Once parameters look right, run vibe task add and bind it to this project.",
"promptWatch": "Help me create a watch. I want to wait for: [describe here, e.g. \"CI workflow #1234 to finish\"]. Notify me when the condition is met. Once parameters look right, run vibe watch add."
+ },
++ "searchRunsPlaceholder": "Search runs…",
++ "runStatus": {
++ "all": "All",
++ "queued": "Queued",
++ "running": "Running",
++ "succeeded": "Succeeded",
++ "failed": "Failed",
++ "canceled": "Canceled"
++ },
++ "runType": {
++ "agent_run": "Agent run",
++ "watch": "Watch check",
++ "scheduled": "Scheduled task",
++ "task_run": "Task run",
++ "hook_send": "Message delivery",
++ "webhook": "Webhook trigger",
++ "watch_runtime": "Watcher heartbeat",
++ "unknown": "Run"
++ },
++ "runTypeFilter": {
++ "label": "Run type",
++ "default": "Default (no heartbeats)",
++ "all": "All types"
++ },
++ "noTaskMatches": "No tasks match this view. Clear the filters or search.",
++ "noWatchMatches": "No watches match this view. Clear the filters or search.",
++ "noRunMatches": "No runs match this view. Clear the filters or search.",
++ "taskKind": {
++ "command": "Command"
++ },
++ "onFailure": {
++ "none": "Notice only (no Agent)",
++ "agent": "Escalate to an Agent"
++ },
+ "run": {
+ "definitionDeleted": "(deleted)"
+ },
+ "health": {
+ "failing": "failing",
+ "degraded": "degraded",
+ "unknown": "health unknown"
+ },
+ "lifecycle": {
+ "running": "Running",
+ "waiting": "Waiting",
+ "paused": "Paused",
+ "finished": "Finished",
+ "normal": "Finished",
+ "timeout": "Timed out",
+ "error": "Failed",
+ "unknown": "Unknown"
+ },
+ "kind": {
+ "task": "Scheduled task",
+ "watch": "Watch"
+ },
+ "when": {
+ "today": "today {{time}}",
+ "tomorrow": "tomorrow {{time}}",
+ "yesterday": "yesterday {{time}}",
+ "dateTime": "{{date}} {{time}}",
+ "wallClock": "{{time}} ({{timezone}})"
+ },
+ "cron": {
+ "everyMinute": "every minute",
+ "everyMinutes": "every {{count}} min",
+ "daily": "every day at {{time}}",
+ "weekly": "{{days}} at {{time}}",
+ "weekday": {
+ "sun": "Sun",
+ "mon": "Mon",
+ "tue": "Tue",
+ "wed": "Wed",
+ "thu": "Thu",
+ "fri": "Fri",
+ "sat": "Sat"
+ },
+ "weekdaySeparator": ", "
}
},
"chat": {
@@@ -3032,7 -2764,7 +3057,10 @@@
"pinnedConfirm": "Pinned — “{{title}}” is in your Dock",
"addToHomeTitle": "Add to Home Screen",
"addToHomeBodySafari": "Tap here to open in a new tab, then Share → “Add to Home Screen”.",
-- "addToHomeBodyPwa": "Copy the link above and open it in Safari, then tap Share → “Add to Home Screen”."
++ "addToHomeBodyPwa": "Copy the link above and open it in Safari, then tap Share → “Add to Home Screen”.",
++ "launchMenu": "Open Show Page",
++ "newWindow": "New window",
++ "newLink": "New link"
},
"titlePlaceholder": "Session title",
"pickAgent": "Pick an agent",
@@@ -3058,16 -2790,9 +3086,10 @@@
"scheduled": "Scheduled task",
"watch": "Watch",
"webhook": "Webhook",
- "showIntent": "Page action",
"harness": "From agent",
"from": "From",
-- "agentFallback": "agent"
- },
- "annotation": {
- "titleUser": "User annotation",
- "titleAgent": "Agent annotation",
- "resolved": "Resolved",
- "screenshot": "Screenshot"
++ "agentFallback": "agent",
++ "showIntent": "Page action"
},
"picker": {
"agent": "Agent",
@@@ -3099,23 -2822,10 +3119,25 @@@
"stop": "Stop",
"attach": "Attach files",
"voice": "Voice input",
- "stopRecording": "Stop recording",
+ "stopRecording": "Finish recording",
"cancelRecording": "Cancel recording",
+ "removeAttachment": "Remove",
- "dropOverlay": "Drop files to attach"
++ "dropOverlay": "Drop files to attach",
++ "placeholderArchived": "This session is archived — read-only",
++ "placeholderSystem": "Avibe posts workspace notifications here — this session does not accept messages",
+ "voiceProcessing": "Processing recording",
+ "voiceRetry": "Retry transcription",
+ "voiceCopyTranscript": "Copy recovered transcript",
+ "voiceTranscriptCopied": "Recovered transcript copied",
+ "voiceDiscard": "Discard recording",
+ "voiceFailed": "Voice transcription failed. Your recording is available to retry.",
+ "voiceTimedOut": "Voice transcription timed out. Your recording is available to retry.",
+ "voiceUnavailable": "Voice transcription is temporarily unavailable.",
+ "voiceTooLarge": "This recording is too large to transcribe.",
+ "voiceEmpty": "No speech was detected in this recording.",
+ "voicePermissionFailed": "Microphone access failed. Check your browser permission and try again.",
+ "voiceStartFailed": "Voice recording could not start in this browser. Reload the page or try a supported browser.",
- "voiceDraftChanged": "The draft changed during voice input. The recovered transcript is available to copy.",
- "removeAttachment": "Remove",
- "dropOverlay": "Drop files to attach"
++ "voiceDraftChanged": "The draft changed during voice input. The recovered transcript is available to copy."
},
"media": {
"preview": "Preview",
@@@ -3183,6 -2893,6 +3205,16 @@@
"sendNow": "Send now",
"recall": "Recall to input",
"remove": "Remove from queue"
++ },
++ "archived": {
++ "sendBlocked": "This session is archived and read-only.",
++ "editBlocked": "This session is archived and can no longer be changed."
++ },
++ "annotation": {
++ "titleUser": "User annotation",
++ "titleAgent": "Agent annotation",
++ "resolved": "Resolved",
++ "screenshot": "Screenshot"
}
},
"vaults": {
@@@ -3451,12 -3160,515 +3482,556 @@@
"dismiss": "Dismiss",
"saveAndWake": "Save & let the agent continue",
"ambiguousProvision": "Multiple pending requests need this secret. Open the request-specific Provide secret row in Vaults so the requested details are preserved.",
-- "saveFailed": "Couldn't save the secret. Please try again."
++ "saveFailed": "Couldn't save the secret. Please try again.",
++ "expired": "This session is archived — this request has expired."
},
"history": "History",
"audit": {
"title": "Recent activity",
"empty": "No activity yet."
}
+ },
+ "memory": {
+ "title": "Memory",
+ "betaTitle": "Memory · Beta",
+ "subtitle": "A personal memory distilled from your Workbench and private-IM messages — review it, search it, or clear it here.",
+ "setup": {
+ "runtimeRequired": "Install the Memory runtime first",
+ "runtimeRequiredHint": "Install or repair Memory from Dependencies. You can still disable Memory or clear stored data below."
+ },
+ "tabs": {
+ "status": "Status",
+ "profile": "Profile",
+ "search": "Search",
+ "settings": "Settings"
+ },
+ "remoteUnavailable": {
+ "title": "Available on this device only",
+ "description": "Memory settings and data are visible only from a direct connection to this Avibe install — not through Avibe Cloud or another remote route."
+ },
+ "status": {
+ "title": "Status",
+ "loading": "Checking status…",
+ "loadFailed": "Couldn't load Memory status.",
+ "refresh": "Refresh",
+ "state": {
+ "disabled": "Disabled",
+ "starting": "Starting",
+ "ready": "Ready",
+ "syncing": "Syncing",
+ "degraded": "Degraded",
+ "down": "Down",
+ "clearing": "Clearing",
+ "error": "Error"
+ },
+ "syncing": "Syncing",
+ "succeeded": "Succeeded",
+ "receiptUnknown": "Result unknown",
+ "receiptUnknownHint": "Delivered, but the distillation receipt was lost.",
+ "distillFailed": "Failed",
+ "dead": "Dead",
+ "deadHint": "Delivery was not acknowledged by the Memory engine.",
+ "missed": "Missed",
+ "fault": {
+ "credential": "The Memory engine cannot call the configured model endpoint. Check API key balance and permissions.",
+ "engine": "The Memory engine reported an internal error. Restarting it usually clears the fault."
+ },
+ "faultAction": {
+ "credential": "Open credential settings",
+ "engine": "Restart Memory engine"
+ },
+ "dismissFault": "Dismiss processing alert",
+ "engineRestartStarted": "Memory engine restart started.",
+ "engineRestartFailed": "Memory engine restart failed.",
+ "providerTitle": "Memory engine (EverOS)",
+ "providerSubtitle": "Latest provider observation",
+ "observation": {
+ "succeeded": "Succeeded",
+ "rejected": "Rejected",
+ "unknown": "Unknown"
+ },
+ "flushStatus": "Provider status",
+ "flushError": "Error code",
+ "flushAt": "Observed at",
+ "requestId": "Request ID",
+ "copyRequestId": "Copy request ID",
+ "queueBytes": "Queued text",
+ "storageUsed": "Local storage used",
+ "lastSuccess": "Last successful distillation",
+ "lastSuccessNever": "Never",
+ "failureLog": {
+ "title": "Failure log",
+ "subtitle": "Sanitized delivery and distillation failures retained for {{days}} days.",
+ "empty": "No retained failures.",
+ "loadFailed": "Couldn't load the Memory failure log.",
+ "errorCode": "Error code",
+ "attempts": "Attempts",
+ "kind": {
+ "delivery_abandoned": "Delivery abandoned",
+ "distillation_rejected": "Distillation rejected",
+ "result_unknown": "Result unknown"
+ }
+ }
+ },
+ "profile": {
+ "description": "The provider's current distilled profile of you, built from captured messages.",
+ "loading": "Loading profile…",
+ "empty": "No profile yet — keep chatting, then check back once messages have been processed.",
+ "loadFailed": "Couldn't load your profile.",
+ "warningUnavailable": "A profile isn't available from this provider yet. This is expected, not an error — try Search instead, or check back later.",
+ "disabledHint": "Enable Memory to view your profile.",
+ "refresh": "Refresh",
+ "sourceNote": "Distilled from your conversation history."
+ },
+ "search": {
+ "description": "Search your distilled profile, episodes, and facts.",
+ "placeholder": "Search your memory…",
+ "button": "Search",
+ "searching": "Searching…",
+ "empty": "No results.",
+ "searchFailed": "Search failed.",
+ "disabledHint": "Enable Memory to search.",
+ "sourceNote": "Distilled from your conversation history."
+ },
+ "settings": {
+ "loading": "Loading settings…",
+ "loadFailed": "Couldn't load Memory settings.",
+ "enableLabel": "Memory",
+ "enableHint": "Distill eligible Workbench messages and bound, enabled private-IM messages into a per-user searchable memory.",
+ "dependencyNotReady": "The memory-runtime dependency isn't ready yet. Install or repair it from Settings → Dependencies, then try enabling Memory again.",
+ "goToDependencies": "Open Dependencies",
+ "llmTitle": "LLM endpoint",
+ "embeddingTitle": "Embedding endpoint",
+ "baseUrl": "Base URL",
+ "baseUrlPlaceholder": "https://api.example.com/v1",
+ "model": "Model",
+ "modelPlaceholder": "model name",
+ "apiKey": "API key",
+ "apiKeySet": "A key is set — leave blank to keep it.",
+ "apiKeyNotSet": "No key set.",
+ "apiKeyPlaceholder": "sk-…",
+ "apiKeyClearHint": "Keys are write-only — Avibe never shows a saved key back to you.",
+ "embeddingLocked": "Changing the embedding endpoint or model is disabled while memory data exists. Run Clear all first.",
+ "embeddingStatusPending": "Confirming Memory state… the embedding endpoint unlocks once it's confirmed no data exists.",
+ "save": "Save settings",
+ "saving": "Saving…",
+ "saveFailed": "Couldn't save Memory settings.",
+ "saved": "Memory settings saved.",
+ "disclosureTitle": "Before you enable Memory",
+ "disclosure": [
+ "Eligible Workbench and bound, enabled private-IM text is copied into a bounded local queue for processing.",
+ "Once a message succeeds or exhausts its retries, its text is scrubbed immediately; a content-free tombstone may remain for up to 90 days, bounded to the newest 100,000 rows.",
+ "The Memory LLM and embedding endpoints are separate from your agent's model subscriptions.",
+ "These remote endpoints receive captured text or search queries and may retain them under their own policy.",
+ "Private-IM text has already traveled over that platform before capture and remains subject to that platform's own retention and sync.",
+ "The local runtime retains unflushed raw messages and extracted data in local state in addition to the visible profile.",
+ "Disabling Memory freezes local data rather than deleting it — use Clear all to remove it.",
+ "Clear all removes this install's local Memory data but cannot retract copies already sent to a remote endpoint or your original chat history.",
+ "Delivery to the Memory endpoints is at-least-once — a rare duplicate derived memory is possible after a timeout or crash.",
+ "Each platform user has a separate memory scope; identities are not linked across platforms."
+ ],
+ "clearKeyLabel": "Clear the saved key"
+ },
+ "clear": {
+ "button": "Clear all",
+ "confirmTitle": "Clear all local Memory data?",
+ "confirmDescription": "This removes your distilled profile, episodes, facts, and any pending queued text on this install.",
+ "removesTitle": "This removes:",
+ "removes": [
+ "Your visible distilled profile",
+ "Hidden local buffers and indexes used to build it",
+ "Pending and finished items in the local processing queue"
+ ],
+ "keepsTitle": "This does not remove:",
+ "keeps": [
+ "Your original Avibe chat history",
+ "Copies already sent to a remote Memory endpoint",
+ "Copies or snapshots you created yourself",
+ "Any data stored outside the dedicated Memory folder",
+ "Existing logs, crash reports, or backups",
+ "Physical traces on the storage device — this is not a secure wipe"
+ ],
+ "confirmLabel": "Clear all",
+ "clearing": "Clearing…",
+ "cleared": "Memory data cleared.",
+ "failed": "Clear failed."
+ },
+ "kind": {
+ "profile": "Profile",
+ "episode": "Episode",
+ "fact": "Fact"
+ }
+ },
+ "organization": {
+ "nav": {
+ "overview": "Overview",
+ "instances": "Avibes",
+ "members": "Members",
+ "groups": "Groups",
+ "resources": "Resources"
+ },
+ "actions": {
+ "backToControlPanel": "Control Panel",
+ "openRemoteAccess": "Open Remote Access",
+ "signIn": "Sign in with Avibe Cloud",
+ "signInAgain": "Sign in with the same account",
+ "signOut": "Sign out of Organization management",
+ "reload": "Review latest",
+ "saving": "Saving...",
+ "saveChanges": "Save changes",
+ "sendInvite": "Send invite",
+ "inviteMember": "Invite member",
+ "editMember": "Edit member",
+ "removeMember": "Remove member",
+ "resendInvite": "Resend invite",
+ "exportCsv": "Export CSV",
+ "newGroup": "New group",
+ "editGroup": "Edit group",
+ "archiveGroup": "Archive group",
+ "restoreGroup": "Restore group",
+ "manageMembers": "Manage members",
+ "saveMembers": "Save members",
+ "addAccess": "Add access",
+ "editAccess": "Edit access",
+ "removeAccess": "Remove access",
+ "addBinding": "Add binding",
+ "removeBinding": "Remove binding",
+ "manage": "Manage"
+ },
+ "roles": {
+ "owner": "Owner",
+ "admin": "Admin",
+ "member": "Member"
+ },
+ "status": {
+ "active": "Active",
+ "invited": "Invited",
+ "removed": "Removed"
+ },
+ "sync": {
+ "none": "No managed policies",
+ "in_sync": "In sync",
+ "applying": "Applying",
+ "offline": "Offline",
+ "error": "Error",
+ "deleted": "Deleted"
+ },
+ "sidebar": {
+ "section": "Organization",
+ "organizationCount": "{{count}} organizations",
+ "switchOrganization": "Switch Organization",
+ "cloudConnected": "Cloud connected",
+ "sessionRemaining": "management session · {{minutes}}m",
+ "openMenu": "Open Organization menu"
+ },
+ "states": {
+ "loadingTitle": "Loading Organization",
+ "loadingBody": "Fetching the latest Organization data from Avibe Cloud.",
+ "notConnectedTitle": "Avibe Cloud is not connected",
+ "notConnectedBody": "Connect this Avibe to Avibe Cloud before opening Organization management.",
+ "signInTitle": "Sign in required",
+ "signInBody": "Sign in to Avibe Cloud to establish a short-lived Organization management session.",
+ "reauthorizingTitle": "Reauthorizing",
+ "reauthorizingBody": "Restoring your Organization management session with the same Cloud account.",
+ "mismatchTitle": "Cloud account does not match",
+ "mismatchBody": "The Avibe session and Cloud account belong to different users. Sign in again with the same account used for this Avibe session.",
+ "unreachableTitle": "Avibe Cloud is unreachable",
+ "unreachableBody": "Organization data could not be reached. Your local Avibe remains available.",
+ "revokedTitle": "Organization access was revoked",
+ "revokedBody": "This management session is no longer valid. Sign in again to confirm your current access.",
+ "emptyTitle": "No Organizations available",
+ "emptyBody": "The signed-in Cloud account is not an active member of an Organization.",
+ "unavailableTitle": "This Organization page is unavailable",
+ "unavailableBody": "Your current Organization or Avibe access does not allow this page.",
+ "errorTitle": "Unable to complete the request",
+ "conflictTitle": "This policy changed elsewhere",
+ "conflictBody": "Your draft was not saved. Review it, then reload the latest version before making changes again."
+ },
+ "errors": {
+ "generic": "Avibe could not complete this Organization request.",
+ "forbidden": "Your current Organization role does not allow this action.",
+ "organization_not_found": "This Organization is unavailable.",
+ "organization_member_not_found": "This member is no longer available.",
+ "organization_group_not_found": "This group is no longer available.",
+ "organization_group_archived": "Archived groups cannot be added to a new policy.",
+ "instance_not_found": "This Avibe is unavailable.",
+ "project_not_found": "This Project is unavailable.",
+ "resource_not_found": "This resource is unavailable.",
+ "member_email_taken": "That email already belongs to this Organization.",
+ "group_name_taken": "A group with that name already exists.",
+ "too_many_entries": "This policy has too many entries.",
+ "invalid_project_access_intent": "Choose a valid Project access rule.",
+ "invalid_project_access_principal": "One Project access principal is invalid.",
+ "invalid_project_access_role": "One Project access role is invalid.",
+ "invalid_resource_acl_intent": "Choose a valid Resource audience.",
+ "invalid_email": "Enter a valid email address.",
+ "invalid_domain": "Enter a valid email domain.",
+ "duplicate_instance_access_principal": "Each Avibe access principal can appear only once.",
+ "duplicate_project_access_principal": "Each Project principal can appear only once.",
+ "owner_entry_locked": "The Avibe owner's implicit access cannot be changed.",
+ "resource_sync_conflict": "This policy changed elsewhere. Review the latest version before saving.",
+ "organization_member_conflict": "This member changed elsewhere. Review the latest version before trying again.",
+ "organization_group_conflict": "This group changed elsewhere. Review the latest version before trying again."
+ },
+ "fields": {
+ "name": "Name",
+ "description": "Description",
+ "color": "Color",
+ "email": "Email",
+ "role": "Role",
+ "groups": "Groups",
+ "member": "Member",
+ "status": "Status",
+ "principalType": "Principal type",
+ "principal": "Principal"
+ },
+ "colors": {
+ "mint": "Mint",
+ "cyan": "Cyan",
+ "blue": "Blue",
+ "violet": "Violet",
+ "rose": "Rose",
+ "gold": "Gold"
+ },
+ "principals": {
+ "organization_group": "Group",
+ "email": "Email",
+ "email_domain": "Email domain"
+ },
+ "breadcrumb": {
+ "overview": "Organization / Overview",
+ "members": "Organization / Members",
+ "groups": "Organization / Groups",
+ "groupDetail": "Organization / Groups / {{name}}",
+ "instances": "Organization / Avibes",
+ "resources": "Organization / Resources"
+ },
+ "overview": {
+ "description": "Manage membership, access, and policy health for this Organization.",
+ "memberDescription": "Your Organization membership and the Avibes available to you.",
+ "memberBreakdown": "{{invited}} invited · {{removed}} removed",
+ "groupBreakdown": "{{archived}} archived",
+ "projects": "Projects",
+ "projectCountUnavailable": "Count unavailable",
+ "policySync": "Policy sync",
+ "needsAttention": "Needs attention",
+ "instanceNeedsAttention": "{{name}} has policy changes that need attention.",
+ "projectSyncNeedsAttention": "{{name}} has Project policies that need attention.",
+ "resourceSyncNeedsAttention": "{{name}} has Resource policies that need attention.",
+ "noAttention": "All visible managed policies are healthy.",
+ "pendingInvites": "Pending invites",
+ "pendingInvitesBody": "{{count}} invitation(s) are waiting to be accepted.",
+ "viewAllInstances": "View all Avibes",
+ "memberSafeTitle": "Member view",
+ "memberSafeBody": "You can see your own membership and the Avibes available to you. Member directories and Resource policy composition are visible only to Organization managers."
+ },
+ "members": {
+ "description": "Invite members, assign Organization roles, and manage group membership.",
+ "memberDescription": "View your Organization role and group membership.",
+ "filterLabel": "Filter members",
+ "filterAll": "All",
+ "active": "Active",
+ "invited": "Invited",
+ "removed": "Removed",
+ "admins": "Admins",
+ "searchPlaceholder": "Search members...",
+ "emptyTitle": "No members found",
+ "emptyBody": "No members match the current view.",
+ "inviteTitle": "Invite a member",
+ "inviteBody": "Send an Organization invitation and optionally assign initial groups.",
+ "editTitle": "Edit member",
+ "editBody": "Changes to role and complete group membership share one revision.",
+ "emailPlaceholder": "[email protected]",
+ "downgradeTitle": "Downgrade this admin?",
+ "downgradeBody": "{{email}} will lose Organization management access. Their membership and group assignments will remain unchanged.",
+ "downgradeConfirm": "Downgrade to member",
+ "removeTitle": "Remove this member?",
+ "removeBody": "{{email}} will lose Organization membership and any access derived from it."
+ },
+ "groups": {
+ "description": "Build reusable Organization audiences and inspect every policy that references them.",
+ "memberDescription": "View Organization groups and your own group membership.",
+ "active": "Active",
+ "archived": "Archived",
+ "filterLabel": "Filter groups",
+ "searchPlaceholder": "Search groups...",
+ "emptyTitle": "No groups found",
+ "emptyBody": "No groups match the current view.",
+ "noDescription": "No description",
+ "yourGroup": "Your group",
+ "createTitle": "Create group",
+ "createBody": "Create an Organization group and optionally add initial members.",
+ "editTitle": "Edit group",
+ "editBody": "Update the group's display details.",
+ "initialMembers": "Initial members",
+ "manageMembersTitle": "Manage group members",
+ "manageMembersBody": "Replace the complete member list for {{name}}.",
+ "referencedBy": "Referenced by",
+ "moreReferences": "+{{count}} more",
+ "archiveTitle": "Archive this group?",
+ "archiveBody": "{{name}} is referenced by {{count}} active policy item(s).",
+ "archiveImpactTitle": "Archive impact",
+ "archiveImpactBody": "Existing references remain visible but stop granting access. The archived group cannot be selected for new policies."
+ },
+ "instances": {
+ "description": "Organization-bound Avibes you can see. Manage access and Project policy without changing pairing or hostnames.",
+ "searchPlaceholder": "Search Avibes...",
+ "emptyTitle": "No Avibes found",
+ "emptyBody": "No Organization-bound Avibes are available in this view.",
+ "you": "You",
+ "organizationOwner": "Avibe owner",
+ "ownerProtected": "Owner identity protected",
+ "youAreOwner": "you are the Avibe owner",
+ "paired": "Paired",
+ "notPaired": "Not paired",
+ "accessCount": "{{count}} access entries",
+ "accessTab": "Access",
+ "projectsTab": "Projects",
+ "tabsLabel": "Avibe management views",
+ "columns": {
+ "instance": "Avibe",
+ "owner": "Owner",
+ "address": "Public address",
+ "status": "Status",
+ "access": "Access",
+ "sync": "Sync"
+ },
+ "status": {
+ "pending": "Pending",
+ "active": "Online",
+ "disabled": "Disabled",
+ "deleted": "Deleted"
+ }
+ },
+ "access": {
+ "viewer": "Viewer",
+ "editor": "Editor",
+ "ownerTitle": "{{owner}} · Avibe owner",
+ "ownerBody": "Implicit owner-equivalent access. It cannot be edited or removed as an entry.",
+ "emptyTitle": "No explicit access entries",
+ "emptyBody": "Only the implicit Avibe owner currently has access.",
+ "addTitle": "Add Avibe access",
+ "editTitle": "Edit Avibe access",
+ "dialogBody": "Grant a group, individual email, or email domain Viewer or Editor access.",
+ "emailPlaceholder": "[email protected]",
+ "domainPlaceholder": "example.com",
+ "narrowTitle": "Narrow this access entry?",
+ "narrowBody": "The previous principal or Editor capability will stop applying after this change.",
+ "removeTitle": "Remove this access entry?",
+ "removeBody": "{{principal}} will lose access granted by this entry.",
+ "columns": {
+ "principal": "Principal",
+ "type": "Type",
+ "role": "Role"
+ }
+ },
+ "projects": {
+ "searchPlaceholder": "Search Projects...",
+ "safeDescriptorNotice": "Safe descriptors only. Local Project paths are never displayed or sent. Project access can only narrow the Avibe role.",
+ "emptyTitle": "No Projects found",
+ "emptyBody": "This Avibe has not published any active managed Project descriptors.",
+ "accessRule": "Access rule",
+ "bindings": "Restricted bindings",
+ "bindingRequired": "Restricted access requires at least one binding.",
+ "usesAvibeRole": "Uses Avibe role",
+ "ownerOnlyAudience": "Avibe owner only",
+ "bindingCount": "{{count}} binding(s)",
+ "dialogTitle": "Manage {{name}} access",
+ "dialogBody": "Organization management authority lets you change this policy; it does not grant you permission to use the Project.",
+ "narrowTitle": "Narrow this Project's access?",
+ "narrowBody": "This change removes an existing audience, downgrades Editor access, or switches to a more restrictive rule.",
+ "modes": {
+ "inherit": "Inherit",
+ "restricted": "Restricted",
+ "owner_only": "Owner-only"
+ },
+ "modeHelp": {
+ "inherit": "Use each principal's effective Avibe role.",
+ "restricted": "Allow one or more explicit groups, emails, or domains. This rule can only narrow the Avibe role.",
+ "owner_only": "Only the canonical owner of this Avibe can use this Project. Organization managers can manage the policy but do not gain use access."
+ },
+ "columns": {
+ "project": "Project",
+ "rule": "Access rule",
+ "bindings": "Bindings",
+ "sync": "Sync"
+ }
+ },
+ "resources": {
+ "description": "Manage which Organization audience may use each resource. Resource use never grants permission to edit, delete, or re-share it.",
+ "tabsLabel": "Resource kinds",
+ "accessLevel": "Audience",
+ "selectGroups": "Selected groups",
+ "groupRequired": "Select at least one group.",
+ "dialogTitle": "Manage {{name}} audience",
+ "dialogBody": "Choose Private, the whole Organization, or selected Organization groups.",
+ "narrowTitle": "Narrow this resource audience?",
+ "narrowBody": "Some people who can use this resource now will lose access after this change.",
+ "emptyTitle": "No resources found",
+ "emptyBody": "No active {{kind}} descriptors are available.",
+ "everyActiveMember": "Every active member",
+ "ownerOnly": "Resource owner only",
+ "kinds": {
+ "agent": "Agents",
+ "vault_secret": "Vault secrets",
+ "skill": "Skills",
+ "show_page": "Show Pages"
+ },
+ "levels": {
+ "private": "Private",
+ "public": "Organization",
+ "scope": "Selected groups"
+ },
+ "levelHelp": {
+ "private": "Only the resource owner can use it through this Organization ACL.",
+ "public": "Every active member of this Organization may use it, subject to all other access layers.",
+ "scope": "Only active members of the selected groups may use it, subject to all other access layers."
+ },
+ "columns": {
+ "access": "Access",
+ "audience": "Audience",
+ "sync": "Sync"
+ }
+ }
++ },
++ "models": {
++ "eligibility": {
++ "subscription_wrong_client": "{{vendor}} subscriptions only work in {{backend}}",
++ "opencode_api_key_only": "OpenCode can only be supplied by API-key sources",
++ "consent_required": "Needs your consent for experimental hub supply first"
++ },
++ "oauth": {
++ "upstream_failed": "The vendor didn't complete this sign-in, please retry",
++ "engine_unavailable": "The Hub isn't responding, please retry",
++ "submission_failed": "Couldn't submit what you pasted, please retry",
++ "ambiguous_engine_binding": "Couldn't tell which account signed in — do one at a time, then retry",
++ "binding_failed": "That account is already used by another source",
++ "expired": "Authorization timed out, please reconnect"
++ },
++ "probe": {
++ "native_cli_unavailable": "Can't use the CLI's sign-in",
++ "no_candidate": {
++ "waiting": "Every source is cooling down",
++ "interrupted": "No source can serve this model right now"
++ }
++ },
++ "source": {
++ "cooldown": {
++ "network": "Network unreachable",
++ "timeout": "Repeated timeouts",
++ "rate_limited": "Rate limited",
++ "quota_exhausted": "Cycle quota used up",
++ "server_error": "Upstream server error"
++ },
++ "needs_action": {
++ "oauth_expired": "Needs a new sign-in",
++ "balance_exhausted": "Out of balance — top it up",
++ "credential_revoked": "Credential revoked — enter a new one",
++ "account_banned": "Account is restricted"
++ },
++ "error": {
++ "unclassified": "Unknown error — temporarily unavailable"
++ }
++ }
}
}
diff --cc ui/src/i18n/zh.json
index 00c7e0ecd,53cef1e8d..9272feaa1
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@@ -107,12 -106,7 +106,15 @@@
"proxyUrl": "代理地址(可选)",
"proxyUrlHint": "SOCKS5、SOCKS4、HTTP 或 HTTPS 代理。留空则回退到系统 SOCKS 代理探测,未配置时直连。",
"proxyUrlCollapsedHint": "(留空则尝试系统代理,否则直连)",
- "locked": "已锁定"
++ "locked": "已锁定",
++ "archived": "已归档",
++ "systemSession": "系统",
+ "duration": {
+ "seconds": "秒",
+ "minutes": "分",
+ "hours": "小时",
+ "days": "天"
+ }
},
"nav": {
"dashboard": "控制台",
@@@ -1125,56 -977,9 +1134,16 @@@
"qualityUnknown": "测量中",
"qualityRecovering": "正在优化",
"qualityDegraded": "异常",
+ "optimizeRoute": "优化线路",
+ "optimizingRoute": "优化中...",
- "optimizeStarted": "第二条 Connector 正在评估更优线路"
++ "optimizeStarted": "第二条 Connector 正在评估更优线路",
+ "protocolAutomatic": "{{protocol}}(自动)",
+ "protocolUnknown": "检测中",
+ "connectorPath": "连接器 · {{protocol}} · {{connections}}/4 · 往返 {{rtt}}",
+ "rttUnavailable": "不可用",
+ "requestPath": "远程请求 · P95 {{p95}} · P99 {{p99}} · {{slow}}% 超过 1 秒",
+ "requestPathUnavailable": "远程请求不可用 · {{success}}/{{count}} 成功",
- "requestPathMeasuring": "正在测量远程请求 · {{count}} 个样本",
- "optimizeRoute": "优化线路",
- "optimizingRoute": "优化中...",
- "optimizeStarted": "第二条 Connector 正在评估更优线路"
- },
- "models": {
- "eligibility": {
- "subscription_wrong_client": "{{vendor}} 订阅仅可供 {{backend}} 使用",
- "opencode_api_key_only": "OpenCode 只能由 API Key 来源供给",
- "consent_required": "需要先同意实验性中枢供给"
- },
- "oauth": {
- "upstream_failed": "厂商没有完成这次登录,请重试",
- "engine_unavailable": "中枢没有响应,请重试",
- "submission_failed": "粘贴的内容没能提交,请重试",
- "ambiguous_engine_binding": "分不清登录的是哪个账号,请一次只登一个再重试",
- "binding_failed": "该账号已被另一来源使用",
- "expired": "授权超时,请重新连接"
- },
- "probe": {
- "native_cli_unavailable": "用不上 CLI 的登录",
- "no_candidate": {
- "waiting": "所有来源都在冷却",
- "interrupted": "现在没有来源能提供这个模型"
- }
- },
- "source": {
- "cooldown": {
- "network": "网络不通",
- "timeout": "连续超时",
- "rate_limited": "触发限流",
- "quota_exhausted": "本周期额度用完",
- "server_error": "上游服务异常"
- },
- "needs_action": {
- "oauth_expired": "需要重新登录",
- "balance_exhausted": "余额不足,需要充值",
- "credential_revoked": "凭据已失效,需要重新填写",
- "account_banned": "账号被限制使用"
- },
- "error": {
- "unclassified": "未知错误,暂时不可用"
- }
- }
++ "requestPathMeasuring": "正在测量远程请求 · {{count}} 个样本"
},
"accessBlocked": {
"title": "无法在此地址打开控制台",
@@@ -1221,7 -1025,25 +1189,27 @@@
"remote_access_not_running": "请先启动远程访问,再优化线路。",
"route_optimization_unavailable": "线路优化正在进行中,或当前仍处于冷却期。",
"route_optimization_start_failed": "Avibe 无法启动线路优化,请查看远程访问运行日志。",
- "bind_code_limit_reached": "可用绑定码过多,请先撤销一个未使用的绑定码,再创建新的绑定码。"
+ "bind_code_limit_reached": "可用绑定码过多,请先撤销一个未使用的绑定码,再创建新的绑定码。",
+ "memory_disabled": "记忆功能已禁用,或当前连接无法访问它。",
+ "memory_invalid_input": "该记忆请求无效。",
+ "memory_input_too_large": "输入内容对记忆功能来说太大了。",
+ "memory_queue_full": "记忆队列目前已满。",
+ "memory_low_disk_space": "当前磁盘空间不足,无法用于记忆功能。",
+ "memory_store_unavailable": "记忆存储当前不可用。",
+ "memory_runtime_missing": "memory-runtime 依赖尚未安装。",
+ "memory_runtime_unsupported": "memory-runtime 依赖在此平台上不受支持。",
+ "memory_runtime_install_failed": "memory-runtime 依赖安装失败。",
+ "memory_sidecar_unavailable": "记忆 sidecar 当前不可访问。",
+ "memory_provider_timeout": "记忆请求超时。",
+ "memory_provider_response_invalid": "记忆返回了无效的响应。",
+ "memory_processing_failed": "记忆处理失败。",
+ "memory_clear_failed": "清除记忆数据失败。",
+ "memory_runtime_unpublished": "当前 Avibe 版本尚未发布记忆运行时。",
+ "memory_runtime_manifest_missing": "记忆运行时的清单缺失。",
+ "memory_runtime_manifest_unavailable": "无法下载记忆运行时的清单。",
- "memory_runtime_archive_unavailable": "记忆运行时的下载包当前不可用。"
++ "memory_runtime_archive_unavailable": "记忆运行时的下载包当前不可用。",
++ "session_agent_unavailable": "源会话的 Agent 已不可用。请选择一个已启用的 Agent 来复刻此会话。",
++ "reserved_session": "该会话由 Avibe 管理,只接收工作区通知。"
},
"apps": {
"title": "应用",
@@@ -1599,7 -1420,7 +1586,8 @@@
"kbdOpen": "打开",
"kbdClose": "关闭",
"footerNote": "应用与消息内容 · 全部会话",
-- "scopeAll": "全部会话"
++ "scopeAll": "全部会话",
++ "includeArchived": "包含已归档"
},
"inbox": {
"eyebrow": "收件箱",
@@@ -2582,6 -2403,6 +2571,28 @@@
"movedForeground": "已移到前台",
"movedBackground": "已移到后台",
"endGone": "该会话已不在运行。"
++ },
++ "triggerDetail": {
++ "taskType": "Task",
++ "watchType": "Watch",
++ "enabled": "已启用",
++ "disabled": "已禁用",
++ "schedule": "计划",
++ "nextRun": "下次运行",
++ "command": "命令",
++ "runtime": "运行时",
++ "running": "运行中",
++ "runningPid": "运行中 · pid {{pid}}",
++ "notRunning": "未运行",
++ "firedSessions": "触发的会话",
++ "noFiredSessions": "该窗口内未触发任何会话。",
++ "runsTitle": "最近运行",
++ "taskActiveLabel": "已启用",
++ "watchActiveLabel": "监视中",
++ "enabledToast": "已启用",
++ "disabledToast": "已禁用",
++ "openInHarness": "在 Harness 中打开",
++ "toggleFailed": "更新失败,请重试。"
}
},
"showDisabled": "显示已禁用",
@@@ -2604,7 -2426,8 +2616,8 @@@
"noSearchMatch": "没有匹配的 Agent。",
"selectPrompt": "选择一个 Agent 查看配置。",
"makeDefault": "设为默认",
- "deleteConfirm": "确认删除 Agent \"{{name}}\"?此操作不可撤销。",
+ "deleteConfirm": "确认归档 Agent \"{{name}}\"?它将从 Agent 列表中消失,但已有会话和自动化仍会使用已保存的配置。",
+ "deleteInUse": "Agent \"{{name}}\" 正被一个或多个频道使用,无法删除。",
"detail": {
"enabled": "已启用",
"enabledHint": "关掉后此 Agent 不会被新会话选用,已运行的会话不受影响",
@@@ -2792,41 -2616,15 +2806,20 @@@
},
"harness": {
"title": "Harness",
- "subtitle": "定时任务、Watch、Webhook 及其运行历史。",
+ "subtitle": "定时任务、Watch 及其运行历史。",
+ "soon": "敬请期待",
"create": "创建",
"searchPlaceholder": "搜索…",
- "searchRunsPlaceholder": "搜索运行记录…",
"statusFilter": {
"all": "全部",
+ "enabled": "仅启用",
- "disabled": "仅禁用"
++ "disabled": "仅禁用",
+ "active": "进行中",
+ "waiting": "在等",
+ "running": "在跑",
+ "paused": "已暂停",
+ "finished": "已结束"
},
- "runStatus": {
- "all": "全部",
- "queued": "排队中",
- "running": "运行中",
- "succeeded": "已成功",
- "failed": "已失败",
- "canceled": "已取消"
- },
- "runType": {
- "agent_run": "Agent 运行",
- "watch": "监听检查",
- "scheduled": "定时任务",
- "task_run": "任务运行",
- "hook_send": "消息投递",
- "webhook": "Webhook 触发",
- "watch_runtime": "监听心跳",
- "unknown": "运行"
- },
- "runTypeFilter": {
- "label": "运行类型",
- "default": "默认(隐藏心跳)",
- "all": "全部类型"
- },
"filtered": "{{shown}}/{{total}}",
"bannerToggle": {
"title": "后台任务横幅",
@@@ -2877,23 -2686,8 +2881,17 @@@
"source": "来源",
"parentRun": "父 Run",
"callback": "回传",
- "effort": "推理 {{value}}"
+ "effort": "推理 {{value}}",
++ "triggeredBy": "触发来源",
++ "sessionDeleted": "会话已删除",
+ "waitingSince": "开始等待",
+ "onFailure": "失败处理",
+ "timeout": "超时",
+ "timeoutSeconds": "{{seconds}} 秒",
+ "timeoutNone": "不限时",
+ "timeoutDefault": "{{duration}}(默认)",
+ "lastExitCode": "最近退出码"
},
- "taskKind": {
- "command": "命令"
- },
- "onFailure": {
- "none": "仅通知(无 Agent)",
- "agent": "升级给 Agent 处理"
- },
"sessionPolicy": {
"createPerRun": "每次运行新建会话",
"createOnce": "建一次后复用",
@@@ -2935,51 -2719,6 +2933,85 @@@
"kindWatch": "等待器",
"promptTask": "请帮我创建一个后台任务。我的需求是:[在这里描述,例如「每个工作日早上 9:30 总结昨天的 PR 评论」]。请确认参数后用 vibe task add 创建,并把任务挂到当前项目。",
"promptWatch": "请帮我创建一个等待器(watch)。我希望监听:[在这里描述,例如「等 CI 工作流 #1234 跑完」]。条件满足后通知我。请确认参数后用 vibe watch add 创建。"
+ },
++ "searchRunsPlaceholder": "搜索运行记录…",
++ "runStatus": {
++ "all": "全部",
++ "queued": "排队中",
++ "running": "运行中",
++ "succeeded": "已成功",
++ "failed": "已失败",
++ "canceled": "已取消"
++ },
++ "runType": {
++ "agent_run": "Agent 运行",
++ "watch": "监听检查",
++ "scheduled": "定时任务",
++ "task_run": "任务运行",
++ "hook_send": "消息投递",
++ "webhook": "Webhook 触发",
++ "watch_runtime": "监听心跳",
++ "unknown": "运行"
++ },
++ "runTypeFilter": {
++ "label": "运行类型",
++ "default": "默认(隐藏心跳)",
++ "all": "全部类型"
++ },
++ "noTaskMatches": "当前视图没有匹配的任务。请清除筛选或搜索。",
++ "noWatchMatches": "当前视图没有匹配的 Watch。请清除筛选或搜索。",
++ "noRunMatches": "当前视图没有匹配的运行记录。请清除筛选或搜索。",
++ "taskKind": {
++ "command": "命令"
++ },
++ "onFailure": {
++ "none": "仅通知(无 Agent)",
++ "agent": "升级给 Agent 处理"
++ },
+ "run": {
+ "definitionDeleted": "(已删除)"
+ },
+ "health": {
+ "failing": "连续失败",
+ "degraded": "近期失败",
+ "unknown": "状态未知"
+ },
+ "lifecycle": {
+ "running": "运行中",
+ "waiting": "等待中",
+ "paused": "已暂停",
+ "finished": "已结束",
+ "normal": "正常结束",
+ "timeout": "已超时",
+ "error": "出错结束",
+ "unknown": "未知"
+ },
+ "kind": {
+ "task": "定时任务",
+ "watch": "Watch"
+ },
+ "when": {
+ "today": "今天 {{time}}",
+ "tomorrow": "明天 {{time}}",
+ "yesterday": "昨天 {{time}}",
+ "dateTime": "{{date}} {{time}}",
+ "wallClock": "{{time}}({{timezone}})"
+ },
+ "cron": {
+ "everyMinute": "每分钟",
+ "everyMinutes": "每 {{count}} 分钟",
+ "daily": "每天 {{time}}",
+ "weekly": "每周{{days}} {{time}}",
+ "weekday": {
+ "sun": "日",
+ "mon": "一",
+ "tue": "二",
+ "wed": "三",
+ "thu": "四",
+ "fri": "五",
+ "sat": "六"
+ },
+ "weekdaySeparator": "、"
}
},
"chat": {
@@@ -3032,7 -2764,7 +3057,10 @@@
"pinnedConfirm": "已固定 —「{{title}}」已在你的 Dock 中",
"addToHomeTitle": "添加到主屏幕",
"addToHomeBodySafari": "点此处在新页面中打开,再点「分享」 →「添加到主屏幕」。",
-- "addToHomeBodyPwa": "复制上方链接,在 Safari 中打开,再点分享 →「添加到主屏幕」。"
++ "addToHomeBodyPwa": "复制上方链接,在 Safari 中打开,再点分享 →「添加到主屏幕」。",
++ "launchMenu": "打开 Show Page",
++ "newWindow": "新窗口",
++ "newLink": "新链接"
},
"titlePlaceholder": "会话标题",
"pickAgent": "选择 Agent",
@@@ -3058,16 -2790,9 +3086,10 @@@
"scheduled": "定时任务",
"watch": "Watch 监听",
"webhook": "Webhook",
- "showIntent": "页面操作",
"harness": "来自 Agent",
"from": "来自",
-- "agentFallback": "智能体"
- },
- "annotation": {
- "titleUser": "用户批注",
- "titleAgent": "Agent 批注",
- "resolved": "已处理",
- "screenshot": "截图"
++ "agentFallback": "智能体",
++ "showIntent": "页面操作"
},
"picker": {
"agent": "Agent",
@@@ -3099,23 -2822,10 +3119,25 @@@
"stop": "停止",
"attach": "添加附件",
"voice": "语音输入",
- "stopRecording": "停止录音",
+ "stopRecording": "完成录音",
"cancelRecording": "取消录音",
+ "removeAttachment": "移除",
- "dropOverlay": "拖放文件以添加"
++ "dropOverlay": "拖放文件以添加",
++ "placeholderArchived": "会话已归档,仅可查看",
++ "placeholderSystem": "Avibe 在这里发布工作区通知,该会话不接受发送消息",
+ "voiceProcessing": "正在处理录音",
+ "voiceRetry": "重试转写",
+ "voiceCopyTranscript": "复制已恢复的文字",
+ "voiceTranscriptCopied": "已复制恢复的文字",
+ "voiceDiscard": "丢弃录音",
+ "voiceFailed": "语音转写失败,录音已保留,可以重试。",
+ "voiceTimedOut": "语音转写超时,录音已保留,可以重试。",
+ "voiceUnavailable": "语音转写暂时不可用。",
+ "voiceTooLarge": "这段录音太大,无法转写。",
+ "voiceEmpty": "这段录音中没有检测到语音。",
+ "voicePermissionFailed": "无法使用麦克风,请检查浏览器权限后重试。",
+ "voiceStartFailed": "当前浏览器无法启动语音录制,请刷新页面或更换支持的浏览器。",
- "voiceDraftChanged": "语音输入期间草稿已变化,已保留整理结果供复制。",
- "removeAttachment": "移除",
- "dropOverlay": "拖放文件以添加"
++ "voiceDraftChanged": "语音输入期间草稿已变化,已保留整理结果供复制。"
},
"media": {
"preview": "预览",
@@@ -3183,6 -2893,6 +3205,16 @@@
"sendNow": "立即发送",
"recall": "撤回到输入框",
"remove": "移出队列"
++ },
++ "archived": {
++ "sendBlocked": "该会话已归档,无法发送消息。",
++ "editBlocked": "该会话已归档,无法再修改。"
++ },
++ "annotation": {
++ "titleUser": "用户批注",
++ "titleAgent": "Agent 批注",
++ "resolved": "已处理",
++ "screenshot": "截图"
}
},
"vaults": {
@@@ -3451,12 -3160,515 +3482,556 @@@
"dismiss": "忽略",
"saveAndWake": "保存并让 AI 继续",
"ambiguousProvision": "有多个待处理请求都需要这个密钥。请在 Vaults 里打开对应请求的填写行,这样才能保留请求里的详细设置。",
-- "saveFailed": "保存失败,请重试。"
++ "saveFailed": "保存失败,请重试。",
++ "expired": "该会话已归档,此请求已失效。"
},
"history": "历史",
"audit": {
"title": "最近活动",
"empty": "暂无活动。"
}
+ },
+ "memory": {
+ "title": "记忆",
+ "betaTitle": "记忆 · Beta",
+ "subtitle": "从你的 Workbench 和私聊消息中提炼出的个人记忆——在这里查看、搜索或清除。",
+ "setup": {
+ "runtimeRequired": "请先安装记忆运行时",
+ "runtimeRequiredHint": "请前往依赖页面安装或修复记忆运行时。你仍可在下方停用记忆或清除已存储的数据。"
+ },
+ "tabs": {
+ "status": "状态",
+ "profile": "画像",
+ "search": "搜索",
+ "settings": "设置"
+ },
+ "remoteUnavailable": {
+ "title": "仅限本机访问",
+ "description": "记忆的设置和数据仅在直接连接到本机 Avibe 时可见——通过 Avibe Cloud 或其他远程方式无法访问。"
+ },
+ "status": {
+ "title": "状态",
+ "loading": "正在检查状态…",
+ "loadFailed": "无法加载记忆状态。",
+ "refresh": "刷新",
+ "state": {
+ "disabled": "已禁用",
+ "starting": "启动中",
+ "ready": "就绪",
+ "syncing": "同步中",
+ "degraded": "降级",
+ "down": "不可用",
+ "clearing": "清除中",
+ "error": "错误"
+ },
+ "syncing": "处理中",
+ "succeeded": "成功",
+ "receiptUnknown": "结果未知",
+ "receiptUnknownHint": "已投递,但无法确认是否已提炼(回执丢失)。",
+ "distillFailed": "失败",
+ "dead": "已放弃",
+ "deadHint": "投递未获记忆引擎确认。",
+ "missed": "已跳过",
+ "fault": {
+ "credential": "记忆引擎无法调用已配置的模型接口,请检查 API Key 余额/权限。",
+ "engine": "记忆引擎内部错误,重启引擎通常可以恢复。"
+ },
+ "faultAction": {
+ "credential": "打开凭据设置",
+ "engine": "重启记忆引擎"
+ },
+ "dismissFault": "关闭处理告警",
+ "engineRestartStarted": "已开始重启记忆引擎。",
+ "engineRestartFailed": "记忆引擎重启失败。",
+ "providerTitle": "记忆引擎 (EverOS)",
+ "providerSubtitle": "最近一次提供方回执",
+ "observation": {
+ "succeeded": "成功",
+ "rejected": "拒绝",
+ "unknown": "未知"
+ },
+ "flushStatus": "提供方状态",
+ "flushError": "错误代码",
+ "flushAt": "观察时间",
+ "requestId": "请求 ID",
+ "copyRequestId": "复制请求 ID",
+ "queueBytes": "排队文本",
+ "storageUsed": "本地已用存储",
+ "lastSuccess": "最近提炼成功时间",
+ "lastSuccessNever": "从未",
+ "failureLog": {
+ "title": "失败日志",
+ "subtitle": "保留最近 {{days}} 天的脱敏投递与提炼失败记录。",
+ "empty": "暂无失败记录。",
+ "loadFailed": "无法加载记忆失败日志。",
+ "errorCode": "错误代码",
+ "attempts": "尝试次数",
+ "kind": {
+ "delivery_abandoned": "投递已放弃",
+ "distillation_rejected": "提炼被拒绝",
+ "result_unknown": "处理结果未知"
+ }
+ }
+ },
+ "profile": {
+ "description": "由已捕获的消息提炼出的、你当前的画像。",
+ "loading": "正在加载画像…",
+ "empty": "还没有画像——继续聊天,消息处理后再来看看。",
+ "loadFailed": "无法加载你的画像。",
+ "warningUnavailable": "该提供方暂不支持画像。这是预期行为,不是错误——可以试试搜索,或稍后再来看看。",
+ "disabledHint": "启用记忆后即可查看画像。",
+ "refresh": "刷新",
+ "sourceNote": "由你的对话历史提炼而来。"
+ },
+ "search": {
+ "description": "搜索你的画像、事件和事实。",
+ "placeholder": "搜索你的记忆…",
+ "button": "搜索",
+ "searching": "搜索中…",
+ "empty": "没有结果。",
+ "searchFailed": "搜索失败。",
+ "disabledHint": "启用记忆后即可搜索。",
+ "sourceNote": "由你的对话历史提炼而来。"
+ },
+ "settings": {
+ "loading": "正在加载设置…",
+ "loadFailed": "无法加载记忆设置。",
+ "enableLabel": "记忆",
+ "enableHint": "将符合条件的 Workbench 消息和已绑定、已启用用户的私聊消息提炼为按用户隔离的可搜索记忆。",
+ "dependencyNotReady": "memory-runtime 依赖尚未就绪。请先在「设置 → 依赖」中安装或修复,然后重新尝试启用记忆。",
+ "goToDependencies": "前往依赖页面",
+ "llmTitle": "LLM 端点",
+ "embeddingTitle": "Embedding 端点",
+ "baseUrl": "Base URL",
+ "baseUrlPlaceholder": "https://api.example.com/v1",
+ "model": "模型",
+ "modelPlaceholder": "模型名称",
+ "apiKey": "API Key",
+ "apiKeySet": "已设置密钥——留空可保留原值。",
+ "apiKeyNotSet": "尚未设置密钥。",
+ "apiKeyPlaceholder": "sk-…",
+ "apiKeyClearHint": "密钥仅可写入——Avibe 不会把已保存的密钥回显给你。",
+ "embeddingLocked": "已有记忆数据时无法更改 Embedding 端点或模型,请先执行「清除全部」。",
+ "embeddingStatusPending": "正在确认记忆状态……确认没有数据后,Embedding 端点将解锁。",
+ "save": "保存设置",
+ "saving": "保存中…",
+ "saveFailed": "无法保存记忆设置。",
+ "saved": "记忆设置已保存。",
+ "disclosureTitle": "启用记忆前请了解",
+ "disclosure": [
+ "符合条件的 Workbench 文本和已绑定、已启用用户的私聊文本会被复制到有界本地队列中等待处理。",
+ "一条消息处理成功或重试耗尽后,其文本会立即被清除;一个不含内容的去重标记最多保留 90 天,且以最新的 100,000 条为上限。",
+ "记忆使用的 LLM 与 Embedding 端点与你的 Agent 模型订阅是分开的。",
+ "这些远程端点会接收到被捕获的文本或搜索查询,并可能按其自身策略保留。",
+ "私聊文本在被捕获前已经过该平台传输,并继续受该平台自身的留存与同步策略约束。",
+ "本地运行时除了可见的画像外,还会在本地状态中保留尚未处理的原始消息和提取数据。",
+ "禁用记忆只会冻结本地数据,不会删除——如需删除请使用「清除全部」。",
+ "「清除全部」只会移除本机上的本地记忆数据,无法追回已发送到远程端点的副本,也不会影响原始聊天记录。",
+ "发往记忆端点的投递是至少一次——超时或崩溃后偶尔可能出现重复的派生记忆。",
+ "每个平台用户拥有独立的记忆范围;不同平台之间不会自动关联身份。"
+ ],
+ "clearKeyLabel": "清除已保存的密钥"
+ },
+ "clear": {
+ "button": "清除全部",
+ "confirmTitle": "清除全部本地记忆数据?",
+ "confirmDescription": "这会移除你的画像、事件、事实,以及本机上任何尚未处理的排队文本。",
+ "removesTitle": "将会移除:",
+ "removes": [
+ "你可见的画像",
+ "用于构建画像的隐藏本地缓冲区和索引",
+ "本地处理队列中待处理和已完成的条目"
+ ],
+ "keepsTitle": "不会移除:",
+ "keeps": [
+ "你原始的 Avibe 聊天记录",
+ "已发送到远程记忆端点的副本",
+ "你自己创建的副本或快照",
+ "存储在专用记忆目录之外的任何数据",
+ "现有的日志、崩溃报告或备份",
+ "存储设备上的物理残留——这不是安全擦除"
+ ],
+ "confirmLabel": "清除全部",
+ "clearing": "清除中…",
+ "cleared": "记忆数据已清除。",
+ "failed": "清除失败。"
+ },
+ "kind": {
+ "profile": "画像",
+ "episode": "事件",
+ "fact": "事实"
+ }
+ },
+ "organization": {
+ "nav": {
+ "overview": "概览",
+ "instances": "Avibe",
+ "members": "成员",
+ "groups": "群组",
+ "resources": "资源"
+ },
+ "actions": {
+ "backToControlPanel": "控制面板",
+ "openRemoteAccess": "打开远程访问",
+ "signIn": "登录 Avibe Cloud",
+ "signInAgain": "使用同一账号重新登录",
+ "signOut": "退出组织管理",
+ "reload": "查看最新版本",
+ "saving": "保存中...",
+ "saveChanges": "保存更改",
+ "sendInvite": "发送邀请",
+ "inviteMember": "邀请成员",
+ "editMember": "编辑成员",
+ "removeMember": "移除成员",
+ "resendInvite": "重新发送邀请",
+ "exportCsv": "导出 CSV",
+ "newGroup": "新建群组",
+ "editGroup": "编辑群组",
+ "archiveGroup": "归档群组",
+ "restoreGroup": "恢复群组",
+ "manageMembers": "管理成员",
+ "saveMembers": "保存成员",
+ "addAccess": "添加访问权限",
+ "editAccess": "编辑访问权限",
+ "removeAccess": "移除访问权限",
+ "addBinding": "添加绑定",
+ "removeBinding": "移除绑定",
+ "manage": "管理"
+ },
+ "roles": {
+ "owner": "所有者",
+ "admin": "管理员",
+ "member": "成员"
+ },
+ "status": {
+ "active": "活跃",
+ "invited": "已邀请",
+ "removed": "已移除"
+ },
+ "sync": {
+ "none": "没有受管策略",
+ "in_sync": "已同步",
+ "applying": "应用中",
+ "offline": "离线",
+ "error": "错误",
+ "deleted": "已删除"
+ },
+ "sidebar": {
+ "section": "组织",
+ "organizationCount": "{{count}} 个组织",
+ "switchOrganization": "切换组织",
+ "cloudConnected": "Cloud 已连接",
+ "sessionRemaining": "管理会话 · {{minutes}} 分钟",
+ "openMenu": "打开组织菜单"
+ },
+ "states": {
+ "loadingTitle": "正在加载组织",
+ "loadingBody": "正在从 Avibe Cloud 获取最新组织数据。",
+ "notConnectedTitle": "尚未连接 Avibe Cloud",
+ "notConnectedBody": "请先将此 Avibe 连接到 Avibe Cloud,再打开组织管理。",
+ "signInTitle": "需要登录",
+ "signInBody": "登录 Avibe Cloud,以建立短期有效的组织管理会话。",
+ "reauthorizingTitle": "正在重新授权",
+ "reauthorizingBody": "正在使用同一 Cloud 账号恢复组织管理会话。",
+ "mismatchTitle": "Cloud 账号不匹配",
+ "mismatchBody": "当前 Avibe 会话与 Cloud 账号属于不同用户。请使用建立此 Avibe 会话的同一账号重新登录。",
+ "unreachableTitle": "无法连接 Avibe Cloud",
+ "unreachableBody": "暂时无法获取组织数据,本地 Avibe 仍可正常使用。",
+ "revokedTitle": "组织访问权限已撤销",
+ "revokedBody": "此管理会话已失效。请重新登录以确认当前权限。",
+ "emptyTitle": "没有可用组织",
+ "emptyBody": "当前 Cloud 账号不是任何组织的活跃成员。",
+ "unavailableTitle": "无法访问此组织页面",
+ "unavailableBody": "当前组织权限或 Avibe 权限不允许访问此页面。",
+ "errorTitle": "无法完成请求",
+ "conflictTitle": "策略已在其他位置更改",
+ "conflictBody": "你的草稿尚未保存。请先检查草稿,再重新加载最新版本后继续修改。"
+ },
+ "errors": {
+ "generic": "Avibe 无法完成此组织请求。",
+ "forbidden": "当前组织角色不允许执行此操作。",
+ "organization_not_found": "无法访问此组织。",
+ "organization_member_not_found": "此成员已不可用。",
+ "organization_group_not_found": "此群组已不可用。",
+ "organization_group_archived": "不能把已归档群组添加到新策略。",
+ "instance_not_found": "无法访问此 Avibe。",
+ "project_not_found": "无法访问此 Project。",
+ "resource_not_found": "无法访问此资源。",
+ "member_email_taken": "该邮箱已属于此组织。",
+ "group_name_taken": "已存在同名群组。",
+ "too_many_entries": "此策略包含过多条目。",
+ "invalid_project_access_intent": "请选择有效的 Project 访问规则。",
+ "invalid_project_access_principal": "某个 Project 访问主体无效。",
+ "invalid_project_access_role": "某个 Project 访问角色无效。",
+ "invalid_resource_acl_intent": "请选择有效的资源受众。",
+ "invalid_email": "请输入有效的邮箱地址。",
+ "invalid_domain": "请输入有效的邮箱域名。",
+ "duplicate_instance_access_principal": "同一个 Avibe 访问主体只能出现一次。",
+ "duplicate_project_access_principal": "同一个 Project 主体只能出现一次。",
+ "owner_entry_locked": "不能修改 Avibe 所有者的隐式访问权限。",
+ "resource_sync_conflict": "策略已在其他位置更改,请检查最新版本后再保存。",
+ "organization_member_conflict": "成员已在其他位置更改,请检查最新版本后重试。",
+ "organization_group_conflict": "群组已在其他位置更改,请检查最新版本后重试。"
+ },
+ "fields": {
+ "name": "名称",
+ "description": "描述",
+ "color": "颜色",
+ "email": "邮箱",
+ "role": "角色",
+ "groups": "群组",
+ "member": "成员",
+ "status": "状态",
+ "principalType": "主体类型",
+ "principal": "访问主体"
+ },
+ "colors": {
+ "mint": "薄荷绿",
+ "cyan": "青色",
+ "blue": "蓝色",
+ "violet": "紫罗兰",
+ "rose": "玫红",
+ "gold": "金色"
+ },
+ "principals": {
+ "organization_group": "群组",
+ "email": "邮箱",
+ "email_domain": "邮箱域名"
+ },
+ "breadcrumb": {
+ "overview": "组织 / 概览",
+ "members": "组织 / 成员",
+ "groups": "组织 / 群组",
+ "groupDetail": "组织 / 群组 / {{name}}",
+ "instances": "组织 / Avibe",
+ "resources": "组织 / 资源"
+ },
+ "overview": {
+ "description": "管理此组织的成员、访问权限和策略同步状态。",
+ "memberDescription": "查看你的组织成员身份和可访问的 Avibe。",
+ "memberBreakdown": "{{invited}} 个已邀请 · {{removed}} 个已移除",
+ "groupBreakdown": "{{archived}} 个已归档",
+ "projects": "Project",
+ "projectCountUnavailable": "计数暂不可用",
+ "policySync": "策略同步",
+ "needsAttention": "需要处理",
+ "instanceNeedsAttention": "{{name}} 的策略变更需要处理。",
+ "projectSyncNeedsAttention": "{{name}} 的 Project 策略需要处理。",
+ "resourceSyncNeedsAttention": "{{name}} 的资源策略需要处理。",
+ "noAttention": "所有可见的受管策略状态正常。",
+ "pendingInvites": "待接受邀请",
+ "pendingInvitesBody": "有 {{count}} 个邀请等待接受。",
+ "viewAllInstances": "查看全部 Avibe",
+ "memberSafeTitle": "成员视图",
+ "memberSafeBody": "你可以查看自己的成员身份和可访问的 Avibe。成员目录和资源策略构成仅对组织管理者可见。"
+ },
+ "members": {
+ "description": "邀请成员、分配组织角色并管理群组成员关系。",
+ "memberDescription": "查看你的组织角色和群组成员关系。",
+ "filterLabel": "筛选成员",
+ "filterAll": "全部",
+ "active": "活跃",
+ "invited": "已邀请",
+ "removed": "已移除",
+ "admins": "管理员",
+ "searchPlaceholder": "搜索成员...",
+ "emptyTitle": "没有找到成员",
+ "emptyBody": "当前视图中没有匹配的成员。",
+ "inviteTitle": "邀请成员",
+ "inviteBody": "发送组织邀请,并可选择初始群组。",
+ "editTitle": "编辑成员",
+ "editBody": "角色和完整群组成员关系共用同一 revision。",
+ "emailPlaceholder": "[email protected]",
+ "downgradeTitle": "将此管理员降级?",
+ "downgradeBody": "{{email}} 将失去组织管理权限,其成员身份和群组分配保持不变。",
+ "downgradeConfirm": "降级为成员",
+ "removeTitle": "移除此成员?",
+ "removeBody": "{{email}} 将失去组织成员身份以及由此获得的全部权限。"
+ },
+ "groups": {
+ "description": "创建可复用的组织受众,并检查引用这些群组的全部策略。",
+ "memberDescription": "查看组织群组和你自己的群组成员关系。",
+ "active": "活跃",
+ "archived": "已归档",
+ "filterLabel": "筛选群组",
+ "searchPlaceholder": "搜索群组...",
+ "emptyTitle": "没有找到群组",
+ "emptyBody": "当前视图中没有匹配的群组。",
+ "noDescription": "没有描述",
+ "yourGroup": "我的群组",
+ "createTitle": "创建群组",
+ "createBody": "创建组织群组,并可选择初始成员。",
+ "editTitle": "编辑群组",
+ "editBody": "更新群组的展示信息。",
+ "initialMembers": "初始成员",
+ "manageMembersTitle": "管理群组成员",
+ "manageMembersBody": "替换 {{name}} 的完整成员列表。",
+ "referencedBy": "引用位置",
+ "moreReferences": "另有 {{count}} 项",
+ "archiveTitle": "归档此群组?",
+ "archiveBody": "{{name}} 被 {{count}} 个活跃策略项引用。",
+ "archiveImpactTitle": "归档影响",
+ "archiveImpactBody": "现有引用仍会显示,但不再授予访问权限;已归档群组不能加入新策略。"
+ },
+ "instances": {
+ "description": "你可以看到的组织 Avibe。可管理访问权限和 Project 策略,但不会改变配对或域名。",
+ "searchPlaceholder": "搜索 Avibe...",
+ "emptyTitle": "没有找到 Avibe",
+ "emptyBody": "当前视图中没有可用的组织 Avibe。",
+ "you": "你",
+ "organizationOwner": "Avibe 所有者",
+ "ownerProtected": "所有者身份受保护",
+ "youAreOwner": "你是此 Avibe 的所有者",
+ "paired": "已配对",
+ "notPaired": "未配对",
+ "accessCount": "{{count}} 条访问规则",
+ "accessTab": "访问权限",
+ "projectsTab": "Project",
+ "tabsLabel": "Avibe 管理视图",
+ "columns": {
+ "instance": "Avibe",
+ "owner": "所有者",
+ "address": "公开地址",
+ "status": "状态",
+ "access": "访问规则",
+ "sync": "同步"
+ },
+ "status": {
+ "pending": "等待中",
+ "active": "在线",
+ "disabled": "已停用",
+ "deleted": "已删除"
+ }
+ },
+ "access": {
+ "viewer": "查看者",
+ "editor": "编辑者",
+ "ownerTitle": "{{owner}} · Avibe 所有者",
+ "ownerBody": "这是隐式的所有者同等权限,不能作为普通条目编辑或移除。",
+ "emptyTitle": "没有显式访问条目",
+ "emptyBody": "当前只有隐式的 Avibe 所有者可以访问。",
+ "addTitle": "添加 Avibe 访问权限",
+ "editTitle": "编辑 Avibe 访问权限",
+ "dialogBody": "为群组、单个邮箱或邮箱域名授予查看者或编辑者权限。",
+ "emailPlaceholder": "[email protected]",
+ "domainPlaceholder": "example.com",
+ "narrowTitle": "收窄此访问权限?",
+ "narrowBody": "保存后,原访问主体或编辑能力将不再生效。",
+ "removeTitle": "移除此访问条目?",
+ "removeBody": "{{principal}} 将失去此条目授予的访问权限。",
+ "columns": {
+ "principal": "访问主体",
+ "type": "类型",
+ "role": "角色"
+ }
+ },
+ "projects": {
+ "searchPlaceholder": "搜索 Project...",
+ "safeDescriptorNotice": "这里只显示安全描述信息,不会显示或发送本地 Project 路径。Project 权限只能收窄 Avibe 角色。",
+ "emptyTitle": "没有找到 Project",
+ "emptyBody": "此 Avibe 尚未发布活跃的受管 Project 描述信息。",
+ "accessRule": "访问规则",
+ "bindings": "受限绑定",
+ "bindingRequired": "受限访问至少需要一个绑定。",
+ "usesAvibeRole": "使用 Avibe 角色",
+ "ownerOnlyAudience": "仅 Avibe 所有者",
+ "bindingCount": "{{count}} 个绑定",
+ "dialogTitle": "管理 {{name}} 的访问权限",
+ "dialogBody": "组织管理权限只允许你修改此策略,不会因此获得 Project 使用权限。",
+ "narrowTitle": "收窄此 Project 的访问权限?",
+ "narrowBody": "此更改会移除现有受众、将编辑者降为查看者,或切换到更严格的规则。",
+ "modes": {
+ "inherit": "继承",
+ "restricted": "受限",
+ "owner_only": "仅所有者"
+ },
+ "modeHelp": {
+ "inherit": "使用各访问主体在此 Avibe 上的有效角色。",
+ "restricted": "允许一个或多个明确的群组、邮箱或域名;此规则只能收窄 Avibe 角色。",
+ "owner_only": "只有此 Avibe 的所有者可以使用此 Project。组织管理者可以管理策略,但不会因此获得使用权限。"
+ },
+ "columns": {
+ "project": "Project",
+ "rule": "访问规则",
+ "bindings": "绑定",
+ "sync": "同步"
+ }
+ },
+ "resources": {
+ "description": "管理每项资源可由哪些组织受众使用。可以使用资源不代表可以编辑、删除或再次分享资源。",
+ "tabsLabel": "资源类型",
+ "accessLevel": "受众",
+ "selectGroups": "选择群组",
+ "groupRequired": "请至少选择一个群组。",
+ "dialogTitle": "管理 {{name}} 的受众",
+ "dialogBody": "选择私有、整个组织或指定组织群组。",
+ "narrowTitle": "收窄此资源的受众?",
+ "narrowBody": "部分当前可以使用此资源的成员将在更改后失去访问权限。",
+ "emptyTitle": "没有找到资源",
+ "emptyBody": "没有可用的活跃{{kind}}描述信息。",
+ "everyActiveMember": "每个活跃成员",
+ "ownerOnly": "仅资源所有者",
+ "kinds": {
+ "agent": "Agent",
+ "vault_secret": "Vault 密钥",
+ "skill": "Skill",
+ "show_page": "Show Page"
+ },
+ "levels": {
+ "private": "私有",
+ "public": "组织",
+ "scope": "指定群组"
+ },
+ "levelHelp": {
+ "private": "通过此组织 ACL,仅资源所有者可以使用。",
+ "public": "此组织的每个活跃成员都可以使用,但仍需满足其他全部权限层。",
+ "scope": "只有指定群组的活跃成员可以使用,并且仍需满足其他全部权限层。"
+ },
+ "columns": {
+ "access": "访问级别",
+ "audience": "受众",
+ "sync": "同步"
+ }
+ }
++ },
++ "models": {
++ "eligibility": {
++ "subscription_wrong_client": "{{vendor}} 订阅仅可供 {{backend}} 使用",
++ "opencode_api_key_only": "OpenCode 只能由 API Key 来源供给",
++ "consent_required": "需要先同意实验性中枢供给"
++ },
++ "oauth": {
++ "upstream_failed": "厂商没有完成这次登录,请重试",
++ "engine_unavailable": "中枢没有响应,请重试",
++ "submission_failed": "粘贴的内容没能提交,请重试",
++ "ambiguous_engine_binding": "分不清登录的是哪个账号,请一次只登一个再重试",
++ "binding_failed": "该账号已被另一来源使用",
++ "expired": "授权超时,请重新连接"
++ },
++ "probe": {
++ "native_cli_unavailable": "用不上 CLI 的登录",
++ "no_candidate": {
++ "waiting": "所有来源都在冷却",
++ "interrupted": "现在没有来源能提供这个模型"
++ }
++ },
++ "source": {
++ "cooldown": {
++ "network": "网络不通",
++ "timeout": "连续超时",
++ "rate_limited": "触发限流",
++ "quota_exhausted": "本周期额度用完",
++ "server_error": "上游服务异常"
++ },
++ "needs_action": {
++ "oauth_expired": "需要重新登录",
++ "balance_exhausted": "余额不足,需要充值",
++ "credential_revoked": "凭据已失效,需要重新填写",
++ "account_banned": "账号被限制使用"
++ },
++ "error": {
++ "unclassified": "未知错误,暂时不可用"
++ }
++ }
}
}
diff --cc ui/src/lib/apiFetch.test.ts
index 6b342d642,dd728149b..6a08fd71b
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@@ -49,72 -50,14 +51,83 @@@ describe('apiFetch remote auth recovery
expect(deferRemoteAuthRedirect).not.toHaveBeenCalled();
});
+ it('honors the request signal while a shared CSRF request is pending', async () => {
+ let resolveCsrf!: (response: Response) => void;
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL) =>
+ new Promise<Response>((resolve) => {
+ expect(input).toBe('/api/csrf-token');
+ resolveCsrf = resolve;
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const controller = new AbortController();
+ const request = apiFetch('/api/asr/transcribe', {
+ method: 'POST',
+ signal: controller.signal,
+ });
+
+ controller.abort(new DOMException('transcription timed out', 'TimeoutError'));
+
+ await expect(request).rejects.toMatchObject({ name: 'TimeoutError' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ // Let the shared mint settle so it cannot leak into later tests.
+ resolveCsrf(Response.json({ csrf_token: 'token' }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+ it('does not impose the voice deadline on callers without a signal', async () => {
+ vi.useFakeTimers();
+ let resolveCsrf!: (response: Response) => void;
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(
+ () => new Promise<Response>((resolve) => {
+ resolveCsrf = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(Response.json({ ok: true }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const request = apiFetch('/api/settings', { method: 'POST' });
+ await vi.advanceTimersByTimeAsync(4_001);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ resolveCsrf(Response.json({ csrf_token: 'token' }));
+ await expect(request).resolves.toMatchObject({ status: 200 });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('evicts a stalled shared CSRF fetch after a deadline-bound caller aborts', async () => {
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => new Promise<Response>(() => undefined))
+ .mockResolvedValueOnce(Response.json({ csrf_token: 'fresh-token' }))
+ .mockResolvedValueOnce(Response.json({ text: 'ok' }));
+ vi.stubGlobal('fetch', fetchMock);
+ const controller = new AbortController();
+
+ const stalled = apiFetch('/api/asr/transcribe', {
+ method: 'POST',
+ signal: controller.signal,
+ });
+ const stalledResult = expect(stalled).rejects.toMatchObject({ name: 'TimeoutError' });
+ controller.abort(new DOMException('transcription timed out', 'TimeoutError'));
+
+ await stalledResult;
+ await expect(apiFetch('/api/asr/transcribe', { method: 'POST' })).resolves.toMatchObject({
+ status: 200,
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
++
+ it('recovers from a successful session probe that requires authorization refresh', async () => {
+ await recoverRemoteAuthFromSessionProbe(Response.json({
+ remote: true,
+ authenticated: false,
+ authorization_refresh_required: true,
+ }));
+
+ expect(deferRemoteAuthRedirect).toHaveBeenCalledOnce();
+ expect(window.location.assign).not.toHaveBeenCalled();
+ });
});
diff --cc ui/src/lib/useMessageSearch.ts
index 8fd65889b,144ebff36..d20e95e12
--- a/ui/src/lib/useMessageSearch.ts
+++ b/ui/src/lib/useMessageSearch.ts
@@@ -29,10 -26,9 +29,10 @@@ export function useMessageSearch
query: string,
opts?: UseMessageSearchOptions,
): UseMessageSearchState {
- const { searchMessages } = useApi();
+ const { connectWorkbenchEvents, searchMessages } = useApi();
const minLength = opts?.minLength ?? 1;
const debounceMs = opts?.debounceMs ?? 200;
+ const includeArchived = opts?.includeArchived ?? false;
const [results, setResults] = useState<MessageSearchResult | null>(null);
const [loading, setLoading] = useState(false);
@@@ -86,7 -93,7 +97,7 @@@
window.clearTimeout(timer);
seqRef.current += 1;
};
- }, [query, minLength, debounceMs, includeArchived, searchMessages]);
- }, [query, minLength, debounceMs, searchMessages, authorizationVersion]);
++ }, [query, minLength, debounceMs, includeArchived, searchMessages, authorizationVersion]);
return { results, loading, error };
}
diff --cc ui/src/lib/useNewSession.test.ts
index 94ed2341b,a8c575136..61d6592ad
--- a/ui/src/lib/useNewSession.test.ts
+++ b/ui/src/lib/useNewSession.test.ts
@@@ -1,72 -1,86 +1,146 @@@
- import { describe, expect, it } from 'vitest';
+ import { describe, expect, it, vi } from 'vitest';
-import type { VibeAgentBrief } from '../context/ApiContext';
-import { createLatestAgentProjectionLoader } from './useNewSession';
+import type { VibeAgentBrief, WorkbenchProject } from '../context/ApiContext';
- import { isProjectDefaultAgentAvailable, projectDefaultAgentRoute } from './useNewSession';
++import {
++ createLatestAgentProjectionLoader,
++ isProjectDefaultAgentAvailable,
++ projectDefaultAgentRoute,
++} from './useNewSession';
+
+const project = (agentName: string): WorkbenchProject =>
+ ({
+ default_agent: { agent_name: agentName },
+ }) as WorkbenchProject;
+
+const agent = (over: Partial<VibeAgentBrief>): VibeAgentBrief =>
+ ({
+ id: 'agent-1',
+ name: 'pm',
+ display_name: 'pm',
+ description: null,
+ backend: 'claude',
+ model: null,
+ reasoning_effort: null,
+ enabled: true,
+ archived: false,
+ archived_at: null,
+ source: 'user',
+ updated_at: '2026-08-01T00:00:00Z',
+ ...over,
+ }) as VibeAgentBrief;
+
+describe('isProjectDefaultAgentAvailable', () => {
+ it('accepts an enabled live project default', () => {
+ expect(isProjectDefaultAgentAvailable(project('pm'), [agent({})])).toBe(true);
+ });
+
+ it('accepts a legacy normalized-equivalent project default', () => {
+ expect(
+ isProjectDefaultAgentAvailable(
+ project('PROJECT-MANAGER'),
+ [agent({ name: 'Project Manager' })],
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects an archived internal project default that is absent from the live catalog', () => {
+ expect(isProjectDefaultAgentAvailable(project('_pm-8dd7'), [agent({ name: 'codex' })])).toBe(false);
+ });
+
+ it('rejects disabled or archived catalog entries', () => {
+ expect(isProjectDefaultAgentAvailable(project('pm'), [agent({ enabled: false })])).toBe(false);
+ expect(isProjectDefaultAgentAvailable(project('pm'), [agent({ archived: true })])).toBe(false);
+ });
+});
+
+describe('projectDefaultAgentRoute', () => {
+ it('pins the project Agent by stable ID for session creation', () => {
+ const target = project('pm');
+ target.default_agent = {
+ agent_backend: 'claude',
+ agent_id: 'agent-original',
+ agent_name: 'pm',
+ agent_variant: 'claude',
+ model: 'claude-opus-5',
+ reasoning_effort: 'high',
+ };
+
+ expect(projectDefaultAgentRoute(target, [agent({ id: 'agent-replacement' })])).toEqual({
+ agent_name: 'pm',
+ agent_id: 'agent-original',
+ agent_variant: 'claude',
+ model: 'claude-opus-5',
+ reasoning_effort: 'high',
+ });
+ });
+});
+
+ const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+ };
+
-const agent = (name: string): VibeAgentBrief => ({
- id: name,
- name,
- description: null,
- backend: 'codex',
- model: null,
- reasoning_effort: null,
- enabled: true,
- source: 'user',
- updated_at: '2026-01-01T00:00:00Z',
-});
-
+ type AgentProjection = {
+ ok: boolean;
+ agents: VibeAgentBrief[];
+ default_agent_name: string | null;
+ };
+
+ describe('createLatestAgentProjectionLoader', () => {
+ it('ignores a pre-revocation response that completes after the refreshed projection', async () => {
+ const stale = deferred<AgentProjection>();
+ const refreshed = deferred<AgentProjection>();
+ const fetchAgents = vi
+ .fn()
+ .mockImplementationOnce(() => stale.promise)
+ .mockImplementationOnce(() => refreshed.promise);
+ const applyProjection = vi.fn();
+ const setProjectionLoaded = vi.fn();
+ const loader = createLatestAgentProjectionLoader(fetchAgents, applyProjection, setProjectionLoaded);
+
+ const initialLoad = loader.load();
+ const authorizationRefresh = loader.load();
+ expect(setProjectionLoaded.mock.calls).toEqual([[false], [false]]);
+ const authorizedProjection = {
+ ok: true,
- agents: [agent('still-authorized')],
++ agents: [agent({ id: 'still-authorized', name: 'still-authorized' })],
+ default_agent_name: 'still-authorized',
+ };
+ refreshed.resolve(authorizedProjection);
+ await authorizationRefresh;
+
+ stale.resolve({
+ ok: true,
- agents: [agent('revoked')],
++ agents: [agent({ id: 'revoked', name: 'revoked' })],
+ default_agent_name: 'revoked',
+ });
+ await initialLoad;
+
+ expect(applyProjection).toHaveBeenCalledTimes(1);
+ expect(applyProjection).toHaveBeenCalledWith(authorizedProjection);
+ expect(setProjectionLoaded.mock.calls).toEqual([[false], [false], [true]]);
+ });
+
+ it('marks a failed latest projection resolved without applying stale data', async () => {
+ const failed = deferred<AgentProjection>();
+ const applyProjection = vi.fn();
+ const setProjectionLoaded = vi.fn();
+ const loader = createLatestAgentProjectionLoader(
+ () => failed.promise,
+ applyProjection,
+ setProjectionLoaded,
+ );
+
+ const load = loader.load();
+ failed.reject(new Error('network failed'));
+ await load;
+
+ expect(applyProjection).toHaveBeenCalledWith(null);
+ expect(setProjectionLoaded.mock.calls).toEqual([[false], [true]]);
+ });
+ });
diff --cc vibe/api.py
index 603a7a9a7,48eb88211..7c1f1c08d
--- a/vibe/api.py
+++ b/vibe/api.py
@@@ -69,10 -68,7 +69,11 @@@ from modules.agents.catalog import
)
from modules.agents.subagent_router import list_codex_subagents
from core.vibe_agents import (
+ AgentArchivedEditError,
+ AgentArchiveError,
+ AgentNameValidationError,
+ AgentReferenceRewriteError,
+ VibeAgentAccessError,
VibeAgentStore,
iter_global_agent_files,
parse_agent_file,
@@@ -1336,20 -1386,13 +1394,22 @@@ def _parse_agent_enabled_field(payload
raise ValueError("Agent enabled must be a JSON boolean")
-def get_vibe_agents(*, backend: Optional[str] = None, include_disabled: bool = False) -> dict:
+def get_vibe_agents(
+ *,
+ backend: Optional[str] = None,
+ include_disabled: bool = False,
+ include_archived: bool = False,
+) -> dict:
_ensure_builtin_default_agents()
+ user_context = resolve_resource_access_context()
store = VibeAgentStore()
try:
normalized_backend = validate_agent_backend(backend) if backend else None
- agents = store.list_agents(include_disabled=include_disabled, user_context=user_context)
+ agents = store.list_agents(
+ include_disabled=include_disabled,
+ include_archived=include_archived,
++ user_context=user_context,
+ )
if normalized_backend:
agents = [agent for agent in agents if agent.backend == normalized_backend]
default_agent = store.get_default_agent()
@@@ -1384,19 -1529,17 +1546,20 @@@ def create_vibe_agent(payload: dict) -
raise ValueError("Agent metadata must be an object")
store = VibeAgentStore()
try:
- agent = store.create(
- name=str(payload.get("name") or "").strip(),
- backend=validate_agent_backend(str(payload.get("backend") or "")),
- description=payload.get("description"),
- model=payload.get("model"),
- reasoning_effort=payload.get("reasoning_effort") or payload.get("effort"),
- system_prompt=payload.get("system_prompt"),
- metadata=metadata,
- enabled=_parse_agent_enabled_field(payload, default=True),
- user_context=resolve_resource_access_context(),
- )
+ try:
+ agent = store.create(
+ name=str(payload.get("name") or "").strip(),
+ backend=validate_agent_backend(str(payload.get("backend") or "")),
+ description=payload.get("description"),
+ model=payload.get("model"),
+ reasoning_effort=payload.get("reasoning_effort") or payload.get("effort"),
+ system_prompt=payload.get("system_prompt"),
+ metadata=metadata,
+ enabled=_parse_agent_enabled_field(payload, default=True),
++ user_context=resolve_resource_access_context(),
+ )
+ except AgentNameValidationError as exc:
+ return _agent_name_validation_error(exc)
return {"ok": True, "agent": _vibe_agent_payload(agent)}
finally:
store.close()
@@@ -1448,14 -1589,8 +1611,19 @@@ def update_vibe_agent(name: str, payloa
store = VibeAgentStore()
try:
+ context = resolve_resource_access_context()
- agent = store.update(name, user_context=context, **kwargs)
+ try:
- agent = store.rename(name, new_name) if renaming else store.update(name, **kwargs)
++ agent = (
++ store.rename(name, new_name, user_context=context)
++ if renaming
++ else store.update(name, user_context=context, **kwargs)
++ )
+ except AgentNameValidationError as exc:
+ return _agent_name_validation_error(exc)
+ except AgentArchivedEditError as exc:
+ return _agent_archived_edit_error(exc)
+ except AgentReferenceRewriteError as exc:
+ return _agent_reference_rewrite_error(exc)
return {"ok": True, "agent": _vibe_agent_payload(agent)}
finally:
store.close()
@@@ -1506,33 -1599,27 +1674,35 @@@ def _agent_reference_rewrite_error(exc
def remove_vibe_agent(name: str) -> dict:
store = VibeAgentStore()
try:
+ context = resolve_resource_access_context()
+ store.require_manageable(name, user_context=context)
- counts = store.reference_counts(name)
- if any(counts.values()):
- return {
- "ok": False,
- "code": "agent_in_use",
- "message": f"agent '{name}' is still referenced",
- "references": counts,
- }
try:
- archived = store.archive(name)
- removed = store.remove(name, user_context=context)
- except ValueError as exc:
++ archived = store.archive(name, user_context=context)
+ except AgentArchiveError as exc:
+ try:
+ lang = V2Config.load().language
+ except Exception:
+ lang = "en"
return {
"ok": False,
- "code": "agent_builtin",
- "message": str(exc),
+ "code": exc.code,
+ "message": backend_t(
+ f"error.agentArchive.{exc.code}.message",
+ lang,
+ agent=exc.agent_name,
+ ),
}
- if not removed:
+ except AgentReferenceRewriteError as exc:
+ return _agent_reference_rewrite_error(exc)
+ if archived is None:
return {"ok": False, "code": "agent_not_found", "message": f"agent '{name}' not found"}
- return {"ok": True, "removed_agent": name}
+ return {
+ "ok": True,
+ "removed_agent": archived.original_name,
+ "archived_agent": _vibe_agent_payload(archived.agent, brief=True),
+ "references": archived.references,
+ "default_agent_name": archived.default_agent_name,
+ }
finally:
store.close()
diff --cc vibe/i18n/en.json
index 8d19fed02,7be7b60aa..ae56c777c
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@@ -33,109 -25,11 +25,110 @@@
"invalidCommand": "The watch worker command is invalid."
}
},
+ "queueCoalesced": {
+ "summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",
+ "messagesLabel": "Coalesced callback messages:",
+ "latestLabel": "Latest callback message after {additional} additional trigger(s):",
+ "burstHint": "This callback source is firing frequently. Inspect the related watch/task and pause, remove, or update it if it is looping."
++ },
++ "agentInitiatedContinuation": "Agent-initiated continuation",
+ "command": {
+ "workdirMissing": "Working directory does not exist: {cwd}",
+ "supervisorExitedDuringStartup": "Command supervisor exited during startup.",
+ "workerNotRecorded": "The command was not started because its worker could not be recorded.",
+ "supervisorFailed": "Command supervisor failed: {detail}",
+ "unknownSupervisorFailure": "Unknown supervisor failure.",
+ "protocolErrors": {
+ "specTooLarge": "The command specification is too large.",
+ "invalidEncoding": "The command specification is not valid UTF-8.",
+ "invalidJson": "The command specification is not valid JSON.",
+ "unsupportedVersion": "The command specification version is unsupported.",
+ "invalidCommand": "The command is invalid."
+ },
+ "timedOut": "Command timed out after {seconds} second(s).",
+ "exited": "Command exited with status {code}.",
+ "exitedWithDetail": "Command exited with status {code}: {detail}"
+ },
+ "task": {
+ "resultNotRecorded": "The result of this run could not be recorded: the task was reclaimed, repointed or removed while it was running, so its stored state is unchanged."
+ },
- "queueCoalesced": {
- "summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",
- "messagesLabel": "Coalesced callback messages:",
- "latestLabel": "Latest callback message after {additional} additional trigger(s):",
- "burstHint": "This callback source is firing frequently. Inspect the related watch/task and pause, remove, or update it if it is looping."
- },
+ "run": {
+ "interrupted": {
+ "noTerminalResult": "[Avibe Harness] This run ended without the Agent producing a result. The turn was released before the Agent replied, so no output was recorded. Check the Agent logs, then run it again if the work still needs doing.",
+ "stopped": "[Avibe Harness] This run was stopped before the Agent produced a result, so it has no final result. Any output the Agent had already sent is still kept on the run.",
+ "refusedConcurrentTurn": "[Avibe Harness] This run was skipped because another turn was already in flight for the same session. A session runs one turn at a time; trigger it again once the current turn finishes.",
+ "backendRefresh": "[Avibe Harness] This run was interrupted because its Agent runtime was refreshed while the run was in flight, usually right after an Agent setting was saved. Nothing is wrong with the run itself — trigger it again.",
+ "restarted": "[Avibe Harness] This run was interrupted because the service shut down while it was in flight. The interrupted attempt was recorded and will not be replayed after restart. Trigger it again if the work still needs doing.",
+ "interrupted": "[Avibe Harness] This run was interrupted while it was in flight. The interrupted attempt was recorded and was not requeued. Trigger it again if the work still needs doing.",
+ "orphaned": "[Avibe Harness] This run was left marked as running with nothing executing it, most likely because the service restarted while it was in flight. Any output it had already sent is still kept on the run. Run it again if the work still needs doing.",
+ "transportUnavailable": "[Avibe Harness] This run stayed queued because its chat platform never reconnected, so it was never delivered. Check the platform connection in Settings, then trigger it again.",
+ "queueHoldExpired": "[Avibe Harness] This run stayed queued behind its session's turn queue for too long and was never started. Check whether that session has a stuck turn, then trigger this run again."
+ },
+ "fallbackResult": {
+ "canceled": "The run was canceled before producing a result.",
+ "failed": "The run failed before producing a result."
+ },
+ "bindingUnresolvedRetry": "Pinned agent session {session} cannot accept a turn ({attempt}/{threshold}). This definition will be paused after {threshold} consecutive unresolvable-target failures. Re-point it with: vibe task update {id} --session-id <id>.",
+ "bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}."
+ },
+ "notice": {
+ "failed": "[Avibe Harness] Scheduled work \"{name}\" failed.",
+ "interrupted": "[Avibe Harness] Scheduled work \"{name}\" was interrupted ({reason}). Nothing is wrong with the definition itself.",
+ "commandLine": "Command: {command}",
+ "error": "Error: {error}",
+ "commandExit": "Exit code: {exitCode}",
+ "unknownError": "no error text was recorded",
+ "definition": "Definition: {id}",
+ "paused": "It is currently PAUSED and will not fire again until you resume it: vibe task resume {id}",
+ "taskFinished": "This one-shot task has already finished and will not fire again.",
+ "nextRun": "Next scheduled run: {when}",
+ "rerun": "Re-run it now with: vibe task run {id} — or inspect it with: vibe task show {id}",
+ "watchPaused": "It is currently PAUSED and will not watch again until you resume it: vibe watch resume {id}",
+ "watchRetired": "This watch has already finished and will not watch again.",
+ "watchShow": "Inspect it with: vibe watch show {id}",
+ "rebound": "[Avibe Harness] Scheduled work \"{name}\" lost the agent session it was pinned to, so it was reconnected to a new one and kept running.",
+ "reboundSessions": "Previous session: {previous} → new session: {new}",
+ "reboundSettingsPreserved": "The previous session's workdir, Agent and model were preserved.",
+ "reboundSettingsReset": "The previous session's settings could not be recovered, so this work now runs on the scope defaults.",
+ "reboundRepin": "Pin it to a different session with: vibe task update {id} --session-id <session-id>",
+ "show": "Inspect it with: vibe task show {id}",
+ "definitionDeleted": "This definition no longer exists, so it cannot be re-run, resumed or re-pinned — only this run's record remains.",
+ "runInspect": "Inspect the run with: vibe runs show {id}",
+ "workspaceSession": "Workspace notifications",
+ "workspaceSessionProtected": "This session receives Avibe's workspace failure notifications and cannot be archived or modified.",
+ "workspaceSessionReadOnly": "This session only receives Avibe's workspace failure notifications — it does not accept messages.",
+ "failureClass": "Failure class: {failureClass}",
+ "lastSucceeded": "Last succeeded: {when}",
+ "origin": "Created in: {origin}",
+ "originLink": "Open the message that created it: {url}",
+ "originChannel": "{platform} channel {channel}",
+ "originChannelThread": "{platform} channel {channel} (thread {thread})",
+ "originDirect": "a {platform} direct message with {user}",
+ "platform": {
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "lark": "Feishu/Lark",
+ "wechat": "WeChat",
+ "avibe": "the Avibe Workbench"
+ },
+ "class": {
+ "noTerminalResult": "the turn ended without the agent returning a result",
+ "refusedConcurrentTurn": "another turn was already running in its session",
+ "transportUnavailable": "the platform it delivers to was unreachable",
+ "queueHoldExpired": "it waited in the queue until its hold expired",
+ "deliveryTargetMissing": "the agent session it delivers to no longer exists"
+ },
+ "reason": {
+ "stopped": "it was stopped manually",
+ "backendRefresh": "its Agent runtime was refreshed",
+ "interrupted": "its active execution was interrupted",
+ "evicted": "its session was evicted",
+ "restarted": "the service restarted",
+ "lifetimeTimeout": "its session reached its lifetime limit",
+ "orphaned": "it was left running with nothing executing it",
+ "unknown": "for a reason outside the run itself"
+ }
}
},
"common": {
@@@ -187,109 -81,51 +180,109 @@@
}
},
"error": {
+ "channelNotEnabled": "This channel is not enabled. Please go to the control panel to enable it.",
+ "unknownCommand": "Unknown command: `/{command}`\n\nPlease use `@avibe /start` to access all bot features.",
+ "clearSession": "Error clearing session: {error}",
+ "settingsFailed": "Failed to open settings. Please try again.",
+ "cwdChangeFailed": "Failed to open directory change dialog. Please try again.",
+ "resumeFailed": "Failed to open resume dialog. Please try again.",
+ "stopFailed": "Error sending stop command: {error}",
+ "cwdSetFailed": "Error setting working directory: {error}",
+ "cwdCreateFailed": "Cannot create directory: {error}",
+ "cwdNotDirectory": "Path exists but is not a directory: `{path}`",
+ "cwdGetFailed": "Error getting working directory: {error}",
+ "showSettings": "Error showing settings: {error}",
+ "toggleSettingFailed": "Failed to toggle setting: {error}",
+ "messageTypesInfoFailed": "Error showing message types info",
+ "helpInfoFailed": "Error showing help information",
+ "routingFailed": "Error showing routing settings: {error}",
+ "routingModalFailed": "Failed to open agent settings. Please try again.",
+ "settingsUpdateFailed": "Failed to update settings: {error}",
+ "languageUpdateFailed": "Language update failed. Please try again.",
+ "resumeSubmitFailed": "Failed to resume session: {error}",
+ "routingUpdateFailed": "Failed to update routing: {error}",
+ "updateUnavailable": "Update action is not available right now.",
+ "unknownAction": "Unknown action: {action}",
+ "processActionFailed": "Error processing action: {error}",
+ "agentNotConfigured": "Agent `{agent}` uses the {backend} backend, but that backend is not available. {hint}",
+ "agentNotConfiguredHint": {
+ "opencode": "Enable the OpenCode backend, install the OpenCode CLI, or set OPENCODE_CLI_PATH.",
+ "claude": "Enable the Claude Code backend and make sure the Claude Code CLI path is configured.",
+ "codex": "Enable the Codex backend, install the Codex CLI, or set CODEX_CLI_PATH.",
+ "generic": "Choose an enabled Agent in Agent settings, or enable the backend this Agent uses."
+ },
+ "processMessageFailed": "Error: {error}",
+ "streamTurnInProgress": "⚠️ A reply is already streaming for this session — wait for it to finish, then try again.",
+ "sessionReset": "Session error detected. Session has been reset. Please try your message again.",
+ "sessionConnectionLost": "Connection to Claude was lost. Please try your message again.",
+ "claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.",
+ "sessionGeneric": "An error occurred: {error}",
+ "resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?",
+ "resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it.",
+ "fileAttachmentUploadFailedWithLink": "⚠️ I could not deliver {filename} as a WeChat file. You can download it from Avibe after signing in if prompted:\n{url}",
+ "fileAttachmentUploadFailedNoLink": "⚠️ I could not deliver {filename} as a WeChat file. Please ask me to resend it or use another channel.",
+ "opencodeQuestionToolDisabled": "OpenCode asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",
+ "opencodeQuestionToolDisabledRestored": "Restored OpenCode session asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",
+ "opencodeEmptyResponse": "OpenCode finished without a model reply. Provider: {provider}; model: {model}; reasoning: {variant}. OpenCode did not expose a provider error for this run.",
- "opencodeProviderRuntimeError": "OpenCode provider request failed. Provider: {provider}; model: {model}; reasoning: {variant}. Detail: {detail}"
++ "opencodeProviderRuntimeError": "OpenCode provider request failed. Provider: {provider}; model: {model}; reasoning: {variant}. Detail: {detail}",
+ "settingsConflict": {
+ "message": "Agent routing changed while these settings were open.",
+ "hint": "Reload the settings and apply your change again."
+ },
+ "scopeAgentUnavailable": {
+ "message": "Agent `{agent}` is unavailable for this route.",
+ "hint": "Choose an enabled Agent and apply the setting again."
+ },
+ "projectAgentConflict": {
+ "message": "The project's Agent changed while Project Settings was open.",
+ "hint": "Reload Project Settings and apply your change again."
+ },
+ "projectAgentUnavailable": {
+ "message": "Agent `{agent}` is unavailable for this project.",
+ "hint": "Choose an enabled Agent and apply the project setting again."
+ },
+ "sessionFork": {
+ "agentUnavailable": {
+ "message": "The source session's Agent is no longer available for a new fork.",
+ "hint": "Choose an enabled Agent override that uses the same backend."
+ }
+ },
+ "sessionArchived": "This session is archived and can no longer be changed.",
+ "agentArchive": {
+ "agent_builtin": {
+ "message": "Agent `{agent}` is built in and cannot be deleted.",
+ "hint": "Built-in default Agents are created from enabled Backends and cannot be deleted."
+ },
+ "agent_already_archived": {
+ "message": "Agent `{agent}` is already archived.",
+ "hint": "Use the archived Agent's internal name only for existing durable references."
+ },
+ "agent_no_default_replacement": {
+ "message": "The default Agent `{agent}` cannot be archived without another enabled Agent.",
+ "hint": "Keep another enabled Agent available when archiving the current default."
+ }
+ },
+ "agentLifecycle": {
+ "agent_archived_read_only": {
+ "message": "Agent `{agent}` is archived and cannot be edited.",
+ "hint": "Archived Agents are read-only and remain available only to existing durable references."
+ },
+ "agent_reference_metadata_invalid": {
+ "message": "Avibe cannot update Agent references because a task or watch contains invalid metadata.",
+ "hint": "Repair or remove the malformed task or watch metadata, then try again."
+ }
+ },
+ "agentNameValidation": {
+ "agent_name_reserved": {
+ "message": "Agent names starting with `_` are reserved for Avibe.",
+ "hint": "Choose an Agent name that does not start with `_`."
+ },
+ "agent_name_path_separator": {
+ "message": "Agent names cannot contain `/` or `\\`.",
+ "hint": "Choose an Agent name without path separators."
+ }
+ },
- "channelNotEnabled": "This channel is not enabled. Please go to the control panel to enable it.",
- "unknownCommand": "Unknown command: `/{command}`\n\nPlease use `@avibe /start` to access all bot features.",
- "clearSession": "Error clearing session: {error}",
- "settingsFailed": "Failed to open settings. Please try again.",
- "cwdChangeFailed": "Failed to open directory change dialog. Please try again.",
- "resumeFailed": "Failed to open resume dialog. Please try again.",
- "stopFailed": "Error sending stop command: {error}",
- "cwdSetFailed": "Error setting working directory: {error}",
- "cwdCreateFailed": "Cannot create directory: {error}",
- "cwdNotDirectory": "Path exists but is not a directory: `{path}`",
- "cwdGetFailed": "Error getting working directory: {error}",
- "showSettings": "Error showing settings: {error}",
- "toggleSettingFailed": "Failed to toggle setting: {error}",
- "messageTypesInfoFailed": "Error showing message types info",
- "helpInfoFailed": "Error showing help information",
- "routingFailed": "Error showing routing settings: {error}",
- "routingModalFailed": "Failed to open agent settings. Please try again.",
- "settingsUpdateFailed": "Failed to update settings: {error}",
- "languageUpdateFailed": "Language update failed. Please try again.",
- "resumeSubmitFailed": "Failed to resume session: {error}",
- "routingUpdateFailed": "Failed to update routing: {error}",
- "updateUnavailable": "Update action is not available right now.",
- "unknownAction": "Unknown action: {action}",
- "processActionFailed": "Error processing action: {error}",
- "agentNotConfigured": "Agent `{agent}` uses the {backend} backend, but that backend is not available. {hint}",
- "agentNotConfiguredHint": {
- "opencode": "Enable the OpenCode backend, install the OpenCode CLI, or set OPENCODE_CLI_PATH.",
- "claude": "Enable the Claude Code backend and make sure the Claude Code CLI path is configured.",
- "codex": "Enable the Codex backend, install the Codex CLI, or set CODEX_CLI_PATH.",
- "generic": "Choose an enabled Agent in Agent settings, or enable the backend this Agent uses."
- },
- "processMessageFailed": "Error: {error}",
- "streamTurnInProgress": "⚠️ A reply is already streaming for this session — wait for it to finish, then try again.",
- "sessionReset": "Session error detected. Session has been reset. Please try your message again.",
- "sessionConnectionLost": "Connection to Claude was lost. Please try your message again.",
- "claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.",
- "sessionGeneric": "An error occurred: {error}",
- "resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?",
- "resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it.",
- "fileAttachmentUploadFailedWithLink": "⚠️ I could not deliver {filename} as a WeChat file. You can download it from Avibe after signing in if prompted:\n{url}",
- "fileAttachmentUploadFailedNoLink": "⚠️ I could not deliver {filename} as a WeChat file. Please ask me to resend it or use another channel.",
- "opencodeQuestionToolDisabled": "OpenCode asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",
- "opencodeQuestionToolDisabledRestored": "Restored OpenCode session asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",
- "opencodeEmptyResponse": "OpenCode finished without a model reply. Provider: {provider}; model: {model}; reasoning: {variant}. OpenCode did not expose a provider error for this run.",
- "opencodeProviderRuntimeError": "OpenCode provider request failed. Provider: {provider}; model: {model}; reasoning: {variant}. Detail: {detail}",
+ "opencodeBackendError": "OpenCode error: {error}"
},
"success": {
"settingsUpdated": "Settings updated successfully!",
@@@ -548,7 -380,7 +540,8 @@@
"timedOut": "{backend} setup timed out. Start setup again to retry.",
"success": "{backend} login is active again.",
"failed": "{backend} setup failed: {detail}",
-- "unknownFailure": "Unknown login failure."
++ "unknownFailure": "Unknown login failure.",
++ "apiKeyRecoveryPrompt": "{backend} rejected the configured API key. Check the API key and Base URL in Settings, save them, and retry."
},
"stop": {
"noActiveSession": "No active session to stop for this channel."
@@@ -670,7 -521,7 +682,8 @@@
"upstream_protocol_error": "The upstream response did not match the expected protocol.",
"upstream_request_invalid": "The upstream service rejected the request.",
"upstream_unauthorized": "The upstream service rejected authorization after refresh.",
-- "upstream_error": "The upstream service returned an error."
++ "upstream_error": "The upstream service returned an error.",
++ "invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source."
},
"events": {
"sourceFallback": "source",
@@@ -689,28 -536,13 +698,36 @@@
"network": "network unavailable",
"recovery": "recovered",
"manual": "manual change",
- "mapping": "model mapping applied"
- }
+ "mapping": "model mapping applied",
+ "credential_expired": "credential expired",
+ "credential_revoked": "credential revoked",
+ "balance_exhausted": "balance exhausted",
+ "account_banned": "account unavailable",
+ "permission_denied": "request permission denied",
+ "unclassified_error": "unclassified source error",
+ "no_enabled_source": "no source is enabled",
+ "no_eligible_source": "no source is eligible",
+ "model_unsupported": "no source supports this model"
- }
++ },
++ "skip": "{from_source}: {reason}; skipped",
++ "mapping_applied": "{from_source} -> {model}: model mapping applied",
++ "channel_switch": "{from_source}: supply channel changed",
++ "needs_action": "{from_source}: {reason}; action required",
++ "supply_interrupted": "{model}: {reason}; model supply interrupted"
+ },
+ "launch": {
+ "retry": "The next turn has already switched routes. Retry directly.",
+ "waiting": "Model {model} is temporarily unavailable. Waiting for {source} to recover at {retry_at}.",
+ "interrupted": "Model {model} is unavailable: {blockers}. Open Models to resolve it.",
+ "native_cli_unavailable": "CLI login is not available in this process",
+ "no_enabled_source": "Model {model} has no enabled source. Open Models to configure one.",
+ "no_eligible_source": "Model {model} has no source eligible for {backend}. Open Models to configure one.",
+ "model_unsupported": "No source supports model {model}. Open Models to configure one."
}
},
+ "errors": {
+ "project_access_denied": "You don't have permission to start a session in this project."
+ },
"remote_access": {
"oauth_error": {
"sign_in_again": "Sign in again",
@@@ -730,5 -562,5 +747,12 @@@
"invalid_oauth_nonce_title": "We couldn't verify this sign-in",
"invalid_oauth_nonce_body": "This sign-in attempt couldn't be verified, so we stopped to keep your account secure. Start over to continue."
}
++ },
++ "show": {
++ "event": {
++ "acceptanceUnknown": "The Show event may still be processing. It was not replayed locally.",
++ "dispatchFailed": "The Show event was recorded, but its agent turn could not be delivered.",
++ "idConflict": "This Show event ID is already bound to different event contents."
++ }
}
}
diff --cc vibe/i18n/zh.json
index af20589c5,c08051a41..d48ec41ff
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@@ -58,84 -30,6 +30,105 @@@
"messagesLabel": "已合并的 callback 消息:",
"latestLabel": "后续又触发 {additional} 次后的最新 callback 消息:",
"burstHint": "这个 callback 来源正在频繁触发。请检查相关 watch/task;如果它在循环触发,请 pause、remove 或 update。"
+ },
++ "agentInitiatedContinuation": "Agent 主动发起的续接",
++ "command": {
++ "workdirMissing": "工作目录不存在:{cwd}",
++ "supervisorExitedDuringStartup": "命令监控进程在启动期间退出。",
++ "workerNotRecorded": "未启动命令:无法记录其监控进程。",
++ "supervisorFailed": "命令监控进程失败:{detail}",
++ "unknownSupervisorFailure": "未知的监控进程错误。",
++ "protocolErrors": {
++ "specTooLarge": "命令配置过大。",
++ "invalidEncoding": "命令配置不是有效的 UTF-8。",
++ "invalidJson": "命令配置不是有效的 JSON。",
++ "unsupportedVersion": "不支持此命令配置版本。",
++ "invalidCommand": "命令无效。"
++ },
++ "timedOut": "命令在 {seconds} 秒后超时。",
++ "exited": "命令退出,状态码 {code}。",
++ "exitedWithDetail": "命令退出,状态码 {code}:{detail}"
++ },
++ "task": {
++ "resultNotRecorded": "无法记录本次运行的结果:任务在运行期间被回收、改绑或删除,其存储状态未发生变化。"
++ },
+ "run": {
+ "interrupted": {
+ "noTerminalResult": "[Avibe Harness] 本次 run 结束时 Agent 没有产出结果。turn 在 Agent 回复前就被释放,因此没有记录任何输出。请检查 Agent 日志;如果这项工作仍需完成,请重新运行。",
+ "stopped": "[Avibe Harness] 本次 run 在 Agent 产出结果前被停止,因此没有最终结果。Agent 此前已经发出的输出仍会保留在这次 run 上。",
+ "refusedConcurrentTurn": "[Avibe Harness] 本次 run 被跳过:同一 session 已有另一个 turn 正在执行。一个 session 同时只运行一个 turn,请在当前 turn 结束后重新触发。",
+ "backendRefresh": "[Avibe Harness] 本次 run 执行途中,它所用的 Agent 运行时被刷新,因此被中断,通常发生在刚保存 Agent 设置之后。这次 run 本身没有问题,请重新触发。",
+ "restarted": "[Avibe Harness] 本次 run 执行途中服务已关闭,因此被中断。该次执行已被记录,服务重启后不会重放。如果这项工作仍需完成,请重新触发。",
+ "interrupted": "[Avibe Harness] 本次 run 在执行途中被中断。该次执行已被记录,不会重新排队。如果这项工作仍需完成,请重新触发。",
+ "orphaned": "[Avibe Harness] 本次 run 一直标记为 running,但已经没有任何执行在推进它,通常是服务在它执行途中重启导致的。它此前已经发出的输出仍会保留在这次 run 上。如果这项工作仍需完成,请重新运行。",
+ "transportUnavailable": "[Avibe Harness] 本次 run 一直排队等待,因为它对应的聊天平台始终没有重新连接,消息也就无法送达。请在设置中检查该平台连接,然后重新触发。",
+ "queueHoldExpired": "[Avibe Harness] 本次 run 在所属 session 的 turn 队列后面排队过久,始终没有开始执行。请检查该 session 是否有卡住的 turn,然后重新触发这次 run。"
+ },
+ "fallbackResult": {
+ "canceled": "本次 run 在产出结果前被取消,因此没有结果。",
+ "failed": "本次 run 在产出结果前失败,因此没有结果。"
+ },
+ "bindingUnresolvedRetry": "绑定的 Agent 会话 {session} 无法接收请求({attempt}/{threshold})。连续 {threshold} 次出现目标会话不可用后,该定义将自动暂停。请用以下命令重新绑定:vibe task update {id} --session-id <id>。",
+ "bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。"
+ },
+ "notice": {
+ "failed": "[Avibe Harness] 后台任务「{name}」执行失败。",
+ "interrupted": "[Avibe Harness] 后台任务「{name}」被中断({reason}),任务本身没有问题。",
+ "commandLine": "命令:{command}",
+ "error": "错误:{error}",
+ "commandExit": "退出码:{exitCode}",
+ "unknownError": "未记录错误信息",
+ "definition": "任务 ID:{id}",
+ "paused": "该任务当前已暂停,恢复前不会再次触发:vibe task resume {id}",
+ "taskFinished": "这个一次性任务已经结束,不会再次触发。",
+ "nextRun": "下次运行时间:{when}",
+ "rerun": "立即重跑:vibe task run {id};查看详情:vibe task show {id}",
+ "watchPaused": "该监视当前已暂停,恢复前不会再次监视:vibe watch resume {id}",
+ "watchRetired": "该监视已经结束,不会再次监视。",
+ "watchShow": "查看详情:vibe watch show {id}",
+ "rebound": "[Avibe Harness] 后台任务「{name}」绑定的 Agent 会话已不存在,已自动重新绑定到新会话并继续运行。",
+ "reboundSessions": "原会话:{previous} → 新会话:{new}",
+ "reboundSettingsPreserved": "已保留原会话的工作目录、Agent 与模型设置。",
+ "reboundSettingsReset": "无法恢复原会话的设置,该任务现在使用当前作用域的默认配置。",
+ "reboundRepin": "如需改绑到其他会话:vibe task update {id} --session-id <session-id>",
+ "show": "查看详情:vibe task show {id}",
+ "definitionDeleted": "该定义已不存在,无法重跑、恢复或改绑,只保留这次运行的记录。",
+ "runInspect": "查看这次运行:vibe runs show {id}",
+ "workspaceSession": "工作区通知",
+ "workspaceSessionProtected": "该会话用于接收 Avibe 的工作区失败通知,无法归档或修改。",
+ "workspaceSessionReadOnly": "该会话只接收 Avibe 的工作区失败通知,不接受发送消息。",
+ "failureClass": "失败类型:{failureClass}",
+ "lastSucceeded": "上次成功时间:{when}",
+ "origin": "创建位置:{origin}",
+ "originLink": "打开创建它的那条消息:{url}",
+ "originChannel": "{platform} 频道 {channel}",
+ "originChannelThread": "{platform} 频道 {channel}(话题 {thread})",
+ "originDirect": "{platform} 上与 {user} 的私聊",
+ "platform": {
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "lark": "飞书/Lark",
+ "wechat": "微信",
+ "avibe": "Avibe 工作台"
+ },
+ "class": {
+ "noTerminalResult": "本轮结束时 Agent 没有返回任何结果",
+ "refusedConcurrentTurn": "所属会话中已有另一轮在执行",
+ "transportUnavailable": "投递目标平台不可达",
+ "queueHoldExpired": "在队列中等待超时",
+ "deliveryTargetMissing": "它要投递的 Agent 会话已不存在"
+ },
+ "reason": {
+ "stopped": "被手动停止",
+ "backendRefresh": "所用的 Agent 运行时被刷新",
+ "interrupted": "正在执行的任务被中断",
+ "evicted": "所属会话被回收",
+ "restarted": "服务重启",
+ "lifetimeTimeout": "所属会话达到生命周期上限",
+ "orphaned": "已无任何执行在推进它",
+ "unknown": "原因在这次运行之外"
+ }
}
},
"common": {
@@@ -187,109 -81,51 +180,109 @@@
}
},
"error": {
+ "channelNotEnabled": "此频道未启用。请前往控制面板启用它。",
+ "unknownCommand": "未知命令:`/{command}`\n\n请使用 `@avibe /start` 访问所有机器人功能。",
+ "clearSession": "清除会话时出错:{error}",
+ "settingsFailed": "无法打开设置。请重试。",
+ "cwdChangeFailed": "无法打开目录更改对话框。请重试。",
+ "resumeFailed": "无法打开恢复对话框。请重试。",
+ "stopFailed": "发送停止命令时出错:{error}",
+ "cwdSetFailed": "设置工作目录时出错:{error}",
+ "cwdCreateFailed": "无法创建目录:{error}",
+ "cwdNotDirectory": "路径存在但不是目录:`{path}`",
+ "cwdGetFailed": "获取工作目录时出错:{error}",
+ "showSettings": "显示设置时出错:{error}",
+ "toggleSettingFailed": "切换设置失败:{error}",
+ "messageTypesInfoFailed": "显示消息类型说明时出错",
+ "helpInfoFailed": "显示帮助信息时出错",
+ "routingFailed": "显示路由设置时出错:{error}",
+ "routingModalFailed": "无法打开 Agent 设置。请重试。",
+ "settingsUpdateFailed": "更新设置失败:{error}",
+ "languageUpdateFailed": "语言更新失败,请重试。",
+ "resumeSubmitFailed": "恢复会话失败:{error}",
+ "routingUpdateFailed": "更新路由失败:{error}",
+ "updateUnavailable": "当前无法执行更新操作。",
+ "unknownAction": "未知操作:{action}",
+ "processActionFailed": "处理操作时出错:{error}",
+ "agentNotConfigured": "Agent `{agent}` 使用 {backend} backend,但该 backend 当前不可用。{hint}",
+ "agentNotConfiguredHint": {
+ "opencode": "请启用 OpenCode backend,安装 OpenCode CLI,或设置 OPENCODE_CLI_PATH。",
+ "claude": "请启用 Claude Code backend,并确认 Claude Code CLI 路径已配置。",
+ "codex": "请启用 Codex backend,安装 Codex CLI,或设置 CODEX_CLI_PATH。",
+ "generic": "请在 Agent 设置里选择一个已启用的 Agent,或启用该 Agent 使用的 backend。"
+ },
+ "processMessageFailed": "出错:{error}",
+ "streamTurnInProgress": "⚠️ 这个会话已经有一条回复在生成中,请等它完成后再试。",
+ "sessionReset": "检测到会话错误。会话已重置,请重试。",
+ "sessionConnectionLost": "与 Claude 的连接已断开,请重试。",
+ "claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。",
+ "sessionGeneric": "发生错误:{error}",
+ "resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?",
+ "resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。",
+ "fileAttachmentUploadFailedWithLink": "⚠️ {filename} 没能作为微信文件直接发送。你可以通过 Avibe 下载;如提示登录,请先登录:\n{url}",
+ "fileAttachmentUploadFailedNoLink": "⚠️ {filename} 没能作为微信文件直接发送。请让我重新发送,或换一个渠道接收这个文件。",
+ "opencodeQuestionToolDisabled": "OpenCode 发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",
+ "opencodeQuestionToolDisabledRestored": "恢复中的 OpenCode 会话发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",
+ "opencodeEmptyResponse": "OpenCode 已结束,但没有产出模型回复。Provider:{provider};模型:{model};推理强度:{variant}。这次运行里 OpenCode 没有暴露服务商错误。",
- "opencodeProviderRuntimeError": "OpenCode 服务商请求失败。Provider:{provider};模型:{model};推理强度:{variant}。详情:{detail}"
++ "opencodeProviderRuntimeError": "OpenCode 服务商请求失败。Provider:{provider};模型:{model};推理强度:{variant}。详情:{detail}",
+ "settingsConflict": {
+ "message": "这些设置打开后,Agent 路由已发生变化。",
+ "hint": "请重新加载设置后再次修改。"
+ },
+ "scopeAgentUnavailable": {
+ "message": "Agent `{agent}` 无法用于此路由。",
+ "hint": "请选择一个已启用的 Agent 后重新保存。"
+ },
+ "projectAgentConflict": {
+ "message": "项目设置打开后,该项目的 Agent 已发生变化。",
+ "hint": "请重新加载项目设置后再次修改。"
+ },
+ "projectAgentUnavailable": {
+ "message": "Agent `{agent}` 无法用于此项目。",
+ "hint": "请选择一个已启用的 Agent 后重新保存项目设置。"
+ },
+ "sessionFork": {
+ "agentUnavailable": {
+ "message": "源会话的 Agent 已无法用于创建新的复刻会话。",
+ "hint": "请选择使用相同 backend 的已启用 Agent 作为覆盖项。"
+ }
+ },
+ "sessionArchived": "该会话已归档,无法再修改。",
+ "agentArchive": {
+ "agent_builtin": {
+ "message": "Agent `{agent}` 是内置 Agent,无法删除。",
+ "hint": "内置默认 Agent 由已启用的 Backend 创建,无法删除。"
+ },
+ "agent_already_archived": {
+ "message": "Agent `{agent}` 已归档。",
+ "hint": "已归档 Agent 的内部名称仅供现有持久引用继续使用。"
+ },
+ "agent_no_default_replacement": {
+ "message": "没有其他已启用 Agent 时,无法归档默认 Agent `{agent}`。",
+ "hint": "归档当前默认 Agent 前,请保留另一个已启用 Agent。"
+ }
+ },
+ "agentLifecycle": {
+ "agent_archived_read_only": {
+ "message": "Agent `{agent}` 已归档,无法编辑。",
+ "hint": "已归档 Agent 为只读状态,仅供现有持久引用继续使用。"
+ },
+ "agent_reference_metadata_invalid": {
+ "message": "任务或监控包含无效元数据,Avibe 无法更新 Agent 引用。",
+ "hint": "请修复或删除元数据异常的任务或监控,然后重试。"
+ }
+ },
+ "agentNameValidation": {
+ "agent_name_reserved": {
+ "message": "Agent 名称不能以下划线 `_` 开头;该命名空间由 Avibe 保留。",
+ "hint": "请选择不以下划线 `_` 开头的 Agent 名称。"
+ },
+ "agent_name_path_separator": {
+ "message": "Agent 名称不能包含 `/` 或 `\\`。",
+ "hint": "请选择不含路径分隔符的 Agent 名称。"
+ }
+ },
- "channelNotEnabled": "此频道未启用。请前往控制面板启用它。",
- "unknownCommand": "未知命令:`/{command}`\n\n请使用 `@avibe /start` 访问所有机器人功能。",
- "clearSession": "清除会话时出错:{error}",
- "settingsFailed": "无法打开设置。请重试。",
- "cwdChangeFailed": "无法打开目录更改对话框。请重试。",
- "resumeFailed": "无法打开恢复对话框。请重试。",
- "stopFailed": "发送停止命令时出错:{error}",
- "cwdSetFailed": "设置工作目录时出错:{error}",
- "cwdCreateFailed": "无法创建目录:{error}",
- "cwdNotDirectory": "路径存在但不是目录:`{path}`",
- "cwdGetFailed": "获取工作目录时出错:{error}",
- "showSettings": "显示设置时出错:{error}",
- "toggleSettingFailed": "切换设置失败:{error}",
- "messageTypesInfoFailed": "显示消息类型说明时出错",
- "helpInfoFailed": "显示帮助信息时出错",
- "routingFailed": "显示路由设置时出错:{error}",
- "routingModalFailed": "无法打开 Agent 设置。请重试。",
- "settingsUpdateFailed": "更新设置失败:{error}",
- "languageUpdateFailed": "语言更新失败,请重试。",
- "resumeSubmitFailed": "恢复会话失败:{error}",
- "routingUpdateFailed": "更新路由失败:{error}",
- "updateUnavailable": "当前无法执行更新操作。",
- "unknownAction": "未知操作:{action}",
- "processActionFailed": "处理操作时出错:{error}",
- "agentNotConfigured": "Agent `{agent}` 使用 {backend} backend,但该 backend 当前不可用。{hint}",
- "agentNotConfiguredHint": {
- "opencode": "请启用 OpenCode backend,安装 OpenCode CLI,或设置 OPENCODE_CLI_PATH。",
- "claude": "请启用 Claude Code backend,并确认 Claude Code CLI 路径已配置。",
- "codex": "请启用 Codex backend,安装 Codex CLI,或设置 CODEX_CLI_PATH。",
- "generic": "请在 Agent 设置里选择一个已启用的 Agent,或启用该 Agent 使用的 backend。"
- },
- "processMessageFailed": "出错:{error}",
- "streamTurnInProgress": "⚠️ 这个会话已经有一条回复在生成中,请等它完成后再试。",
- "sessionReset": "检测到会话错误。会话已重置,请重试。",
- "sessionConnectionLost": "与 Claude 的连接已断开,请重试。",
- "claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。",
- "sessionGeneric": "发生错误:{error}",
- "resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?",
- "resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。",
- "fileAttachmentUploadFailedWithLink": "⚠️ {filename} 没能作为微信文件直接发送。你可以通过 Avibe 下载;如提示登录,请先登录:\n{url}",
- "fileAttachmentUploadFailedNoLink": "⚠️ {filename} 没能作为微信文件直接发送。请让我重新发送,或换一个渠道接收这个文件。",
- "opencodeQuestionToolDisabled": "OpenCode 发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",
- "opencodeQuestionToolDisabledRestored": "恢复中的 OpenCode 会话发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",
- "opencodeEmptyResponse": "OpenCode 已结束,但没有产出模型回复。Provider:{provider};模型:{model};推理强度:{variant}。这次运行里 OpenCode 没有暴露服务商错误。",
- "opencodeProviderRuntimeError": "OpenCode 服务商请求失败。Provider:{provider};模型:{model};推理强度:{variant}。详情:{detail}",
+ "opencodeBackendError": "OpenCode 错误:{error}"
},
"success": {
"settingsUpdated": "设置更新成功!",
@@@ -548,7 -380,7 +540,8 @@@
"timedOut": "{backend} 登录修复已超时,请重新发起 setup 再试一次。",
"success": "{backend} 已重新登录,可继续使用。",
"failed": "{backend} 登录修复失败:{detail}",
-- "unknownFailure": "未知登录失败。"
++ "unknownFailure": "未知登录失败。",
++ "apiKeyRecoveryPrompt": "{backend} 拒绝了当前配置的 API Key。请在设置中检查 API Key 和 Base URL,保存后重试。"
},
"stop": {
"noActiveSession": "此频道没有要停止的活动会话。"
@@@ -670,7 -521,7 +682,8 @@@
"upstream_protocol_error": "上游响应不符合预期协议。",
"upstream_request_invalid": "上游服务拒绝了请求。",
"upstream_unauthorized": "刷新后上游服务仍拒绝授权。",
-- "upstream_error": "上游服务返回错误。"
++ "upstream_error": "上游服务返回错误。",
++ "invalid_source_order": "来源顺序包含不可用、不适用或重复的来源。"
},
"events": {
"sourceFallback": "来源",
@@@ -689,28 -536,13 +698,36 @@@
"network": "网络暂不可用",
"recovery": "已恢复",
"manual": "手动调整",
- "mapping": "已应用模型映射"
- }
+ "mapping": "已应用模型映射",
+ "credential_expired": "凭证已过期",
+ "credential_revoked": "凭证已撤销",
+ "balance_exhausted": "余额不足",
+ "account_banned": "账户不可用",
+ "permission_denied": "请求权限被拒绝",
+ "unclassified_error": "来源发生未分类错误",
+ "no_enabled_source": "没有已启用的来源",
+ "no_eligible_source": "没有适用的来源",
+ "model_unsupported": "没有来源支持此模型"
- }
++ },
++ "skip": "{from_source}:{reason},已跳过",
++ "mapping_applied": "{from_source} -> {model}:已应用模型映射",
++ "channel_switch": "{from_source}:供给通道已切换",
++ "needs_action": "{from_source}:{reason},需要处理",
++ "supply_interrupted": "{model}:{reason},模型供给已中断"
+ },
+ "launch": {
+ "retry": "下一回合已自动换线,直接重试即可",
+ "waiting": "模型 {model} 暂时不可用,等待 {source} 于 {retry_at} 自动恢复。",
+ "interrupted": "模型 {model} 当前不可用:{blockers}。请前往 Models 处理。",
+ "native_cli_unavailable": "当前进程无法使用 CLI 登录",
+ "no_enabled_source": "模型 {model} 没有已启用的来源。请前往 Models 配置。",
+ "no_eligible_source": "模型 {model} 没有适用于 {backend} 的来源。请前往 Models 配置。",
+ "model_unsupported": "没有来源支持模型 {model}。请前往 Models 配置。"
}
},
+ "errors": {
+ "project_access_denied": "你没有权限在这个项目中创建会话。"
+ },
"remote_access": {
"oauth_error": {
"sign_in_again": "重新登录",
@@@ -730,5 -562,5 +747,12 @@@
"invalid_oauth_nonce_title": "无法验证此次登录",
"invalid_oauth_nonce_body": "本次登录未能通过验证,为保护你的账户已中止。请重新登录以继续。"
}
++ },
++ "show": {
++ "event": {
++ "acceptanceUnknown": "Show 事件可能仍在处理中,未在本地重复提交。",
++ "dispatchFailed": "Show 事件已记录,但未能投递对应的 Agent turn。",
++ "idConflict": "此 Show 事件 ID 已绑定到不同的事件内容。"
++ }
}
}
diff --cc vibe/internal_client.py
index 94219ab52,468e86fd3..304148b65
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@@ -188,14 -304,11 +298,12 @@@ async def dispatch_async
responds ``202`` right away (the reply arrives over the persistent
``message.new`` session stream, not this response). Returns
``{"status_code", "body"}`` so the caller can distinguish a started turn
- (202) from a concurrent-turn refusal (409). Raises
- ``InternalServerUnavailable`` on socket failure so the route can degrade.
+ from one accepted into the shared queue. A pre-connect failure raises
+ ``InternalServerUnavailable``; a post-connect timeout raises
+ ``InternalServerTimeout`` because acceptance is unknown.
"""
- target = (socket_path or default_socket_path()).expanduser().resolve()
- if not target.exists():
- raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+ target = await _verified_socket_path_async(socket_path)
transport = httpx.AsyncHTTPTransport(uds=str(target))
try:
async with httpx.AsyncClient(
diff --cc vibe/remote_access.py
index ecfbcd725,af44ff9bd..a48c54ec5
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@@ -80,7 -97,18 +102,19 @@@ _RECOVERY_ATTEMPTS: list[float] = [
_RECOVERY_CANCEL_EVENT = threading.Event()
_RECOVERY_MANUAL_BYPASS_USED = False
_RECOVERY_EMERGENCY_BYPASS_USED = False
+_PREFERRED_PROTOCOL: str | None = None
+ _RESOURCE_ACL_SYNC_LOCK = threading.Lock()
+ _RESOURCE_ACL_SYNC_POLL_LOCK = threading.Lock()
+ _RESOURCE_ACL_SYNC_POLL_STARTED = False
+ _RESOURCE_ACL_SYNC_ERROR_CODE_RE = re.compile(r"\A[a-z0-9][a-z0-9_:-]{0,119}\Z")
+ _RESOURCE_ACL_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})
+ _RESOURCE_ACL_ACCESS_LEVELS = frozenset({"public", "scope", "private"})
+ _RESOURCE_ACL_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})
+ _RESOURCE_ACL_MAX_REVISION = (1 << 53) - 1
+ _RESOURCE_ACL_PENDING_VAULT_RELEASE_PREFIX = "resource_acl_pending_vault_release:"
+ _INSTANCE_ACCESS_ROLES = frozenset({"owner", "editor", "viewer"})
+ _INSTANCE_ACCESS_SOURCES = frozenset({"owner", "public_instance", "email", "email_domain", "organization_group"})
+ _ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
_BLOCKED_PAIRING_BACKEND_HOSTS = {
"localhost",
"localhost.localdomain",
@@@ -607,10 -774,11 +854,11 @@@ def runtime_status_payload(config: V2Co
"tunnel_running": bool(current.get("running")),
"cloudflared_found": bool(current.get("binary_found")),
"expected_origin_service": origin_service_for_pairing(config),
- "observed_origin_service": _observed_cloudflared_origin_service(),
}
+ if observed_origin_service:
+ payload["observed_origin_service"] = observed_origin_service
quality = current.get("tunnel_quality")
- if isinstance(quality, dict) and quality.get("schema_version") == 1:
+ if isinstance(quality, dict) and quality.get("schema_version") in {1, 2}:
payload["tunnel_quality"] = quality
error = last_error or current.get("error")
if error:
diff --cc vibe/ui_server.py
index 10a3992cf,d82d656ce..fd0b4213f
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@@ -20,10 -20,9 +20,10 @@@ import tim
from collections import OrderedDict, deque
from contextlib import contextmanager
from datetime import datetime, timezone
+from enum import Enum
from pathlib import Path
from types import SimpleNamespace
- from typing import Any, Callable
+ from typing import Any, Callable, Mapping
from urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplit
import psutil
@@@ -58,10 -51,9 +58,11 @@@ from core.terminal_service import TERMI
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
from vibe.i18n import get_supported_languages, t
from vibe.logging_config import application_log_paths
+from vibe.message_types import types_with
from vibe.runtime import get_ui_dist_path, get_working_dir
from vibe.sentry_integration import init_sentry
+from storage.delivery_states import ADMITTED_DELIVERY_STATES
+ from vibe.ui_memory_routes import register_memory_routes
logger = logging.getLogger(__name__)
@@@ -3020,9 -3449,31 +3453,33 @@@ def config_get()
# default is never mistaken for a completed setup. The write side
# (``save_config``) already creates the file on the first real save.
config = settings_service.load_config_or_default()
- payload = api.config_to_payload(config)
+ payload = api.client_config_payload(config)
+ payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
- return jsonify(payload)
+ authorization_context = getattr(g, "authorization_context", None)
+ if authorization_context is not None and authorization_context.can_manage_instance:
+ return jsonify(payload)
+
+ ui_payload = payload.get("ui")
+ return jsonify(
+ {
+ "mode": payload.get("mode"),
+ "version": payload.get("version"),
+ "setup_state": payload.get("setup_state"),
+ "language": payload.get("language"),
++ "capabilities": payload.get("capabilities"),
+ "ui": {
+ key: ui_payload[key]
+ for key in (
+ "instance_name",
+ "default_instance_name",
+ "chat_message_font_size",
+ "show_agent_activity",
+ "show_tool_calls",
+ )
+ if isinstance(ui_payload, dict) and key in ui_payload
+ },
+ }
+ )
_MODEL_HUB_SERVICE = None
@@@ -3450,19 -3814,22 +3909,33 @@@ def vibe_agents_get()
"true",
"yes",
}
- return jsonify(api.get_vibe_agents(backend=request.args.get("backend") or None, include_disabled=include_disabled))
+ include_archived = str(request.args.get("include_archived") or "").lower() in {
+ "1",
+ "true",
+ "yes",
+ }
+ return jsonify(
+ api.get_vibe_agents(
+ backend=request.args.get("backend") or None,
+ include_disabled=include_disabled,
+ include_archived=include_archived,
+ )
+ )
- except ValueError as exc:
+ except (ValueError, PermissionError) as exc:
+ return _vibe_agent_error_response(exc)
+
+
+ @app.route("/api/agent-onboarding", methods=["GET", "POST"])
+ def vibe_agent_onboarding():
+ """Inventory or explicitly register existing Agents with Organization ACL."""
+
+ from vibe import api
+
+ try:
+ if request.method == "POST":
+ return jsonify(api.onboard_vibe_agents())
+ return jsonify(api.get_vibe_agent_onboarding())
+ except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@@ -3566,8 -3933,8 +4039,8 @@@ def vibe_agents_post()
from vibe import api
try:
- return jsonify(api.create_vibe_agent(request.json or {}))
+ return _vibe_agent_result_response(api.create_vibe_agent(request.json or {}))
- except ValueError as exc:
+ except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@@ -3597,8 -3964,8 +4070,8 @@@ def vibe_agent_patch(name)
from vibe import api
try:
- return jsonify(api.update_vibe_agent(name, request.json or {}))
+ return _vibe_agent_result_response(api.update_vibe_agent(name, request.json or {}))
- except ValueError as exc:
+ except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@@ -3962,92 -4329,20 +4435,97 @@@ def vault_audit_get()
return jsonify(api.get_vault_audit(secret_name=secret, limit=limit))
+def _coded_error_response(code: str, message: str, status: int, **extra: Any):
+ """THE error body for any route whose failure carries a machine-readable code.
+
+ Nested ``error`` object, because the Web UI's shared parser
+ (``selectApiErrorFields`` in ``ui/src/context/ApiContext.tsx``) reads ``data.error``
+ FIRST and treats a *string* ``error`` as the code itself. So the flat
+ ``{"error": "<sentence>", "code": "<code>"}`` shape silently DESTROYS the code:
+ callers get ``ApiError.code == "<sentence>"``, ``errors.<code>`` never resolves,
+ the sentence is rendered verbatim under every locale, and any client branch keyed
+ on the code (e.g. the archived-session convergence subscription) never fires.
+
+ The flat top-level ``code``/``message`` are kept alongside for the CLI and any
+ direct consumer that reads them. ``extra`` carries route-specific detail fields.
+
+ One builder rather than per-route dict literals so a new coded route inherits the
+ right shape; ``tests/test_ui_server_fastapi.py`` guards both directions (every
+ builder survives the parser, and no route hand-rolls the flat coded shape).
+ """
+ return (
+ jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message, **extra}),
+ status,
+ )
+
+
+def _settings_conflict_response(exc):
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ key = "error.settingsConflict"
+ return _coded_error_response(
+ exc.code,
+ t(f"{key}.message", lang),
+ 409,
+ hint=t(f"{key}.hint", lang),
+ details={"scope_id": exc.scope_id},
+ )
+
+
+def _scope_agent_unavailable_response(exc):
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ key = "error.scopeAgentUnavailable"
+ return _coded_error_response(
+ exc.code,
+ t(f"{key}.message", lang, agent=exc.agent_name),
+ 400,
+ hint=t(f"{key}.hint", lang),
+ details={"agent_name": exc.agent_name},
+ )
+
+
+def _project_agent_conflict_response(exc):
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ key = "error.projectAgentConflict"
+ return _coded_error_response(
+ exc.code,
+ t(f"{key}.message", lang),
+ 409,
+ hint=t(f"{key}.hint", lang),
+ details=exc.details,
+ )
+
+
+def _project_agent_unavailable_response(exc):
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ key = "error.projectAgentUnavailable"
+ return _coded_error_response(
+ exc.code,
+ t(f"{key}.message", lang, agent=exc.agent_name),
+ 400,
+ hint=t(f"{key}.hint", lang),
+ details={"agent_name": exc.agent_name},
+ )
+
+
def _show_page_error_response(exc):
code = getattr(exc, "code", "invalid_show_page_request")
- # A conflict (not a malformed request) when the page is in the wrong state or
- # the chosen suffix is already claimed.
+ if code == "resource_access_forbidden":
+ status = 403
+ # A conflict (not a malformed request) when the page is in the wrong state or
+ # the chosen suffix is already claimed.
- status = 409 if code in {"not_public", "share_id_taken"} else 400
++ elif code in {"not_public", "share_id_taken"}:
++ status = 409
+ else:
- status = 409 if code in {"not_public", "share_id_taken"} else 400
- message = str(exc)
- # Structured ``error`` so the Web UI's shared handler localizes via
- # ``errors.<code>`` and falls back to the human message (not the raw code)
- # for any code without an i18n key; top-level ``code``/``message`` stay for
- # the CLI/any direct consumer.
- return jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}), status
++ status = 400
+ return _coded_error_response(code, str(exc), status)
@app.route("/api/show-pages", methods=["GET"])
@@@ -4168,8 -4492,14 +4675,13 @@@ def _dock_error_response(exc)
# A missing Show Page (nothing to pin) is a 404; a malformed id or a bad
# order is a 400. Structured ``error`` so the Web UI's shared handler can
# localize via ``errors.<code>`` and fall back to the human message.
- status = 404 if code in {"show_page_not_found", "session_not_found"} else 400
+ if code == "resource_access_forbidden":
+ status = 403
+ elif code in {"show_page_not_found", "session_not_found"}:
+ status = 404
+ else:
+ status = 400
- message = str(exc)
- return jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}), status
+ return _coded_error_response(code, str(exc), status)
@app.route("/api/dock", methods=["GET"])
@@@ -5890,15 -7022,12 +7223,16 @@@ def projects_update(project_id: str)
project_id,
display_name=display_name,
folder_path=folder_path,
+ authorization_context=getattr(g, "authorization_context", None),
**agent_kwargs,
)
+ except projects_service.StaleProjectAgentBindingError as err:
+ return _project_agent_conflict_response(err)
+ except projects_service.ProjectAgentUnavailableError as err:
+ return _project_agent_unavailable_response(err)
except LookupError as err:
return jsonify({"error": str(err)}), 404
- except (FileNotFoundError, NotADirectoryError) as err:
+ except (FileNotFoundError, NotADirectoryError, ValueError) as err:
return jsonify({"error": str(err)}), 400
return jsonify(project)
@@@ -6550,21 -7691,21 +7937,32 @@@ async def sessions_bootstrap(session_id
session_id=session_id,
limit=50,
types=messages_service.TRANSCRIPT_TYPES,
- include_metadata_sources=("show_page",),
tail=True,
)
- queued = messages_service.list_queued(conn, session_id) if can_chat else []
- draft = messages_service.get_draft(conn, session_id) if can_chat else None
+ from storage import message_deliveries
+
- queued = message_deliveries.list_queued(conn, session_id)
- draft = message_deliveries.get_draft(conn, session_id)
++ queued = (
++ [
++ message_deliveries.public_delivery_payload(item)
++ for item in message_deliveries.list_queued(conn, session_id)
++ ]
++ if can_chat
++ else []
++ )
++ draft = message_deliveries.get_draft(conn, session_id) if can_chat else None
- try:
- agents_payload = vibe_api.get_vibe_agents(include_disabled=False, include_archived=True)
- except Exception:
- logger.exception("sessions_bootstrap: failed to load Vibe Agents")
- agents_payload = {"agents": [], "default_agent_name": None}
+ agents_payload = {"agents": [], "default_agent_name": None}
+ if can_chat:
+ try:
- agents_payload = vibe_api.get_vibe_agents(include_disabled=False)
++ agents_payload = vibe_api.get_vibe_agents(
++ include_disabled=False,
++ include_archived=True,
++ )
+ except Exception:
+ logger.exception("sessions_bootstrap: failed to load Vibe Agents")
try:
- config_payload = vibe_api.config_to_payload(settings_service.load_config_or_default())
+ config_payload = vibe_api.client_config_payload(settings_service.load_config_or_default())
except Exception:
logger.exception("sessions_bootstrap: failed to load config")
config_payload = None
@@@ -6840,26 -7907,18 +8251,33 @@@ async def sessions_update(session_id: s
if {"visibility", "scope_id"}.intersection(updatable)
else None
)
- session = workbench_sessions_service.update_session(conn, session_id, **updatable)
+ session = workbench_sessions_service.update_session(
+ conn,
+ session_id,
+ authorization_context=getattr(g, "authorization_context", None),
+ **updatable,
+ )
except LookupError as err:
return jsonify({"error": str(err)}), 404
+ except workbench_sessions_service.SessionArchivedError:
+ # Archive is terminal — the read-only chat UI relies on this backstop. The
+ # short-circuit above already answers the common case; this catches a
+ # session archived BETWEEN that read and this write, and keeps the service
+ # guard authoritative rather than trusting the route's preflight.
+ return _session_archived_response()
+ except workbench_sessions_service.ReservedSessionError as err:
+ # The reserved workspace-notifications session refuses modification the
+ # same way it refuses archive: a flipped visibility or title would
+ # un-project the system surface until the next heal. Mirror the DELETE
+ # route's 403 + localized copy so the two guards read as one contract.
+ return _reserved_session_response(
+ RESERVED_SESSION_PROTECTED_I18N_KEY,
+ code=getattr(err, "code", "reserved_session"),
+ )
- except (ValueError, PermissionError) as err:
+ except ValueError as err:
return jsonify({"error": str(err)}), 400
+ except PermissionError as err:
+ return jsonify({"error": str(err)}), 403
except workbench_sessions_service.SessionBackendLockedError as err:
# A session is pinned to its backend once it has a conversation (or a
# running turn); the UI may switch the agent within the same backend,
@@@ -6926,7 -7981,7 +8344,11 @@@ def sessions_archive_preview(session_id
engine = _projects_engine()
try:
with engine.connect() as conn:
-- workbench_sessions_service.get_session(conn, session_id) # 404 if missing
++ workbench_sessions_service.get_session(
++ conn,
++ session_id,
++ authorization_context=getattr(g, "authorization_context", None),
++ )
counts = workbench_sessions_service.count_bound_resources(conn, session_id)
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@@ -6976,17 -8032,15 +8399,23 @@@ async def sessions_archive(session_id:
engine = _projects_engine()
try:
with engine.begin() as conn:
- session = workbench_sessions_service.archive_session(conn, session_id)
+ session = workbench_sessions_service.archive_session(
+ conn,
+ session_id,
+ authorization_context=getattr(g, "authorization_context", None),
+ )
except LookupError as err:
return jsonify({"error": str(err)}), 404
+ except ShowPageError as err:
+ return _show_page_error_response(err)
+ except PermissionError as err:
+ # A session the runtime reserves (today: the workspace-notifications row that
+ # is D5 rung (5)'s home). ``storage`` raises a machine ``code`` and carries no
+ # user-facing text, because the configured language is only resolvable up here.
+ code = getattr(err, "code", "forbidden")
+ if code == "reserved_session":
+ return _reserved_session_response(RESERVED_SESSION_PROTECTED_I18N_KEY, code=code)
+ return _coded_error_response(code, str(err), 403)
revoked_vault_scopes = session.pop("revoked_vault_grant_scopes", [])
@@@ -7117,7 -8170,10 +8546,11 @@@ def search_messages_list()
engine = _projects_engine()
with engine.connect() as conn:
result = messages_service.search_messages(
- conn, query=query, limit=limit, include_archived=include_archived
+ conn,
+ query=query,
+ limit=limit,
++ include_archived=include_archived,
+ scope_ids=_request_accessible_project_scope_ids(conn),
)
return jsonify(result)
@@@ -8114,11 -9006,18 +9591,18 @@@ async def sessions_messages_create(sess
"""
from core.services import sessions as workbench_sessions_service
+ from core.web_push_notifications import (
+ WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA,
+ web_push_authorization_context_record,
+ )
+ from modules.im.message_facts import is_ordinary_workbench_text
from storage import messages_service
+ from storage.agent_session_rows import session_is_runtime_owned
from vibe import internal_client
- from vibe.sse_broker import broker
payload = request.json or {}
+ memory_user_id = _workbench_memory_user_id()
+ memory_cli_admitted = memory_user_id is not None
text = payload.get("text")
content = payload.get("content")
if text is None and not content:
@@@ -8130,7 -9034,10 +9619,15 @@@
engine = _projects_engine()
try:
with engine.connect() as conn:
-- session = workbench_sessions_service.get_session(conn, session_id)
++ session = workbench_sessions_service.get_session(
++ conn,
++ session_id,
++ authorization_context=getattr(g, "authorization_context", None),
++ )
+ from core.vibe_agents import ensure_session_agent_access
+
- ensure_session_agent_access(conn, session)
++ _config, _session_payload, user_context = _remote_resource_access_context()
++ ensure_session_agent_access(conn, session, user_context=user_context)
# Archived sessions are terminal + inert: refuse to start a turn on one
# even via a stale/direct request (the workbench hides them from the
# list, so this only fires on a leftover tab or a hand-crafted call).
@@@ -8178,43 -9076,82 +9677,52 @@@
)
def _persist_user_row() -> dict | None:
- """Reserve the user's row as ``pending`` (hidden from transcript/queue/
- inbox) + clear any saved draft, WITHOUT publishing. This locks the row's
- ``(created_at, id)`` BEFORE the turn dispatches (so a fast reply can't
- sort ahead of its prompt) yet keeps it invisible during the dispatch
- window, so another tab can't briefly see it as a sent prompt (Codex P2).
- The caller promotes it (→ user / queued) once the outcome is known.
- Returns ``None`` if the session was archived in the meantime."""
+ """Atomically persist one unaccepted submission as a Delivery."""
+ from storage import message_deliveries
+ from storage.agent_session_rows import reserve_write_lock
+
with engine.begin() as conn:
- # Re-check archive ATOMICALLY with the reservation: a concurrent archive
- # may have committed since the pre-flight check above, and the session
- # must stay terminal — no new row, no turn.
+ reserve_write_lock(conn)
if workbench_sessions_service.is_session_archived(conn, session_id):
return None
+ delivery_id = message_deliveries.new_delivery_id()
+ message_metadata = {
+ **(payload.get("metadata") or {}),
+ "_web_push_user_key": web_push_user_key,
+ "_memory_user_id": memory_user_id,
+ "_memory_cli_admitted": memory_cli_admitted,
+ "_memory_ordinary_text": memory_ordinary_text,
+ }
+ message_metadata.pop(WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA, None)
+ if web_push_authorization_context is not None:
+ message_metadata[WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA] = [
+ web_push_authorization_context
+ ]
- row = messages_service.append(
+ row = message_deliveries.insert_delivery(
conn,
- scope_id=session["scope_id"],
+ delivery_id=delivery_id,
session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.PENDING_TYPE,
- text=text if isinstance(text, str) else None,
- content=content if isinstance(content, dict) else None,
- metadata=message_metadata,
- author_id=web_push_user_key,
- author_name=payload.get("author_name"),
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text=text if isinstance(text, str) else None,
+ content=content if isinstance(content, dict) else None,
- metadata={
- **(payload.get("metadata") or {}),
- "_web_push_user_key": web_push_user_key,
- },
++ metadata=message_metadata,
+ author_id=web_push_user_key,
+ author_name=payload.get("author_name"),
+ ),
+ dispatch_text=dispatch_text,
+ history_event={"kind": "admission", "priority": "p3", "state": "reserved"},
)
- # A quick-reply click is a side action, not the user submitting their
- # composer text — keep any saved draft intact for it.
if not quick_reply_for:
- messages_service.clear_draft(conn, session_id)
+ message_deliveries.set_draft(conn, session_id, None)
workbench_sessions_service.touch_session(conn, session_id)
- return message_deliveries.delivery_payload(row)
- return row
-
- def _promote_and_publish(row: dict) -> dict:
- """Promote the reserved pending row to a transcript-visible ``user`` row
- and fan it out (message.new + activity + inbox bump). Returns the row
- with its type corrected. The agent-reply side rides the controller→
- browser bridge, but the user row is persisted in this UI process so the
- controller bus never sees it."""
- with engine.begin() as conn:
- promoted = messages_service.promote_pending(conn, row["id"], "user")
- if not promoted:
- # The row wasn't pending anymore: the controller already promoted it
- # (e.g. enqueued as 'queued' via the busy-session path) before our
- # dispatch call failed/returned. Don't publish a phantom 'user'
- # transcript row alongside the still-queued item — nudge the queue view
- # and report it as queued instead (Codex P2).
- broker.publish("queue.updated", {"session_id": session_id, "scope_id": session["scope_id"]})
- return {**row, "type": "queued"}
- row = {**row, "type": "user"}
- broker.publish("message.new", row)
- broker.publish(
- "session.activity",
- {"session_id": session_id, "scope_id": session["scope_id"], "event": "user_message"},
- )
- try:
- with engine.connect() as conn:
- inbox_row = messages_service.get_inbox_session(conn, session_id, platform="avibe")
- if inbox_row is not None:
- broker.publish("inbox.session.updated", inbox_row)
- except Exception:
- logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)
- return row
++ return message_deliveries.public_delivery_payload(row)
# Reserve the row FIRST (pending), then decide by the dispatch outcome.
message = _persist_user_row()
@@@ -8242,76 -9173,28 +9750,80 @@@
"text": dispatch_text,
"scope_id": session["scope_id"],
"user_message_id": message.get("id"),
+ "display_text": message.get("text") or "",
+ "content": content if isinstance(content, dict) else None,
+ "metadata": payload.get("metadata") or {},
+ "author_id": web_push_user_key,
+ "author_name": payload.get("author_name"),
"files": attachment_specs,
+ "user_id": memory_user_id,
+ "message_id": message.get("id"),
+ "memory_cli_admitted": memory_cli_admitted,
+ "is_ordinary_text": memory_ordinary_text,
}
+
+ def _current_delivery_response() -> dict:
+ from storage import message_deliveries
+
+ with engine.connect() as conn:
+ current = message_deliveries.get_delivery(conn, str(message["id"]))
+ if current is None:
+ return dict(message)
- payload = message_deliveries.delivery_payload(current)
++ payload = message_deliveries.public_delivery_payload(current)
+ if current["state"] == "queued":
+ payload["type"] = "queued"
+ payload["queued"] = True
+ return payload
+
+ def _retire_unclaimed_delivery(reason: str) -> dict:
+ from storage import message_deliveries
+ from storage.agent_session_rows import reserve_write_lock
+
+ with engine.begin() as conn:
+ reserve_write_lock(conn)
+ message_deliveries.retire_reserved(
+ conn,
+ session_id,
+ str(message["id"]),
+ reason=reason,
+ )
+ return _current_delivery_response()
+
try:
result = await internal_client.dispatch_async(dispatch_payload)
+ except internal_client.InternalServerTimeout as exc:
+ current = _current_delivery_response()
+ return jsonify(
+ {
+ **current,
+ "dispatch_error": "dispatch_pending",
+ "detail": str(exc),
+ }
+ ), 504
except internal_client.InternalServerUnavailable as exc:
- # Couldn't reach the controller — promote + surface the row so the
- # user still sees their message, plus the failure.
- published = _promote_and_publish(message)
- return jsonify({**published, "dispatch_error": "internal_unavailable", "detail": str(exc)}), 502
+ current = _retire_unclaimed_delivery("internal_dispatch_unavailable")
+ return jsonify(
+ {
+ **current,
+ "dispatch_error": "internal_unavailable",
+ "detail": str(exc),
+ }
+ ), 502
except Exception as exc:
- # The socket existed but the call failed another way (ReadTimeout, a
- # non-JSON / 500 response, etc.). The row is still reserved as hidden
- # ``pending`` and the draft was cleared, so WITHOUT this the user's text
- # would vanish from both transcript and queue behind an error. Promote +
- # publish it with the error, same as the unavailable branch (Codex P2).
- logger.warning("dispatch_async call failed for session %s: %s", session_id, exc, exc_info=True)
- published = _promote_and_publish(message)
- return jsonify({**published, "dispatch_error": "dispatch_failed", "detail": str(exc)}), 502
+ logger.warning(
+ "dispatch_async acceptance is unknown for session %s: %s",
+ session_id,
+ exc,
+ exc_info=True,
+ )
+ current = _current_delivery_response()
+ return jsonify(
+ {
+ **current,
+ "dispatch_error": "dispatch_pending",
+ "detail": str(exc),
+ }
+ ), 502
status = result.get("status_code", 500)
body = result.get("body") or {}
# Quick-reply accepted (turn started OR queued) → record the choice on the
@@@ -8456,7 -9341,7 +9982,10 @@@ def sessions_queue_list(session_id: str
engine = _projects_engine()
with engine.connect() as conn:
- queued = message_deliveries.list_queued(conn, session_id)
- queued = messages_service.list_queued(conn, session_id)
++ queued = [
++ message_deliveries.public_delivery_payload(item)
++ for item in message_deliveries.list_queued(conn, session_id)
++ ]
return jsonify({"queued": queued})
@@@ -10015,6 -10855,28 +11703,46 @@@ def _show_event_response_payload
return public_event
-def _show_dispatch_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
++def _show_dispatch_response_payload(
++ event_payload: dict[str, Any],
++ *,
++ public: bool = False,
++) -> dict[str, Any]:
+ if not public:
+ return event_payload
+ return {
+ key: _redact_public_dispatch_value(value)
+ for key, value in event_payload.items()
- if key not in {"session_id", "scope_id", "message_id", "message", "user_message_id"}
++ if key
++ not in {
++ "session_id",
++ "scope_id",
++ "message_id",
++ "message",
++ "user_message_id",
++ }
+ }
+
+
+ def _redact_public_dispatch_value(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {
+ key: _redact_public_dispatch_value(nested)
+ for key, nested in value.items()
- if key not in {"session_id", "scope_id", "message_id", "message", "user_message_id"}
++ if key
++ not in {
++ "session_id",
++ "scope_id",
++ "message_id",
++ "message",
++ "user_message_id",
++ }
+ }
+ if isinstance(value, list):
+ return [_redact_public_dispatch_value(item) for item in value]
+ return value
+
+
def _show_events_list_payload(
payload: dict[str, Any],
*,
@@@ -10102,7 -11022,13 +11888,23 @@@ async def _show_events_stream
public_share_id=public_share_id,
),
)
- elif event_type == "show.dispatch" and isinstance(event_payload, dict) and _event_visible(event_payload):
- yield _sse_frame("show.dispatch", _show_dispatch_response_payload(event_payload, public=public))
++ elif (
++ event_type == "show.dispatch"
++ and isinstance(event_payload, dict)
++ and _event_visible(event_payload)
++ ):
++ yield _sse_frame(
++ "show.dispatch",
++ _show_dispatch_response_payload(
++ event_payload,
++ public=public,
++ ),
++ )
except asyncio.TimeoutError:
+ if not _authorization_is_current():
+ return
+ if authorization_refresh_at is not None and time.time() >= authorization_refresh_at:
+ return
yield ": ping\n\n"
except asyncio.CancelledError:
raise