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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(sessions): decouple visibility from scope placement (#957)
Call White3857f8321c61
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex b5461d59a..346fce83d 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -157,11 +157,9 @@ class MessageHandler(BaseHandler):from core.message_mirror import mirror_inboundmirror_inbound(context, control_message)- elif not (context.platform_specific or {}).get("suppress_delivery"):- # Harness turn (scheduled / watch / webhook). Skip the mirror when- # the run suppresses delivery (a ``no_delivery`` target): the- # dispatcher keeps that run's output private, so persisting its- # prompt would leak the input into the visible transcript.+ else:+ # Harness turns retain a complete local transcript even when their+ # session is background-only; visibility gates outward delivery.from core.message_mirror import mirror_harness_inboundmirror_harness_inbound(context, message)@@ -216,6 +214,15 @@ class MessageHandler(BaseHandler):)if not session_agent_backend and resolved_target.get("agent_backend"):session_agent_backend = str(resolved_target["agent_backend"])+ if resolved_target.get("agent_session_id"):+ # The concrete persisted target owns outward delivery. Resolve+ # this before the backend guard below: existing sessions already+ # carry a backend, so the fallback anchor lookup is intentionally+ # skipped for them.+ platform_payload["suppress_delivery"] = (+ resolved_target.get("visibility") == "background"+ )+ context.platform_specific = platform_payload# Pin an EXISTING thread to its OWN backend. avibe carries the session# row in ``agent_session_target``; IM/CLI turns don't, so look up the# thread's (scope, anchor) row and adopt its agent/backend. A thread@@ -233,6 +240,13 @@ class MessageHandler(BaseHandler):if existing_thread:requested_vibe_agent = existing_thread.get("agent_name") or requested_vibe_agentsession_agent_backend = existing_thread.get("agent_backend") or session_agent_backend+ # Scope is only placement. A persisted session's visibility is+ # the single outward-delivery gate, including ordinary IM turns+ # after an agent promotes or backgrounds the session via CLI/API.+ platform_payload["suppress_delivery"] = (+ existing_thread.get("visibility") == "background"+ )+ context.platform_specific = platform_payloadresolve_vibe_agent = getattr(self.controller, "resolve_vibe_agent_for_context", None)vibe_agent = Noneif requested_vibe_agent and callable(resolve_vibe_agent):diff --git a/core/internal_server.py b/core/internal_server.pyindex d0d336dc0..d5f117707 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -160,22 +160,21 @@ def create_app(controller: "Controller") -> FastAPI:engine = get_cached_sqlite_engine()with engine.begin() as conn:scope_id = _scope_id_for_session(conn, session_id)- if scope_id is not None:- try:- messages_service.append(- conn,- scope_id=scope_id,- session_id=session_id,- platform="avibe",- author="harness",- source="harness",- message_type=messages_service.QUEUED_TYPE,- text=text,- metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},- native_message_id=native_message_id or None,- )- except IntegrityError:- logger.info("scheduled turn duplicate native id already queued: %s", native_message_id)+ try:+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.QUEUED_TYPE,+ text=text,+ metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},+ native_message_id=native_message_id or None,+ )+ except IntegrityError:+ logger.info("scheduled turn duplicate native id already queued: %s", native_message_id)return await manager.submit(session_id, context, text, source=SOURCE_SCHEDULED, enqueue=_enqueue)@@ -753,6 +752,7 @@ def _build_session_context("session_anchor": session_row.get("session_anchor"),}platform_specific["agent_session_target"] = target+ platform_specific["suppress_delivery"] = session_row.get("visibility") == "background"if session_row.get("agent_name"):platform_specific["vibe_agent_name"] = session_row["agent_name"]diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 5f00fcc35..a140ba1fb 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -1430,8 +1430,7 @@ class ConsolidatedMessageDispatcher:await self._collapse_status_bubble(context, im_client, reason=terminal_reason)await self._clear_consolidated_state(context)self._signal_turn_complete(context)- suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery"))- if level != "silent" and not is_error and not suppress_delivery:+ if level != "silent" and not is_error:# A CLEAN silent completion — ``level='normal'`` with an# empty/``<silent>``-stripped body (we're already inside the# ``level=='silent' or not text.strip()`` branch, so here the@@ -1444,12 +1443,9 @@ class ConsolidatedMessageDispatcher:# ``level='silent'`` and ``is_error=False`` — a stop legitimately# stays ``interrupted``, so ``not is_error`` is the wrong gate.# Backend failures also arrive ``level='silent'`` (after a- # visible notify), and are excluded here too. And a- # ``suppress_delivery`` run is a private/background turn that- # intentionally leaves NO message history — writing a marker- # would pollute the cross-platform store + activity/fork state,- # so it is excluded (mirrors the suppressed-delivery path that- # already skips ``persist_agent_message``).+ # visible notify), and are excluded here too. Background+ # sessions still keep this local terminal marker; visibility+ # suppresses outward delivery, not durable history.try:persist_silent_completion_marker(context)except Exception:@@ -1512,8 +1508,7 @@ class ConsolidatedMessageDispatcher:self._release_runtime_turn(context)# Persistence is decided per delivery path below, not here, so that:- # * suppressed scheduled runs (intentionally private) never leak into- # the cross-platform messages history,+ # * background sessions retain local history without platform delivery,# * a user-facing result/notify that fails every IM send isn't recorded# as if the user received it (matches the old success-only mirror),# * intermediate assistant/tool_call log rows STILL persist pre-mute so@@ -1524,13 +1519,48 @@ class ConsolidatedMessageDispatcher:if (context.platform_specific or {}).get("suppress_delivery"):try:- message_id = f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"+ recorded_text = self._fold_footer(persist_text, result_footer)+ persisted_output = None+ if canonical_type == "result":+ result_type = "error" if is_error else "result"+ if target_context.platform == "avibe":+ background_enhanced = process_reply(+ text,+ include_quick_replies=quick_replies_on,+ keep_file_links=True,+ )+ recorded_text = self._fold_footer(+ background_enhanced.text or persist_text,+ result_footer,+ )+ persisted_output = persist_agent_message(+ target_context,+ result_type,+ recorded_text,+ quick_replies=[b.text for b in background_enhanced.buttons] or None,+ metadata=output_metadata,+ native_message_id=native_output_id,+ )+ else:+ persisted_output = persist_agent_message(+ target_context,+ result_type,+ recorded_text,+ metadata=output_metadata,+ native_message_id=native_output_id,+ )+ else:+ persisted_output = persist_agent_message(+ target_context,+ canonical_type,+ recorded_text,+ metadata=output_metadata,+ native_message_id=native_output_id,+ )+ message_id = (persisted_output or {}).get("id") or (+ f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"+ )terminal_status = None- # Delivery is suppressed (private scheduled/agent_run), so the footer- # can't ride subtext — fold the show_duration footnote into the- # RECORDED text so the stored result keeps the duration/token info- # that used to live in the body. No-op when there is no footer.- recorded_text = self._fold_footer(text, result_footer)if (canonical_type == "result"and (context.platform_specific or {}).get("task_trigger_kind") == "agent_run"diff --git a/core/message_mirror.py b/core/message_mirror.pyindex d0156c7a0..04917588e 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -193,6 +193,7 @@ def _session_row(conn, session_id: str) -> Optional[dict]:agent_sessions.c.scope_id,agent_sessions.c.agent_name,agent_sessions.c.agent_backend,+ agent_sessions.c.visibility,).where(agent_sessions.c.id == session_id)).mappings().first()return dict(row) if row else None@@ -270,6 +271,7 @@ def persist_silent_completion_marker(context: MessageContext) -> None:if not context.platform:returnsession_id = (context.platform_specific or {}).get("agent_session_id")+ suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery"))engine = get_cached_sqlite_engine()inbox_row = Nonewith engine.begin() as conn:@@ -279,7 +281,7 @@ def persist_silent_completion_marker(context: MessageContext) -> None:else:session_row = Nonescope_id = _resolve_scope_id(conn, context)- if scope_id is None:+ if scope_id is None and session_row is None:returnagent_name, _backend = _agent_provenance_from_context(context, session_row)_append_quietly(@@ -299,7 +301,7 @@ def persist_silent_completion_marker(context: MessageContext) -> None:)# Recompute the session's inbox row so the awaiting/replied flag clears live.# avibe-only (the workbench inbox is avibe-scoped; IM rows aren't shown there).- if context.platform == "avibe" and session_id:+ if context.platform == "avibe" and session_id and not suppress_delivery:inbox_row = messages_service.get_inbox_session(conn, session_id)if inbox_row is not None:# Same ``inbox.session.updated`` event a visible reply publishes — but NOT@@ -347,6 +349,7 @@ def persist_agent_message(if (canonical_type or "") == "system":returnsession_id = (context.platform_specific or {}).get("agent_session_id")+ suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery"))try:engine = get_cached_sqlite_engine()inbox_row = None@@ -374,7 +377,7 @@ def persist_agent_message(session_row = Nonescope_id = _resolve_scope_id(conn, context)row_session_id = session_id- if scope_id is None:+ if scope_id is None and session_row is None:return# Provenance: every agent reply is source='agent'; name = the# session's agent (from the dispatch context). source_id (author_id)@@ -407,7 +410,11 @@ def persist_agent_message(# (the dispatcher uploads those to the platform separately). Scoped to# the user-visible result/notify rows so we don't mint tokens for the# hidden intermediate assistant stream.- if context.platform == "avibe" and message_type in ("result", "notify", "error") and row_session_id:+ if (+ context.platform == "avibe"+ and message_type in ("result", "notify", "error")+ and row_session_id+ ):try:from core.workbench_media import rewrite_agent_media@@ -441,14 +448,14 @@ def persist_agent_message(# Recompute the session's inbox row so the realtime event can patch# the browser without a refetch. avibe-only: the workbench inbox is# scoped to avibe sessions (IM rows persist but aren't shown there).- if context.platform == "avibe" and session_id:+ if context.platform == "avibe" and session_id and not suppress_delivery:inbox_row = messages_service.get_inbox_session(conn, session_id)# tool_call rows never enter ``messages``/TRANSCRIPT_TYPES; when the Chat# activity panel is enabled they fan out here as a synthesized# ``message.new`` so an open Chat page shows the step live. Default off →# no publish (strict no-op). Return None to preserve the tool_call contract.if is_tool_call:- if context.platform == "avibe" and _activity_streaming_enabled():+ if context.platform == "avibe" and not suppress_delivery and _activity_streaming_enabled():_publish_activity_event(tool_event_row)return None# Fan the row out to an open Chat page (session-scoped stream), then bump@@ -460,7 +467,7 @@ def persist_agent_message(# avibe-only: IM rows now carry a session_id too, but the workbench Chat is# avibe-only, so keep the live fan-out scoped to avibe (an IM session has no# open Chat consumer; publishing it would be dead traffic).- if context.platform == "avibe" and (+ if context.platform == "avibe" and not suppress_delivery and (message_type in messages_service.TRANSCRIPT_TYPESor (message_type == "assistant" and _activity_streaming_enabled())):@@ -529,13 +536,15 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:trigger_kind = spec.get("task_trigger_kind")definition_id = spec.get("task_definition_id")session_id = spec.get("agent_session_id")+ suppress_delivery = bool(spec.get("suppress_delivery"))try:engine = get_cached_sqlite_engine()appended_row = Noneinbox_row = Nonewith engine.begin() as conn:if context.platform == "avibe":- scope_id = _scope_id_for_session(conn, session_id) if session_id else None+ session_row = _session_row(conn, session_id) if session_id else None+ scope_id = session_row["scope_id"] if session_row else Nonerow_session_id = session_idelse:# Attribute the prompt to the SAME scope the reply lands in. A@@ -558,7 +567,8 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:# session_id too so the harness prompt joins to its session, the# same way the agent reply does in ``persist_agent_message``.row_session_id = session_id- if scope_id is None:+ session_row = None+ if scope_id is None and session_row is None:returnappended_row = _append_quietly(conn,@@ -577,12 +587,12 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:# Recompute the inbox card so the harness prompt re-ranks the session# + flips its activity for other open views (avibe only; the inbox is# avibe-scoped). No-op until the session has a result row.- if context.platform == "avibe" and row_session_id:+ if context.platform == "avibe" and row_session_id and not suppress_delivery:inbox_row = messages_service.get_inbox_session(conn, row_session_id)# Surface the harness-triggered prompt on an open Chat page immediately,# so the upcoming agent reply isn't shown with no originating turn.# avibe-only: IM rows carry a session_id now but have no open Chat consumer.- if context.platform == "avibe":+ if context.platform == "avibe" and not suppress_delivery:_publish_session_message(appended_row)if inbox_row is not None:from core.inbox_events import busdiff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 741dfcd6a..fa14c07bc 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -184,6 +184,8 @@ class ResolvedSessionIdTarget:agent_backend: stragent_variant: strnative_session_id: str+ scope_id: Optional[str] = None+ visibility: str = "foreground"agent_id: Optional[str] = Noneagent_name: Optional[str] = Nonemodel: Optional[str] = None@@ -220,7 +222,9 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = Nonerow = conn.execute(select(agent_sessions.c.id,+ agent_sessions.c.scope_id,agent_sessions.c.status,+ agent_sessions.c.visibility,agent_sessions.c.agent_id,agent_sessions.c.agent_name,agent_sessions.c.agent_backend,@@ -233,7 +237,6 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = Nonescopes.c.platform,scopes.c.scope_type,scopes.c.native_id,- scopes.c.metadata_json.label("scope_metadata_json"),agent_sessions.c.metadata_json.label("session_metadata_json"),).join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)@@ -253,32 +256,39 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None# in depth for manual ``--session-id`` runs and any stragglers).if str(row["status"] or "") == "archived":raise ValueError(f"agent session is archived: {raw}")+ persisted_scope_id = str(row["scope_id"] or "").strip() or Noneplatform = str(row["platform"] or "")scope_type = str(row["scope_type"] or "")- scope_id = str(row["native_id"] or "")+ native_scope_id = str(row["native_id"] or "")# ``project`` is the avibe workbench's scope type (sessions live under# ``avibe::project::proj_<hex>``). A session-id target carries the concrete# ``session_id`` (the row PK) regardless of scope type, and the dispatch binds# the reply to that reserved session via ``agent_session_target`` — so a# project-scoped row IS a valid task target. (``--session-key`` targeting stays# channel/user-only: a bare project key wouldn't identify a single session.)- if not platform or scope_type not in {"channel", "user", "project"} or not scope_id:+ if persisted_scope_id is None:+ platform = "avibe"+ scope_type = "project"+ native_scope_id = raw+ elif not platform or scope_type not in {"channel", "user", "project"} or not native_scope_id:raise ValueError(f"agent session id cannot be used as a task target: {raw}")anchor = str(row["session_anchor"] or "")- thread_id = _thread_id_from_session_anchor(anchor, platform=platform, scope_id=scope_id)- session_metadata = _json_loads(row["session_metadata_json"], {})- scope_metadata = _json_loads(row["scope_metadata_json"], {})- suppress_delivery = bool(- (isinstance(session_metadata, dict) and session_metadata.get("no_delivery"))- or (isinstance(scope_metadata, dict) and scope_metadata.get("no_delivery"))+ thread_id = (+ None+ if persisted_scope_id is None or anchor == raw+ else _thread_id_from_session_anchor(anchor, platform=platform, scope_id=native_scope_id))+ session_metadata = _json_loads(row["session_metadata_json"], {})+ visibility = str(row["visibility"] or "foreground")return ResolvedSessionIdTarget(session_id=raw,+ scope_id=persisted_scope_id,+ visibility=visibility,session_key=ParsedSessionKey(platform=platform,scope_type=scope_type,- scope_id=scope_id,+ scope_id=native_scope_id,thread_id=thread_id,),agent_backend=str(row["agent_backend"] or ""),@@ -291,7 +301,7 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = Noneworkdir=row["workdir"],session_anchor=str(row["session_anchor"] or ""),metadata=session_metadata if isinstance(session_metadata, dict) else {},- suppress_delivery=suppress_delivery,+ suppress_delivery=visibility == "background",)@@ -1712,15 +1722,6 @@ class ScheduledTaskService:registry.ack_completed_output(activity)return- if target.suppress_delivery:- logger.info(- "Recovered Activity %s targets a no-delivery Session; settling without output",- getattr(activity, "id", ""),- )- self._settle_activity_without_output(activity)- registry.ack_completed_output(activity)- return-delivery_target = target.session_keydelivery_key = str((getattr(activity, "metadata", None) or {}).get("delivery_key_external")@@ -2612,24 +2613,29 @@ class ScheduledTaskService:workdir: Optional[str] = None,) -> str:scope_id = ""- legacy_delivery_target: Optional[ParsedSessionKey] = Noneif isinstance(metadata, dict):scope_id = str(metadata.get("session_scope_id") or "").strip()- if not scope_id:- legacy_delivery_target = parse_session_key(str(deliver_key or "").strip()) if deliver_key else None- scope_id = legacy_delivery_target.session_scope if legacy_delivery_target is not None else ""- if not scope_id:- raise ValueError("session creation requires scope_id")+ if not scope_id and deliver_key:+ # Definitions created before session_scope_id stored placement only+ # in deliver_key. Preserve those recurring definitions while new+ # definitions continue to persist the explicit metadata field.+ try:+ scope_id = parse_scope_id(deliver_key).session_scope+ except ValueError:+ try:+ scope_id = parse_session_key(deliver_key).session_scope+ except ValueError:+ passfrom config import paths as config_pathsfrom core.vibe_agents import VibeAgentStorefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_configfrom storage.sessions_service import SQLiteSessionsService- target = parse_scope_id(scope_id)+ target = parse_scope_id(scope_id) if scope_id else Noneensure_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 not agent_name else _ScopeAgentTarget(None)+ scope_target = self._resolve_scope_agent_target(scope_id) if scope_id and not agent_name else _ScopeAgentTarget(None)resolved_agent_name = agent_name or scope_target.agent_nameagent = agent_store.require_enabled(resolved_agent_name) if resolved_agent_name else agent_store.get_default_agent()finally:@@ -2639,16 +2645,27 @@ class ScheduledTaskService:agent_backend = agent.backendservice = SQLiteSessionsService(config_paths.get_sqlite_state_path())try:- session_id = service.reserve_agent_session(- scope_key=target.session_scope,- agent_backend=agent_backend,- session_anchor=f"{session_anchor_for_target(target)}:runtime_{uuid4().hex[:12]}",- agent_id=agent.id if agent else None,- agent_name=agent.name if agent else None,- model=agent.model if agent else None,- reasoning_effort=agent.reasoning_effort if agent else None,- workdir=workdir,- )+ common = {+ "agent_backend": agent_backend,+ "session_anchor": (+ f"{session_anchor_for_target(target)}:runtime_{uuid4().hex[:12]}"+ if target is not None+ else f"runtime_{uuid4().hex[:12]}"+ ),+ "agent_id": agent.id if agent else None,+ "agent_name": agent.name if agent else None,+ "model": agent.model if agent else None,+ "reasoning_effort": agent.reasoning_effort if agent else None,+ "workdir": workdir,+ "visibility": "background",+ }+ if target is None:+ session_id = service.reserve_standalone_agent_session(**common)+ else:+ session_id = service.reserve_agent_session(+ scope_key=target.session_scope,+ **common,+ )finally:service.close()if not session_id:diff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.pyindex 28ecceb3b..0301d6540 100644--- a/core/services/agent_run_target.py+++ b/core/services/agent_run_target.py@@ -43,6 +43,7 @@ class AgentRunTarget:model: Optional[str] = Nonereasoning_effort: Optional[str] = Nonenative_session_id: Optional[str] = None+ visibility: str = "foreground"def to_payload(self) -> dict[str, Any]:return {@@ -62,6 +63,7 @@ class AgentRunTarget:"model": self.model,"reasoning_effort": self.reasoning_effort,"native_session_id": self.native_session_id,+ "visibility": self.visibility,}@@ -307,6 +309,7 @@ def _cached_target(model=_optional_str(cached.get("model")),reasoning_effort=_optional_str(cached.get("reasoning_effort")),native_session_id=_optional_str(cached.get("native_session_id")),+ visibility=str(cached.get("visibility") or "foreground"),)@@ -593,6 +596,7 @@ def _target_from_session_row(model=_optional_str(row.get("model")),reasoning_effort=_optional_str(row.get("reasoning_effort")),native_session_id=_optional_str(row.get("native_session_id")),+ visibility=str(row.get("visibility") or "foreground"),)diff --git a/core/services/running_agents.py b/core/services/running_agents.pyindex 0cf3e94cf..7e676ec11 100644--- a/core/services/running_agents.py+++ b/core/services/running_agents.py@@ -129,6 +129,8 @@ def _make_row("platform": None,"scope_type": None,"scope_display_name": None,+ "scope_id": None,+ "visibility": None,"trigger_source": None,"agent_name": None,"openable_in_chat": False,@@ -407,10 +409,10 @@ def _enrich_from_db(rows: list[dict[str, Any]]) -> None:agent_sessions.c.workdir,agent_sessions.c.agent_name,agent_sessions.c.last_active_at,+ agent_sessions.c.visibility,scopes.c.platform.label("scope_platform"),scopes.c.scope_type.label("scope_scope_type"),scopes.c.display_name.label("scope_display_name"),- scopes.c.native_type.label("scope_native_type"),).select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)).where(agent_sessions.c.session_anchor.in_(anchors))@@ -460,32 +462,20 @@ def _apply_session_meta(r: dict[str, Any], meta: dict[str, Any]) -> None:# scope row is missing (FK is nullable / SET NULL).split_platform, split_scope_type = _split_scope_id(scope_id)platform = meta.get("scope_platform") or split_platform- # Private agent runs (``vibe agent run`` / one agent invoking another) are- # NOT IM sessions: ``reserve_private_agent_session`` stamps the scope with a- # PLACEHOLDER platform (the configured primary platform — slack/discord/…,- # only "slack" when config is unreadable) but marks it- # ``native_type="private_agent_run"``. So keying off ``native_type`` (not the- # platform) catches these uniformly on every install. Without this guard the- # row would be mislabeled as a real IM session. Treat it as an agent-initiated- # internal run: no IM platform, ``trigger_source="agent"``, not chat-openable.- is_private_run = meta.get("scope_native_type") == "private_agent_run"r["session_id"] = meta.get("id")r["title"] = meta.get("title")- r["platform"] = None if is_private_run else platform+ r["platform"] = platform+ r["scope_id"] = scope_idr["scope_type"] = meta.get("scope_scope_type") or split_scope_typer["scope_display_name"] = meta.get("scope_display_name")+ r["visibility"] = meta.get("visibility") or "foreground"r["agent_name"] = meta.get("agent_name")if not r.get("workdir"):r["workdir"] = meta.get("workdir")- # Trigger source: agent-initiated for private agent runs; otherwise human.- # (scheduled/watch/webhook/callback are only asserted when a harness run- # reliably links them, which is not modeled here.)- r["trigger_source"] = "agent" if is_private_run else "human"- # Private agent runs are internal (``no_delivery``) — not user chat sessions —- # so they are not openable. Any other persisted session IS openable in the- # workbench Chat by its id, IM sessions included (mirrors how the Inbox /- # sidebar navigate to ``/chat/<session_id>``).- r["openable_in_chat"] = bool(meta.get("id")) and not is_private_run+ # Run lineage owns precise trigger provenance; this live-process view only+ # distinguishes whether a persisted Session exists.+ r["trigger_source"] = r.get("trigger_source") or "human"+ r["openable_in_chat"] = bool(meta.get("id"))async def _end_orphan_pid(pid: int) -> dict[str, Any]:diff --git a/core/services/session_fork.py b/core/services/session_fork.pyindex 916efaace..396eadc5f 100644--- a/core/services/session_fork.py+++ b/core/services/session_fork.py@@ -112,6 +112,7 @@ def reserve_forked_session(model: Optional[str] = None,reasoning_effort: Optional[str] = None,scope_id: Optional[str] = None,+ visibility: str = "foreground",trim_latest_running_turn: bool = False,native_turn_started: bool = False,db_path: Optional[Path] = None,@@ -238,8 +239,6 @@ def reserve_forked_session(if target_scope_id != row["scope_id"]:metadata["fork_target_scope_id"] = target_scope_idmetadata["legacy_scope_key"] = target_scope_id- metadata.pop("private_agent_run", None)- metadata.pop("no_delivery", None)session_id = create_agent_session_row(conn,scope_id=target_scope_id,@@ -256,6 +255,7 @@ def reserve_forked_session(workdir=row["workdir"],native_session_id="",title=target_title,+ visibility=visibility,metadata=metadata,now=now,require_workdir=False,diff --git a/core/services/sessions.py b/core/services/sessions.pyindex 2bdd290fa..77fb0d810 100644--- a/core/services/sessions.py+++ b/core/services/sessions.py@@ -71,7 +71,7 @@ __all__ = ["touch_session","update_session","reserve_agent_session",- "reserve_private_agent_session",+ "reserve_standalone_agent_session",]@@ -122,6 +122,7 @@ def reserve_agent_session(model: Optional[str] = None,reasoning_effort: Optional[str] = None,workdir: Optional[str] = None,+ visibility: str = "foreground",metadata: Optional[dict] = None,db_path: Optional[Path] = None,) -> Optional[str]:@@ -143,15 +144,15 @@ def reserve_agent_session(model=model,reasoning_effort=reasoning_effort,workdir=workdir,+ visibility=visibility,metadata=metadata,)finally:service.close()-def reserve_private_agent_session(+def reserve_standalone_agent_session(*,- platform: str,agent_backend: str,session_anchor: str,agent_id: Optional[str] = None,@@ -159,18 +160,15 @@ def reserve_private_agent_session(model: Optional[str] = None,reasoning_effort: Optional[str] = None,workdir: Optional[str] = None,+ visibility: str = "background",metadata: Optional[dict] = None,db_path: Optional[Path] = None,) -> Optional[str]:- """Reserve a private (no IM scope) session, e.g. when ``vibe agent run``- is invoked without ``--deliver-key``. Mirrors- ``SQLiteSessionsService.reserve_private_agent_session``.- """+ """Reserve a background-capable session with no Scope."""service = _open_legacy_service(db_path)try:- return service.reserve_private_agent_session(- platform=platform,+ return service.reserve_standalone_agent_session(agent_backend=agent_backend,session_anchor=session_anchor,agent_id=agent_id,@@ -178,6 +176,7 @@ def reserve_private_agent_session(model=model,reasoning_effort=reasoning_effort,workdir=workdir,+ visibility=visibility,metadata=metadata,)finally:diff --git a/core/session_turns.py b/core/session_turns.pyindex 562679364..be9f45bd6 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -425,7 +425,7 @@ def _write_coalesced_native_id_markers(conn: Any, segment: list[dict]) -> None:returnfirst = segment[0]suppresses_delivery = _scheduled_segment_suppresses_delivery(segment)- marker_ids = native_ids if suppresses_delivery else native_ids[1:]+ marker_ids = native_ids[1:]if not marker_ids:returndiff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex a29ff2a2c..351d6b417 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -246,12 +246,14 @@ Useful Harness queries include schema discovery, current session lookup, existin`vibe watch add` creates a managed monitor, usually backed by a small script or command, for any observable condition that must be watched until true: product signals, business events, files, logs, CI/reviews/deploys, service health, data freshness, and similar signals. Watches created from an Avibe Agent shell follow up in this conversation by default. If `--cwd` is omitted, Avibe runs the waiter from the caller working directory when available.-Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. By default this creates a private/background Session for the target Agent, returns immediately, and from this Avibe Agent shell sends the final result back to this conversation. Avibe records caller provenance for both async and `--sync` runs. Pass `--sync` only when the current process must wait for the result. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later; pass `--callback-session-id <id>` only to route the final result elsewhere. Add `--same-scope` when the new Session should live under the same Workbench project or IM scope as the caller. Add `--scope-id <scopes.id>` only when placing the new Session in a specific existing scope.+Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. By default this creates a background Session in the caller's scope, returns immediately, and sends the final result back to this conversation. Outside an Agent shell, a caller-less run creates a standalone background Session with its own Show workspace. Avibe records caller provenance for both async and `--sync` runs. Pass `--visibility foreground` only when the new Session should deliver outward. Pass `--sync` only when the current process must wait for the result. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later; pass `--callback-session-id <id>` only to route the final result elsewhere. Add `--same-scope` to require the caller/source scope. Add `--scope-id <scopes.id>` only when placing the new Session in a specific existing scope.Use `vibe agent run --fork-self --message ...` when work should branch from this current Session's native backend context without mutating it. Use `--fork-session <source-session-id>` only when branching from a different explicit Session. Forks keep the source Session backend, scope, and cwd by default; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same.When `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings; those properties belong to the Session itself. Use a new Session or a fork when those properties need to differ.+Use `vibe session update --visibility foreground|background` to promote or hide a persisted Session independently of its scope. Use `--scope-id <scopes.id>` to move it to another scope or `--scope-id none` to make it standalone; moving scope never changes its stored workdir.+For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--message "..."` or `--message-file <path>` as the follow-up instruction template sent with waiter output. Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement.Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id.@@ -265,7 +267,7 @@ The table below is generated from currently enabled Agents at prompt-injection tRules:- All Agents listed in the generated table are enabled. Use the `Agent Name` value exactly as listed in shell commands such as `vibe agent show <agent-name>` and `vibe agent run --agent <agent-name> ...`.-- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate private/background Session for the target Agent.+- `--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing. Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate background Session for the target Agent.- `--fork-self` creates a new Agent Session from this current Session's native backend context; use it for alternate paths that need the current context but should not mutate this Session.- `--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context.- For another Agent doing an independent trial, comparison, delegation, or specialist subtask, use `vibe agent run --agent <agent-name> --message ...`.diff --git a/core/workbench_media.py b/core/workbench_media.pyindex 2aa339b8f..a3814bd83 100644--- a/core/workbench_media.py+++ b/core/workbench_media.py@@ -32,7 +32,7 @@ logger = logging.getLogger(__name__)def register_agent_reply_media(conn: Connection,*,- scope_id: str,+ scope_id: str | None,session_id: str | None,kind: str,local_path: str,@@ -50,7 +50,7 @@ def register_agent_reply_media()-def rewrite_agent_media(conn: Connection, *, scope_id: str, session_id: str, text: str) -> str:+def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: str, text: str) -> str:"""Return *text* with ``file://`` links rewritten to media-proxy URLs.Registers each referenced file in ``media_objects`` (same transaction as thediff --git a/docs/plans/agent-run-scope-semantics.md b/docs/plans/agent-run-scope-semantics.mdindex d15dd6e15..6f4e1eec1 100644--- a/docs/plans/agent-run-scope-semantics.md+++ b/docs/plans/agent-run-scope-semantics.md@@ -16,9 +16,9 @@ context as a first-class API.- Callback routing is a run-level completion policy, not a session-leveldefault. Synchronous runs should still record the callback route so a futurelong-running sync turn can detach into async without losing its return path.-- Scope placement is a session-level decision. It decides where a newly-created- session lives: a private/background scope, the caller/source scope, or a- specific `scopes.id`.+- Scope placement is a session-level decision. It decides whether a newly-created+ session lives under the caller/source scope, a specific `scopes.id`, or as a+ standalone session (`scope_id=NULL`). Visibility is independent of placement.- Message delivery overrides are not scope placement. Legacy transportoverrides should leave the agent-facing CLI surface.- New commands should use `--scope-id` or `--same-scope`.@@ -31,9 +31,10 @@ When an agent runs another agent with no explicit target:vibe agent run --agent claude --message "Review this patch"```-Avibe treats it as:+Avibe treats it as (superseded by+[`agents-run-graph-and-session-visibility.md`](agents-run-graph-and-session-visibility.md#part-c--scope--visibility-decoupling--standalone-sessions)):-- create a new private/background session;+- create a new background session in the caller session's scope;- use the caller shell cwd as the new session cwd;- record callback route to the caller session when `AVIBE_SESSION_ID` exists;- queue the run and return immediately by default.@@ -49,7 +50,8 @@ Use `--sync` only when the CLI process must wait for the run result. The legacy| `--fork-session <session-id>` | Fork the specified source session. || `--same-scope` | Place a newly-created session in the caller/source session's scope. || `--scope-id <scopes.id>` | Place a newly-created session in the exact scope row. |-| no scope parameter on create | Create a private/background session. |+| no scope parameter on create, with caller | Use the caller scope and background visibility. |+| no scope parameter on create, without caller | Create a standalone background session. |Forks inherit the source session's scope and cwd by default. `--same-scope` istherefore redundant but acceptable for fork commands. `--scope-id` may be used@@ -59,7 +61,8 @@ to fork into a different scope.| Operation | Default cwd || --- | --- |-| create private/background session | caller shell cwd |+| create with implicit caller scope | caller shell cwd |+| create standalone without caller | session Show workspace || create with `--same-scope` | selected scope workdir || create with `--scope-id` | selected scope workdir || fork self/session | source session cwd |@@ -86,13 +89,12 @@ sync runs, the route is recorded for future detach-to-async behavior.- Single-object session commands may default object id from `AVIBE_SESSION_ID`.- `vibe task add` / `vibe watch add` default their target session to`AVIBE_SESSION_ID` when they continue an existing session.-- When a task or watch creates sessions, agents should use `--same-scope` or- `--scope-id <scopes.id>`. The selected placement scope is stored in definition- metadata as `session_scope_id`, so future `create-session-per-run` triggers- can create the session in the right Workbench project or IM scope.-- `vibe task add` and `vibe watch add` snapshot the caller shell cwd when- `--cwd` is omitted. That cwd is reused when the definition later creates- sessions.+- A task/watch `create-session-per-run` definition uses stored+ `session_scope_id` when present; without one it creates a standalone+ background session. See the newer Part C specification linked above.+- `--cwd` remains an explicit per-definition override. Without it, scoped+ create-per-run sessions snapshot the selected scope workdir at reservation;+ standalone create-per-run sessions use their own Show workspace.## Migrationdiff --git a/docs/plans/agents-run-graph-and-session-visibility.md b/docs/plans/agents-run-graph-and-session-visibility.mdnew file mode 100644index 000000000..3e8ebcc56--- /dev/null+++ b/docs/plans/agents-run-graph-and-session-visibility.md@@ -0,0 +1,243 @@+# Agents Run Graph + Session Visibility Decoupling++Status: **APPROVED (owner, 2026-07-23)** — decisions D1/D4/D5 accepted as+recommended; D2 = keep the Harness Runs tab for now; D3 resolved as+**standalone sessions** (see Part C). Implementation lanes: M1 backend+(codex), M2 graph UI (claude).++Design source: `../avibe-docs/design.pen` frames+`vibe-remote — Agents · 运行图 Graph (Dark)` (node `KfgtJ`) and+`Agents · 运行图 — 规格注解 (Spec)` (node `anu5U`). Exported PNGs:+`_tmp/design-exports/KfgtJ.png`, `_tmp/design-exports/anu5U.png` (workspace+root, not committed).++Interface contract (frozen for parallel lanes):+`docs/plans/agents-run-graph-contract.md`.++Related plans: `agent-run-scope-semantics.md` (updated by Part C),+`agent-scope-model.md`, `agent-run-callback-session.md`.++## Background / problems++1. **Agents → Running tab is a flat list.** `RunningAgentsTab` shows live+ backend processes but no lineage: which session spawned which, and where+ results report back. The data already exists on `agent_runs`+ (`source_kind`, `source_actor` = caller session id, `parent_run_id`,+ `callback_session_id`, `callback_run_id`, `metadata_json.caller_context`)+ and is fully persisted for finished runs — nothing renders it.+2. **Harness → Runs duplicates the "what is running" surface** with a raw,+ hard-to-read run list. Users see two half-truths: Agents/Running (live+ processes, no history, no lineage) and Harness/Runs (all runs, no+ relationships, no session links).+3. **Scope conflates placement with visibility.** A `vibe agent run` without a+ scope target creates a synthetic scope+ (`scopes.native_type == "private_agent_run"`, placeholder platform,+ `no_delivery`) purely so the session falls outside every scope-keyed list+ query. Consequences:+ - a foreground session cannot be hidden;+ - a background session cannot be brought to the foreground (only+ `session fork` into a project scope approximates it, creating a new row);+ - background sessions' chat history is unreachable from the UI+ (`openable_in_chat=false` is keyed off the pseudo-scope marker).++## Goals++- One place answers "who is doing what, who started it, who gets the report":+ an interactive **run graph** on the Agents page, covering live **and**+ finished sessions.+- Every node is inspectable (detail panel) and every session — including+ background ones — can open its full chat history at `/chat/:sessionId`.+- Decouple **scope = placement** (which project/channel, workdir defaults,+ settings inheritance, routing) from **visibility = foreground/background**+ (whether the user sees it in session lists/inbox). Both become independently+ mutable.+- Make **standalone sessions** (no project) a first-class model state, with+ the session's own Show Page workspace as its default working directory.+- Converge the "runs" story so `agent_runs` stays the single store and the UI+ surfaces are projections of it.++Non-goals (this batch): multi-user ACLs; changing callback semantics;+removing the Harness Runs tab (owner: keep for now); user-facing "new+standalone session" entry point (model support only); mobile canvas rendering+(mobile degrades to a grouped list).++## Part A — Agents run graph++### Information architecture++- Agents page tabs: `Agent 列表` (definitions, unchanged) and `运行`+ (the graph; **replaces** the flat running list on desktop — D1 approved;+ badge = live session count). Mobile keeps a grouped list view fed by the+ same graph API.+- Filters: 活跃 / 含历史 segmented; time window (default 24h) applies to+ history; project filter (including `独立` bucket); `显示后台会话` toggle+ (default on).++### Graph semantics (all from existing columns)++- **Node = agent session** (`agent_sessions`), plus **trigger chips** for+ Task/Watch definitions (`run_definitions`).+- **Spawn edge** (solid, mint): runs with `source_kind='agent'`;+ `source_actor` (caller session) → `session_id` (spawned/continued session).+ Aggregate multiple runs between the same pair (edge carries run count).+- **Callback edge** (dashed, cyan): `callback_session_id` — the report route;+ state from `callback_status`.+- **Trigger edge** (dashed, violet): `run_type in (scheduled, watch)` via+ `definition_id` → carrying session. Chip click → Harness definition detail.+- **Node status**: live from the running-agents service (`active`/`idle`/+ `orphan`), else latest run terminal status (`queued`/`succeeded`/`failed`/+ `canceled`). History mode adds ended sessions within the time window.+- Roots (user-facing conversations) render with the foreground (eye) marker;+ background sessions show eye-off and dim when ended.++### Node detail panel++Session title + agent/backend/model/effort; facts: project (scope, or 独立),+workdir, visibility (+ inline `移到前台` / `隐藏` action), 启动方+(source_actor link — click selects that node), 汇报到 (callback target),+trigger source; a short per-session run timeline (each row deep-links to the+Harness run record); actions: `打开会话` (primary, `/chat/:sessionId`),+visibility toggle, `取消 Run` (active runs).++### API and frontend++- `GET /api/agents/graph` per the frozen contract doc. Server-side assembly+ in a new read-only `core/services/agent_graph.py`+ (`agent_sessions ⋈ scopes` + `agent_runs` aggregation + running-agents+ liveness merge). Window cap + `truncated` flag.+- Realtime: reuse SSE `runs_updated` / turn events to refetch; no new+ transport.+- Frontend: **@xyflow/react (React Flow)** + a layered left→right layout+ (dagre or elk) — D5 approved. Node card is a React component reusing+ existing `ui/src/components/ui/` primitives; design.pen is the visual+ source of truth.++## Part B — Harness Runs convergence++Principle: `agent_runs` remains the only store; views are projections.++- **The Runs tab stays** (owner D2: keep for now). Same-batch improvements:+ - Run detail renders the missing session/lineage fields+ (`session_id` + open-chat link, `source_kind`/`source_actor`,+ `parent_run_id`, callback fields) instead of hiding them.+ - Graph node detail run rows deep-link to `/harness?tab=runs&run=<id>`;+ existing backgroundActivity deep links keep working.+- Division of labor: **Agents·运行 = collaboration view** (who is working,+ who called whom), **Harness = triggers + audit trail** (Tasks/Watches+ definitions, Runs ledger). Removing the top-level Runs tab is explicitly+ deferred; revisit after the graph has been in daily use.++## Part C — scope / visibility decoupling + standalone sessions++### Model++- `agent_sessions.visibility TEXT NOT NULL DEFAULT 'foreground'`+ ∈ `foreground | background` (+ index; alembic migration).+- **Scope goes back to placement only.** A session either hangs on a real+ scope (workbench project or IM channel) **or has `scope_id = NULL` =+ standalone session (独立会话)** — a first-class state, not an error. The+ `private_agent_run` pseudo-scope is retired for new sessions.+- **Standalone session workdir = the session's own Show Page workspace**+ (`~/.avibe/show/<session_id>`, i.e. what `vibe show path` reports).+ Chicken-and-egg resolution: session ids are minted in-process+ (`storage/agent_session_rows.new_session_id`) **before** the row INSERT —+ the id is not DB-assigned. Creation flow:+ 1. mint `session_id`;+ 2. compute `workdir = <show workspace root>/<session_id>`;+ 3. `mkdir -p` that directory (the full Show Runtime scaffold stays lazy —+ directory existence is enough for a valid cwd; first `vibe show` use+ scaffolds the app as today);+ 4. INSERT the session row with the explicit `workdir` (explicit workdir+ already wins over scope snapshot in `create_agent_session_row`).+ Result: the session's work products, files, and its Show Page live in one+ self-contained, git-checkpointed folder per session.+- Placement defaults for `vibe agent run` (supersedes the corresponding rows+ in `agent-run-scope-semantics.md`):+ - no scope param + caller context → **caller session's scope**,+ `visibility='background'`; cwd rule unchanged (caller shell cwd).+ - `--same-scope` / `--scope-id` → as today; visibility defaults to+ `background` for delegated runs; explicit `--visibility foreground`+ opt-in.+ - no caller and no scope (human CLI outside a session) → **standalone**+ (`scope_id=NULL`) + `visibility='background'` + show-workspace workdir.+ - task/watch `create_per_run` sessions → definition's `session_scope_id`+ when present, else standalone; `visibility='background'` unless the+ definition says otherwise (D4 approved).+ - future user-facing "新建独立会话" → standalone + foreground (out of+ scope this batch; the model must support it).+- **Delivery rule**: `visibility='background'` ⇒ suppress outward platform+ delivery (today's `no_delivery`), callbacks unaffected. Promoting to+ foreground restores normal delivery from the next turn on. One rule+ replaces the metadata flag: 前台会说话,后台只干活、走 callback。+- **Query gates** switch from scope-shape heuristics to the flag:+ - workbench session list / `vibe session list` / inbox:+ `visibility='foreground'` (+ existing `status='active'`);+ - running-agents service: `openable_in_chat = true` for every persisted+ session (background included);+ - graph & Harness always see both visibilities;+ - scope joins become LEFT JOINs; NULL scope renders as the `独立` bucket.++### Operations++- API: `PATCH /api/sessions/:id { visibility }`; scope move is a separate+ operation (`{ scope_id }`, may be NULL for standalone) that does not touch+ the session's snapshotted workdir.+- CLI: `vibe session update --visibility foreground|background` and+ `--scope-id <scopes.id>|none`; agent-facing so an agent can surface a+ session it wrongly backgrounded.+- UI: graph detail panel buttons (`移到前台` / `隐藏`); session list row menu+ gets `隐藏会话`; hidden sessions reachable via the graph's+ `显示后台会话` toggle.+- Realtime contract: every PATCH or CLI placement edit publishes the same+ `session.activity` `updated` event with `session_id`, nullable `scope_id`,+ `title`, and `visibility`. Foreground-only list and Inbox consumers remove a+ row when `visibility='background'` and reconcile it when it returns to+ foreground or moves scope. M1 owns the shared backend event path; M2 owns+ the `ui/**` consumption so the two lanes do not edit `ApiContext.tsx` in+ parallel.++### Migration++1. Add column, backfill `foreground`.+2. Sessions on `private_agent_run` scopes → `visibility='background'`;+ re-parent `scope_id` to the caller session's scope via+ `agent_runs.source_actor` / `metadata_json.caller_context` when+ resolvable, **else `scope_id=NULL` (standalone)**. Session anchors are+ self-anchored (anchor = session id) so `(scope_id, session_anchor)`+ uniqueness holds — verify in migration tests. Existing workdirs stay+ untouched.+3. Keep legacy pseudo-scope rows for history until a later cleanup; stop+ creating new ones. `session_fork` stops stripping `private_agent_run`+ metadata (no longer meaningful).+4. Sweep every `private_agent_run` / `no_delivery` read site+ (`running_agents._apply_session_meta`, inbox/message services, delivery+ paths) to the new flag — fix the class, not instances.++## Phasing & lanes++- **M1 (backend, codex lane)**: visibility column + standalone sessions ++ placement defaults + delivery rule + query gates + CLI/API ops + migration+ + tests. No UI dependency. Branch `feat/session-visibility-decoupling`.+- **M2 (graph, claude lane)**: `core/services/agent_graph.py` ++ `GET /api/agents/graph` + Agents 运行 tab (React Flow) + detail panel ++ mobile list fallback + Harness RunDetail session/lineage enrichment.+ Branch `feat/agents-run-graph`. Contract-first; visibility actions call the+ M1 PATCH and degrade gracefully until M1 merges.+- Merge order M1 → M2 (M2 rebases). Mutual no-touch zones and exact file+ scopes are in the lane briefs; both lanes follow+ `.agents/skills/pr-delivery-loop/SKILL.md`.+- Later (separate batch): pseudo-scope row cleanup; Runs tab IA revisit;+ user-facing standalone session entry.++## Decision log (owner, 2026-07-23)++- D1 graph replaces desktop Running list — **approved**.+- D2 Harness Runs tab — **keep for now**; demotion deferred.+- D3 caller-less / project-less sessions — **standalone sessions**+ (`scope_id=NULL`), default workdir = own Show Page workspace directory;+ chicken-and-egg solved by pre-minting the session id (Part C).+- D4 task/watch-created sessions default background — **approved**.+- D5 @xyflow/react dependency — **approved**.+- D6 placement-change realtime ownership — **backend event contract in M1,+ browser consumption in M2**; M1 does not expand into `ui/**` because M2+ already owns the shared event client.diff --git a/docs/plans/agents-run-graph-contract.md b/docs/plans/agents-run-graph-contract.mdnew file mode 100644index 000000000..3ab47ce10--- /dev/null+++ b/docs/plans/agents-run-graph-contract.md@@ -0,0 +1,122 @@+# Contract: Agents Graph API + Session Visibility (FROZEN 2026-07-23)++Frozen interface contract for the two parallel lanes of+`agents-run-graph-and-session-visibility.md`. **Deviations require+orchestrator sign-off first** — do not negotiate field changes lane-to-lane.++## 1. Visibility enum (M1 owns, M2 consumes)++- `agent_sessions.visibility` ∈ `"foreground" | "background"`.+ No other values. Absent/legacy rows read as `"foreground"` after backfill.+- Standalone session: `agent_sessions.scope_id IS NULL`.++## 2. Session update (M1 owns)++`PATCH /api/sessions/<session_id>` accepts (in addition to existing fields):++```json+{ "visibility": "background" }+{ "scope_id": "avibe::project::proj_272e944ca452" }+{ "scope_id": null }+```++- `visibility` and `scope_id` are independent; either may appear alone.+- Response: the standard session payload, now always including+ `visibility` and (nullable) `scope_id`, `project_id`.+- Errors: `400` invalid value; `404` unknown session. Changing `scope_id`+ never mutates the session's stored `workdir`.++CLI equivalent: `vibe session update [--visibility foreground|background]+[--scope-id <scopes.id>|none]`.++## 3. Graph endpoint (M2 owns; shape frozen for both)++`GET /api/agents/graph?window=24h&project=<project_id|all|standalone>&include_ended=1&include_background=1`++- `window`: `1h|6h|24h|7d` (default `24h`); bounds history lookback+ (`agent_runs.created_at >= now - window`, plus all currently-live+ sessions regardless of window).+- `include_ended=0` ⇒ live sessions only. `include_background=0` ⇒+ foreground nodes only (edges to hidden nodes are dropped with them).++Response:++```json+{+ "ok": true,+ "generated_at": "2026-07-23T02:00:00Z",+ "window": "24h",+ "counts": { "active": 3, "idle": 1, "queued": 1, "ended": 4,+ "background": 5, "foreground": 3 },+ "nodes": [+ {+ "session_id": "ses7y3jff7b6r",+ "title": "Vaults M2 · 总控分派",+ "agent_name": "pm",+ "agent_backend": "claude",+ "model": "claude-fable-5",+ "reasoning_effort": "max",+ "status": "active",+ "live": true,+ "visibility": "foreground",+ "scope_id": "avibe::project::proj_272e944ca452",+ "project_id": "proj_272e944ca452",+ "scope_label": "vibe-remote",+ "platform": "avibe",+ "workdir": "/Users/cyh/vibe-remote-project",+ "openable_in_chat": true,+ "created_at": "2026-07-21T10:10:22Z",+ "last_active_at": "2026-07-23T01:58:00Z",+ "elapsed_seconds": 4320,+ "run_counts": { "total": 6, "running": 1 }+ }+ ],+ "trigger_nodes": [+ {+ "definition_id": "def_abc123",+ "definition_type": "scheduled",+ "name": "每日选题灵感",+ "schedule_label": "cron 10:17",+ "enabled": true+ }+ ],+ "edges": [+ { "kind": "spawn", "from": "ses_caller", "to": "ses_child",+ "run_count": 2, "last_run_id": "run_x", "last_at": "..." },+ { "kind": "callback", "from": "ses_child", "to": "ses_caller",+ "status": "pending", "last_run_id": "run_x" },+ { "kind": "trigger", "from": "def:def_abc123", "to": "ses_child",+ "run_count": 5, "last_at": "..." }+ ],+ "truncated": false+}+```++Semantics:++- Node `status` ∈ `active|idle|orphan` (live, from running-agents service)+ or `queued|succeeded|failed|canceled` (latest run outcome for non-live).+ `live` distinguishes the two families.+- `title` may be null → client falls back to `agent_name + session_id`+ suffix. `scope_label`/`project_id`/`scope_id`/`platform` null ⇒ standalone+ (`独立`).+- Edge node references: sessions by `session_id`; trigger chips by+ `def:<definition_id>`.+- `spawn` edges: aggregated per (caller session → callee session) from runs+ with `source_kind='agent'` and `source_actor` set.+- `callback` edges: emitted whenever `callback_session_id` is set (even when+ it equals the spawn caller — the client decides rendering). `status` ∈+ `pending|sent|failed|skipped` (from `callback_status`; null → `pending`).+- `trigger` edges: runs with `run_type in ('scheduled','watch')` grouped by+ `definition_id`.+- Cap: server may truncate to the most recent 300 nodes; set+ `truncated: true` when it does.++## 4. Graph payload consumers++- Desktop: React Flow canvas (Agents → 运行 tab).+- Mobile: grouped list rendering of the same payload (tree indentation by+ spawn edges).+- The running list's `end` action continues to use the existing+ `POST /api/running-agents/end` — the graph detail panel calls it+ unchanged.diff --git a/storage/agent_events_service.py b/storage/agent_events_service.pyindex 5f6950d40..219d7808a 100644--- a/storage/agent_events_service.py+++ b/storage/agent_events_service.py@@ -61,7 +61,7 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:def append(conn: Connection,*,- scope_id: str,+ scope_id: Optional[str],session_id: Optional[str],platform: str,event_type: str,diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.pyindex 5952d71e4..4f27dd1d8 100644--- a/storage/agent_session_rows.py+++ b/storage/agent_session_rows.py@@ -12,6 +12,7 @@ from storage.models import agent_sessions, scope_settingsSESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"JSON_VALUE_PREFIX = "__json__:"+SESSION_VISIBILITIES = frozenset({"foreground", "background"})def utc_now_iso() -> str:@@ -63,6 +64,7 @@ def create_agent_session_row(conn: Connection,*,scope_id: str | None,+ session_id: str | None = None,session_anchor: str | None,agent_backend: str,agent_variant: str | None = None,@@ -74,6 +76,7 @@ def create_agent_session_row(native_session_id: Any = "",title: str | None = None,status: str = "active",+ visibility: str = "foreground",agent_status: str = "idle",metadata: dict[str, Any] | None = None,now: str | None = None,@@ -90,7 +93,11 @@ def create_agent_session_row(if require_workdir and not resolved_workdir:raise ValueError(f"cannot create agent session without workdir for scope_id={scope_id!r}")- row_id = new_session_id(conn)+ visibility_value = str(visibility or "").strip()+ if visibility_value not in SESSION_VISIBILITIES:+ raise ValueError(f"invalid session visibility: {visibility!r}")++ row_id = str(session_id or new_session_id(conn))anchor = str(session_anchor) if session_anchor is not None else row_idnow_value = now or utc_now_iso()backend = str(agent_backend or "")@@ -111,6 +118,7 @@ def create_agent_session_row(native_session_id=encode_session_value(native_session_id),title=title_value,status=status,+ visibility=visibility_value,agent_status=agent_status,metadata_json=json.dumps(dict(metadata or {}), separators=(",", ":"), ensure_ascii=False),created_at=now_value,diff --git a/storage/alembic/versions/20260723_0032_session_visibility.py b/storage/alembic/versions/20260723_0032_session_visibility.pynew file mode 100644index 000000000..42ee39827--- /dev/null+++ b/storage/alembic/versions/20260723_0032_session_visibility.py@@ -0,0 +1,186 @@+"""decouple session visibility from scope placement++Revision ID: 20260723_0032+Revises: 20260721_0031+Create Date: 2026-07-23+"""++from __future__ import annotations++import json++import sqlalchemy as sa+from alembic import op++revision = "20260723_0032"+down_revision = "20260721_0031"+branch_labels = None+depends_on = None+++def _tables(bind) -> set[str]:+ return {+ str(row[0])+ for row in bind.exec_driver_sql(+ "select name from sqlite_master where type = 'table'"+ )+ }+++def _columns(bind, table: str) -> dict[str, tuple]:+ return {+ str(row[1]): tuple(row)+ for row in bind.exec_driver_sql(f'pragma table_info("{table}")').fetchall()+ }+++def _indexes(bind, table: str) -> set[str]:+ return {+ str(row[1])+ for row in bind.exec_driver_sql(f'pragma index_list("{table}")').fetchall()+ }+++def _caller_session_id(run, known_session_ids: set[str]) -> str | None:+ source_actor = str(run.source_actor or "").strip()+ if source_actor in known_session_ids:+ return source_actor+ try:+ metadata = json.loads(run.metadata_json or "{}")+ except (TypeError, ValueError):+ return None+ caller = metadata.get("caller_context") if isinstance(metadata, dict) else None+ if not isinstance(caller, dict):+ return None+ return str(caller.get("session_id") or "").strip() or None+++def _backfill_legacy_sessions(bind) -> None:+ legacy_ids = {+ str(row[0])+ for row in bind.exec_driver_sql(+ """+ select s.id+ from agent_sessions as s+ join scopes as sc on sc.id = s.scope_id+ where sc.native_type = 'private_agent_run'+ """+ ).fetchall()+ }+ if not legacy_ids:+ return++ rows = bind.exec_driver_sql("select id, scope_id from agent_sessions").fetchall()+ original_scope = {str(row[0]): row[1] for row in rows}+ runs = bind.exec_driver_sql(+ """+ select session_id, source_actor, metadata_json+ from agent_runs+ where session_id is not null+ order by created_at desc, id desc+ """+ ).fetchall()+ caller_by_session: dict[str, str] = {}+ for run in runs:+ spawned_id = str(run.session_id or "").strip()+ if spawned_id in caller_by_session:+ continue+ caller_id = _caller_session_id(run, set(original_scope))+ if caller_id in original_scope:+ caller_by_session[spawned_id] = caller_id++ def resolved_scope(session_id: str, seen: set[str]) -> str | None:+ if session_id in seen:+ return None+ scope_id = original_scope.get(session_id)+ if session_id not in legacy_ids:+ return str(scope_id) if scope_id else None+ caller_id = caller_by_session.get(session_id)+ if not caller_id:+ return None+ return resolved_scope(caller_id, {*seen, session_id})++ # Self-anchoring before the scope move preserves the unique+ # (scope_id, session_anchor) invariant even when siblings converge.+ for session_id in legacy_ids:+ bind.exec_driver_sql(+ """+ update agent_sessions+ set session_anchor = ?, scope_id = ?, visibility = 'background'+ where id = ?+ """,+ (session_id, resolved_scope(session_id, set()), session_id),+ )+++def upgrade() -> None:+ bind = op.get_bind()+ tables = _tables(bind)+ if "agent_sessions" not in tables:+ return++ if "visibility" not in _columns(bind, "agent_sessions"):+ op.add_column(+ "agent_sessions",+ sa.Column("visibility", sa.String(), nullable=False, server_default="foreground"),+ )+ if "ix_agent_sessions_visibility" not in _indexes(bind, "agent_sessions"):+ op.create_index("ix_agent_sessions_visibility", "agent_sessions", ["visibility"])++ message_refs: dict[str, list[tuple[str, str]]] = {}+ for table, key_column in (+ ("show_session_events", "id"),+ ("media_objects", "token"),+ ):+ if table in tables:+ message_refs[table] = [+ (str(row[0]), str(row[1]))+ for row in bind.exec_driver_sql(+ f"select {key_column}, message_id from {table} where message_id is not null"+ ).fetchall()+ ]++ if "messages" in tables and _columns(bind, "messages")["scope_id"][3]:+ with op.batch_alter_table("messages") as batch_op:+ batch_op.alter_column("scope_id", existing_type=sa.String(), nullable=True)+ existing_message_ids = {+ str(row[0])+ for row in bind.exec_driver_sql("select id from messages").fetchall()+ }+ for table, key_column in (+ ("show_session_events", "id"),+ ("media_objects", "token"),+ ):+ for row_key, message_id in message_refs.get(table, []):+ if message_id in existing_message_ids:+ bind.exec_driver_sql(+ f"update {table} set message_id = ? where {key_column} = ?",+ (message_id, row_key),+ )+ if "agent_events" in tables and _columns(bind, "agent_events")["scope_id"][3]:+ with op.batch_alter_table("agent_events") as batch_op:+ batch_op.alter_column("scope_id", existing_type=sa.String(), nullable=True)+ if "media_objects" in tables and _columns(bind, "media_objects")["scope_id"][3]:+ with op.batch_alter_table("media_objects") as batch_op:+ batch_op.alter_column("scope_id", existing_type=sa.String(), nullable=True)++ _backfill_legacy_sessions(bind)+++def downgrade() -> None:+ bind = op.get_bind()+ tables = _tables(bind)+ if "messages" in tables:+ bind.exec_driver_sql("delete from messages where scope_id is null")+ with op.batch_alter_table("messages") as batch_op:+ batch_op.alter_column("scope_id", existing_type=sa.String(), nullable=False)+ if "agent_events" in tables:+ bind.exec_driver_sql("delete from agent_events where scope_id is null")+ with op.batch_alter_table("agent_events") as batch_op:+ batch_op.alter_column("scope_id", existing_type=sa.String(), nullable=False)+ if "media_objects" in tables:+ bind.exec_driver_sql("delete from media_objects where scope_id is null")+ with op.batch_alter_table("media_objects") as batch_op:+ batch_op.alter_column("scope_id", existing_type=sa.String(), nullable=False)+ op.drop_index("ix_agent_sessions_visibility", table_name="agent_sessions")+ op.drop_column("agent_sessions", "visibility")diff --git a/storage/background.py b/storage/background.pyindex bd2fd9b13..c471c11b7 100644--- a/storage/background.py+++ b/storage/background.py@@ -1931,6 +1931,7 @@ class SQLiteBackgroundTaskStore:if session_id:row = conn.execute(select(+ agent_sessions.c.scope_id,agent_sessions.c.title,scopes.c.platform,scopes.c.scope_type,@@ -1946,7 +1947,11 @@ class SQLiteBackgroundTaskStore:if row is not None:platform = (row["platform"] or "").strip()scope_type = (row["scope_type"] or "").strip()- is_workbench = platform == "avibe" or scope_type == "project"+ is_workbench = (+ row["scope_id"] is None+ or platform == "avibe"+ or scope_type == "project"+ )summary["session_platform"] = platform or Nonesummary["session_scope_kind"] = scope_type or Nonesummary["session_is_workbench"] = is_workbenchdiff --git a/storage/media_service.py b/storage/media_service.pyindex 0e3dd851f..88866ccaf 100644--- a/storage/media_service.py+++ b/storage/media_service.py@@ -62,7 +62,7 @@ def _probe_image_dimensions(def register(conn: Connection,*,- scope_id: str,+ scope_id: Optional[str],session_id: Optional[str],kind: str,source: str,diff --git a/storage/messages_service.py b/storage/messages_service.pyindex e2f1a9d88..c7110b572 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -188,6 +188,7 @@ def search_messages(.where(messages.c.content_text.ilike(f"%{like}%", escape="\\"))# Archived sessions are soft-deleted — never surface their messages..where(agent_sessions.c.status != "archived")+ .where(agent_sessions.c.visibility == "foreground")# Archived PROJECTS are modelled as scope_settings.enabled = 0 (the# sessions stay active), so exclude a disabled scope's messages too. A# missing scope_settings row (legacy / folder-less project) is enabled.@@ -234,7 +235,7 @@ def search_messages(def append(conn: Connection,*,- scope_id: str,+ scope_id: Optional[str],session_id: Optional[str],platform: str,author: str,@@ -762,7 +763,13 @@ def get_draft(conn: Connection, session_id: str) -> Optional[dict[str, Any]]:return _row_to_payload(dict(row)) if row else None-def set_draft(conn: Connection, *, scope_id: str, session_id: str, text: Optional[str]) -> Optional[dict[str, Any]]:+def set_draft(+ conn: Connection,+ *,+ scope_id: Optional[str],+ session_id: str,+ text: Optional[str],+) -> Optional[dict[str, Any]]:"""Upsert the session's draft (one row per session). Blank text clears it."""conn.execute(delete(messages).where(messages.c.session_id == session_id).where(messages.c.type == DRAFT_TYPE)@@ -816,7 +823,12 @@ def unread_counts(or_(messages.c.session_id.is_(None),messages.c.session_id.not_in(- select(agent_sessions.c.id).where(agent_sessions.c.status == "archived")+ select(agent_sessions.c.id).where(+ or_(+ agent_sessions.c.status == "archived",+ agent_sessions.c.visibility != "foreground",+ )+ )),))@@ -850,7 +862,16 @@ def unread_counts_by_session(.where(messages.c.session_id.is_not(None))# Archived sessions are inert — their unread results must not light the# sidebar / global badge.- .where(messages.c.session_id.not_in(select(agent_sessions.c.id).where(agent_sessions.c.status == "archived")))+ .where(+ messages.c.session_id.not_in(+ select(agent_sessions.c.id).where(+ or_(+ agent_sessions.c.status == "archived",+ agent_sessions.c.visibility != "foreground",+ )+ )+ )+ ).group_by(messages.c.session_id))if platform is not None:@@ -987,7 +1008,10 @@ def list_inbox_sessions())# Archived sessions are hidden everywhere — keep them out of the inbox feed too.- session_rows = session_rows.where(agent_sessions.c.status != "archived")+ session_rows = session_rows.where(+ agent_sessions.c.status != "archived",+ agent_sessions.c.visibility == "foreground",+ )if only_session:session_rows = session_rows.where(agent_sessions.c.id == only_session)diff --git a/storage/migrations.py b/storage/migrations.pyindex 3bee6a1d8..3f3481c0c 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -68,7 +68,7 @@ PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = INITIAL_TABLES | {HEAD_REQUIRED_COLUMNS = {"agents": {"enabled"},"scope_settings": {"agent_name"},- "agent_sessions": {"agent_id", "agent_name"},+ "agent_sessions": {"agent_id", "agent_name", "visibility"},"messages": {"type", "source"},"run_definitions": {"deleted_at",@@ -599,6 +599,12 @@ def _repair_initial_required_columns(conn: sqlite3.Connection, tables: set[str])if "agent_name" not in columns:conn.execute('alter table "agent_sessions" add column "agent_name" VARCHAR')changed = True+ if "visibility" not in columns:+ conn.execute(+ 'alter table "agent_sessions" add column "visibility" '+ "VARCHAR not null default 'foreground'"+ )+ changed = Truereturn changed@@ -617,6 +623,10 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:if "agent_sessions" in tables:+ conn.execute(+ "create index if not exists ix_agent_sessions_visibility "+ "on agent_sessions (visibility)"+ )conn.execute("create index if not exists ix_agent_sessions_scope_status_activity ""on agent_sessions (scope_id, status, last_active_at, created_at, id)"diff --git a/storage/models.py b/storage/models.pyindex 5d94a8913..2e855fc4a 100644--- a/storage/models.py+++ b/storage/models.py@@ -120,6 +120,7 @@ agent_sessions = Table(Column("native_session_id", Text, nullable=False),Column("title", Text, nullable=True),Column("status", String, nullable=False),+ Column("visibility", String, nullable=False, server_default="foreground"),# Live agent-runtime status, distinct from the lifecycle ``status``# (active/archived). One of ``idle`` / ``running`` / ``failed`` —# ``running`` while a turn is in flight, ``failed`` when the most recent@@ -132,6 +133,7 @@ agent_sessions = Table(Index("ix_agent_sessions_scope_anchor_workdir", "scope_id", "session_anchor", "workdir"),Index("ix_agent_sessions_backend_variant", "agent_backend", "agent_variant"),Index("ix_agent_sessions_status_activity", "status", "last_active_at"),+ Index("ix_agent_sessions_visibility", "visibility"),Index("ix_agent_sessions_scope_status_activity", "scope_id", "status", "last_active_at", "created_at", "id"),Index("ix_agent_sessions_native_session", "native_session_id"),)@@ -295,7 +297,7 @@ agent_events = Table("agent_events",metadata,Column("id", String, primary_key=True),- Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=True),Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),Column("turn_id", String, nullable=True),Column("run_id", String, nullable=True),@@ -328,7 +330,7 @@ messages = Table("messages",metadata,Column("id", String, primary_key=True),- Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=True),Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),Column("platform", String, nullable=False),Column("author", String, nullable=False),@@ -411,7 +413,7 @@ media_objects = Table("media_objects",metadata,Column("token", String, primary_key=True),- Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=True),Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),Column("message_id", String, ForeignKey("messages.id", ondelete="SET NULL"), nullable=True),Column("kind", String, nullable=False),diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex be50a4769..4973a1c29 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -21,6 +21,7 @@ from storage.agent_session_rows import (create_agent_session_row,decode_session_value,encode_session_value,+ new_session_id,normalize_workdir,snapshot_scope_workdir,)@@ -156,6 +157,7 @@ class SQLiteSessionsService:model: str | None = None,reasoning_effort: str | None = None,workdir: str | None = None,+ visibility: str = "foreground",metadata: dict[str, Any] | None = None,) -> str | None:now = _utc_now_iso()@@ -176,15 +178,15 @@ class SQLiteSessionsService:model=model,reasoning_effort=reasoning_effort,workdir=_new_session_workdir(conn, scope_id, workdir),+ visibility=visibility,metadata={"legacy_scope_key": str(scope_key), **dict(metadata or {})},now=now,require_workdir=False,)- def reserve_private_agent_session(+ def reserve_standalone_agent_session(self,*,- platform: str,agent_backend: str,session_anchor: str,agent_id: str | None = None,@@ -192,30 +194,22 @@ class SQLiteSessionsService:model: str | None = None,reasoning_effort: str | None = None,workdir: str | None = None,+ visibility: str = "background",metadata: dict[str, Any] | None = None,) -> str:+ """Reserve a session with no Scope and its own lazy Show workspace."""now = _utc_now_iso()- platform_key = str(platform or "slack").strip() or "slack"- native_id = f"private-agent-run-{secrets.token_hex(8)}"- scope_key = f"{platform_key}::{native_id}"backend = str(agent_backend or "default")- metadata_payload = {"private_agent_run": True, "no_delivery": True}with self.engine.begin() as conn:- scope_id = upsert_scope(- conn,- platform_key,- "channel",- native_id,- display_name="Private Agent Run",- native_type="private_agent_run",- is_private=True,- supports_threads=False,- metadata=metadata_payload,- now=now,- )+ session_id = new_session_id(conn)+ resolved_workdir = normalize_workdir(workdir)+ if resolved_workdir is None:+ resolved_workdir = str(paths.get_show_page_dir(session_id))+ Path(resolved_workdir).mkdir(parents=True, exist_ok=True)return create_agent_session_row(conn,- scope_id=scope_id,+ session_id=session_id,+ scope_id=None,agent_backend=_agent_backend(backend),agent_variant=backend,session_anchor=session_anchor,@@ -224,10 +218,10 @@ class SQLiteSessionsService:agent_name=agent_name,model=model,reasoning_effort=reasoning_effort,- workdir=workdir,- metadata={"legacy_scope_key": scope_key, **metadata_payload, **dict(metadata or {})},+ workdir=resolved_workdir,+ visibility=visibility,+ metadata=dict(metadata or {}),now=now,- require_workdir=False,)def ensure_agent_session_id(diff --git a/storage/vault_service.py b/storage/vault_service.pyindex b7b5b7cdb..c32ae8cf9 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -987,6 +987,7 @@ def _request_session_summary(conn: Connection, session_id: str | None) -> dict[srow = conn.execute(select(agent_sessions.c.id,+ agent_sessions.c.scope_id,agent_sessions.c.title,scopes.c.platform,scopes.c.scope_type,@@ -1008,7 +1009,7 @@ def _request_session_summary(conn: Connection, session_id: str | None) -> dict[s}platform = str(row["platform"] or "").strip()scope_kind = str(row["scope_type"] or "").strip()- is_workbench = platform == "avibe" or scope_kind == "project"+ is_workbench = row["scope_id"] is None or platform == "avibe" or scope_kind == "project"title = row["title"]label = title if is_workbench else (row["display_name"] or row["native_id"] or title or session_id)return {diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 0c50f6963..78c5026b0 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -17,12 +17,18 @@ from __future__ import annotationsimport jsonimport osfrom datetime import datetime, timezone+from pathlib import Pathfrom typing import Any, Optionalfrom sqlalchemy import and_, func, or_, select, updatefrom sqlalchemy.engine import Connection-from storage.agent_session_rows import create_agent_session_row+from config import paths+from storage.agent_session_rows import (+ SESSION_VISIBILITIES,+ create_agent_session_row,+ new_session_id,+)from storage.db import escape_sql_likefrom storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_onefrom storage.models import (@@ -78,6 +84,7 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:"model": row.get("model"),"reasoning_effort": row.get("reasoning_effort"),"status": row.get("status"),+ "visibility": row.get("visibility") or "foreground",# Live agent-runtime status (idle/running/failed), separate from the# lifecycle ``status``. Older rows predating the column read as ``idle``."agent_status": row.get("agent_status") or "idle",@@ -125,7 +132,7 @@ def list_sessions(case-insensitive title LIKE match (LIKE metacharacters escaped)."""- query = select(agent_sessions)+ query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")if scope_id is not None:query = query.where(agent_sessions.c.scope_id == scope_id)if status is not None and status != "all":@@ -214,9 +221,18 @@ def list_sessions_page(without a second COUNT query."""request = PageRequest(page=max(int(page), 1), limit=max(int(limit), 1))- query = select(agent_sessions).where(agent_sessions.c.status == "active")+ query = select(agent_sessions).where(+ agent_sessions.c.status == "active",+ agent_sessions.c.visibility == "foreground",+ )if platform:- query = query.where(agent_sessions.c.scope_id.like(f"{platform}::%"))+ platform_filter = agent_sessions.c.scope_id.like(f"{platform}::%")+ if platform == "avibe":+ # Standalone sessions are Web/Workbench sessions without project+ # placement. Keep them visible through the agent-facing avibe type+ # filter even though their payload correctly has no platform.+ platform_filter = or_(agent_sessions.c.scope_id.is_(None), platform_filter)+ query = query.where(platform_filter)query = (query.order_by(agent_sessions.c.last_active_at.desc(),@@ -234,7 +250,7 @@ def list_sessions_page(def create_session(conn: Connection,*,- scope_id: str,+ scope_id: Optional[str],agent_backend: str,agent_name: Optional[str] = None,agent_id: Optional[str] = None,@@ -242,36 +258,40 @@ def create_session(model: Optional[str] = None,reasoning_effort: Optional[str] = None,title: Optional[str] = None,+ visibility: str = "foreground",metadata: Optional[dict[str, Any]] = None,) -> dict[str, Any]:- """Create a workbench session inside the given project scope.+ """Create a session in a Scope or as a standalone session.Pulls ``workdir`` from ``scope_settings`` so Agent runs already knowwhere to cd. ``native_session_id`` stays empty — Claude / OpenCode /Codex fill it on their first turn."""- scope_row = conn.execute(- select(- scopes.c.id,- scope_settings.c.workdir,- scope_settings.c.enabled,- scope_settings.c.agent_name,- agents.c.backend.label("agent_backend"),- scope_settings.c.agent_variant,- scope_settings.c.model,- scope_settings.c.reasoning_effort,- )- .select_from(- scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id)- .outerjoin(agents, agents.c.name == scope_settings.c.agent_name)- )- .where(scopes.c.id == scope_id)- ).mappings().first()- if scope_row is None:- raise LookupError(f"Scope not found: {scope_id}")- if scope_row.get("enabled") == 0:- raise PermissionError(f"Scope is archived: {scope_id}")+ scope_row: dict[str, Any] = {}+ if scope_id is not None:+ found = conn.execute(+ select(+ scopes.c.id,+ scope_settings.c.workdir,+ scope_settings.c.enabled,+ scope_settings.c.agent_name,+ agents.c.backend.label("agent_backend"),+ scope_settings.c.agent_variant,+ scope_settings.c.model,+ scope_settings.c.reasoning_effort,+ )+ .select_from(+ scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id)+ .outerjoin(agents, agents.c.name == scope_settings.c.agent_name)+ )+ .where(scopes.c.id == scope_id)+ ).mappings().first()+ if found is None:+ raise LookupError(f"Scope not found: {scope_id}")+ scope_row = dict(found)+ if scope_row.get("enabled") == 0:+ raise PermissionError(f"Scope is archived: {scope_id}")if agent_name and not agent_backend:agent_backend = _backend_for_agent_name(conn, str(agent_name))# Inherit the project's default Agent when the caller didn't pin a backend.@@ -299,8 +319,14 @@ def create_session(if metadata:metadata_payload.update(metadata)- session_id = create_agent_session_row(+ session_id = new_session_id(conn)+ workdir = scope_row.get("workdir") or os.getcwd()+ if scope_id is None:+ workdir = str(paths.get_show_page_dir(session_id))+ Path(workdir).mkdir(parents=True, exist_ok=True)+ create_agent_session_row(conn,+ session_id=session_id,scope_id=scope_id,agent_id=agent_id,agent_name=agent_name,@@ -310,8 +336,9 @@ def create_session(reasoning_effort=reasoning_effort,# Workbench sessions self-anchor; IM platforms use the parent message ts.session_anchor=None,- workdir=scope_row.get("workdir") or os.getcwd(),+ workdir=workdir,title=title,+ visibility=visibility,metadata=metadata_payload,now=now,)@@ -348,10 +375,13 @@ def update_session(agent_variant: Any = _UNSET,model: Any = _UNSET,reasoning_effort: Any = _UNSET,+ visibility: Any = _UNSET,+ scope_id: Any = _UNSET,) -> dict[str, Any]:existing = conn.execute(select(agent_sessions.c.id,+ agent_sessions.c.scope_id,agent_sessions.c.agent_backend,agent_sessions.c.native_session_id,agent_sessions.c.agent_status,@@ -430,6 +460,47 @@ def update_session(values["model"] = model or Noneif reasoning_effort is not _UNSET:values["reasoning_effort"] = reasoning_effort or None+ if visibility is not _UNSET:+ visibility_value = str(visibility or "").strip()+ if visibility_value not in SESSION_VISIBILITIES:+ raise ValueError(f"invalid session visibility: {visibility!r}")+ values["visibility"] = visibility_value+ if scope_id is not _UNSET:+ target_scope_id = str(scope_id) if scope_id is not None else None+ target_scope = None+ if scope_id is not None:+ scope = conn.execute(+ select(+ scopes.c.id,+ scopes.c.platform,+ scopes.c.native_id,+ scope_settings.c.enabled,+ )+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))+ .where(scopes.c.id == target_scope_id)+ ).first()+ if scope is None:+ raise ValueError(f"Scope not found: {scope_id}")+ if scope.enabled == 0:+ raise PermissionError(f"Scope is archived: {scope_id}")+ target_scope = scope+ values["scope_id"] = target_scope_id+ if target_scope_id != existing.scope_id:+ # Legacy IM caches still consult this metadata key first. A scope+ # move must stop pinning the session to the old channel; removing+ # the override lets the loader derive the key from the new scope.+ existing_metadata.pop("legacy_scope_key", None)+ values["metadata_json"] = _dumps_metadata(existing_metadata)+ # A session anchor encodes its delivery thread relative to its+ # scope. Carrying the old anchor across a move can reinterpret the+ # old channel id as a thread under the new scope. Standalone rows+ # self-anchor; scoped rows use a unique suffix whose base resolves+ # to the destination scope (and therefore no thread).+ values["session_anchor"] = (+ session_id+ if target_scope is None+ else f"{target_scope.platform}_{target_scope.native_id}:session_{session_id}"+ )stmt = update(agent_sessions).where(agent_sessions.c.id == session_id)if backend_changes:diff --git a/tests/test_agent_run_target.py b/tests/test_agent_run_target.pyindex 958533c95..a29341e8e 100644--- a/tests/test_agent_run_target.py+++ b/tests/test_agent_run_target.py@@ -148,6 +148,46 @@ def test_im_channel_scope_workdir_creates_session_snapshot(tmp_path):assert session["agent_variant"] == "codex"+def test_existing_background_im_target_carries_visibility(tmp_path):+ workdir = tmp_path / "channel"+ controller = _controller(tmp_path)+ with controller.sqlite_engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="slack",+ scope_type="channel",+ native_id="C123",+ now="2026-06-04T05:00:00Z",+ )+ _seed_scope_settings(conn, scope_id, workdir=str(workdir))+ session_id = create_agent_session_row(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_variant="codex",+ session_anchor="slack_171717.123",+ native_session_id="native-codex",+ workdir=str(workdir),+ visibility="background",+ )++ ctx = MessageContext(+ user_id="U1",+ channel_id="C123",+ platform="slack",+ thread_id="171717.123",+ )+ target = resolve_agent_run_target(+ ctx,+ controller=controller,+ base_session_id="slack_171717.123",+ )++ assert target.agent_session_id == session_id+ assert target.visibility == "background"+ assert ctx.platform_specific["agent_run_target"]["visibility"] == "background"++def test_new_im_session_uses_resolved_vibe_agent(tmp_path):workdir = tmp_path / "channel"agent = SimpleNamespace(diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.pyindex a8d80f20d..9a9f08214 100644--- a/tests/test_cli_agent_run_schema.py+++ b/tests/test_cli_agent_run_schema.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport jsonimport sysfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import patchimport pytest@@ -56,6 +57,7 @@ _EXPECTED_KEYS = {"session_id","deliver_key","scope_id",+ "visibility","callback_session_id","caller_context","callback_notice",@@ -70,6 +72,7 @@ _EXPECTED_RUN_KEYS_QUEUED = {"agent_name","session_id","scope_id",+ "visibility","callback_session_id","source_kind","source_actor",@@ -967,6 +970,7 @@ def test_agent_run_fork_session_reserves_new_session_and_persists_metadata(tmp_passert row["native_session_id"] == ""assert row["model"] == "gpt-5.2"assert row["reasoning_effort"] == "low"+ assert row["scope_id"] == "avibe::project::proj_fork_cli"assert row["session_anchor"] == payload["session_id"]@@ -1066,6 +1070,101 @@ def test_agent_run_create_same_scope_snapshots_scope_workdir(tmp_path: Path, capassert row["workdir"] == str(tmp_path)+def test_agent_run_same_scope_rejects_standalone_caller(tmp_path: Path, capsys) -> None:+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state++ state_home = tmp_path / "home"+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):+ ensure_sqlite_state()+ db_path = state_home / "state" / "vibe.sqlite"+ with create_sqlite_engine(db_path).begin() as conn:+ caller_session_id = sessions_service.create_session(+ conn,+ scope_id=None,+ agent_backend="codex",+ agent_name="worker",+ )["id"]+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")+ args = _parse_agent_run(+ ["--agent", "worker", "--same-scope", "--async", "--no-callback", "--message", "hi"]+ )++ with (+ patch.dict("os.environ", {"AVIBE_SESSION_ID": caller_session_id}),+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),+ ):+ result = cli.cmd_agent_run(args)++ assert result == 1+ payload = json.loads(capsys.readouterr().err)+ assert payload["code"] == "standalone_session_has_no_scope"+ assert payload["details"]["session_id"] == caller_session_id+++def test_agent_run_same_scope_rejects_standalone_fork_source(monkeypatch) -> None:+ args = _parse_agent_run(+ [+ "--agent",+ "worker",+ "--fork-session",+ "ses-standalone",+ "--same-scope",+ "--async",+ "--no-callback",+ "--message",+ "hi",+ ]+ )+ monkeypatch.setattr(cli, "_scope_id_from_session_id", lambda *_args, **_kwargs: None)++ with pytest.raises(cli.TaskCliError) as exc_info:+ cli._resolve_agent_run_scope_key(+ args,+ caller_context=None,+ source_session_id="ses-standalone",+ )++ assert exc_info.value.code == "standalone_session_has_no_scope"+++def test_agent_run_fork_defaults_to_source_scope_not_caller_scope(monkeypatch) -> None:+ args = _parse_agent_run(+ [+ "--agent",+ "worker",+ "--fork-session",+ "ses-source",+ "--async",+ "--no-callback",+ "--message",+ "hi",+ ]+ )+ resolved: list[str] = []+ monkeypatch.setattr(+ cli,+ "_scope_id_from_session_id",+ lambda session_id, **_kwargs: resolved.append(session_id) or "avibe::project::proj_caller",+ )++ scope_id = cli._resolve_agent_run_scope_key(+ args,+ caller_context=SimpleNamespace(session_id="ses-caller"),+ source_session_id="ses-source",+ )++ # None is intentional: reserve_forked_session interprets it as inherit the+ # source scope. Reaching the caller resolver here would override placement.+ assert scope_id is None+ assert resolved == []++def test_agent_run_create_scope_id_snapshots_scope_workdir(tmp_path: Path, capsys, monkeypatch) -> None:from sqlalchemy import select@@ -1256,13 +1355,8 @@ def test_agent_run_fork_rejects_cross_backend_agent(tmp_path: Path, capsys) -> Nassert payload["code"] == "session_fork_failed"-def test_agent_run_private_session_workdir_follows_invocation_cwd(tmp_path: Path, capsys, monkeypatch) -> None:- """A private (no --deliver-key) reservation snapshots the CLI invocation's- cwd as the new session's workdir — like every other CLI tool — instead of- leaving it blank and falling to the global default cwd at dispatch."""-- import os-+def test_agent_run_callerless_session_workdir_uses_show_workspace(tmp_path: Path, capsys, monkeypatch) -> None:+ """A caller-less run reserves a standalone Session in its Show workspace."""from storage.importer import ensure_sqlite_statestate_home = tmp_path / "home"@@ -1276,7 +1370,6 @@ def test_agent_run_private_session_workdir_follows_invocation_cwd(tmp_path: Pathrequest_store = cli.TaskExecutionStore(tmp_path / "task_requests")args = _parse_agent_run(["--agent", "worker", "--async", "--no-callback", "--message", "hi"])monkeypatch.chdir(invoke_dir)- expected = os.getcwd()with (patch("vibe.cli._agent_store", return_value=agent_store),@@ -1288,7 +1381,9 @@ def test_agent_run_private_session_workdir_follows_invocation_cwd(tmp_path: Pathassert result == 0payload = json.loads(capsys.readouterr().out)- assert _read_session_workdir(db_path, payload["session_id"]) == expected+ expected = state_home / "show" / payload["session_id"]+ assert _read_session_workdir(db_path, payload["session_id"]) == str(expected)+ assert expected.is_dir()def test_agent_run_explicit_cwd_wins(tmp_path: Path, capsys, monkeypatch) -> None:@@ -1350,14 +1445,22 @@ def test_agent_run_cwd_rejected_with_existing_session(capsys) -> None:def test_resolve_run_cwd_defaults_by_session_target(monkeypatch, tmp_path: Path) -> None:- """Without --cwd, private sessions snapshot the caller cwd, while scoped- sessions leave cwd unset so creation snapshots the selected scope workdir."""+ """Caller placement uses its cwd; standalone/scoped reservations derive theirs."""from types import SimpleNamespacemonkeypatch.chdir(tmp_path)args = SimpleNamespace(cwd=None)- assert cli._resolve_run_cwd(args, session_policy="create", help_command="x") == str(tmp_path)+ assert cli._resolve_run_cwd(args, session_policy="create", help_command="x") is None+ assert (+ cli._resolve_run_cwd(+ args,+ session_policy="create",+ invocation_cwd_default=True,+ help_command="x",+ )+ == str(tmp_path)+ )assert cli._resolve_run_cwd(args, session_policy="create", scoped_session=True, help_command="x") is Noneargs = SimpleNamespace(cwd=str(tmp_path), deliver_key="slack::channel::C123")diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex 8ebec2381..ccbac5e53 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -640,6 +640,40 @@ def test_task_add_create_per_run_scope_id_records_session_scope_metadata(tmp_patassert payload["task"]["agent_name"] == "project-agent"+def test_task_add_create_per_run_without_scope_records_standalone_definition(tmp_path: Path, capsys) -> None:+ db_path = tmp_path / "state" / "vibe.sqlite"+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ args = _parse_task_add(+ [+ "--agent",+ "worker",+ "--create-session-per-run",+ "--cron",+ "0 * * * *",+ "--message",+ "hello",+ ]+ )++ with (+ patch.dict(os.environ, {"AVIBE_SESSION_ID": ""}, clear=False),+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_store", return_value=store),+ ):+ result = cli.cmd_task_add(args)++ assert result == 0+ task = json.loads(capsys.readouterr().out)["task"]+ assert task["session_policy"] == "create_per_run"+ assert task["session_id"] is None+ assert task["deliver_key"] is None+ assert task["cwd"] is None+ assert "session_scope_id" not in task["metadata"]+ assert "session_workdir" not in task["metadata"]++def test_task_add_create_session_scope_id_supports_project_scope(tmp_path: Path, capsys) -> None:db_path = tmp_path / "state" / "vibe.sqlite"agent_store = cli.VibeAgentStore(db_path)@@ -701,6 +735,8 @@ def test_task_add_create_session_scope_id_supports_project_scope(tmp_path: Path,assert payload["task"]["session_policy"] == "create_once"target = cli.resolve_session_id_target(payload["task"]["session_id"], db_path=db_path)assert target.session_key.session_scope == "avibe::project::proj-once-task"+ assert target.visibility == "foreground"+ assert target.suppress_delivery is Falseassert target.workdir == str(tmp_path)assert payload["task"]["cwd"] is Noneassert payload["task"]["metadata"]["session_scope_id"] == "avibe::project::proj-once-task"@@ -1751,7 +1787,7 @@ def test_hook_send_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Paassert payload["warnings"][0]["code"] == "lark_user_not_bound"-def test_agent_run_private_async_reserves_session_and_queues_request(tmp_path: Path, capsys) -> None:+def test_agent_run_standalone_async_reserves_background_session(tmp_path: Path, capsys) -> None:db_path = tmp_path / "state" / "vibe.sqlite"agent_store = cli.VibeAgentStore(db_path)agent = agent_store.create(name="worker", backend="codex")@@ -1762,7 +1798,10 @@ def test_agent_run_private_async_reserves_session_and_queues_request(tmp_path: Ppatch("vibe.cli._agent_store", return_value=agent_store),patch("vibe.cli._task_request_store", return_value=request_store),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- patch("vibe.cli._primary_platform", return_value="slack"),+ patch(+ "storage.sessions_service.paths.get_show_page_dir",+ side_effect=lambda session_id: tmp_path / "show" / session_id,+ ),):result = cli.cmd_agent_run(args)@@ -1775,6 +1814,116 @@ def test_agent_run_private_async_reserves_session_and_queues_request(tmp_path: Passert queued["request_type"] == "agent_run"assert queued["session_id"] == payload["session_id"]assert queued["agent_name"] == "worker"+ with sqlite3.connect(db_path) as conn:+ row = conn.execute(+ "select scope_id, visibility, workdir from agent_sessions where id = ?",+ (payload["session_id"],),+ ).fetchone()+ assert row == (None, "background", str(tmp_path / "show" / payload["session_id"]))+ assert (tmp_path / "show" / payload["session_id"]).is_dir()+++def test_agent_run_caller_scope_default_keeps_caller_cwd_and_same_scope_uses_scope_cwd(+ tmp_path: Path,+ capsys,+ monkeypatch,+) -> None:+ from core.services import sessions as sessions_service+ from sqlalchemy import select+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.models import agent_sessions, scope_settings+ from storage.settings_service import upsert_scope++ home = tmp_path / "home"+ invocation_cwd = tmp_path / "caller-cwd"+ scope_cwd = tmp_path / "scope-cwd"+ invocation_cwd.mkdir()+ scope_cwd.mkdir()+ monkeypatch.setenv("AVIBE_HOME", str(home))+ ensure_sqlite_state()+ db_path = home / "state" / "vibe.sqlite"+ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_caller",+ now="2026-07-23T00:00:00Z",+ )+ conn.execute(+ scope_settings.insert().values(+ scope_id=scope_id,+ enabled=1,+ role=None,+ workdir=str(scope_cwd),+ agent_name=None,+ agent_backend=None,+ agent_variant=None,+ model=None,+ reasoning_effort=None,+ require_mention=None,+ settings_version=1,+ settings_json="{}",+ created_at="2026-07-23T00:00:00Z",+ updated_at="2026-07-23T00:00:00Z",+ )+ )+ caller = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="caller",+ )++ monkeypatch.setenv("AVIBE_SESSION_ID", caller["id"])+ monkeypatch.chdir(invocation_cwd)+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")++ def run(extra: list[str]) -> dict:+ args = _parse_agent_run(+ ["--agent", "worker", "--no-callback", *extra, "--message", "hello"]+ )+ with (+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_request_store", return_value=request_store),+ ):+ assert cli.cmd_agent_run(args) == 0+ return json.loads(capsys.readouterr().out)++ implicit = run([])+ explicit = run(["--same-scope"])+ visible = run(["--visibility", "foreground"])++ with engine.connect() as conn:+ rows = {+ row.id: row+ for row in conn.execute(+ select(+ agent_sessions.c.id,+ agent_sessions.c.scope_id,+ agent_sessions.c.visibility,+ agent_sessions.c.workdir,+ ).where(+ agent_sessions.c.id.in_(+ [implicit["session_id"], explicit["session_id"], visible["session_id"]]+ )+ )+ )+ }++ assert rows[implicit["session_id"]].scope_id == scope_id+ assert rows[implicit["session_id"]].visibility == "background"+ assert rows[implicit["session_id"]].workdir == str(invocation_cwd)+ assert rows[explicit["session_id"]].scope_id == scope_id+ assert rows[explicit["session_id"]].visibility == "background"+ assert rows[explicit["session_id"]].workdir == str(scope_cwd)+ assert rows[visible["session_id"]].scope_id == scope_id+ assert rows[visible["session_id"]].visibility == "foreground"+ assert rows[visible["session_id"]].workdir == str(invocation_cwd)def test_agent_run_create_session_uses_scope_anchor_for_channel_deliver_key(tmp_path: Path, capsys) -> None:@@ -1931,7 +2080,7 @@ def test_agent_run_create_session_scope_id_uses_unique_project_anchors(tmp_path:assert all(anchor.startswith("avibe_proj_unique:run_") for anchor in anchors)-def test_agent_run_private_async_uses_no_delivery_channel_scope_for_lark(tmp_path: Path, capsys) -> None:+def test_agent_run_standalone_does_not_create_platform_pseudo_scope(tmp_path: Path, capsys) -> None:db_path = tmp_path / "state" / "vibe.sqlite"agent_store = cli.VibeAgentStore(db_path)agent_store.create(name="worker", backend="codex")@@ -1942,7 +2091,10 @@ def test_agent_run_private_async_uses_no_delivery_channel_scope_for_lark(tmp_patpatch("vibe.cli._agent_store", return_value=agent_store),patch("vibe.cli._task_request_store", return_value=request_store),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),- patch("vibe.cli._primary_platform", return_value="lark"),+ patch(+ "storage.sessions_service.paths.get_show_page_dir",+ side_effect=lambda session_id: tmp_path / "show" / session_id,+ ),):result = cli.cmd_agent_run(args)@@ -1950,21 +2102,11 @@ def test_agent_run_private_async_uses_no_delivery_channel_scope_for_lark(tmp_patpayload = json.loads(capsys.readouterr().out)with sqlite3.connect(db_path) as conn:row = conn.execute(- """- select scopes.platform, scopes.scope_type, scopes.native_type, scopes.metadata_json, agent_sessions.metadata_json- from agent_sessions- join scopes on scopes.id = agent_sessions.scope_id- where agent_sessions.id = ?- """,+ "select scope_id, visibility from agent_sessions where id = ?",(payload["session_id"],),).fetchone()- assert row is not None- assert row[0] == "lark"- assert row[1] == "channel"- assert row[2] == "private_agent_run"- assert json.loads(row[3])["no_delivery"] is True- assert json.loads(row[4])["no_delivery"] is True+ assert row == (None, "background")def test_agent_run_rejects_deprecated_prompt_argument(tmp_path: Path) -> None:@@ -1997,10 +2139,10 @@ def test_agent_run_rejects_cross_backend_agent_for_existing_session(tmp_path: Paservice = SQLiteSessionsService(db_path)try:- session_id = service.reserve_private_agent_session(- platform="slack",+ session_id = service.reserve_standalone_agent_session(agent_backend="claude",session_anchor="slack_private-agent-test",+ workdir=str(tmp_path),)finally:service.close()@@ -2025,11 +2167,11 @@ def test_agent_run_existing_session_allows_matching_agent_hint(tmp_path: Path, cservice = SQLiteSessionsService(db_path)try:- session_id = service.reserve_private_agent_session(- platform="slack",+ session_id = service.reserve_standalone_agent_session(agent_backend="codex",agent_name="codex-worker",session_anchor="slack_private-agent-test",+ workdir=str(tmp_path),)finally:service.close()@@ -2069,11 +2211,11 @@ def test_agent_run_rejects_different_same_backend_agent_for_existing_session(tmpservice = SQLiteSessionsService(db_path)try:- session_id = service.reserve_private_agent_session(- platform="slack",+ session_id = service.reserve_standalone_agent_session(agent_backend="codex",agent_name="session-worker",session_anchor="slack_private-agent-test",+ workdir=str(tmp_path),)finally:service.close()@@ -2185,11 +2327,11 @@ def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_paservice = SQLiteSessionsService(db_path)try:- session_id = service.reserve_private_agent_session(- platform="slack",+ session_id = service.reserve_standalone_agent_session(agent_backend="codex",agent_name="worker",session_anchor="slack_private-agent-test",+ workdir=str(tmp_path),)finally:service.close()diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.pyindex 8b16bd484..52fb61d34 100644--- a/tests/test_cli_watch_command.py+++ b/tests/test_cli_watch_command.py@@ -367,6 +367,43 @@ def test_watch_add_create_per_run_scope_id_records_session_scope_metadata(tmp_paassert payload["watch"]["agent_name"] == "project-agent"+def test_watch_add_create_per_run_without_scope_records_standalone_definition(tmp_path: Path, capsys) -> None:+ db_path = tmp_path / "state" / "vibe.sqlite"+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ store = ManagedWatchStore(tmp_path / "watches.json")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ args = _parse_watch_add(+ [+ "--agent",+ "worker",+ "--create-session-per-run",+ "--shell",+ "echo done",+ ]+ )++ with (+ patch.dict(os.environ, {"AVIBE_SESSION_ID": ""}, clear=False),+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._watch_store", return_value=store),+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),+ patch(+ "vibe.cli._wait_for_watch_startup",+ side_effect=lambda *items, **kwargs: _startup_ok(store, runtime_store, items[2]),+ ),+ ):+ result = cli.cmd_watch_add(args)++ assert result == 0+ watch = json.loads(capsys.readouterr().out)["watch"]+ assert watch["session_policy"] == "create_per_run"+ assert watch["session_id"] is None+ assert watch["deliver_key"] is None+ assert "session_scope_id" not in watch["metadata"]+ assert "session_workdir" not in watch["metadata"]++def test_watch_add_create_session_scope_id_snapshots_scope_workdir(tmp_path: Path, capsys) -> None:db_path = tmp_path / "state" / "vibe.sqlite"agent_store = cli.VibeAgentStore(db_path)@@ -426,6 +463,8 @@ def test_watch_add_create_session_scope_id_snapshots_scope_workdir(tmp_path: Patassert result == 0payload = json.loads(capsys.readouterr().out)target = cli.resolve_session_id_target(payload["watch"]["session_id"], db_path=db_path)+ assert target.visibility == "foreground"+ assert target.suppress_delivery is Falseassert target.workdir == str(tmp_path)assert payload["watch"]["cwd"] == str(invoke_dir)assert "session_workdir" not in payload["watch"]["metadata"]diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex c5fe7caf9..80dcb1559 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -82,7 +82,7 @@ def test_public_surface_is_stable():"update_session",# Legacy IM-style reservation helpers added in C2 for the CLI:"reserve_agent_session",- "reserve_private_agent_session",+ "reserve_standalone_agent_session",# Backend-pin guard raised by update_session on a cross-backend switch:"SessionBackendLockedError",}@@ -172,6 +172,34 @@ def test_update_then_list_reflects_changes(isolated_state):assert page["sessions"][0]["model"] == "claude-sonnet-4-6"+def test_session_lists_only_include_foreground_sessions(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ foreground = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ title="Foreground",+ )+ background = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ title="Background",+ visibility="background",+ )++ with engine.connect() as conn:+ workbench = sessions_service.list_sessions(conn, scope_id=scope_id)+ cli_page = sessions_service.list_sessions_page(conn)+ direct = sessions_service.get_session(conn, background["id"])++ assert [row["id"] for row in workbench["sessions"]] == [foreground["id"]]+ assert [row["id"] for row in cli_page.items] == [foreground["id"]]+ assert direct["visibility"] == "background"++def test_list_sessions_title_query_filters_by_title(isolated_state):"""``#``-mention search: case-insensitive title LIKE, escaping LIKE metachars."""engine = create_sqlite_engine()@@ -245,6 +273,47 @@ def test_update_session_present_null_clears_model_and_effort(isolated_state):assert kept["title"] == "renamed"+def test_update_session_scope_move_drops_stale_legacy_mapping(isolated_state):+ from config import paths+ from core.scheduled_tasks import resolve_session_id_target+ from storage.sessions_service import SQLiteSessionsService++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ original_scope_id = _seed_avibe_scope(conn)+ target_scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_moved",+ now="2026-05-26T13:00:00Z",+ )+ session = sessions_service.create_session(+ conn,+ scope_id=original_scope_id,+ agent_backend="claude",+ metadata={"legacy_scope_key": original_scope_id, "kept": True},+ )+ moved = sessions_service.update_session(conn, session["id"], scope_id=target_scope_id)++ assert moved["scope_id"] == target_scope_id+ assert moved["metadata"]["kept"] is True+ assert "legacy_scope_key" not in moved["metadata"]+ assert moved["session_anchor"] == f"avibe_proj_moved:session_{session['id']}"++ target = resolve_session_id_target(session["id"])+ assert target.scope_id == target_scope_id+ assert target.session_key.thread_id is None++ legacy = SQLiteSessionsService(paths.get_sqlite_state_path())+ try:+ mappings = legacy.load_state().session_mappings+ finally:+ legacy.close()+ assert "avibe::proj_moved" in mappings+ assert original_scope_id not in mappings++def test_update_session_present_null_clears_agent_route(isolated_state):"""The Chat header's "Default" item sends present nulls; update_session mustclear an unpinned route instead of treating null as "field omitted"."""diff --git a/tests/test_harness_payload_enrichment.py b/tests/test_harness_payload_enrichment.pyindex 3f17a71d3..a4f5c643c 100644--- a/tests/test_harness_payload_enrichment.py+++ b/tests/test_harness_payload_enrichment.py@@ -17,6 +17,7 @@ from sqlalchemy import updatesys.path.insert(0, str(Path(__file__).resolve().parents[1]))from storage import workbench_sessions_service+from storage.agent_session_rows import create_agent_session_rowfrom storage.background import SQLiteBackgroundTaskStore, compute_next_run_atfrom storage.db import create_sqlite_enginefrom storage.models import agent_sessions, scope_settings@@ -124,6 +125,52 @@ def test_scheduled_task_payload_resolves_workbench_session(tmp_path: Path) -> Nostore2.close()+def test_scheduled_task_payload_treats_standalone_session_as_openable_workbench(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ _build_schema(db_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ session_id = create_agent_session_row(+ conn,+ scope_id=None,+ session_id="ses_standalone",+ session_anchor=None,+ agent_backend="claude",+ agent_name="default",+ workdir=str(tmp_path),+ title="Standalone audit",+ now=NOW,+ )+ finally:+ engine.dispose()++ store = SQLiteBackgroundTaskStore(db_path)+ try:+ store.upsert_scheduled_task(+ {+ "id": "task_standalone",+ "session_id": session_id,+ "prompt": "hello",+ "schedule_type": "cron",+ "cron": "0 9 * * *",+ "timezone": "UTC",+ "enabled": True,+ "created_at": NOW,+ "updated_at": NOW,+ }+ )+ task = store.get_scheduled_task("task_standalone")+ finally:+ store.close()++ assert task["session_is_workbench"] is True+ assert task["session_platform"] is None+ assert task["session_scope_kind"] is None+ assert task["session_title"] == "Standalone audit"+ assert task["session_label"] == "Standalone audit"++def test_scheduled_task_payload_resolves_im_channel_name(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"_build_schema(db_path)diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex dfa0d1b24..d0603c8ab 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -1755,6 +1755,62 @@ def test_flush_claims_every_coalesced_agent_run(tmp_path, monkeypatch):]+def test_flush_background_agent_run_preserves_primary_prompt(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ from core.message_mirror import mirror_harness_inbound+ from core.scheduled_tasks import TaskExecutionStore+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.models import messages++ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="placeholder",+ message="background prompt",+ agent_name="codex",+ )+ assert request_store.claim(request.id) is not None+ request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})+ session_id = _seed_avibe_session_with_queue(+ [+ (+ "background prompt",+ {+ "message_id": f"agent_run:{request.id}",+ "platform_specific": {+ "task_execution_id": request.id,+ "task_trigger_kind": "agent_run",+ "task_definition_id": None,+ "vibe_agent_name": "codex",+ "suppress_delivery": True,+ },+ },+ )+ ]+ )+ mgr, runs = _manager_capturing_runs()++ async def _mirror_run(sid, context, text, *, source=SOURCE_HUMAN):+ mirror_harness_inbound(context, text)+ runs.append((text, source, context))++ mgr._run = _mirror_run++ assert asyncio.run(mgr.flush_queue(session_id)) is True+ assert len(runs) == 1+ with create_sqlite_engine().connect() as conn:+ rows = conn.execute(+ select(messages).where(messages.c.session_id == session_id)+ ).mappings().all()++ harness_rows = [row for row in rows if row["type"] == "harness"]+ assert [(row["native_message_id"], row["content_text"]) for row in harness_rows] == [+ (f"agent_run:{request.id}", "background prompt")+ ]+ assert [row for row in rows if row["type"] == messages_service.HARNESS_DEDUPE_TYPE] == []++def test_coalesced_agent_run_claim_is_atomic(tmp_path, monkeypatch):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -2334,7 +2390,7 @@ def test_flush_resets_agent_run_claim_when_run_start_fails(tmp_path, monkeypatchassert all(row["metadata"].get("effective_run_id") is None for row in stored.values())-def test_flush_marks_suppressed_first_native_id(tmp_path, monkeypatch):+def test_flush_suppressed_segment_reserves_first_native_id_for_prompt(tmp_path, monkeypatch):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))def prov(execution_id: str) -> dict:@@ -2365,6 +2421,7 @@ def test_flush_marks_suppressed_first_native_id(tmp_path, monkeypatch):assert asyncio.run(mgr.flush_queue(session_id)) is Trueassert len(runs) == 1+ assert runs[0][2].message_id == "watch:def-watch:run-1"with create_sqlite_engine().begin() as conn:dedupe_rows = conn.execute(select(messages)).mappings().all()dedupe_native_ids = {@@ -2372,7 +2429,7 @@ def test_flush_marks_suppressed_first_native_id(tmp_path, monkeypatch):for row in dedupe_rowsif row["type"] == messages_service.HARNESS_DEDUPE_TYPE}- assert dedupe_native_ids == {"watch:def-watch:run-1", "watch:def-watch:run-2"}+ assert dedupe_native_ids == {"watch:def-watch:run-2"}def test_flush_does_not_coalesce_scheduled_callbacks_with_different_delivery(tmp_path, monkeypatch):diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex cd51e74b9..7ac3f4de3 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -494,19 +494,21 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn("[✅ Yes]", persist.call_args.args[2])self.assertIn("Pick one", persist.call_args.args[2])- async def test_suppressed_delivery_is_not_persisted(self):- """Suppressed scheduled output is intentionally private — it must NOT- leak into the cross-platform messages history."""+ async def test_suppressed_delivery_is_persisted_without_platform_send(self):controller = _StubController(platform="slack")dispatcher = ConsolidatedMessageDispatcher(controller)context = MessageContext(user_id="U1", channel_id="C1", platform="slack",platform_specific={"suppress_delivery": True},)- with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ with mock.patch(+ "core.message_dispatcher.persist_agent_message",+ return_value={"id": "msg-background"},+ ) as persist:message_id = await dispatcher.emit_agent_message(context, "result", "private output")- persist.assert_not_called()- self.assertTrue(message_id.startswith("suppressed:"))+ persist.assert_called_once()+ self.assertEqual(message_id, "msg-background")+ self.assertEqual(controller.im_client.sent_messages, [])async def test_suppressed_result_records_folded_footer(self):"""A suppressed (private) result can't ride subtext, so the footnote must@@ -808,11 +810,7 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)marker.assert_not_called()- async def test_suppress_delivery_writes_no_marker(self):- # A private/background run (``suppress_delivery``) intentionally leaves NO- # message history — no silent marker, so it never pollutes the cross-platform- # store / activity / fork state (mirrors the suppressed-delivery path that- # already skips ``persist_agent_message``).+ async def test_suppress_delivery_writes_local_marker(self):controller = _AvibeStatusController()dispatcher = ConsolidatedMessageDispatcher(controller)ctx = MessageContext(@@ -823,7 +821,7 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):"core.message_dispatcher.persist_silent_completion_marker") as marker:await dispatcher.emit_agent_message(ctx, "result", "")- marker.assert_not_called()+ marker.assert_called_once_with(ctx)async def test_silent_backend_failure_collapses_status_as_failed(self):controller = _AvibeStatusController()diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex ee0b1a6d1..517deec8e 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -800,6 +800,31 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(len(controller.agent_service.requests), 1)controller.settings_manager.sessions.materialize_agent_session_route.assert_not_called()+ async def test_background_im_session_suppresses_outward_delivery(self):+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m1",+ platform="slack",+ platform_specific={+ "agent_run_target": {+ "agent_session_id": "ses_background",+ "agent_backend": "codex",+ "visibility": "background",+ }+ },+ )++ await handler.handle_user_message(context, "continue")++ self.assertEqual(len(controller.agent_service.requests), 1)+ agent_name, request = controller.agent_service.requests[0]+ self.assertTrue(request.context.platform_specific["suppress_delivery"])+ self.assertEqual(agent_name, "codex")+async def test_lark_typing_preference_uses_registry_reaction_capability(self):controller = _StubController(platform="lark", ack_mode="typing", typing_result=True)handler = MessageHandler(controller)diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex 9a4911a47..4aee2b632 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -36,7 +36,7 @@ from modules.im import MessageContextfrom storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_events, agent_sessions, messages, scopes+from storage.models import agent_events, agent_sessions, media_objects, messages, scopesfrom storage.settings_service import upsert_scope@@ -760,6 +760,112 @@ def test_harness_inbound_avibe_session_scoped(isolated_state):assert row["content_text"] == "the watched condition fired"+def test_background_standalone_persists_full_turn_without_realtime_delivery(isolated_state):+ from core import inbox_events++ engine = create_sqlite_engine()+ now = "2026-07-23T00:00:00Z"+ with engine.begin() as conn:+ conn.execute(+ agent_sessions.insert().values(+ id="ses_background",+ scope_id=None,+ visibility="background",+ agent_backend="codex",+ agent_variant="default",+ session_anchor="ses_background",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ context = MessageContext(+ user_id="scheduled",+ channel_id="ses_background",+ platform="avibe",+ message_id="scheduled:def_bg:exec_1",+ platform_specific={+ "agent_session_id": "ses_background",+ "task_trigger_kind": "scheduled",+ "task_definition_id": "def_bg",+ "suppress_delivery": True,+ },+ )++ async def scenario():+ sub_id, queue = inbox_events.bus.subscribe()+ try:+ mirror_harness_inbound(context, "background prompt")+ persist_agent_message(context, "result", "background result")+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(queue.get(), timeout=0.1)+ finally:+ inbox_events.bus.unsubscribe(sub_id)++ asyncio.run(scenario())+ with engine.connect() as conn:+ rows = conn.execute(+ select(messages).where(messages.c.session_id == "ses_background").order_by(messages.c.author)+ ).mappings().all()+ assert [(row["author"], row["content_text"]) for row in rows] == [+ ("agent", "background result"),+ ("harness", "background prompt"),+ ]+ assert {row["scope_id"] for row in rows} == {None}+++def test_background_standalone_rewrites_agent_file_links(isolated_state, tmp_path):+ local_file = tmp_path / "report.txt"+ local_file.write_text("standalone artifact", encoding="utf-8")+ engine = create_sqlite_engine()+ now = "2026-07-23T00:00:00Z"+ with engine.begin() as conn:+ conn.execute(+ agent_sessions.insert().values(+ id="ses_background_media",+ scope_id=None,+ visibility="background",+ agent_backend="codex",+ agent_variant="default",+ session_anchor="ses_background_media",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ context = MessageContext(+ user_id="agent",+ channel_id="ses_background_media",+ platform="avibe",+ platform_specific={+ "agent_session_id": "ses_background_media",+ "suppress_delivery": True,+ },+ )+ persist_agent_message(context, "result", f"[report]({local_file.as_uri()})")++ with engine.connect() as conn:+ message = conn.execute(+ select(messages).where(messages.c.session_id == "ses_background_media")+ ).mappings().one()+ media = conn.execute(+ select(media_objects).where(media_objects.c.session_id == "ses_background_media")+ ).mappings().one()++ assert "file://" not in message["content_text"]+ assert "/api/media/" in message["content_text"]+ assert media["scope_id"] is None+ assert media["local_path"] == str(local_file)++def test_harness_inbound_im_scope_keyed(isolated_state):"""A harness turn delivered to an IM channel with NO source session resolvedfalls back to a scope-keyed row (null session_id), tagged source='harness'.diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex ee39d1fb1..07cda2358 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -622,6 +622,46 @@ def test_list_inbox_sessions_per_session_feed(isolated_state):assert b["unread_count"] == by_session["ses_b"]+def test_inbox_and_unread_queries_exclude_background_sessions(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_titled_session(conn, scope_id, "ses_foreground", "Foreground")+ _seed_titled_session(conn, scope_id, "ses_background", "Background")+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == "ses_background")+ .values(visibility="background")+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_foreground",+ "agent",+ "visible",+ "2026-05-30T10:00:00Z",+ read=False,+ )+ _insert_msg(+ conn,+ scope_id,+ "ses_background",+ "agent",+ "hidden",+ "2026-05-30T10:01:00Z",+ read=False,+ )++ with engine.connect() as conn:+ feed = messages_service.list_inbox_sessions(conn, platform="avibe")+ unread = messages_service.unread_counts_by_session(conn, platform="avibe")+ hidden = messages_service.get_inbox_session(conn, "ses_background")++ assert [row["session_id"] for row in feed["sessions"]] == ["ses_foreground"]+ assert unread == {"ses_foreground": 1}+ assert hidden is None++def test_list_inbox_sessions_includes_notify_only_failed_turn(isolated_state):"""A turn that fails before producing any ``result`` persists only a terminal``notify``; that failed conversation must still surface in the inbox (with thediff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex ff721721d..2f272ae88 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -425,9 +425,10 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("`vibe watch add` creates a managed monitor", prompt)self.assertIn("product signals, business events, files, logs, CI/reviews/deploys", prompt)self.assertIn("Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work", prompt)- self.assertIn("returns immediately, and from this Avibe Agent shell sends the final result back to this conversation", prompt)+ self.assertIn("creates a background Session in the caller's scope, returns immediately", prompt)+ self.assertIn("a caller-less run creates a standalone background Session with its own Show workspace", prompt)self.assertIn("Pass `--sync` only when the current process must wait for the result", prompt)- self.assertIn("Add `--same-scope` when the new Session should live under the same Workbench project or IM scope", prompt)+ self.assertIn("Add `--same-scope` to require the caller/source scope", prompt)self.assertIn("Use `vibe agent run --fork-self --message ...` when work should branch from this current Session", prompt)self.assertIn("Forks keep the source Session backend, scope, and cwd by default", prompt)self.assertIn("It does not change that Session's cwd, scope, Agent, model, or reasoning settings", prompt)@@ -450,7 +451,8 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn("CLI Token", prompt)self.assertIn("Use the `Agent Name` value exactly as listed in shell commands", prompt)self.assertIn("`--session-id <id>` resumes that exact Agent Session and its transcript, backend identity, Show Page, and routing", prompt)- self.assertIn("Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate private/background Session", prompt)+ self.assertIn("Without `--session-id`, `--fork-self`, or `--fork-session`, `vibe agent run --agent <agent-name>` creates a separate background Session", prompt)+ self.assertIn("Use `vibe session update --visibility foreground|background`", prompt)self.assertIn("`--fork-self` creates a new Agent Session from this current Session's native backend context", prompt)self.assertIn("`--fork-session <id>` creates a new Agent Session from that explicit source Session's native backend context", prompt)self.assertIn("vibe agent run --agent <agent-name> --message ...", prompt)diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.pyindex eb4b80c36..d375c86c3 100644--- a/tests/test_running_agents_service.py+++ b/tests/test_running_agents_service.py@@ -393,28 +393,25 @@ def test_orphan_dedup_by_pid_when_live_client_lacks_native(monkeypatch):assert {o["pid"] for o in orphans} == {999}-def test_private_agent_run_not_labeled_slack():- # ``reserve_private_agent_session`` stores private agent runs with a- # placeholder ``platform="slack"`` but ``native_type="private_agent_run"``.- # Such a row must NOT be shown as a Slack session.+def test_standalone_background_session_is_openable():row = running_agents._make_row(backend="codex", state="idle", base_session_id="b1")meta = {"id": "ses0000priv",- "scope_id": "slack::channel::private-agent-run-abc123",- "scope_platform": "slack",- "scope_scope_type": "channel",- "scope_display_name": "Private Agent Run",- "scope_native_type": "private_agent_run",+ "scope_id": None,+ "scope_platform": None,+ "scope_scope_type": None,+ "scope_display_name": None,+ "visibility": "background","title": "[Current Task] review","agent_name": "codex","workdir": None,}running_agents._apply_session_meta(row, meta)- assert row["platform"] is None # not "slack"- assert row["trigger_source"] == "agent"- assert row["openable_in_chat"] is False- assert row["scope_display_name"] == "Private Agent Run"+ assert row["platform"] is None+ assert row["visibility"] == "background"+ assert row["openable_in_chat"] is True+ assert row["scope_display_name"] is Nonedef test_real_slack_session_labeled_and_openable():diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 738001bda..b6eec8130 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -1169,7 +1169,11 @@ def test_runtime_session_reservation_uses_canonicalized_scope_agent(tmp_path: Parequest_store=TaskExecutionStore(tmp_path / "task_requests"),)- session_id = service._reserve_runtime_session(agent_name=None, deliver_key="slack::channel::C123")+ session_id = service._reserve_runtime_session(+ agent_name=None,+ deliver_key="slack::channel::C123",+ metadata={"session_scope_id": "slack::channel::C123"},+ )target = resolve_session_id_target(session_id, db_path=db_path)assert target.agent_backend == default_agent.backend@@ -1177,7 +1181,48 @@ def test_runtime_session_reservation_uses_canonicalized_scope_agent(tmp_path: Paassert target.agent_id-def test_runtime_session_reservation_ignores_unresolved_legacy_scope_backend(+def test_runtime_session_reservation_without_scope_creates_background_standalone(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home = tmp_path / "home"+ monkeypatch.setenv("AVIBE_HOME", str(home))++ from core.vibe_agents import VibeAgentStore+ from storage.db import create_sqlite_engine+ from storage.models import agent_sessions++ agent_store = VibeAgentStore()+ try:+ agent_store.ensure_builtin_default_agents(["codex"])+ agent_store.set_default_agent_name("codex")+ finally:+ agent_store.close()++ service = ScheduledTaskService(+ controller=SimpleNamespace(agent_router=SimpleNamespace(global_default="codex")),+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=TaskExecutionStore(tmp_path / "task_requests"),+ )++ session_id = service._reserve_runtime_session(agent_name=None, deliver_key=None)++ with create_sqlite_engine().connect() as conn:+ row = conn.execute(+ select(+ agent_sessions.c.scope_id,+ agent_sessions.c.visibility,+ agent_sessions.c.workdir,+ ).where(agent_sessions.c.id == session_id)+ ).one()+ expected_workdir = home / "show" / session_id+ assert row.scope_id is None+ assert row.visibility == "background"+ assert row.workdir == str(expected_workdir)+ assert expected_workdir.is_dir()+++def test_runtime_session_reservation_preserves_legacy_deliver_key_scope(tmp_path: Path,monkeypatch,) -> None:@@ -1232,6 +1277,8 @@ def test_runtime_session_reservation_ignores_unresolved_legacy_scope_backend(assert target.agent_backend == default_agent.backendassert target.agent_name == default_agent.name+ assert target.scope_id == "slack::channel::C123"+ assert target.visibility == "background"def test_runtime_session_reservation_uses_default_agent_without_scope_agent(@@ -1284,7 +1331,11 @@ def test_runtime_session_reservation_uses_default_agent_without_scope_agent(request_store=TaskExecutionStore(tmp_path / "task_requests"),)- session_id = service._reserve_runtime_session(agent_name=None, deliver_key="slack::channel::C456")+ session_id = service._reserve_runtime_session(+ agent_name=None,+ deliver_key="slack::channel::C456",+ metadata={"session_scope_id": "slack::channel::C456"},+ )target = resolve_session_id_target(session_id, db_path=db_path)assert target.agent_backend == "codex"@@ -1341,8 +1392,13 @@ def test_runtime_session_reservation_uses_unique_anchors_for_reused_scope(request_store=TaskExecutionStore(tmp_path / "task_requests"),)- first_session_id = service._reserve_runtime_session(agent_name=None, deliver_key="slack::channel::C789")- second_session_id = service._reserve_runtime_session(agent_name=None, deliver_key="slack::channel::C789")+ reservation = {+ "agent_name": None,+ "deliver_key": "slack::channel::C789",+ "metadata": {"session_scope_id": "slack::channel::C789"},+ }+ first_session_id = service._reserve_runtime_session(**reservation)+ second_session_id = service._reserve_runtime_session(**reservation)with create_sqlite_engine(db_path).connect() as conn:rows = list(@@ -3323,14 +3379,14 @@ def test_recovered_silent_directive_activity_settles_without_emit() -> None:service.controller.emit_agent_message.assert_not_awaited()-def test_restart_no_delivery_activity_settles_real_run_without_emit(+def test_restart_background_activity_persists_without_outward_delivery(tmp_path: Path,monkeypatch,) -> None:session_id = _make_avibe_session(monkeypatch,tmp_path,- metadata={"no_delivery": True},+ visibility="background",)request_store = TaskExecutionStore()request = request_store.enqueue_agent_run(@@ -3370,7 +3426,12 @@ def test_restart_no_delivery_activity_settles_real_run_without_emit(handle_scheduled_message=lambda *_args, **_kwargs: None,)controller.agent_service = SimpleNamespace(activities=recovered_registry)- controller.emit_agent_message = AsyncMock()+ async def emit_background(context, *_args, **_kwargs):+ assert context.platform_specific["suppress_delivery"] is True+ assert request_store.settle_deferred_run(request.id) is True+ return "msg-background"++ controller.emit_agent_message = AsyncMock(side_effect=emit_background)service = ScheduledTaskService(controller=controller,store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),@@ -3384,7 +3445,7 @@ def test_restart_no_delivery_activity_settles_real_run_without_emit(assert terminal["status"] == "succeeded"assert terminal["result_text"] in {None, ""}assert not terminal["result_payload"].get("outputs")- controller.emit_agent_message.assert_not_awaited()+ controller.emit_agent_message.assert_awaited_once()assert activity_store.list_activities() == []@@ -4676,6 +4737,7 @@ def _make_avibe_session(tmp_path,*,metadata: dict | None = None,+ visibility: str = "foreground",) -> str:"""Create a real avibe workbench session so ``resolve_session_id_target``resolves it to ``platform='avibe'`` (the gate trigger)."""@@ -4715,6 +4777,7 @@ def _make_avibe_session(scope_id=scope_id,agent_backend="claude",agent_name="worker",+ visibility=visibility,metadata=metadata,)return session["id"]diff --git a/tests/test_session_cli.py b/tests/test_session_cli.pyindex 740ac5471..c7ff37c5a 100644--- a/tests/test_session_cli.py+++ b/tests/test_session_cli.py@@ -77,6 +77,28 @@ def test_list_type_filter(monkeypatch, tmp_path, capsys):assert [s["id"] for s in payload["sessions"]] == ["seschat"]+def test_list_avibe_type_includes_foreground_standalone(monkeypatch, tmp_path, capsys):+ from core.services import sessions as sessions_service++ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesweb", platform="avibe", native="proj_a")+ _seed(engine, "seschat", platform="slack", native="C1")+ with engine.begin() as conn:+ standalone = sessions_service.create_session(+ conn,+ scope_id=None,+ agent_backend="codex",+ visibility="foreground",+ )++ _, payload = _run(cli.cmd_session_list, ["session", "list", "--type", "avibe"], capsys)++ assert {session["id"] for session in payload["sessions"]} == {+ "sesweb",+ standalone["id"],+ }++def test_list_pagination_fixed_ten_no_limit_flag(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)for i in range(12):@@ -221,6 +243,56 @@ def test_update_empty_title_clears(monkeypatch, tmp_path, capsys):assert payload["session"]["title"] is None+def test_update_visibility_and_make_standalone_keeps_workdir(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ original_scope_id = _seed(engine, "sesaaa", title="Old")+ posted: dict = {}+ monkeypatch.setattr(+ cli,+ "_post_session_activity_to_live_ui",+ lambda session_id, **kwargs: posted.update(session_id=session_id, **kwargs),+ )+ with engine.begin() as conn:+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == "sesaaa")+ .values(workdir=str(tmp_path / "original-workdir"))+ )+ original_workdir = conn.execute(+ agent_sessions.select().where(agent_sessions.c.id == "sesaaa")+ ).mappings().one()["workdir"]++ code, payload = _run(+ cli.cmd_session_update,+ [+ "session",+ "update",+ "sesaaa",+ "--visibility",+ "background",+ "--scope-id",+ "none",+ ],+ capsys,+ )++ assert code == 0+ assert payload["session"]["visibility"] == "background"+ assert payload["session"]["scope_id"] is None+ assert payload["session"]["project_id"] is None+ assert payload["session"]["workdir"] == original_workdir+ assert posted == {+ "session_id": "sesaaa",+ "previous_scope_id": original_scope_id,+ "previous_visibility": "foreground",+ }+ with engine.connect() as conn:+ anchor = conn.execute(+ agent_sessions.select().where(agent_sessions.c.id == "sesaaa")+ ).mappings().one()["session_anchor"]+ assert anchor == "sesaaa"++def test_update_archived_is_not_found(monkeypatch, tmp_path, capsys):engine = _setup(monkeypatch, tmp_path)_seed(engine, "sesarch", status="archived", title="Old")@@ -402,6 +474,66 @@ def test_cli_activity_endpoint_publishes_with_token(monkeypatch):assert events[0]["event"] == "updated" and events[0]["title"] == "Renamed"+def test_cli_activity_placement_events_match_patch(monkeypatch):+ import vibe.sse_broker as sse_broker+ from core.services import sessions as sessions_service+ from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from tests.ui_server_test_helpers import csrf_headers+ from vibe.ui_server import app++ ensure_sqlite_state(primary_platform="avibe")+ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ scope_id = _seed(engine, "sesplacement", title="Placement")+ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(+ sse_broker.broker,+ "publish",+ lambda topic, data: published.append((topic, data)),+ )++ client = app.test_client()+ response = client.patch(+ "/api/sessions/sesplacement",+ json={"visibility": "background"},+ headers=csrf_headers(client),+ )+ assert response.status_code == 200+ patch_events = [data for topic, data in published if topic == "session.activity"]++ with engine.begin() as conn:+ sessions_service.update_session(+ conn,+ "sesplacement",+ visibility="foreground",+ )+ previous = sessions_service.get_session(conn, "sesplacement")+ sessions_service.update_session(+ conn,+ "sesplacement",+ visibility="background",+ )+ published.clear()++ response = client.post(+ "/api/sessions/sesplacement/cli-activity",+ json={+ "previous_scope_id": previous["scope_id"],+ "previous_visibility": previous["visibility"],+ },+ headers={+ "X-Vibe-Show-Client": "cli",+ SHOW_CLI_EVENT_TOKEN_HEADER: show_cli_event_token(),+ },+ )+ assert response.status_code == 200+ cli_events = [data for topic, data in published if topic == "session.activity"]++ assert previous["scope_id"] == scope_id+ assert cli_events == patch_events++def test_cli_activity_endpoint_rejects_without_token(monkeypatch):from tests.ui_server_test_helpers import csrf_headersfrom vibe.ui_server import appdiff --git a/tests/test_session_fork.py b/tests/test_session_fork.pyindex ea603cf7d..ae3cf4e3f 100644--- a/tests/test_session_fork.py+++ b/tests/test_session_fork.py@@ -780,8 +780,8 @@ def test_reserve_forked_session_reanchors_when_moved_to_new_im_scope(tmp_path: Passert row["session_anchor"].startswith("slack_C999:fork_")assert metadata["fork_target_scope_id"] == target_scope_idassert metadata["legacy_scope_key"] == target_scope_id- assert "private_agent_run" not in metadata- assert "no_delivery" not in metadata+ assert metadata["private_agent_run"] is True+ assert metadata["no_delivery"] is Trueassert rows[0]["session_anchor"] != rows[1]["session_anchor"]resolved = resolve_session_id_target(first_result.session_id, db_path=db_path)diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 05c574017..520bf62eb 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -19,7 +19,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260721_0031"+HEAD_REVISION = "20260723_0032"def _index_sql(conn: sqlite3.Connection, name: str) -> str:@@ -121,9 +121,13 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:media_columns = {row[1] for row in conn.execute("pragma table_info(media_objects)")}+ media_scope_not_null = {+ row[1]: row[3] for row in conn.execute("pragma table_info(media_objects)")+ }["scope_id"]assert "mtime_ns" in media_columns # 20260603_0014: dedup fingerprintassert "width_px" in media_columns # 20260604_0015: zero-shift image boxassert "height_px" in media_columns+ assert media_scope_not_null == 0 # standalone sessions can own uploadsbackground_columns = {row[1]for row in conn.execute(@@ -135,6 +139,134 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:assert version == (HEAD_REVISION,)+def test_session_visibility_migration_reparents_legacy_runs_and_self_anchors(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260721_0031")+ now = "2026-07-23T00:00:00Z"++ with sqlite3.connect(db_path) as conn:+ for scope_id, native_type in (+ ("scope_real", None),+ ("scope_private_a", "private_agent_run"),+ ("scope_private_b", "private_agent_run"),+ ("scope_private_c", "private_agent_run"),+ ):+ 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', ?, ?, 0, 0, '{}', ?, ?, ?)+ """,+ (scope_id, scope_id, native_type, now, now, now),+ )++ def insert_session(session_id: str, scope_id: str, anchor: str, workdir: str) -> None:+ conn.execute(+ """+ insert into agent_sessions (+ id, scope_id, agent_backend, agent_variant, session_anchor,+ workdir, native_session_id, status, agent_status, metadata_json,+ created_at, updated_at, last_active_at+ ) values (?, ?, 'codex', 'codex', ?, ?, '', 'active', 'idle', '{}', ?, ?, ?)+ """,+ (session_id, scope_id, anchor, workdir, now, now, now),+ )++ insert_session("ses_caller", "scope_real", "caller", "/caller")+ insert_session("ses_source", "scope_real", "source", "/source")+ insert_session("ses_legacy_a", "scope_private_a", "same-anchor", "/legacy-a")+ insert_session("ses_legacy_b", "scope_private_b", "same-anchor", "/legacy-b")+ insert_session("ses_legacy_c", "scope_private_c", "unresolved", "/legacy-c")++ conn.execute(+ """+ insert into media_objects (+ token, scope_id, session_id, kind, source, local_path, created_at+ ) values (+ 'media_existing', 'scope_real', 'ses_caller', 'file',+ 'user_upload', '/tmp/existing.txt', ?+ )+ """,+ (now,),+ )++ conn.execute(+ """+ insert into agent_runs (+ id, run_type, status, source_kind, source_actor, session_id,+ cancel_requested, created_at, updated_at, metadata_json+ ) values (+ 'run_source_actor', 'agent_run', 'succeeded', 'agent', 'ses_caller',+ 'ses_legacy_a', 0, ?, ?, '{}'+ )+ """,+ (now, now),+ )+ conn.execute(+ """+ insert into agent_runs (+ id, run_type, status, source_kind, source_actor, session_id,+ cancel_requested, created_at, updated_at, metadata_json+ ) values (+ 'run_metadata', 'agent_run', 'succeeded', 'agent', 'agent:worker',+ 'ses_legacy_b', 0, ?, ?, ?+ )+ """,+ (now, now, json.dumps({"caller_context": {"session_id": "ses_source"}})),+ )+ conn.commit()++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ rows = conn.execute(+ """+ select id, scope_id, session_anchor, visibility, workdir+ from agent_sessions where id like 'ses_legacy_%' order by id+ """+ ).fetchall()+ pseudo_scope_count = conn.execute(+ "select count(*) from scopes where native_type = 'private_agent_run'"+ ).fetchone()[0]+ unique_index = conn.execute(+ "select [unique] from pragma_index_list('agent_sessions') where name = 'uq_agent_sessions_scope_anchor'"+ ).fetchone()+ media_scope_not_null = {+ row[1]: row[3] for row in conn.execute("pragma table_info(media_objects)")+ }["scope_id"]+ existing_media = conn.execute(+ "select scope_id, session_id from media_objects where token = 'media_existing'"+ ).fetchone()+ conn.execute(+ """+ insert into media_objects (+ token, scope_id, session_id, kind, source, local_path, created_at+ ) values (+ 'media_standalone', null, 'ses_legacy_c', 'file',+ 'user_upload', '/tmp/standalone.txt', ?+ )+ """,+ (now,),+ )++ assert rows == [+ ("ses_legacy_a", "scope_real", "ses_legacy_a", "background", "/legacy-a"),+ ("ses_legacy_b", "scope_real", "ses_legacy_b", "background", "/legacy-b"),+ ("ses_legacy_c", None, "ses_legacy_c", "background", "/legacy-c"),+ ]+ assert pseudo_scope_count == 3+ assert unique_index == (1,)+ assert media_scope_not_null == 0+ assert existing_media == ("scope_real", "ses_caller")++ from core.scheduled_tasks import resolve_session_id_target++ promoted = resolve_session_id_target("ses_legacy_a", db_path=db_path)+ assert promoted.scope_id == "scope_real"+ assert promoted.session_key.thread_id is None++def test_run_migrations_serializes_alembic_context(monkeypatch, tmp_path: Path) -> None:first_entered = threading.Event()second_entered = threading.Event()diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex 68ed63278..bf9d86990 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -826,6 +826,136 @@ def test_patch_backend_switch_blocked_while_turn_in_flight(isolated_state, tmp_pin_flight.assert_awaited_once()+def test_patch_session_visibility_and_scope_are_independent(isolated_state, tmp_path, monkeypatch):+ from storage.db import create_sqlite_engine+ from storage.models import agent_sessions+ import vibe.sse_broker as sse_broker+ from vibe.ui_server import app++ original_scope_id, session_id = _make_session(tmp_path)+ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(sse_broker.broker, "publish", lambda topic, data: published.append((topic, data)))+ engine = create_sqlite_engine()+ with engine.connect() as conn:+ original_workdir = conn.execute(+ agent_sessions.select().where(agent_sessions.c.id == session_id)+ ).mappings().one()["workdir"]++ client = app.test_client()+ headers = csrf_headers(client)+ visibility_response = client.patch(+ f"/api/sessions/{session_id}",+ json={"visibility": "background"},+ headers=headers,+ )+ assert visibility_response.status_code == 200+ assert visibility_response.get_json()["visibility"] == "background"+ assert visibility_response.get_json()["scope_id"] == original_scope_id+ activity = [data for topic, data in published if topic == "session.activity"]+ assert activity[-2]["event"] == "updated"+ assert activity[-2]["visibility"] == "background"+ assert activity[-1] == {+ "session_id": session_id,+ "scope_id": original_scope_id,+ "event": "user_message",+ "reason": "session_placement_changed",+ }++ published.clear()+ scope_response = client.patch(+ f"/api/sessions/{session_id}",+ json={"scope_id": None},+ headers=headers,+ )+ assert scope_response.status_code == 200+ body = scope_response.get_json()+ assert body["visibility"] == "background"+ assert body["scope_id"] is None+ assert body["project_id"] is None+ assert body["workdir"] == original_workdir+ activity = [data for topic, data in published if topic == "session.activity"]+ assert [event["event"] for event in activity] == ["updated", "user_message"]+ assert activity[-1]["scope_id"] == original_scope_id++ published.clear()+ foreground_response = client.patch(+ f"/api/sessions/{session_id}",+ json={"visibility": "foreground", "scope_id": original_scope_id},+ headers=headers,+ )+ assert foreground_response.status_code == 200+ assert foreground_response.get_json()["workdir"] == original_workdir+ activity = [data for topic, data in published if topic == "session.activity"]+ assert [event["event"] for event in activity] == ["updated", "created"]+ assert activity[-1]["scope_id"] == original_scope_id+++def test_patch_session_rejects_invalid_visibility(isolated_state, tmp_path):+ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)+ client = app.test_client()+ response = client.patch(+ f"/api/sessions/{session_id}",+ json={"visibility": "hidden"},+ headers=csrf_headers(client),+ )++ assert response.status_code == 400+++def test_patch_session_rejects_unknown_target_scope_as_invalid_value(isolated_state, tmp_path):+ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)+ client = app.test_client()+ response = client.patch(+ f"/api/sessions/{session_id}",+ json={"scope_id": "avibe::project::missing"},+ headers=csrf_headers(client),+ )++ assert response.status_code == 400+++def test_standalone_session_accepts_attachment_upload(isolated_state):+ import base64++ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine+ from storage.models import media_objects+ from vibe.ui_server import app++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ session = sessions_service.create_session(+ conn,+ scope_id=None,+ agent_backend="codex",+ visibility="foreground",+ )++ client = app.test_client()+ response = client.post(+ f"/api/sessions/{session['id']}/attachments",+ json={+ "name": "standalone.txt",+ "mime": "text/plain",+ "data": base64.b64encode(b"standalone upload").decode("ascii"),+ },+ headers=csrf_headers(client),+ )++ assert response.status_code == 201+ token = response.get_json()["token"]+ with engine.connect() as conn:+ row = conn.execute(+ media_objects.select().where(media_objects.c.token == token)+ ).mappings().one()+ assert row["scope_id"] is None+ assert row["session_id"] == session["id"]++def test_patch_agent_name_only_backend_switch_blocked_while_turn_in_flight(isolated_state, tmp_path):"""A selected Vibe Agent implies its backend. The UI often sends only``agent_name`` when changing the picker, so the route must derive thediff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex 0232ae3ad..7a1dda2e2 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -780,6 +780,32 @@ def test_vault_request_ui_payload_resolves_workbench_session_summary():assert "session" not in agent_payload["request"]+def test_vault_request_ui_payload_links_standalone_session():+ with api._vault_engine().begin() as conn:+ _insert_workbench_session(conn, session_id="ses_vault_standalone", title="Standalone deploy")+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == "ses_vault_standalone")+ .values(scope_id=None)+ )+ vault_service.create_provision_request(+ conn,+ "STANDALONE_TOKEN",+ requester={"source": "agent-cli", "session_id": "ses_vault_standalone"},+ )++ listed = api.get_vault_requests(session="ses_vault_standalone")++ assert listed["requests"][0]["session"] == {+ "id": "ses_vault_standalone",+ "title": "Standalone deploy",+ "label": "Standalone deploy",+ "platform": None,+ "scope_kind": None,+ "is_workbench": True,+ }++def test_list_requests_scopes_by_session():# A session-scoped query returns only that session's requests (filtered before the limit).with api._vault_engine().begin() as conn:diff --git a/tests/test_vault_request_im_notifications.py b/tests/test_vault_request_im_notifications.pyindex 2e01c02d0..6f96c9cab 100644--- a/tests/test_vault_request_im_notifications.py+++ b/tests/test_vault_request_im_notifications.py@@ -49,6 +49,7 @@ def _seed_session(scope_type: str = "channel",native_id: str = "C123",session_anchor: str | None = None,+ visibility: str = "foreground",metadata_json: str = "{}",) -> None:engine = create_sqlite_engine(db_path)@@ -88,6 +89,7 @@ def _seed_session(native_session_id="native-1",title=None,status="active",+ visibility=visibility,agent_status="idle",metadata_json=metadata_json,created_at=now,@@ -217,9 +219,9 @@ def test_workbench_session_is_not_notified(tmp_path: Path) -> None:assert controller.emitted == []-def test_suppressed_delivery_session_is_not_notified(tmp_path: Path) -> None:+def test_background_session_is_not_notified(tmp_path: Path) -> None:db_path = tmp_path / "state.sqlite"- _seed_session(db_path, metadata_json='{"no_delivery": true}')+ _seed_session(db_path, visibility="background")controller = FakeController()result = asyncio.run(diff --git a/vibe/cli.py b/vibe/cli.pyindex fcbc76b0d..eadce6109 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -1044,9 +1044,11 @@ def _agent_run_examples_text() -> str:"""\Session target:Use --session-id to continue an existing Agent Session.- Omit --session-id/--fork-self/--fork-session to create a private background Session for --agent.- Use --same-scope to place a new Session in the caller/source Session's scope.+ Omit --session-id/--fork-self/--fork-session to create a background Session for --agent.+ Inside an Agent shell it inherits the caller scope and invocation cwd; outside one it is standalone with its own Show workspace.+ Use --same-scope to explicitly place a new Session in the caller/source Session's scope.Use --scope-id <scopes.id> to place a new Session in a specific existing scope.+ New and forked delegated Sessions default to --visibility background; pass foreground to enable outward delivery.--cwd only applies to new Sessions; existing Sessions keep their own cwd.Callback:@@ -1874,9 +1876,22 @@ def _validate_existing_scope_id(scope_id: str, *, help_command: str):return target-def _scope_id_from_session_id(session_id: str, *, help_command: str) -> str:+def _scope_id_from_session_id(session_id: str, *, help_command: str) -> Optional[str]:resolved = resolve_session_id_target(session_id)- return resolved.session_key.to_key(include_thread=False)+ return resolved.scope_id+++def _require_scope_id_from_session_id(session_id: str, *, help_command: str) -> str:+ scope_id = _scope_id_from_session_id(session_id, help_command=help_command)+ if scope_id is None:+ raise TaskCliError(+ f"session has no scope: {session_id}",+ code="standalone_session_has_no_scope",+ hint="Use --scope-id to choose a scope, or omit --same-scope to create another standalone Session.",+ help_command=help_command,+ details={"session_id": session_id},+ )+ return scope_iddef _legacy_scope_key_from_target(value: Optional[str]) -> str:@@ -1897,13 +1912,29 @@ def _resolve_agent_run_scope_key(args, *, caller_context, source_session_id: Optreturn _validate_existing_scope_id(raw_scope_id, help_command="vibe agent run --help").session_scopeif bool(getattr(args, "same_scope", False)):if source_session_id:- return _scope_id_from_session_id(source_session_id, help_command="vibe agent run --help")+ return _require_scope_id_from_session_id(source_session_id, help_command="vibe agent run --help")caller_session_id = _require_caller_session_id(caller_context,purpose="--same-scope",help_command="vibe agent run --help",)- return _scope_id_from_session_id(caller_session_id, help_command="vibe agent run --help")+ return _require_scope_id_from_session_id(caller_session_id, help_command="vibe agent run --help")+ if source_session_id:+ # Leave placement implicit so reserve_forked_session inherits the+ # source Session's scope (including standalone) and preserves its+ # anchor semantics. Most importantly, do not fall through to a caller+ # in another project. --scope-id remains the opt-in move.+ return None+ if caller_context is not None:+ try:+ return _scope_id_from_session_id(+ caller_context.session_id,+ help_command="vibe agent run --help",+ )+ except ValueError:+ # A stale/injected caller id that is not present in this state DB is+ # not a usable placement context; fall back to standalone creation.+ return Nonereturn None@@ -1933,7 +1964,7 @@ def _resolve_definition_scope_key(args, *, caller_context, help_command: str) ->purpose="--same-scope",help_command=help_command,)- return _scope_id_from_session_id(caller_session_id, help_command=help_command)+ return _require_scope_id_from_session_id(caller_session_id, help_command=help_command)if legacy_deliver_key:return _parse_validated_session_key(legacy_deliver_key, help_command=help_command).session_scopereturn None@@ -1957,7 +1988,7 @@ def _scope_id_payload_from_session(session_id: Optional[str]) -> Optional[str]:if not session_id:return Nonetry:- return resolve_session_id_target(session_id).session_key.to_key(include_thread=False)+ return resolve_session_id_target(session_id).scope_idexcept ValueError:return None@@ -2849,9 +2880,9 @@ def cmd_task_update(args):else:cwd = task.cwdscope_key = requested_scope_key or str(metadata.get("session_scope_id") or "").strip() or _legacy_scope_key_from_target(deliver_key)- if session_policy in {"create_once", "create_per_run"} and not scope_key:+ if session_policy == "create_once" and not scope_key:raise TaskCliError(- "--scope-id or --same-scope is required when a stored definition creates sessions",+ "--scope-id or --same-scope is required when a stored definition creates one reusable Session",code="missing_delivery_target",hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",help_command="vibe task update --help",@@ -3446,6 +3477,7 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:scope_id = (getattr(args, "scope_id", None) or "").strip()deliver_key = (getattr(args, "deliver_key", None) or "").strip()agent_name = (getattr(args, "agent", None) or "").strip()+ visibility = (getattr(args, "visibility", None) or "").strip()if bool(getattr(args, "async_run", False)) and bool(getattr(args, "sync_run", False)):raise TaskCliError("use either --async or --sync, not both",@@ -3519,6 +3551,13 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:hint="An existing --session-id keeps its original scope.",help_command=help_command,)+ if session_id and visibility:+ raise TaskCliError(+ "--visibility only applies when creating or forking a Session",+ code="visibility_with_existing_session",+ hint="Use `vibe session update --visibility ...` to change an existing Session.",+ help_command=help_command,+ )if session_id and (create_session or create_per_run):raise TaskCliError("use either --session-id or --create-session, not both",@@ -3583,9 +3622,9 @@ def _validate_definition_session_policy(hint="Use --create-session or --create-session-per-run with --scope-id/--same-scope, or omit the scope placement flag.",help_command=help_command,)- if (create_session or create_per_run) and not (deliver_key or scope_id or same_scope):+ if create_session and not (deliver_key or scope_id or same_scope):raise TaskCliError(- "--scope-id or --same-scope is required when a stored definition creates sessions",+ "--scope-id or --same-scope is required when a stored definition creates one reusable Session",code="missing_delivery_target",hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",help_command=help_command,@@ -3717,12 +3756,14 @@ def _validate_definition_delivery_target():if session_policy == "create_per_run":if not scope_key:- raise TaskCliError(- "--scope-id or --same-scope is required when a stored definition creates sessions",- code="missing_delivery_target",- hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",- help_command=help_command,- )+ if post_to or deliver_key:+ raise TaskCliError(+ "delivery overrides require a scoped Session target",+ code="missing_delivery_target",+ hint="Add --scope-id/--same-scope, or omit delivery overrides for a standalone background Session.",+ help_command=help_command,+ )+ return None, Nonesession_target = _parse_validated_scope_id(scope_key, help_command=help_command)return _validate_delivery_override_for_target(session_target,@@ -3744,13 +3785,15 @@ def _resolve_run_cwd(*,session_policy: str,scoped_session: bool = False,+ invocation_cwd_default: bool = False,help_command: str,) -> Optional[str]:"""Working directory for a session this run RESERVES.An explicit ``--cwd`` must exist and always wins for blank session creation.- Without it, scoped sessions snapshot the scope's default workdir, while- private/background sessions follow the CLI invocation's cwd.+ Without it, explicit scope placement snapshots the scope default. A new+ delegated Session follows the caller shell cwd; a caller-less standalone+ Session gets its own Show workspace from the reservation service.Existing and forked sessions keep their own cwd, so ``--cwd`` is an error."""raw = (getattr(args, "cwd", None) or "").strip()@@ -3775,7 +3818,7 @@ def _resolve_run_cwd(return resolvedif scoped_session:return None- return os.getcwd()+ return os.getcwd() if invocation_cwd_default else Nonedef _resolve_definition_session_cwd(@@ -3802,6 +3845,8 @@ def _resolve_definition_session_cwd(return existing_cwdif scoped_session:return None+ if session_policy == "create_per_run":+ return Nonereturn os.getcwd()@@ -3906,6 +3951,7 @@ def _reserve_cli_session(workdir: Optional[str] = None,metadata: Optional[dict] = None,session_anchor_target=None,+ visibility: str = "background",) -> str:# Route through ``core.services.sessions`` so the CLI shares the same# business API as the UI server and the future N3 internal endpoint;@@ -3925,13 +3971,12 @@ def _reserve_cli_session(model=agent.model,reasoning_effort=agent.reasoning_effort,workdir=workdir,+ visibility=visibility,metadata={"scope_placement": "explicit", **dict(metadata or {})},)else:- platform = _primary_platform()- session_anchor = f"{platform}_private-agent-{uuid4().hex[:12]}"- session_id = sessions_service.reserve_private_agent_session(- platform=platform,+ session_anchor = f"standalone_{uuid4().hex[:12]}"+ session_id = sessions_service.reserve_standalone_agent_session(agent_backend=agent.backend,session_anchor=session_anchor,agent_id=agent.id,@@ -3939,6 +3984,7 @@ def _reserve_cli_session(model=agent.model,reasoning_effort=agent.reasoning_effort,workdir=workdir,+ visibility=visibility,metadata=metadata,)if not session_id:@@ -3969,6 +4015,7 @@ def _reserve_forked_cli_session(model: Optional[str],reasoning_effort: Optional[str],scope_key: Optional[str],+ visibility: str,):from core.services.session_fork import SessionForkError, reserve_forked_session@@ -3979,6 +4026,7 @@ def _reserve_forked_cli_session(model=model,reasoning_effort=reasoning_effort,scope_id=scope_key,+ visibility=visibility,db_path=paths.get_sqlite_state_path(),)except SessionForkError as exc:@@ -4027,6 +4075,7 @@ def _reserve_definition_session(model=agent.model if agent else None,reasoning_effort=agent.reasoning_effort if agent else None,workdir=workdir,+ visibility="foreground",)if not session_id:raise TaskCliError(@@ -4040,6 +4089,7 @@ def _reserve_definition_session(def cmd_agent_run(args):try:caller_context = caller_context_from_env()+ visibility = (getattr(args, "visibility", None) or "background").strip()run_async = _agent_run_is_async(args)message = _resolve_message_input(args,@@ -4079,7 +4129,22 @@ def cmd_agent_run(args):)session_id = (args.session_id or "").strip() or Nonesession_key = ""- scope_key = _resolve_agent_run_scope_key(args, caller_context=caller_context, source_session_id=source_session_id)+ scope_key = (+ _resolve_agent_run_scope_key(+ args,+ caller_context=caller_context,+ source_session_id=source_session_id,+ )+ if session_policy != "existing"+ else None+ )+ has_resolved_caller_placement = False+ if caller_context is not None and session_policy != "existing":+ try:+ resolve_session_id_target(caller_context.session_id)+ has_resolved_caller_placement = True+ except ValueError:+ passlegacy_reservation_target = Noneif not scope_key and (args.deliver_key or "").strip():# Hidden legacy compatibility: external docs and prompts should use@@ -4090,7 +4155,12 @@ def cmd_agent_run(args):run_cwd = _resolve_run_cwd(args,session_policy=session_policy,- scoped_session=bool(scope_key),+ scoped_session=bool(+ _has_modern_scope_target(args) or (args.deliver_key or "").strip()+ ),+ invocation_cwd_default=has_resolved_caller_placement+ and not _has_modern_scope_target(args)+ and not (args.deliver_key or "").strip(),help_command="vibe agent run --help",)agent = _agent_store().require_enabled(agent_name) if agent_name else None@@ -4126,6 +4196,7 @@ def cmd_agent_run(args):workdir=run_cwd,metadata=session_metadata,session_anchor_target=legacy_reservation_target,+ visibility=visibility,)elif session_policy == "none":session_id = _reserve_cli_session(@@ -4133,6 +4204,7 @@ def cmd_agent_run(args):scope_key=scope_key,workdir=run_cwd,metadata=session_metadata,+ visibility=visibility,)elif session_policy == "fork":fork_result = _reserve_forked_cli_session(@@ -4141,6 +4213,7 @@ def cmd_agent_run(args):model=args.model,reasoning_effort=args.reasoning_effort,scope_key=scope_key,+ visibility=visibility,)session_id = fork_result.session_idif agent_name:@@ -4200,6 +4273,7 @@ def cmd_agent_run(args):"session_policy": session_policy,"session_id": session_id,"scope_id": resolved_scope_id,+ "visibility": target.visibility if session_id else visibility,"deliver_key": legacy_deliver_key,"callback_session_id": callback_session_id,"async": run_async,@@ -4212,6 +4286,7 @@ def cmd_agent_run(args):"agent_name": agent.name if agent else None,"session_id": session_id,"scope_id": resolved_scope_id,+ "visibility": target.visibility if session_id else visibility,"callback_session_id": callback_session_id,"source_kind": source_kind,"source_actor": source_actor,@@ -4555,7 +4630,7 @@ def cmd_data_query(args):# ``vibe session`` — Agent-facing session management. ``list`` / ``get`` are-# read-only; ``update`` renames a title only. All three go through the shared+# read-only; ``update`` edits title, visibility, or scope placement. All three go through the shared# ``core.services.sessions`` business API (same entry the UI server uses) and# never surface archived (soft-deleted) sessions._SESSION_PAGE_SIZE = 10@@ -4692,6 +4767,30 @@ def cmd_session_update(args):from core.services import sessions as sessions_servicetry:+ updates = {}+ if getattr(args, "title", None) is not None:+ updates["title"] = args.title+ updates["title_source"] = "agent"+ if getattr(args, "visibility", None) is not None:+ updates["visibility"] = args.visibility+ raw_scope_id = getattr(args, "scope_id", None)+ if raw_scope_id is not None:+ cleaned_scope_id = str(raw_scope_id).strip()+ updates["scope_id"] = (+ None+ if cleaned_scope_id.lower() == "none"+ else _validate_existing_scope_id(+ cleaned_scope_id,+ help_command="vibe session update --help",+ ).session_scope+ )+ if not updates:+ raise TaskCliError(+ "no update field supplied",+ code="missing_session_update",+ hint="Pass --title, --visibility, or --scope-id.",+ help_command="vibe session update --help",+ )session_id, session_default_notice = _resolve_caller_session_id(args,purpose="Session",@@ -4701,13 +4800,8 @@ def cmd_session_update(args):with engine.begin() as conn:# Validate first so an archived/missing id is a clean not-found rather# than silently writing a title onto a soft-deleted row.- sessions_service.get_active_session(conn, session_id)- # title_source="agent": this is the agent setting its own session title (vs- # "user" for a human Web UI edit). Both are deliberate, so neither gets- # auto-overwritten nor re-nudged — see DELIBERATE_TITLE_SOURCES.- payload = sessions_service.update_session(- conn, session_id, title=args.title, title_source="agent"- )+ previous_session = sessions_service.get_active_session(conn, session_id)+ payload = sessions_service.update_session(conn, session_id, **updates)except LookupError:_print_task_error(TaskCliError(@@ -4723,7 +4817,11 @@ def cmd_session_update(args):return 1# The DB write is committed above; ping a running UI so the rename shows live# (best-effort — never affects this command's result).- _post_session_activity_to_live_ui(session_id)+ _post_session_activity_to_live_ui(+ session_id,+ previous_scope_id=previous_session.get("scope_id"),+ previous_visibility=previous_session.get("visibility"),+ )_print_cli_payload("agent_session",updated=True,@@ -7874,9 +7972,9 @@ def cmd_watch_update(args):else None)scope_key = requested_scope_key or str(metadata.get("session_scope_id") or "").strip() or _legacy_scope_key_from_target(deliver_key)- if session_policy in {"create_once", "create_per_run"} and not scope_key:+ if session_policy == "create_once" and not scope_key:raise TaskCliError(- "--scope-id or --same-scope is required when a stored definition creates sessions",+ "--scope-id or --same-scope is required when a stored definition creates one reusable Session",code="missing_delivery_target",hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",help_command="vibe watch update --help",@@ -10456,7 +10554,12 @@ def _post_show_mark_to_live_ui(session_id: str, payload: dict) -> dict | None:return _post_show_event_to_live_ui(session_id, payload)-def _post_session_activity_to_live_ui(session_id: str) -> None:+def _post_session_activity_to_live_ui(+ session_id: str,+ *,+ previous_scope_id: Optional[str],+ previous_visibility: Optional[str],+) -> None:"""Best-effort: ping a running UI so it broadcasts a ``session.activity`` updatefor this session (e.g. after ``vibe session update`` renames it). The CLI writesthe DB in a separate process from the in-proc SSE broker, so without this the@@ -10475,9 +10578,15 @@ def _post_session_activity_to_live_ui(session_id: str) -> None:if not status.get("ui_pid") or not port:returnurl = f"http://{_ui_show_events_host(config)}:{int(port)}/api/sessions/{quote(session_id, safe='')}/cli-activity"+ body = json.dumps(+ {+ "previous_scope_id": previous_scope_id,+ "previous_visibility": previous_visibility,+ }+ ).encode("utf-8")http_request = urllib.request.Request(url,- data=b"{}",+ data=body,method="POST",headers={"Content-Type": "application/json",@@ -11804,14 +11913,19 @@ def build_parser():agent_run_parser.add_argument("--create-session-per-run", action="store_true", help=argparse.SUPPRESS)agent_run_parser.add_argument("--same-scope", action="store_true", help="Place a new or forked Session in the caller/source Session scope")agent_run_parser.add_argument("--scope-id", help="Existing scopes.id that should own the new or forked Session")+ agent_run_parser.add_argument(+ "--visibility",+ choices=("foreground", "background"),+ help="Visibility for the new or forked Session (default: background)",+ )agent_run_parser.add_argument("--deliver-key", help=argparse.SUPPRESS)agent_run_parser.add_argument("--model", help="Model override for the new forked Session")agent_run_parser.add_argument("--reasoning-effort", help="Reasoning effort override for the new forked Session")agent_run_parser.add_argument("--cwd",help=(- "Working directory for the NEW session. Private sessions default to the invocation "- "directory; scoped sessions default to the scope workdir. Invalid with --session-id "+ "Working directory for the NEW session. Caller-delegated sessions default to the invocation "+ "directory; explicit scoped sessions use the scope workdir; standalone sessions use their Show workspace. Invalid with --session-id ""(an existing session keeps its own working directory)."),)@@ -11906,14 +12020,23 @@ def build_parser():_add_json_noop(session_get_parser)session_update_parser = session_subparsers.add_parser("update",- help="Update a session's title (title only)",- description="Update only the title of one active session. No other field can be changed here.",+ help="Update a session's title, visibility, or scope",+ description="Update one active Session. Moving scope never changes its stored working directory.",formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe session update --help",)session_update_parser.add_argument("session_id", nargs="?", help="Agent Session ID")session_update_parser.add_argument(- "--title", required=True, help="New title. Pass an empty string to clear it (reverts to id-based display)."+ "--title", help="New title. Pass an empty string to clear it (reverts to id-based display)."+ )+ session_update_parser.add_argument(+ "--visibility",+ choices=("foreground", "background"),+ help="Show the Session in normal chat lists or keep it background-only.",+ )+ session_update_parser.add_argument(+ "--scope-id",+ help="Move to an existing scopes.id, or pass 'none' to make the Session standalone.",)_add_json_noop(session_update_parser)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 7e0ef60ec..fb0fc9d23 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -6015,6 +6015,64 @@ def _backend_locked_response(err):)+def _publish_session_update_activity(+ broker,+ *,+ session_id: str,+ session: dict,+ previous_session: dict | None = None,+) -> None:+ """Publish one canonical title/placement reconciliation sequence."""+ broker.publish(+ "session.activity",+ {+ "session_id": session_id,+ "scope_id": session.get("scope_id"),+ "event": "updated",+ "title": session.get("title"),+ "visibility": session.get("visibility"),+ },+ )+ if previous_session is None:+ return++ previous_scope_id = previous_session.get("scope_id")+ current_scope_id = session.get("scope_id")+ placement_changed = (+ previous_scope_id != current_scope_id+ or previous_session.get("visibility") != session.get("visibility")+ )+ if not placement_changed:+ return++ # The current sidebar listener patches title-only `updated` events, then+ # reconciles project windows for ordering activity. Reconcile the old scope+ # to remove the row, and treat a foreground row in its new scope as newly+ # visible so an empty loaded project also fetches it.+ if previous_scope_id and (+ previous_scope_id != current_scope_id or session.get("visibility") == "background"+ ):+ broker.publish(+ "session.activity",+ {+ "session_id": session_id,+ "scope_id": previous_scope_id,+ "event": "user_message",+ "reason": "session_placement_changed",+ },+ )+ if current_scope_id and session.get("visibility") == "foreground":+ broker.publish(+ "session.activity",+ {+ "session_id": session_id,+ "scope_id": current_scope_id,+ "event": "created",+ "reason": "session_placement_changed",+ },+ )++@app.route("/api/sessions/<session_id>", methods=["PATCH"])async def sessions_update(session_id: str):from core.services import sessions as workbench_sessions_service@@ -6032,6 +6090,8 @@ async def sessions_update(session_id: str):"agent_variant","model","reasoning_effort",+ "visibility",+ "scope_id",)if key in payload}@@ -6081,25 +6141,29 @@ async def sessions_update(session_id: str):try:with engine.begin() as conn:+ previous_session = (+ workbench_sessions_service.get_session(conn, session_id)+ if {"visibility", "scope_id"}.intersection(updatable)+ else None+ )session = workbench_sessions_service.update_session(conn, session_id, **updatable)except LookupError as err:return jsonify({"error": str(err)}), 404+ except (ValueError, PermissionError) as err:+ return jsonify({"error": str(err)}), 400except 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,# but not across backends.return _backend_locked_response(err)# Broadcast so other surfaces (e.g. the sidebar session list) reflect the- # edit live — renaming a session in the chat header should rename its- # sidebar row without a manual refresh.- broker.publish(- "session.activity",- {- "session_id": session_id,- "scope_id": session.get("scope_id"),- "event": "updated",- "title": session.get("title"),- },+ # edit live. The local CLI route below uses this same sequence after its+ # out-of-process DB write.+ _publish_session_update_activity(+ broker,+ session_id=session_id,+ session=session,+ previous_session=previous_session,)return jsonify(session)@@ -6117,20 +6181,25 @@ def sessions_cli_activity(session_id: str):from core.services import sessions as workbench_sessions_servicefrom vibe.sse_broker import broker+ payload = request.json or {}+ previous_session = None+ if "previous_scope_id" in payload and "previous_visibility" in payload:+ previous_session = {+ "scope_id": payload.get("previous_scope_id"),+ "visibility": payload.get("previous_visibility"),+ }+engine = _projects_engine()try:with engine.connect() as conn:session = workbench_sessions_service.get_session(conn, session_id)except LookupError:return jsonify({"error": "not found"}), 404- broker.publish(- "session.activity",- {- "session_id": session_id,- "scope_id": session.get("scope_id"),- "event": "updated",- "title": session.get("title"),- },+ _publish_session_update_activity(+ broker,+ session_id=session_id,+ session=session,+ previous_session=previous_session,)return jsonify({"ok": True})