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(session): vibe session CLI + IM session_id linkage (#535)
Call White715daf2a0eb1
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 56e44b596..b0a60595d 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -449,6 +449,21 @@ class MessageHandler(BaseHandler):try:await self.controller.agent_service.handle_message(agent_name, request)agent_dispatched = True+ # Back-fill the human prompt's session_id now that dispatch has bound+ # the turn's session. IM inbound is mirrored scope-keyed BEFORE the+ # session PK exists (mirror_inbound runs above, pre-dispatch); the PK+ # now lives on platform_specific['agent_session_id'] — the same field+ # the agent reply uses — so a session's transcript stays complete.+ if is_human and context.platform and context.platform != "avibe" and context.message_id:+ bound_session_id = (context.platform_specific or {}).get("agent_session_id")+ if bound_session_id:+ from core.message_mirror import link_inbound_message_session++ link_inbound_message_session(+ platform=context.platform,+ native_message_id=context.message_id,+ session_id=str(bound_session_id),+ )except KeyError:await self._handle_missing_agent(context, agent_name)# Synchronous terminal failure (no agent dispatched). Settle thediff --git a/core/message_mirror.py b/core/message_mirror.pyindex 6ed4c9076..a8b6de6ed 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -210,13 +210,17 @@ def persist_agent_message(scope_id = session_row["scope_id"] if session_row else Nonerow_session_id = session_idelse:- # IM: attribute the row to the delivery channel (this ``context``- # is the routed target), matching where the reply was sent. The- # cross-platform history is scope-keyed, not session-keyed, so the- # row carries no session_id — same shape as ``mirror_inbound``.+ # IM: the row stays SCOPE-keyed to the delivery channel (this+ # ``context`` is the routed target, matching where the reply was+ # sent), but it now ALSO carries the SOURCE session_id (already+ # resolved into ``agent_session_id``) so a session's full transcript+ # is queryable by ``session_id`` on every platform. ``scope_id`` and+ # ``session_id`` can legitimately differ under routing / ``post_to``:+ # the session join answers "what did this session say", the scope+ # grouping answers "what happened in this channel".session_row = Nonescope_id = _resolve_scope_id(conn, context)- row_session_id = None+ row_session_id = session_idif scope_id is None:return# Provenance: every agent reply is source='agent'; name = the@@ -287,7 +291,10 @@ def persist_agent_message(# transcript-visible types so the live stream carries EXACTLY what the# history fetch returns (assistant / tool_call process-log rows are# persisted for debugging but neither streamed nor fetched) (user request).- if message_type in messages_service.TRANSCRIPT_TYPES:+ # 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 message_type in messages_service.TRANSCRIPT_TYPES:_publish_session_message(appended_row)if inbox_row is not None:from core.inbox_events import bus@@ -352,7 +359,10 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:thread_id=override.get("thread_id"),)scope_id = _resolve_scope_id(conn, deliver_ctx)- row_session_id = None+ # Scope-keyed to the delivery channel, but carry the source+ # 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_idif scope_id is None:returnappended_row = _append_quietly(@@ -376,7 +386,9 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None: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.- _publish_session_message(appended_row)+ # avibe-only: IM rows carry a session_id now but have no open Chat consumer.+ if context.platform == "avibe":+ _publish_session_message(appended_row)if inbox_row is not None:from core.inbox_events import bus@@ -386,7 +398,14 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:def mirror_inbound(context: MessageContext, text: str) -> None:- """Record a human-originated message into the messages table."""+ """Record a human-originated IM message into the messages table.++ Written scope-keyed with ``session_id=None``: the turn's agent session is not+ bound until dispatch, which runs AFTER this inbound mirror. ``message_handler``+ back-fills the session_id via :func:`link_inbound_message_session` once the+ backend binds it, so the human prompt ends up queryable by ``session_id`` like+ the agent reply and every other turn message — only the write order differs.+ """if not text or not text.strip():return@@ -405,6 +424,8 @@ def mirror_inbound(context: MessageContext, text: str) -> None:_append_quietly(conn,scope_id=scope_id,+ # Back-filled post-dispatch by link_inbound_message_session — the+ # session PK isn't known yet at inbound-mirror time.session_id=None,platform=context.platform,author="user",@@ -417,3 +438,35 @@ def mirror_inbound(context: MessageContext, text: str) -> None:)except Exception:logger.exception("mirror_inbound: unexpected failure on platform=%s", context.platform)+++def link_inbound_message_session(*, platform: str, native_message_id: str, session_id: str) -> None:+ """Back-fill ``session_id`` onto the IM inbound row written by :func:`mirror_inbound`.++ ``message_handler`` calls this once dispatch has bound the turn's session (the PK+ is stamped on ``context.platform_specific['agent_session_id']`` — the same field+ :func:`persist_agent_message` reads for the reply). Keyed by the unique+ ``(platform, native_message_id)``, so it stamps exactly this turn's human prompt+ and only while still unlinked. No-op for avibe (its inbound is written+ session-keyed via REST). Best-effort: a failure must never break the turn.+ """+ if not (platform and native_message_id and session_id) or platform == "avibe":+ return+ try:+ from sqlalchemy import update as _sa_update++ from storage.models import messages as _messages++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ conn.execute(+ _sa_update(_messages)+ .where(+ _messages.c.platform == platform,+ _messages.c.native_message_id == str(native_message_id),+ _messages.c.session_id.is_(None),+ )+ .values(session_id=session_id)+ )+ except Exception:+ logger.debug("link_inbound_message_session: back-fill failed", exc_info=True)diff --git a/core/services/sessions.py b/core/services/sessions.pyindex 1a53045f7..c5745ce74 100644--- a/core/services/sessions.py+++ b/core/services/sessions.py@@ -42,9 +42,11 @@ from storage.workbench_sessions_service import (backfill_session_title,count_bound_resources,create_session,+ get_active_session,get_session,is_session_archived,list_sessions,+ list_sessions_page,reset_running_agent_status,set_agent_status,touch_session,@@ -57,9 +59,11 @@ __all__ = ["backfill_session_title","count_bound_resources","create_session",+ "get_active_session","get_session","is_session_archived","list_sessions",+ "list_sessions_page","reset_running_agent_status","set_agent_status","touch_session",diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 9f58fa02d..f5ee111d3 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -203,6 +203,16 @@ _SESSION_END_PROMPT = """\Current session id: `{default_session_id}`. Before using Show Page or Harness commands, target this exact session unless the user explicitly asks to target a different one."""+# Appended to the session reminder ONLY when the session has no user-chosen title+# (empty, or a title_source other than "user" — i.e. auto-generated or not yet set).+# Nudges the agent to set a short, human-scannable title via the CLI so sessions are+# easy to find in `vibe session list`. A CLI update lands as title_source="user", so+# the nudge stops on the next turn — it naturally fires at most once per session.+_SESSION_TITLE_NUDGE = """\+This session's title is {title_state}. If you can tell what it's about, set a concise title (≤10 chars) once, silently — don't mention it to the user:+`vibe session update {default_session_id} --title "<short title>"`+"""+_USER_PREFERENCES_PROMPT = """\@@ -333,8 +343,47 @@ def _build_show_pages_prompt(context: MessageContext, *, avibe_cloud_guidance: s)+def _lookup_session_title(session_id: str) -> Optional[tuple[str, Optional[str]]]:+ """Return ``(title, title_source)`` for a session, or ``None`` if it can't be+ read. Best-effort: a lookup failure must never break prompt injection."""+ try:+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ with engine.connect() as conn:+ row = sessions_service.get_session(conn, session_id)+ title = str(row.get("title") or "").strip()+ metadata = row.get("metadata") if isinstance(row.get("metadata"), dict) else {}+ return title, metadata.get("title_source")+ except Exception:+ logger.debug("session title lookup for prompt nudge failed", exc_info=True)+ return None++def _build_session_end_prompt(context: MessageContext) -> str:- return _SESSION_END_PROMPT.format(default_session_id=_extract_default_session_id(context))+ default_session_id = _extract_default_session_id(context)+ prompt = _SESSION_END_PROMPT.format(default_session_id=default_session_id)+ looked_up = _lookup_session_title(default_session_id)+ if looked_up is not None:+ # Lazy import: keep this module's load storage-free so the agent-setup /+ # session-handler import chain never transitively pulls in sqlite+ # (test_native_session_lightweight_imports_do_not_require_sqlite).+ from storage.workbench_sessions_service import DELIBERATE_TITLE_SOURCES++ title, title_source = looked_up+ # Nudge only when the title is NOT deliberately owned. DELIBERATE_TITLE_SOURCES+ # = {"user", "agent"} covers a title set OR cleared on purpose (update_session+ # stamps the source even for an empty title) — never re-nudge those, or we'd+ # undo a deliberate clear / re-prompt an agent that already named it. Auto+ # sources ("backend", "derived_first_prompt") and a never-touched session (no+ # title_source) still nudge.+ if title_source not in DELIBERATE_TITLE_SOURCES:+ title_state = "not set yet" if not title else f'"{title}" (auto-generated)'+ prompt += "\n" + _SESSION_TITLE_NUDGE.format(+ title_state=title_state, default_session_id=default_session_id+ )+ return promptdef _build_user_preferences_prompt(diff --git a/docs/CLI.md b/docs/CLI.mdindex f3bdd6dc9..6f2653ff8 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -156,6 +156,23 @@ vibe screenshot --json- Prints the saved file path, or a JSON payload with `--json`- Stays at the CLI layer only; it does not add IM commands, bot buttons, or agent prompt injection+### `vibe session`++List, inspect, and rename Agent sessions. `list` and `get` are read-only; `update`+changes the title only. Archived sessions are soft-deleted and never surfaced.++```bash+vibe session list # active sessions, 10 per page, newest activity first+vibe session list --type slack # filter by platform (avibe = Web/Workbench)+vibe session list --page 2 # next page (fixed 10 per page; there is no --limit)+vibe session get sesk8m4q2p7x # full detail for one session+vibe session update sesk8m4q2p7x --title 'Release review' # pass "" to clear the title+```++`--type` accepts a platform id: `avibe` (Web/Workbench), `slack`, `discord`,+`telegram`, `lark`, `wechat`. For richer filtering — by agent, time range, message+content, or cross-table joins — `list` and `get` point you to `vibe data query`.+### `vibe task`Create, inspect, update, run, pause, resume, or remove scheduled tasks.diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 4898121fa..f6b5b3201 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -141,6 +141,20 @@ vibe screenshot --json- 默认输出保存路径;加 `--json` 时输出机器可读的 JSON- 只作为 CLI 层能力存在;不新增 IM 命令、bot 按钮,也不注入 Agent prompt+### `vibe session`++列出、查看并重命名 Agent 会话。`list` 与 `get` 是只读视图;`update` 只改标题。已归档会话视为软删除,任何情况下都不会被列出。++```bash+vibe session list # 未归档会话,每页 10 条,按最近活跃倒序+vibe session list --type slack # 按平台过滤(avibe = Web/Workbench)+vibe session list --page 2 # 翻到下一页(固定每页 10 条;没有 --limit)+vibe session get sesk8m4q2p7x # 单个会话的完整明细+vibe session update sesk8m4q2p7x --title 'Release review' # 传 "" 可清空标题+```++`--type` 取平台 id:`avibe`(Web/Workbench)、`slack`、`discord`、`telegram`、`lark`、`wechat`。需要更高级的筛选——按 Agent、时间段、消息内容或跨表联查——`list` 与 `get` 的返回都会引导你使用 `vibe data query`。+### `vibe task`创建、查看、更新、立即执行、暂停、恢复或删除定时任务。diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex b9828b017..28529dc4e 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -23,6 +23,7 @@ from sqlalchemy import func, select, updatefrom sqlalchemy.engine import Connectionfrom storage.agent_session_rows import create_agent_session_row+from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_onefrom storage.models import (agent_runs,agent_sessions,@@ -45,6 +46,13 @@ SESSION_ID_ALPHABET = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ# omitted ``model`` must leave it untouched._UNSET: Any = object()+# Title sources that mean the title is DELIBERATELY owned (set or cleared on purpose),+# so backend auto-fill must never overwrite it and the "name this session" prompt nudge+# must never re-prompt it. ``user`` = Web UI / human edit; ``agent`` = the agent via+# ``vibe session update``. Auto sources (``backend``, ``derived_first_prompt``) and a+# never-touched session (no title_source) are NOT deliberate.+DELIBERATE_TITLE_SOURCES: tuple[str, ...] = ("user", "agent")+def _utc_now_iso() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")@@ -55,6 +63,10 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:return {"id": row["id"],"scope_id": row.get("scope_id"),+ # Platform is the first ``scope_id`` segment (``make_scope_id`` always+ # builds ``<platform>::<scope_type>::<native_id>``), so it needs no join.+ # ``avibe`` == Web/Workbench; the rest are IM platforms.+ "platform": ((row.get("scope_id") or "").split("::", 1)[0] or None),"project_id": (row.get("scope_id") or "").rsplit("::", 1)[-1] or None,"title": row.get("title"),"agent_id": row.get("agent_id"),@@ -161,6 +173,52 @@ def get_session(conn: Connection, session_id: str) -> dict[str, Any]:return _row_to_payload(dict(row))+def get_active_session(conn: Connection, session_id: str) -> dict[str, Any]:+ """Like :func:`get_session` but treats archived sessions as absent.++ Archived sessions are soft-deleted: the agent-facing ``vibe session`` surface+ must never surface them, so ``get`` / ``update`` raise ``LookupError`` for an+ archived id exactly as they would for a missing one.+ """+ payload = get_session(conn, session_id)+ if payload.get("status") == "archived":+ raise LookupError(f"Session not found: {session_id}")+ return payload+++def list_sessions_page(+ conn: Connection,+ *,+ platform: Optional[str] = None,+ page: int = 1,+ limit: int = 10,+) -> PageResult[dict[str, Any]]:+ """Active sessions, most-recently-active first, offset-paginated for the CLI.++ Always excludes archived (soft-deleted) sessions — they are never surfaced on+ the agent-facing surface. ``platform`` filters by the scope platform via the+ ``<platform>::`` ``scope_id`` prefix (no join needed; see ``make_scope_id``).+ Fetches ``limit + 1`` rows so the caller learns whether a next page exists+ 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")+ if platform:+ query = query.where(agent_sessions.c.scope_id.like(f"{platform}::%"))+ query = (+ query.order_by(+ agent_sessions.c.last_active_at.desc(),+ agent_sessions.c.created_at.desc(),+ agent_sessions.c.id.desc(),+ )+ .limit(request.limit + 1)+ .offset(request.offset)+ )+ rows = [dict(row) for row in conn.execute(query).mappings().all()]+ payloads = [_row_to_payload(row) for row in rows]+ return page_result_from_limit_plus_one(payloads, request)++def create_session(conn: Connection,*,@@ -263,6 +321,7 @@ def update_session(session_id: str,*,title: Any = _UNSET,+ title_source: str = "user",agent_id: Any = _UNSET,agent_name: Any = _UNSET,agent_backend: Any = _UNSET,@@ -302,7 +361,8 @@ def update_session(cleaned = str(title or "").strip()values["title"] = cleaned or Nonemetadata = _load_metadata(existing.metadata_json)- metadata["title_source"] = "user"+ # "user" (Web UI / human) or "agent" (vibe session update) — both deliberate.+ metadata["title_source"] = str(title_source or "user")metadata["title_user_modified_at"] = values["updated_at"]values["metadata_json"] = _dumps_metadata(metadata)if agent_id is not _UNSET:@@ -360,7 +420,7 @@ def backfill_session_title(return Nonemetadata = _load_metadata(row.get("metadata_json"))- if metadata.get("title_source") == "user":+ if metadata.get("title_source") in DELIBERATE_TITLE_SOURCES:return Noneif str(row.get("title") or "").strip():return None@@ -384,7 +444,11 @@ def backfill_session_title(update(agent_sessions).where(agent_sessions.c.id == session_id).where((agent_sessions.c.title.is_(None)) | (agent_sessions.c.title == ""))- .where(func.coalesce(func.json_extract(agent_sessions.c.metadata_json, "$.title_source"), "") != "user")+ .where(+ func.coalesce(func.json_extract(agent_sessions.c.metadata_json, "$.title_source"), "").notin_(+ list(DELIBERATE_TITLE_SOURCES)+ )+ ).values(title=cleaned, metadata_json=_dumps_metadata(metadata), updated_at=now))if result.rowcount == 0:diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex de0559780..c826fd049 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -70,9 +70,11 @@ def test_public_surface_is_stable():"backfill_session_title","count_bound_resources","create_session",+ "get_active_session","get_session","is_session_archived","list_sessions",+ "list_sessions_page","reset_running_agent_status","set_agent_status","touch_session",diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex 3f38db120..7f0dfce0f 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -159,7 +159,10 @@ def test_persist_agent_im_uses_delivery_scope_not_session(isolated_state):select(scopes.c.id).where(scopes.c.platform == "slack", scopes.c.native_id == "C_delivery")).scalar_one()assert row["scope_id"] == delivery_scope # delivery channel, NOT C_source- assert row["session_id"] is None # IM rows are scope-keyed, not session-keyed+ # IM rows are SCOPE-keyed to the delivery channel but ALSO carry the SOURCE+ # session_id, so a routed reply is queryable both ways. Here they differ:+ # scope = C_delivery, session = ses_im (anchored under C_source).+ assert row["session_id"] == "ses_im"assert row["content_text"] == "routed answer"@@ -550,8 +553,10 @@ def test_harness_inbound_avibe_session_scoped(isolated_state):def test_harness_inbound_im_scope_keyed(isolated_state):- """A harness turn delivered to an IM channel is scope-keyed (no session_id),- same shape as ``mirror_inbound`` — but tagged source='harness'."""+ """A harness turn delivered to an IM channel with NO source session resolved+ falls back to a scope-keyed row (null session_id), tagged source='harness'.+ When ``agent_session_id`` IS present it rides along — see+ ``test_session_linkage`` for that case."""ctx = MessageContext(user_id="scheduled",channel_id="C_cron",diff --git a/tests/test_session_cli.py b/tests/test_session_cli.pynew file mode 100644index 000000000..542899d97--- /dev/null+++ b/tests/test_session_cli.py@@ -0,0 +1,342 @@+from __future__ import annotations++import json++from config import paths+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.models import agent_sessions, messages+from storage.settings_service import upsert_scope+from vibe import cli+++def _setup(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ ensure_sqlite_state(primary_platform="avibe")+ return create_sqlite_engine(paths.get_sqlite_state_path())+++def _seed(engine, sid, *, platform="avibe", native="proj_a", title="T", backend="claude", status="active", title_source=None, last_active="2026-06-09T10:00:00Z"):+ now = "2026-06-09T09:00:00Z"+ scope_type = "project" if platform == "avibe" else "channel"+ metadata = {"title_source": title_source} if title_source else {}+ with engine.begin() as conn:+ scope_id = upsert_scope(conn, platform=platform, scope_type=scope_type, native_id=native, now=now)+ conn.execute(+ agent_sessions.insert().values(+ id=sid, scope_id=scope_id, agent_id="agent_internal_" + sid, agent_name=backend,+ agent_backend=backend, agent_variant="default", session_anchor="anc_" + sid,+ native_session_id="nat_" + sid, title=title, status=status, agent_status="idle",+ metadata_json=json.dumps(metadata), created_at=now, updated_at=now, last_active_at=last_active,+ )+ )+ return scope_id+++def _run(cmd, argv, capsys):+ args = cli.build_parser().parse_args(argv)+ code = cmd(args)+ captured = capsys.readouterr()+ stream = captured.out if code == 0 else captured.err+ return code, json.loads(stream)+++# --------------------------------------------------------------------------- list+++def test_list_excludes_archived_and_orders_by_activity(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesaaa", platform="avibe", native="proj_a", last_active="2026-06-09T12:00:00Z")+ _seed(engine, "sesbbb", platform="slack", native="C1", last_active="2026-06-09T13:00:00Z")+ _seed(engine, "sesarch", platform="avibe", native="proj_a", status="archived", last_active="2026-06-09T14:00:00Z")++ code, payload = _run(cli.cmd_session_list, ["session", "list"], capsys)+ assert code == 0+ assert payload["kind"] == "agent_sessions"+ ids = [s["id"] for s in payload["sessions"]]+ assert ids == ["sesbbb", "sesaaa"] # newest activity first; archived excluded+ assert "data query" in payload["message"]+++def test_list_row_has_only_lean_fields(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesaaa", platform="slack", native="C1")+ _, payload = _run(cli.cmd_session_list, ["session", "list"], capsys)+ row = payload["sessions"][0]+ assert set(row) == {"id", "title", "platform", "project_id", "agent_name", "agent_status", "last_active_at"}+ assert row["platform"] == "slack"+ assert "agent_backend" not in row and "status" not in row+++def test_list_type_filter(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesweb", platform="avibe", native="proj_a")+ _seed(engine, "seschat", platform="slack", native="C1")+ _, payload = _run(cli.cmd_session_list, ["session", "list", "--type", "slack"], capsys)+ assert [s["id"] for s in payload["sessions"]] == ["seschat"]+++def test_list_pagination_fixed_ten_no_limit_flag(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ for i in range(12):+ _seed(engine, f"ses{i:02d}", platform="slack", native="C1", last_active=f"2026-06-09T10:{i:02d}:00Z")+ _, page1 = _run(cli.cmd_session_list, ["session", "list"], capsys)+ assert len(page1["sessions"]) == 10+ assert page1["pagination"]["has_more"] is True+ assert page1["pagination"]["next_command"] == "vibe session list --page 2"+ assert "--limit" not in page1["pagination"]["next_command"]+ _, page2 = _run(cli.cmd_session_list, ["session", "list", "--page", "2"], capsys)+ assert len(page2["sessions"]) == 2+ assert page2["pagination"]["has_more"] is False+++def test_list_on_fresh_home_returns_empty(monkeypatch, tmp_path, capsys):+ # No ensure_sqlite_state(): _open_session_engine must bootstrap the DB itself,+ # so a fresh Avibe home returns a clean empty list, not "no such table" (Codex P2).+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ code, payload = _run(cli.cmd_session_list, ["session", "list"], capsys)+ assert code == 0+ assert payload["sessions"] == []+++def test_list_invalid_type_errors(monkeypatch, tmp_path, capsys):+ _setup(monkeypatch, tmp_path)+ code, payload = _run(cli.cmd_session_list, ["session", "list", "--type", "bogus"], capsys)+ assert code == 1+ assert payload["ok"] is False+ assert payload["code"] == "invalid_session_type"+++# ---------------------------------------------------------------------------- get+++def test_get_returns_detail_without_status_agentid_anchor(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesaaa", platform="avibe", native="proj_a")+ code, payload = _run(cli.cmd_session_get, ["session", "get", "sesaaa"], capsys)+ assert code == 0+ s = payload["session"]+ assert s["id"] == "sesaaa"+ assert s["platform"] == "avibe"+ assert s["agent_backend"] == "claude" # backend kept in detail+ for omitted in ("status", "agent_id", "session_anchor"):+ assert omitted not in s+ assert "vibe runs list --session-id sesaaa" in payload["message"]+++def test_get_archived_is_not_found(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesarch", status="archived")+ code, payload = _run(cli.cmd_session_get, ["session", "get", "sesarch"], capsys)+ assert code == 1+ assert payload["code"] == "session_not_found"+++def test_get_missing_is_not_found(monkeypatch, tmp_path, capsys):+ _setup(monkeypatch, tmp_path)+ code, payload = _run(cli.cmd_session_get, ["session", "get", "nope"], capsys)+ assert code == 1+ assert payload["code"] == "session_not_found"+++# ------------------------------------------------------------------------- update+++def test_update_sets_title(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesaaa", title="Old")+ code, payload = _run(cli.cmd_session_update, ["session", "update", "sesaaa", "--title", "New name"], capsys)+ assert code == 0+ assert payload["updated"] is True+ assert payload["session"]["title"] == "New name"+ assert "status" not in payload["session"]+ # An agent-set title is sourced "agent" (vs "user" for a human Web UI edit).+ assert payload["session"]["metadata"]["title_source"] == "agent"+++def test_update_empty_title_clears(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesaaa", title="Old")+ _, payload = _run(cli.cmd_session_update, ["session", "update", "sesaaa", "--title", ""], capsys)+ assert payload["session"]["title"] is None+++def test_update_archived_is_not_found(monkeypatch, tmp_path, capsys):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesarch", status="archived", title="Old")+ code, payload = _run(cli.cmd_session_update, ["session", "update", "sesarch", "--title", "x"], capsys)+ assert code == 1+ assert payload["code"] == "session_not_found"+ # title must not have been written to the soft-deleted row+ with engine.connect() as conn:+ from sqlalchemy import select++ title = conn.execute(select(agent_sessions.c.title).where(agent_sessions.c.id == "sesarch")).scalar_one()+ assert title == "Old"+++# ------------------------------------------------------------------- IM linkage+++def test_im_messages_link_to_session(monkeypatch, tmp_path):+ import core.message_mirror as mm+ from modules.im.base import MessageContext+ from sqlalchemy import select++ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesim", platform="slack", native="C777")++ spec = {"agent_session_id": "sesim", "vibe_agent_name": "claude", "vibe_agent_backend": "claude"}+ # agent reply rides the source session_id; scope stays the delivery channel+ mm.persist_agent_message(+ MessageContext(user_id="U", channel_id="C777", platform="slack", thread_id="t1", platform_specific=spec),+ "result", "answer",+ )+ # human inbound is scope-keyed first, then back-filled+ mm.mirror_inbound(MessageContext(user_id="U", channel_id="C777", platform="slack", thread_id="t1", message_id="m1"), "question")+ mm.link_inbound_message_session(platform="slack", native_message_id="m1", session_id="sesim")+ # harness prompt carrying a source session links too+ mm.mirror_harness_inbound(+ MessageContext(user_id="s", channel_id="C777", platform="slack", message_id="h1",+ platform_specific={"agent_session_id": "sesim", "task_trigger_kind": "scheduled", "task_definition_id": "d1"}),+ "reminder",+ )++ with engine.connect() as conn:+ rows = list(conn.execute(select(messages.c.author, messages.c.session_id)).mappings())+ assert len(rows) == 3+ assert all(r["session_id"] == "sesim" for r in rows)+++def test_link_inbound_is_noop_when_already_linked(monkeypatch, tmp_path):+ import core.message_mirror as mm+ from modules.im.base import MessageContext+ from sqlalchemy import select++ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesim", platform="slack", native="C777")+ _seed(engine, "sesother", platform="slack", native="C777")+ mm.mirror_inbound(MessageContext(user_id="U", channel_id="C777", platform="slack", message_id="m1"), "q")+ mm.link_inbound_message_session(platform="slack", native_message_id="m1", session_id="sesim")+ # a second, different back-fill must not overwrite an already-linked row+ mm.link_inbound_message_session(platform="slack", native_message_id="m1", session_id="sesother")+ with engine.connect() as conn:+ sid = conn.execute(select(messages.c.session_id).where(messages.c.native_message_id == "m1")).scalar_one()+ assert sid == "sesim"+++# ------------------------------------------------------------ title nudge prompt+++def _injection_for(session_id):+ from core.system_prompt_injection import build_system_prompt_injection+ from modules.im.base import MessageContext++ ctx = MessageContext(+ user_id="u", channel_id="c", platform="avibe",+ platform_specific={"agent_session_id": session_id},+ )+ return build_system_prompt_injection(context=ctx)+++def test_title_nudge_when_empty(monkeypatch, tmp_path):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesnone", title="")+ out = _injection_for("sesnone")+ # the command carries the REAL session id (not a <id> placeholder)+ assert 'vibe session update sesnone --title "<short title>"' in out+ assert "not set yet" in out+ assert "silently" in out # only update once, without disturbing the user+++def test_title_nudge_when_auto_generated(monkeypatch, tmp_path):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesauto", title="Some auto title", title_source="backend")+ out = _injection_for("sesauto")+ assert "vibe session update sesauto --title" in out+ assert "auto-generated" in out+++def test_no_title_nudge_when_user_set(monkeypatch, tmp_path):+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesuser", title="Release review", title_source="user")+ out = _injection_for("sesuser")+ assert "vibe session update sesuser --title" not in out+ assert "Current Session Reminder" in out # the reminder itself still renders+++def test_no_title_nudge_when_user_cleared(monkeypatch, tmp_path):+ # A user who deliberately cleared the title (empty + title_source="user") must+ # NOT be nudged, or the agent would undo the clear next turn (Codex P2).+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sescleared", title="", title_source="user")+ out = _injection_for("sescleared")+ assert "vibe session update sescleared --title" not in out+++def test_no_title_nudge_when_agent_set(monkeypatch, tmp_path):+ # Once the agent names it (title_source="agent"), the nudge stops — fires once.+ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesagent", title="CLI design", title_source="agent")+ out = _injection_for("sesagent")+ assert "vibe session update sesagent --title" not in out+++# ------------------------------------------------ live session.activity endpoint+++def test_cli_activity_endpoint_publishes_with_token(monkeypatch):+ # The publish-only endpoint the CLI pings after vibe session update: with a valid+ # local CLI token it re-reads the row and broadcasts session.activity 'updated'.+ import vibe.sse_broker as sse_broker+ 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 vibe.ui_server import app++ ensure_sqlite_state(primary_platform="avibe") # conftest already isolated the home+ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ _seed(engine, "seslive", title="Renamed", title_source="agent")++ published: list = []+ monkeypatch.setattr(sse_broker.broker, "publish", lambda topic, data: published.append((topic, data)))++ resp = app.test_client().post(+ "/api/sessions/seslive/cli-activity",+ json={},+ headers={"X-Vibe-Show-Client": "cli", SHOW_CLI_EVENT_TOKEN_HEADER: show_cli_event_token()},+ )+ assert resp.status_code == 200+ events = [data for topic, data in published if topic == "session.activity"]+ assert events and events[0]["session_id"] == "seslive"+ assert events[0]["event"] == "updated" and events[0]["title"] == "Renamed"+++def test_cli_activity_endpoint_rejects_without_token(monkeypatch):+ from tests.ui_server_test_helpers import csrf_headers+ from vibe.ui_server import app++ client = app.test_client()+ # Valid CSRF (passes the mutation guard) but NO local CLI token -> handler 403.+ resp = client.post("/api/sessions/whatever/cli-activity", json={}, headers=csrf_headers(client))+ assert resp.status_code == 403+++def test_backfill_does_not_overwrite_agent_title(monkeypatch, tmp_path):+ # Backend auto-fill must never clobber a deliberately agent-set title.+ from core.services import sessions as sessions_service++ engine = _setup(monkeypatch, tmp_path)+ _seed(engine, "sesagent", title="Kept", title_source="agent")+ with engine.begin() as conn:+ result = sessions_service.backfill_session_title(+ conn, "sesagent", title="Auto Title", backend="claude"+ )+ assert result is None # skipped+ with engine.connect() as conn:+ from sqlalchemy import select++ title = conn.execute(select(agent_sessions.c.title).where(agent_sessions.c.id == "sesagent")).scalar_one()+ assert title == "Kept"diff --git a/vibe/cli.py b/vibe/cli.pyindex e4788fca2..b78d9bcaf 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -2991,6 +2991,169 @@ def cmd_data_query(args):return 1+# ``vibe session`` — Agent-facing session management. ``list`` / ``get`` are+# read-only; ``update`` renames a title only. 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+# Lean list row: enough to locate a session and tell whether it is busy.+_SESSION_LIST_FIELDS = (+ "id",+ "title",+ "platform",+ "project_id",+ "agent_name",+ "agent_status",+ "last_active_at",+)+# Detail (``get``) drops the lifecycle ``status`` (archived is never returned, so+# it is always "active"), the internal resume ``session_anchor`` (Agents resume by+# id), and ``agent_id`` (``agent_name`` is the Agent's unique key).+_SESSION_GET_OMIT = ("status", "session_anchor", "agent_id")+++def _session_row(payload: dict, *, brief: bool) -> dict:+ if brief:+ return {key: payload.get(key) for key in _SESSION_LIST_FIELDS}+ return {key: value for key, value in payload.items() if key not in _SESSION_GET_OMIT}+++def _validate_session_type(platform: str) -> None:+ from config.platform_registry import PLATFORM_REGISTRY++ if platform not in PLATFORM_REGISTRY:+ valid = ", ".join(sorted(PLATFORM_REGISTRY))+ raise TaskCliError(+ f"unknown --type '{platform}'",+ code="invalid_session_type",+ hint=f"Valid platforms: {valid} (avibe = Web/Workbench).",+ help_command="vibe session list --help",+ )+++def _session_list_hint() -> str:+ return (+ "Need richer filtering (by agent, time range, message content, or joins)? "+ "Use: vibe data query. Find sessions by what was discussed: vibe data query "+ "--sql \"select s.id, s.title from agent_sessions s join messages m "+ "on m.session_id = s.id where m.content_text like '%KEYWORD%' "+ "order by s.last_active_at desc\""+ )+++def _session_get_hint(session_id: str) -> str:+ return (+ f"This session's runs: vibe runs list --session-id {session_id}. "+ "Its messages or any cross-session query: vibe data query "+ "(join messages on session_id)."+ )+++def _open_session_engine():+ # Bootstrap/migrate the SQLite state first so a fresh Avibe home returns a clean+ # empty list / not-found instead of a raw "no such table" error (Codex P2).+ _ensure_cli_sqlite_state()+ return create_sqlite_engine(paths.get_sqlite_state_path())+++def cmd_session_list(args):+ try:+ platform = getattr(args, "type", None)+ if platform:+ _validate_session_type(platform)+ page = getattr(args, "page", None)+ page = int(page) if page is not None else 1+ if page < 1:+ raise TaskCliError("page must be >= 1", code="invalid_pagination", help_command="vibe session list --help")+ from core.services import sessions as sessions_service++ engine = _open_session_engine()+ with engine.connect() as conn:+ result = sessions_service.list_sessions_page(+ conn, platform=platform, page=page, limit=_SESSION_PAGE_SIZE+ )+ command = ["vibe", "session", "list"]+ _add_optional_arg(command, "--type", platform)+ next_command = (+ shlex.join([*command, "--page", str(result.next_page)])+ if result.next_page is not None+ else None+ )+ _print_cli_payload(+ "agent_sessions",+ sessions=[_session_row(row, brief=True) for row in result.items],+ pagination=pagination_payload(result, next_command=next_command),+ message=_session_list_hint(),+ )+ return 0+ except Exception as exc:+ _print_task_error(exc, help_command="vibe session list --help")+ return 1+++def cmd_session_get(args):+ from core.services import sessions as sessions_service++ try:+ engine = _open_session_engine()+ with engine.connect() as conn:+ payload = sessions_service.get_active_session(conn, args.session_id)+ except LookupError:+ _print_task_error(+ TaskCliError(+ f"session '{args.session_id}' not found",+ code="session_not_found",+ details={"session_id": args.session_id},+ ),+ help_command="vibe session get --help",+ )+ return 1+ except Exception as exc:+ _print_task_error(exc, help_command="vibe session get --help")+ return 1+ _print_cli_payload(+ "agent_session",+ session=_session_row(payload, brief=False),+ message=_session_get_hint(args.session_id),+ )+ return 0+++def cmd_session_update(args):+ from core.services import sessions as sessions_service++ try:+ engine = _open_session_engine()+ 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, args.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, args.session_id, title=args.title, title_source="agent"+ )+ except LookupError:+ _print_task_error(+ TaskCliError(+ f"session '{args.session_id}' not found",+ code="session_not_found",+ details={"session_id": args.session_id},+ ),+ help_command="vibe session update --help",+ )+ return 1+ except Exception as exc:+ _print_task_error(exc, help_command="vibe session update --help")+ 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(args.session_id)+ _print_cli_payload("agent_session", updated=True, session=_session_row(payload, brief=False))+ return 0++def cmd_watch_add(args):try:session_policy = _validate_definition_session_policy(@@ -4789,6 +4952,42 @@ 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:+ """Best-effort: ping a running UI so it broadcasts a ``session.activity`` update+ for this session (e.g. after ``vibe session update`` renames it). The CLI writes+ the DB in a separate process from the in-proc SSE broker, so without this the+ rename only shows after a page refresh. Silently no-ops when the UI isn't running+ or is unreachable — it must never affect the CLI command's own result."""+ from urllib.parse import quote++ from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token++ try:+ config = V2Config.load()+ except Exception:+ return+ status = runtime.read_status()+ port = getattr(config.ui, "setup_port", None)+ if not status.get("ui_pid") or not port:+ return+ url = f"http://{_ui_show_events_host(config)}:{int(port)}/api/sessions/{quote(session_id, safe='')}/cli-activity"+ http_request = urllib.request.Request(+ url,+ data=b"{}",+ method="POST",+ headers={+ "Content-Type": "application/json",+ "X-Vibe-Show-Client": "cli",+ SHOW_CLI_EVENT_TOKEN_HEADER: show_cli_event_token(),+ },+ )+ try:+ with urllib.request.urlopen(http_request, timeout=3):+ pass+ except (OSError, TimeoutError, urllib.error.URLError, urllib.error.HTTPError):+ pass++def _with_show_event_dispatch(payload: dict) -> dict:if isinstance(payload.get("annotation"), dict):return {**payload, "annotation": {**payload["annotation"], "dispatch": True}}@@ -5575,6 +5774,55 @@ def build_parser():runs_cancel_parser.add_argument("run_id")_add_json_noop(runs_cancel_parser)+ session_parser = subparsers.add_parser(+ "session",+ help="List, inspect, and rename Agent sessions",+ description=(+ "Manage Avibe Agent sessions. 'list' and 'get' are read-only views; "+ "'update' renames a session's title. Archived sessions are soft-deleted "+ "and never surfaced."+ ),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe session --help",+ error_hint="Run one of the session subcommands below. Start with: vibe session list",+ )+ session_subparsers = session_parser.add_subparsers(dest="session_command", metavar="{list,get,update}")+ session_subparsers.required = True+ session_list_parser = session_subparsers.add_parser(+ "list",+ help="List active sessions, most-recently-active first",+ description="List active (non-archived) Agent sessions, 10 per page, newest activity first.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe session list --help",+ )+ session_list_parser.add_argument(+ "--type",+ help="Filter by platform: avibe (Web/Workbench), slack, discord, telegram, lark, wechat.",+ )+ session_list_parser.add_argument("--page", type=int, help="Page number to return (10 per page). Defaults to 1.")+ _add_json_noop(session_list_parser)+ session_get_parser = session_subparsers.add_parser(+ "get",+ help="Show one session's full detail by ID",+ description="Show full detail for one active session. An archived or missing ID is reported as not found.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe session get --help",+ )+ session_get_parser.add_argument("session_id", help="Agent Session ID")+ _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.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe session update --help",+ )+ session_update_parser.add_argument("session_id", 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)."+ )+ _add_json_noop(session_update_parser)+show_parser = subparsers.add_parser("show",help="Create, inspect, and publish session Show Pages",@@ -6276,6 +6524,14 @@ def main():if args.runs_command == "cancel":sys.exit(cmd_runs_cancel(args))parser.error("runs command is required")+ if args.command == "session":+ if args.session_command == "list":+ sys.exit(cmd_session_list(args))+ if args.session_command == "get":+ sys.exit(cmd_session_get(args))+ if args.session_command == "update":+ sys.exit(cmd_session_update(args))+ parser.error("session command is required")if args.command == "data":if args.data_command == "query":sys.exit(cmd_data_query(args))diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex edadd0893..7f666ebff 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -231,7 +231,7 @@ def _current_origin() -> str:def _is_mutation_guard_exempt() -> bool:if request.path in {"/auth/callback"}:return True- if _is_cli_show_event_request():+ if _is_cli_show_event_request() or _is_cli_session_activity_request():return Truereturn (request.path == "/e2e/simulate-interaction"@@ -239,17 +239,32 @@ def _is_mutation_guard_exempt() -> bool:)-def _is_cli_show_event_request() -> bool:+def _cli_local_event_token_ok() -> bool:+ """The local CLI proves it's co-located with this service by signing the shared+ local secret. Same trust model as the show-event channel."""token = request.headers.get(SHOW_CLI_EVENT_TOKEN_HEADER)return (request.method == "POST"- and re.fullmatch(r"/api/show/sessions/[^/]+/(events|prewarm)", request.path or "") is not Noneand request.headers.get("X-Vibe-Show-Client") == "cli"and bool(token)and hmac.compare_digest(token, show_cli_event_token()))+def _is_cli_show_event_request() -> bool:+ return (+ _cli_local_event_token_ok()+ and re.fullmatch(r"/api/show/sessions/[^/]+/(events|prewarm)", request.path or "") is not None+ )+++def _is_cli_session_activity_request() -> bool:+ return (+ _cli_local_event_token_ok()+ and re.fullmatch(r"/api/sessions/[^/]+/cli-activity", request.path or "") is not None+ )++def _is_show_api_mutation() -> bool:if not (request.path.startswith("/show/") or request.path.startswith("/p/")):return False@@ -3729,6 +3744,37 @@ def sessions_update(session_id: str):return jsonify(session)[email protected]("/api/sessions/<session_id>/cli-activity", methods=["POST"])+def sessions_cli_activity(session_id: str):+ """Internal: a local CLI (e.g. ``vibe session update``) already wrote the DB in+ its own process, so it can't reach this in-process SSE broker. It pings here and+ we re-read the row and broadcast the SAME ``session.activity`` `updated` event the+ Web PATCH emits, so open surfaces (sidebar title, etc.) reflect the change live+ without a refresh. Authed by the local CLI token (see _is_cli_session_activity_request);+ publish-only — never writes — and never exposed to browsers."""+ if not _is_cli_session_activity_request():+ return jsonify({"error": "forbidden"}), 403+ from core.services import sessions as workbench_sessions_service+ from vibe.sse_broker import broker++ 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"),+ },+ )+ return jsonify({"ok": True})++@app.route("/api/sessions/<session_id>/archive-preview", methods=["GET"])def sessions_archive_preview(session_id: str):"""Counts of resources archiving this session will permanently reclaim