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(workbench): permanent session archive (red menu + confirm + resource teardown) (#517)
Call White0c06a346b597
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex f9dc1e6fe..0c866921f 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -192,6 +192,7 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = Nonerow = conn.execute(select(agent_sessions.c.id,+ agent_sessions.c.status,agent_sessions.c.agent_id,agent_sessions.c.agent_name,agent_sessions.c.agent_backend,@@ -218,6 +219,12 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = Noneif row is None:raise ValueError(f"agent session id not found: {raw}")+ # Archived sessions are terminal + inert. A task/watch/run that still targets+ # one by id must NOT fire into it — treat it as an unresolvable target so the+ # run is skipped (archive also reclaims bound definitions, so this is defense+ # in depth for manual ``--session-id`` runs and any stragglers).+ if str(row["status"] or "") == "archived":+ raise ValueError(f"agent session is archived: {raw}")platform = str(row["platform"] or "")scope_type = str(row["scope_type"] or "")scope_id = str(row["native_id"] or "")diff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.pyindex d77a52fb7..8c69e3db7 100644--- a/core/services/agent_run_target.py+++ b/core/services/agent_run_target.py@@ -107,7 +107,8 @@ def resolve_agent_run_target(.select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)).where(agent_sessions.c.id == target_id)).mappings().first()- if row is not None:+ # An archived target is terminal — treat it as gone so no turn resumes it.+ if row is not None and row["status"] != "archived":return _cache_target(context,_target_from_session_row(@@ -143,6 +144,10 @@ def resolve_agent_run_target(.select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)).where(agent_sessions.c.scope_id == scope_id).where(agent_sessions.c.session_anchor == anchor)+ # Never resolve a turn onto an archived row. The archived row's+ # anchor is vacated on archive (so it won't match a live thread+ # anyway); this is the explicit guard, matching the bind path.+ .where(agent_sessions.c.status != "archived").order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc()).limit(1)).mappings().first()diff --git a/core/services/sessions.py b/core/services/sessions.pyindex 2a0755953..1a53045f7 100644--- a/core/services/sessions.py+++ b/core/services/sessions.py@@ -40,8 +40,10 @@ from storage.workbench_sessions_service import (SessionBackendLockedError,archive_session,backfill_session_title,+ count_bound_resources,create_session,get_session,+ is_session_archived,list_sessions,reset_running_agent_status,set_agent_status,@@ -53,8 +55,10 @@ __all__ = ["SessionBackendLockedError","archive_session","backfill_session_title",+ "count_bound_resources","create_session","get_session",+ "is_session_archived","list_sessions","reset_running_agent_status","set_agent_status",diff --git a/core/show_pages.py b/core/show_pages.pyindex a96951620..a4e982dc1 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -17,7 +17,7 @@ from config.v2_config import V2Configfrom core.avibe_cloud import avibe_cloud_connect_guidance, base_public_urlfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config-from storage.models import show_pages+from storage.models import agent_sessions, show_pagesfrom storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_oneVISIBILITY_PRIVATE = "private"@@ -245,10 +245,26 @@ class ShowPageStore:)return page+ def _is_archived(self, session_id: str) -> bool:+ with self.engine.connect() as conn:+ status = conn.execute(+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ return status == "archived"+def update_visibility(self, session_id: str, visibility: str) -> ShowPage:session_id = validate_session_id(session_id)if visibility not in VISIBILITIES:raise ShowPageError(f"Unsupported visibility: {visibility}", code="invalid_visibility")+ # Reject republish BEFORE ``ensure`` so it doesn't first materialize a+ # default (private) page row for an archived session — that would leave+ # ``/show/<id>/`` enabled for a terminal session. The in-txn check below+ # is the atomic authority for the concurrent-archive race.+ if visibility != VISIBILITY_OFFLINE and self._is_archived(session_id):+ raise ShowPageError(+ "Cannot republish the Show Page of an archived session.",+ code="session_archived",+ )page = self.ensure(session_id)now = _utc_now_iso()values: dict[str, Any] = {@@ -259,6 +275,19 @@ class ShowPageStore:if visibility == VISIBILITY_PUBLIC and not page.share_id:values["share_id"] = self._unique_share_id()with self.engine.begin() as conn:+ # Archive is terminal and takes the page offline on purpose — never let+ # an archived session's page be brought back online / re-shared. Checked+ # in the SAME txn as the write so a concurrent archive can't slip in+ # between the check and the update (TOCTOU); raising here rolls back.+ if visibility != VISIBILITY_OFFLINE:+ status = conn.execute(+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ if status == "archived":+ raise ShowPageError(+ "Cannot republish the Show Page of an archived session.",+ code="session_archived",+ )conn.execute(update(show_pages).where(show_pages.c.session_id == session_id).values(**values))updated = self.get(session_id)assert updated is not None@@ -266,6 +295,14 @@ class ShowPageStore:def rotate_share(self, session_id: str) -> tuple[ShowPage, str | None]:session_id = validate_session_id(session_id)+ # Same guard as update_visibility, before ``ensure`` materializes a page:+ # an archived session is terminal, so its share link can't be rotated /+ # re-enabled (and a stale/direct call must not create a default page).+ if self._is_archived(session_id):+ raise ShowPageError(+ "Cannot rotate the share link of an archived session.",+ code="session_archived",+ )page = self.ensure(session_id)if page.visibility != VISIBILITY_PUBLIC:raise ShowPageError(diff --git a/core/show_session_events.py b/core/show_session_events.pyindex a9a23e048..bb5992260 100644--- a/core/show_session_events.py+++ b/core/show_session_events.py@@ -81,10 +81,16 @@ class ShowSessionEventStore:with self.engine.begin() as conn:session = conn.execute(- select(agent_sessions.c.id, agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id).limit(1)+ select(agent_sessions.c.id, agent_sessions.c.scope_id, agent_sessions.c.status)+ .where(agent_sessions.c.id == session_id)+ .limit(1)).mappings().first()if session is None:raise ShowSessionEventError("Agent session not found.", code="session_not_found")+ # Archive is terminal: a still-open Show Page must not keep writing+ # events (which dispatch as new agent work) into an archived session.+ if session["status"] == "archived":+ raise ShowSessionEventError("Agent session is archived.", code="session_archived")conn.execute(show_session_events.insert().values(diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 3a3ebce36..15105e5ab 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -424,6 +424,33 @@ def delete_queued(conn: Connection, ids: list[str]) -> None:conn.execute(delete(messages).where(messages.c.id.in_(ids)))+def clear_queued(conn: Connection, session_id: str) -> int:+ """Drop ALL send-while-busy queued rows for a session. Used by archive so no+ queued prompt can later be flushed into a now-terminal session (on natural+ turn completion or via send-now) — unlike ``delete_queued``, which claims a+ specific id segment during a flush. Returns the number removed."""+ result = conn.execute(+ delete(messages)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == QUEUED_TYPE)+ )+ return result.rowcount or 0+++def clear_pending(conn: Connection, session_id: str) -> int:+ """Drop ALL ``pending`` send reservations for a session. Used by archive: a+ send that reserved its row just before the archive committed must not later+ be promoted into a visible message / accepted turn for a now-terminal session+ — once the row is gone, ``promote_pending`` no-ops on the in-flight send.+ Returns the number removed."""+ result = conn.execute(+ delete(messages)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == PENDING_TYPE)+ )+ return result.rowcount or 0++def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:"""Promote a reserved ``pending`` row to its decided type — ``user`` once theturn is accepted, or ``queued`` when a turn is already running. The row is@@ -514,6 +541,16 @@ def unread_counts(.where(messages.c.author == "agent").where(messages.c.type == "result").where(messages.c.read_at.is_(None))+ # Don't let an archived session's unread results inflate its scope badge+ # (keep null-session rows, which aren't attributable to any session).+ .where(+ or_(+ messages.c.session_id.is_(None),+ messages.c.session_id.not_in(+ select(agent_sessions.c.id).where(agent_sessions.c.status == "archived")+ ),+ )+ ).group_by(messages.c.scope_id))if platform is not None:@@ -542,6 +579,9 @@ def unread_counts_by_session(.where(messages.c.type == "result").where(messages.c.read_at.is_(None)).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"))).group_by(messages.c.session_id))if platform is not None:@@ -686,6 +726,8 @@ def list_inbox_sessions(.join(latest_user, latest_user.c.session_id == latest_agent.c.session_id, isouter=True)))+ # Archived sessions are hidden everywhere — keep them out of the inbox feed too.+ query = query.where(agent_sessions.c.status != "archived")if unread_only:query = query.where(unread_count_col > 0)if only_session:diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 33385d712..8a36b9741 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -359,6 +359,16 @@ class SQLiteSessionsService:values["agent_backend"] = vibe_agent_backend or ""values["agent_variant"] = vibe_agent_backend or "default"with self.engine.begin() as conn:+ # Never resurrect an archived (terminal) session. ``bind_agent_session_by_id``+ # targets an explicit row, bypassing the ``status != 'archived'`` lookup+ # guards — and a turn that was still finishing when the session was+ # archived (the cancel is now best-effort/background) can land a late+ # native-id bind here. Refuse it so the terminal archive sticks.+ current_status = conn.execute(+ select(agent_sessions.c.status).where(agent_sessions.c.id == str(session_id))+ ).scalar_one_or_none()+ if current_status == "archived":+ return Noneif workdir is not None:requested_workdir = str(workdir) or Nonecurrent = conn.execute(@@ -381,6 +391,10 @@ class SQLiteSessionsService:result = conn.execute(agent_sessions.update().where(agent_sessions.c.id == str(session_id))+ # Atomic with the early guard above: never flip an archived row+ # back to active even if the archive commits between that read and+ # this write — the predicate makes the update itself a no-op.+ .where(agent_sessions.c.status != "archived").values(**values))return str(session_id) if result.rowcount else None@@ -403,6 +417,10 @@ class SQLiteSessionsService:select(agent_sessions).where(agent_sessions.c.scope_id == scope_id).where(agent_sessions.c.session_anchor == str(session_anchor))+ # Archived sessions are terminal + inert: a new inbound message on+ # the same thread must NOT adopt an archived row — skip it so the+ # caller falls through to creating a fresh session.+ .where(agent_sessions.c.status != "archived").order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc()).limit(1))@@ -1063,6 +1081,10 @@ def _find_agent_session_row_id(select(agent_sessions.c.id).where(agent_sessions.c.scope_id == scope_id).where(agent_sessions.c.session_anchor == str(session_anchor))+ # Never re-bind onto an archived row. ``bind_agent_session`` flips a found+ # row back to ``status='active'``; skipping archived rows here forces a+ # fresh session for the thread instead of resurrecting an archived one.+ .where(agent_sessions.c.status != "archived"))if backend != "unknown":return conn.execute(diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 79384328b..b9828b017 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -23,7 +23,19 @@ from sqlalchemy import func, select, updatefrom sqlalchemy.engine import Connectionfrom storage.agent_session_rows import create_agent_session_row-from storage.models import agent_sessions, scope_settings, scopes+from storage.models import (+ agent_runs,+ agent_sessions,+ messages,+ run_definitions,+ scope_settings,+ scopes,+ show_pages,+)++# Raw ``agent_runs.status`` values that are not yet terminal — archive cancels these.+_ACTIVE_RUN_STATUSES = ("pending", "queued", "processing", "running")+_PENDING_RUN_STATUSES = ("pending", "queued")SESSION_ID_ALPHABET = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"@@ -380,19 +392,157 @@ def backfill_session_title(return get_session(conn, session_id)+def is_session_archived(conn: Connection, session_id: str) -> bool:+ """True iff the session exists and is archived. The shared write-guard for+ by-id entry points (workbench send, show events) so "archived is terminal" is+ enforced in one place rather than re-derived per caller. Resolution paths+ rely on the archived row's vacated anchor instead (it no longer matches a+ live thread); this covers the entries that target a session by id."""+ status = conn.execute(+ select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ return status == "archived"+++def count_bound_resources(conn: Connection, session_id: str) -> dict[str, int]:+ """Count what archiving ``session_id`` will permanently reclaim: bound+ scheduled tasks + watches (live, not-yet-deleted definitions) and+ not-yet-terminal runs. Shared by the archive teardown and the confirm-dialog+ preview so both agree on the numbers shown vs. acted on."""+ types = (+ conn.execute(+ select(run_definitions.c.definition_type)+ .where(run_definitions.c.session_id == session_id)+ .where(run_definitions.c.deleted_at.is_(None))+ )+ .scalars()+ .all()+ )+ watches = sum(1 for t in types if t == "watch")+ runs = (+ conn.execute(+ select(func.count())+ .select_from(agent_runs)+ .where(agent_runs.c.session_id == session_id)+ .where(agent_runs.c.status.in_(_ACTIVE_RUN_STATUSES))+ ).scalar()+ or 0+ )+ # Send-while-busy queued prompts are user-entered text that archive discards;+ # surface them so the confirm dialog doesn't say "nothing linked" while+ # silently dropping them. (PENDING reservations are transient dispatch state,+ # not user-visible, so they're not counted here.)+ from storage.messages_service import QUEUED_TYPE++ queued = (+ conn.execute(+ select(func.count())+ .select_from(messages)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == QUEUED_TYPE)+ ).scalar()+ or 0+ )+ return {+ "tasks": len(types) - watches,+ "watches": watches,+ "runs": int(runs),+ "queued": int(queued),+ }++def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:+ """Permanently archive a session and reclaim everything bound to it.++ Archive is terminal (there is no un-archive) — so we don't just flip a flag,+ we tear down the resources that would otherwise keep firing into a hidden+ session: bound scheduled tasks + watches are soft-deleted, queued/running+ runs are cancelled, and the Show Page is taken offline. All of it rides the+ caller's transaction so the teardown is atomic with the status flip.++ The one piece that can't live here is cancelling an in-flight chat turn: it+ runs in the controller process, reachable only over the internal socket, so+ the DELETE endpoint does that (best-effort) after this commits. ``agent_status``+ is reset to ``idle`` regardless so the workbench stops showing a "working" dot.++ Returns the archived session payload plus a ``reclaimed`` summary+ (``{tasks, watches, runs}``) for the confirm-dialog / post-archive notice.+ """existing = conn.execute(select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)).scalar_one_or_none()if existing is None:raise LookupError(f"Session not found: {session_id}")now = _utc_now_iso()++ # 1) Mark archived + clear any stale "running" dot, and VACATE the thread+ # anchor. There's a UNIQUE index on (scope_id, session_anchor): leaving the+ # archived row on the live anchor would make the next inbound message on+ # that thread collide on INSERT (the lookup guards force a fresh-row create).+ # Re-anchoring to a per-row sentinel frees the (scope, anchor) slot while+ # keeping this row's own anchor unique; the session stays viewable by id.conn.execute(update(agent_sessions).where(agent_sessions.c.id == session_id)- .values(status="archived", updated_at=now)+ .values(+ status="archived",+ agent_status="idle",+ session_anchor=f"archived:{session_id}",+ updated_at=now,+ ))- return get_session(conn, session_id)++ # Tally before teardown so the response reports what was reclaimed.+ reclaimed = count_bound_resources(conn, session_id)++ # 2) Soft-delete bound scheduled tasks + watches (same table, distinguished by+ # ``definition_type``). Deleting — not pausing — is deliberate: a paused+ # definition could be re-enabled later and would then target a dead session.+ conn.execute(+ update(run_definitions)+ .where(run_definitions.c.session_id == session_id)+ .where(run_definitions.c.deleted_at.is_(None))+ .values(deleted_at=now, updated_at=now)+ )++ # 3) Cancel not-yet-terminal runs for this session. Flag every active run as+ # cancel-requested (the executor honors it for in-flight ones) and+ # terminalize the ones that haven't started.+ if reclaimed["runs"]:+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.session_id == session_id)+ .where(agent_runs.c.status.in_(_ACTIVE_RUN_STATUSES))+ .values(cancel_requested=1, cancel_requested_at=now, updated_at=now)+ )+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.session_id == session_id)+ .where(agent_runs.c.status.in_(_PENDING_RUN_STATUSES))+ .values(status="canceled", completed_at=now)+ )++ # 3b) Reclaim all unsent user input so the terminal session retains none:+ # queued prompts (flushed on completion / send-now), ``pending`` rows a+ # concurrent send reserved just before this committed (``promote_pending``+ # then no-ops on that in-flight send), and the saved composer draft.+ from storage.messages_service import clear_draft, clear_pending, clear_queued++ clear_queued(conn, session_id)+ clear_pending(conn, session_id)+ clear_draft(conn, session_id)++ # 4) Take the Show Page offline so a shared link can't keep serving the+ # archived session (no-op when the session never had one).+ conn.execute(+ update(show_pages)+ .where(show_pages.c.session_id == session_id)+ .values(visibility="offline", offline_at=now, updated_at=now)+ )++ payload = get_session(conn, session_id)+ payload["reclaimed"] = reclaimed+ return payloaddef touch_session(conn: Connection, session_id: str) -> None:diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex 4bca01240..de0559780 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -68,8 +68,10 @@ def test_public_surface_is_stable():# Modern workbench CRUD (takes ``conn``):"archive_session","backfill_session_title",+ "count_bound_resources","create_session","get_session",+ "is_session_archived","list_sessions","reset_running_agent_status","set_agent_status",@@ -94,8 +96,10 @@ def test_each_workbench_function_delegates_to_storage():for name in ("archive_session","backfill_session_title",+ "count_bound_resources","create_session","get_session",+ "is_session_archived","list_sessions","reset_running_agent_status","set_agent_status",diff --git a/tests/test_session_archive.py b/tests/test_session_archive.pynew file mode 100644index 000000000..2f7e25f6f--- /dev/null+++ b/tests/test_session_archive.py@@ -0,0 +1,389 @@+"""Session archive is terminal: it reclaims bound resources and the archived+row becomes inert (never re-bound by inbound routing or task resolution)."""++from __future__ import annotations++import sys+from pathlib import Path++import pytest+from sqlalchemy import select++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config import paths+from core.scheduled_tasks import resolve_session_id_target+from core.show_pages import ShowPageError, ShowPageStore+from core.show_session_events import ShowSessionEventError, ShowSessionEventStore+from storage import messages_service+from storage import workbench_sessions_service as wss+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.models import agent_runs, messages, run_definitions, show_pages+from storage.sessions_service import SQLiteSessionsService++NOW = "2026-06-08T00:00:00Z"+++def _bind_session(service: SQLiteSessionsService, *, channel: str, anchor: str, native: str) -> str:+ sid = service.bind_agent_session(+ scope_key=f"slack::channel::{channel}",+ agent_name="claude",+ session_anchor=anchor,+ native_session_id=native,+ )+ assert sid is not None+ return sid+++def _insert_def(conn, *, def_id: str, session_id: str, definition_type: str, deleted_at=None) -> None:+ conn.execute(+ run_definitions.insert().values(+ id=def_id,+ definition_type=definition_type,+ enabled=1,+ deleted_at=deleted_at,+ session_id=session_id,+ created_at=NOW,+ updated_at=NOW,+ metadata_json="{}",+ )+ )+++def _insert_run(conn, *, run_id: str, session_id: str, status: str) -> None:+ conn.execute(+ agent_runs.insert().values(+ id=run_id,+ run_type="agent",+ status=status,+ session_id=session_id,+ cancel_requested=0,+ created_at=NOW,+ updated_at=NOW,+ metadata_json="{}",+ )+ )+++def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C1", anchor="slack_C1", native="nat1")+ finally:+ service.close()++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.set_agent_status(conn, sid, "running") # simulate a live "working" dot+ _insert_def(conn, def_id="task1", session_id=sid, definition_type="scheduled")+ _insert_def(conn, def_id="watch1", session_id=sid, definition_type="watch")+ # Already-deleted definition + a terminal run must NOT be counted/touched.+ _insert_def(conn, def_id="task_dead", session_id=sid, definition_type="scheduled", deleted_at=NOW)+ _insert_run(conn, run_id="run_q", session_id=sid, status="queued")+ _insert_run(conn, run_id="run_r", session_id=sid, status="running")+ _insert_run(conn, run_id="run_done", session_id=sid, status="succeeded")+ conn.execute(+ show_pages.insert().values(+ session_id=sid, visibility="public", share_id="shareX", created_at=NOW, updated_at=NOW+ )+ )++ with engine.begin() as conn:+ result = wss.archive_session(conn, sid)++ assert result["status"] == "archived"+ assert result["agent_status"] == "idle"+ assert result["reclaimed"] == {"tasks": 1, "watches": 1, "runs": 2, "queued": 0}++ with engine.connect() as conn:+ live_defs = (+ conn.execute(+ select(run_definitions.c.id)+ .where(run_definitions.c.session_id == sid)+ .where(run_definitions.c.deleted_at.is_(None))+ )+ .scalars()+ .all()+ )+ assert live_defs == [] # both live definitions soft-deleted++ runs = {+ r["id"]: r+ for r in conn.execute(select(agent_runs).where(agent_runs.c.session_id == sid)).mappings().all()+ }+ assert runs["run_q"]["status"] == "canceled" # unstarted → terminalized+ assert runs["run_r"]["cancel_requested"] == 1 # in-flight → flagged for the executor+ assert runs["run_done"]["status"] == "succeeded" # terminal → untouched++ page = conn.execute(select(show_pages).where(show_pages.c.session_id == sid)).mappings().first()+ assert page["visibility"] == "offline"+ assert page["offline_at"] is not None+++def test_archived_session_not_reused_for_anchor(monkeypatch, tmp_path: Path) -> None:+ """A new inbound message on the same thread must NOT resurrect an archived+ session, NOR collide on the (scope_id, session_anchor) UNIQUE index — a fresh+ row is bound instead.++ Runs on the MIGRATED schema (``ensure_sqlite_state`` → alembic), because that+ unique index only exists post-migration; ``metadata.create_all`` omits it, so+ a create_all-only test would miss the archived-row collision entirely."""+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C2", anchor="slack_C2", native="nat1")+ assert service.find_session_for_anchor(scope_key="slack::channel::C2", session_anchor="slack_C2") is not None++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.archive_session(conn, sid)++ # Anchor lookup skips the archived row (its anchor was vacated on archive).+ assert service.find_session_for_anchor(scope_key="slack::channel::C2", session_anchor="slack_C2") is None++ # Re-binding the same thread must NOT raise (unique index) and creates a+ # NEW row — never re-activating the archived one.+ sid2 = _bind_session(service, channel="C2", anchor="slack_C2", native="nat2")+ assert sid2 != sid+ assert service.get_agent_session_by_id(sid)["status"] == "archived"+ assert service.get_agent_session_by_id(sid2)["status"] == "active"+ finally:+ service.close()+++def test_resolve_session_id_target_rejects_archived(tmp_path: Path) -> None:+ """A task/watch/run that targets an archived session by id is unresolvable+ (treated as invalid → the run is skipped)."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C3", anchor="slack_C3", native="nat1")+ finally:+ service.close()++ # Resolvable while active.+ resolve_session_id_target(sid, db_path=db_path)++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.archive_session(conn, sid)++ with pytest.raises(ValueError, match="archived"):+ resolve_session_id_target(sid, db_path=db_path)+++def _pending_ids(conn, session_id: str) -> list[str]:+ return list(+ conn.execute(+ select(messages.c.id)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == messages_service.PENDING_TYPE)+ ).scalars()+ )+++def test_archive_clears_queued_and_pending_messages(tmp_path: Path) -> None:+ """Archive drops both send-while-busy queued prompts AND in-flight ``pending``+ send reservations, so neither can flush / be promoted into a terminal session."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C4", anchor="slack_C4", native="nat1")+ scope_id = service.get_agent_session_by_id(sid)["scope_id"]+ finally:+ service.close()++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=sid, text="q1")+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=sid, text="q2")+ # A send mid-dispatch reserved its row as ``pending``; the user also has a+ # saved composer draft.+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=sid,+ platform="avibe",+ author="user",+ message_type=messages_service.PENDING_TYPE,+ text="reserved",+ )+ messages_service.set_draft(conn, scope_id=scope_id, session_id=sid, text="half-typed")+ with engine.connect() as conn:+ assert len(messages_service.list_queued(conn, sid)) == 2+ assert len(_pending_ids(conn, sid)) == 1+ assert messages_service.get_draft(conn, sid)+ # Queued prompts are surfaced in the reclaim preview (not silently dropped).+ assert wss.count_bound_resources(conn, sid)["queued"] == 2++ with engine.begin() as conn:+ wss.archive_session(conn, sid)+ with engine.connect() as conn:+ assert messages_service.list_queued(conn, sid) == []+ assert _pending_ids(conn, sid) == []+ assert not messages_service.get_draft(conn, sid)+++def test_archived_show_page_cannot_be_republished(monkeypatch, tmp_path: Path) -> None:+ """Archive takes the Show Page offline and locks it there — no re-sharing."""+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C5", anchor="slack_C5", native="nat1")+ finally:+ service.close()++ store = ShowPageStore()+ try:+ store.ensure(sid)+ store.update_visibility(sid, "public") # allowed while active++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.archive_session(conn, sid)++ assert store.get(sid).visibility == "offline" # archive took it offline+ with pytest.raises(ShowPageError):+ store.update_visibility(sid, "public") # republish refused+ finally:+ store.close()+++def test_republish_archived_session_creates_no_show_page(monkeypatch, tmp_path: Path) -> None:+ """Republishing an archived session that never had a page must NOT first+ materialize a default page (the guard runs before ``ensure``)."""+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C9", anchor="slack_C9", native="nat1")+ finally:+ service.close()++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.archive_session(conn, sid)++ store = ShowPageStore()+ try:+ with pytest.raises(ShowPageError):+ store.update_visibility(sid, "public")+ finally:+ store.close()++ with engine.connect() as conn:+ row = conn.execute(select(show_pages.c.session_id).where(show_pages.c.session_id == sid)).first()+ assert row is None # no page row was materialized+++def test_bind_by_id_does_not_resurrect_archived(tmp_path: Path) -> None:+ """A late native-id bind (turn finishing after archive) must not flip an+ archived row back to active — archive is terminal."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C10", anchor="slack_C10", native="nat1")+ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.archive_session(conn, sid)++ # The by-id bind targets the explicit archived row, bypassing the anchor+ # lookup guards — it must refuse rather than resurrect.+ assert service.bind_agent_session_by_id(session_id=sid, native_session_id="late-native") is None+ assert service.get_agent_session_by_id(sid)["status"] == "archived"+ finally:+ service.close()+++def test_archived_session_excluded_from_inbox(monkeypatch, tmp_path: Path) -> None:+ """An archived session (and its unread) drops out of the inbox feed + badges."""+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C6", anchor="slack_C6", native="nat1")+ scope_id = service.get_agent_session_by_id(sid)["scope_id"]+ finally:+ service.close()++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ # An unread agent ``result`` makes the session inbox-eligible.+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=sid,+ platform="avibe",+ author="agent",+ message_type="result",+ text="done",+ )+ with engine.connect() as conn:+ feed = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"]+ assert any(s["session_id"] == sid for s in feed)+ assert sid in messages_service.unread_counts_by_session(conn, platform="avibe")++ with engine.begin() as conn:+ wss.archive_session(conn, sid)+ with engine.connect() as conn:+ feed = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"]+ assert all(s["session_id"] != sid for s in feed)+ assert sid not in messages_service.unread_counts_by_session(conn, platform="avibe")+++def test_is_session_archived_flag(tmp_path: Path) -> None:+ """The shared write-guard accessor flips with the session's status."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C7", anchor="slack_C7", native="nat1")+ finally:+ service.close()++ engine = create_sqlite_engine(db_path)+ with engine.connect() as conn:+ assert wss.is_session_archived(conn, sid) is False+ assert wss.is_session_archived(conn, "does-not-exist") is False+ with engine.begin() as conn:+ wss.archive_session(conn, sid)+ with engine.connect() as conn:+ assert wss.is_session_archived(conn, sid) is True+++def test_show_event_rejected_for_archived_session(monkeypatch, tmp_path: Path) -> None:+ """An already-open Show Page can't write events into an archived session."""+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ service = SQLiteSessionsService(db_path)+ try:+ sid = _bind_session(service, channel="C8", anchor="slack_C8", native="nat1")+ finally:+ service.close()++ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ wss.archive_session(conn, sid)++ store = ShowSessionEventStore()+ try:+ with pytest.raises(ShowSessionEventError) as exc:+ store.append(+ sid,+ {+ "type": "assistant.mark.created",+ "mark": {"target": "mark-default-summary", "body": "x"},+ "anchor": {"selector": "[mark-default='summary']", "text": "y"},+ },+ )+ assert exc.value.code == "session_archived"+ finally:+ store.close()diff --git a/ui/src/components/workbench/ArchiveSessionDialog.tsx b/ui/src/components/workbench/ArchiveSessionDialog.tsxnew file mode 100644index 000000000..1474e5501--- /dev/null+++ b/ui/src/components/workbench/ArchiveSessionDialog.tsx@@ -0,0 +1,156 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { AlertTriangle, Loader2 } from 'lucide-react';++import { useApi } from '../../context/ApiContext';+import { Button } from '../ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '../ui/dialog';++interface ArchivePreview {+ tasks: number;+ watches: number;+ runs: number;+ queued: number;+}++export interface ArchiveSessionDialogProps {+ /** The session to archive; ``null`` keeps the dialog inert (no preview fetch). */+ sessionId: string | null;+ sessionTitle?: string | null;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Perform the archive (+ any caller-side state update / navigation). The+ * dialog closes on success; on throw it stays open so the user can retry. */+ onConfirm: () => Promise<void>;+}++// Irreversible-confirm dialog for permanently archiving a session. Archive is+// terminal (no restore) and reclaims the session's bound background work, so the+// dialog spells that out and previews the exact counts before the user commits.+export function ArchiveSessionDialog({+ sessionId,+ sessionTitle,+ open,+ onOpenChange,+ onConfirm,+}: ArchiveSessionDialogProps) {+ const { t } = useTranslation();+ const api = useApi();+ const [preview, setPreview] = useState<ArchivePreview | null>(null);+ const [loadingPreview, setLoadingPreview] = useState(false);+ const [previewError, setPreviewError] = useState(false);+ const [busy, setBusy] = useState(false);++ // Fetch the reclaim preview when the dialog opens for a session. While it's in+ // flight the confirm button stays disabled (don't let a destructive archive+ // commit before the user sees what it deletes); on failure we show an honest+ // "couldn't verify" warning rather than a misleading "nothing linked".+ useEffect(() => {+ if (!open || !sessionId) {+ setPreview(null);+ setPreviewError(false);+ return;+ }+ let alive = true;+ setLoadingPreview(true);+ setPreviewError(false);+ api+ .getArchivePreview(sessionId)+ .then((counts) => {+ if (alive) setPreview(counts);+ })+ .catch(() => {+ if (alive) {+ setPreview(null);+ setPreviewError(true);+ }+ })+ .finally(() => {+ if (alive) setLoadingPreview(false);+ });+ return () => {+ alive = false;+ };+ }, [open, sessionId, api]);++ const confirm = async () => {+ if (busy) return;+ setBusy(true);+ try {+ await onConfirm();+ onOpenChange(false);+ } catch {+ // apiFetch already surfaced the error toast; keep the dialog open for retry.+ } finally {+ setBusy(false);+ }+ };++ const reclaimItems = preview+ ? ([+ preview.tasks > 0 ? t('workbench.archiveSession.reclaimTasks', { n: preview.tasks }) : null,+ preview.watches > 0 ? t('workbench.archiveSession.reclaimWatches', { n: preview.watches }) : null,+ preview.runs > 0 ? t('workbench.archiveSession.reclaimRuns', { n: preview.runs }) : null,+ preview.queued > 0 ? t('workbench.archiveSession.reclaimQueued', { n: preview.queued }) : null,+ ].filter(Boolean) as string[])+ : [];++ const label = sessionTitle?.trim() || t('workbench.untitledSession');++ return (+ <Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>+ <DialogContent className="max-w-[420px]">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <span className="grid size-7 shrink-0 place-items-center rounded-full bg-destructive/12 text-destructive">+ <AlertTriangle className="size-4" />+ </span>+ {t('workbench.archiveSession.title')}+ </DialogTitle>+ <DialogDescription>+ {t('workbench.archiveSession.body', { name: label })}+ </DialogDescription>+ </DialogHeader>++ <div className="rounded-lg border border-destructive/25 bg-destructive/[0.05] px-3.5 py-3 text-[13px] leading-relaxed text-foreground">+ {loadingPreview ? (+ <span className="flex items-center gap-2 text-muted">+ <Loader2 className="size-3.5 animate-spin" />+ {t('workbench.archiveSession.checking')}+ </span>+ ) : previewError ? (+ <span className="text-pink">{t('workbench.archiveSession.previewError')}</span>+ ) : reclaimItems.length > 0 ? (+ <>+ <p className="mb-1.5 font-medium text-destructive">{t('workbench.archiveSession.reclaimIntro')}</p>+ <ul className="list-disc space-y-0.5 pl-4 text-muted">+ {reclaimItems.map((item) => (+ <li key={item}>{item}</li>+ ))}+ </ul>+ </>+ ) : (+ <span className="text-muted">{t('workbench.archiveSession.noReclaim')}</span>+ )}+ </div>++ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>+ {t('common.cancel')}+ </Button>+ <Button type="button" variant="destructive" onClick={confirm} disabled={busy || loadingPreview}>+ {busy ? <Loader2 className="size-4 animate-spin" /> : null}+ {t('workbench.archiveSession.confirm')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex bfab71efd..ba5d2b6dd 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -452,6 +452,12 @@ export const ChatPage: React.FC = () => {if (data.session_id === sessionIdRef.current) void refreshQueue();},onSessionActivity: (data) => {+ if (data.session_id === sessionIdRef.current && data.event === 'archived') {+ // The session you're viewing was archived (here or in another tab) —+ // archive is terminal, so leave the chat.+ goBack();+ return;+ }// A rename (from the sidebar or elsewhere) broadcasts the new title;// keep this chat's header in sync without a reload. Match the CURRENT// route via sessionIdRef like the handlers above.@@ -475,7 +481,7 @@ export const ChatPage: React.FC = () => {},}, { reconnect: connectionEpoch > 0 });return disconnect;- }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, markWorking, connectionEpoch]);+ }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, markWorking, connectionEpoch, goBack]);// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the// SSE feed can be suspended without a clean reconnect, dropping the reply.diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsxindex f269b65e0..ed2ce1646 100644--- a/ui/src/components/workbench/ProjectsPage.tsx+++ b/ui/src/components/workbench/ProjectsPage.tsx@@ -27,6 +27,7 @@ import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { Input } from '../ui/input';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';+import { ArchiveSessionDialog } from './ArchiveSessionDialog';import { NewProjectDialog } from './NewProjectDialog';import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';import { ProjectSettingsDialog } from './ProjectSettingsDialog';@@ -221,8 +222,9 @@ const MobileSessionRow: React.FC<{onOpen: () => void;}> = ({ projectId, session, unread, onOpen }) => {const { t } = useTranslation();- const { renameSession } = useWorkbenchProjectsTree();+ const { renameSession, archiveSession } = useWorkbenchProjectsTree();const [menuOpen, setMenuOpen] = useState(false);+ const [archiveOpen, setArchiveOpen] = useState(false);const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState(session.title ?? '');const inputRef = useRef<HTMLInputElement | null>(null);@@ -303,7 +305,7 @@ const MobileSessionRow: React.FC<{<Ellipsis className="size-3.5" /></Button></PopoverTrigger>- <PopoverContent align="end" className="w-[160px] p-1">+ <PopoverContent align="end" className="w-[176px] p-1"><MenuItemicon={Pencil}onClick={() => {@@ -315,8 +317,25 @@ const MobileSessionRow: React.FC<{>{t('workbench.sessionRename')}</MenuItem>+ <MenuItem+ icon={Archive}+ danger+ onClick={() => {+ setMenuOpen(false);+ setArchiveOpen(true);+ }}+ >+ {t('workbench.sessionArchive')}+ </MenuItem></PopoverContent></Popover>+ <ArchiveSessionDialog+ sessionId={archiveOpen ? session.id : null}+ sessionTitle={session.title}+ open={archiveOpen}+ onOpenChange={setArchiveOpen}+ onConfirm={() => archiveSession(projectId, session.id)}+ /></div>);};diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex bcfa97994..8e77e41de 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -29,6 +29,7 @@ import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContextimport type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';import { formatRelativeTime } from '../../lib/relativeTime';import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';+import { ArchiveSessionDialog } from './ArchiveSessionDialog';import { Button } from '../ui/button';import { Input } from '../ui/input';import { Markdown } from '../ui/markdown';@@ -193,12 +194,14 @@ const SessionRow: React.FC<{unread: number;onSessionMarkRead: (sessionId: string) => void;onRenameSession: (sessionId: string, title: string) => Promise<void>;-}> = ({ session, unread, onSessionMarkRead, onRenameSession }) => {+ onArchiveSession: (sessionId: string) => Promise<void>;+}> = ({ session, unread, onSessionMarkRead, onRenameSession, onArchiveSession }) => {const { t } = useTranslation();const navigate = useNavigate();const location = useLocation();const active = location.pathname === `/chat/${session.id}`;const [menuOpen, setMenuOpen] = useState(false);+ const [archiveOpen, setArchiveOpen] = useState(false);const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState(session.title ?? '');const inputRef = useRef<HTMLInputElement | null>(null);@@ -257,6 +260,7 @@ const SessionRow: React.FC<{const displayName = session.title?.trim() || t('workbench.untitledSession');return (+ <><Popover open={menuOpen} onOpenChange={setMenuOpen}><PopoverAnchor asChild><button@@ -298,7 +302,7 @@ const SessionRow: React.FC<{)}</button></PopoverAnchor>- <PopoverContent align="start" className="w-[160px] p-1">+ <PopoverContent align="start" className="w-[176px] p-1"><buttontype="button"onClick={() => {@@ -312,8 +316,34 @@ const SessionRow: React.FC<{<Pencil className="size-3 text-muted" />{t('workbench.sessionRename')}</button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => {+ setMenuOpen(false);+ setArchiveOpen(true);+ }}+ className="h-auto w-full justify-start gap-2 rounded px-2 py-1.5 text-left text-[12px] font-normal text-pink hover:bg-pink/[0.08] hover:text-pink"+ >+ <Archive className="size-3" />+ {t('workbench.sessionArchive')}+ </Button></PopoverContent></Popover>+ <ArchiveSessionDialog+ sessionId={archiveOpen ? session.id : null}+ sessionTitle={session.title}+ open={archiveOpen}+ onOpenChange={setArchiveOpen}+ onConfirm={async () => {+ await onArchiveSession(session.id);+ // If we're viewing the chat we just archived, leave it directly — don't+ // rely solely on the replay-less SSE 'archived' event to navigate away.+ if (active) navigate('/inbox');+ }}+ />+ </>);};@@ -335,6 +365,7 @@ const ProjectRow: React.FC<{onRename: (next: string) => Promise<void>;onArchive: () => Promise<void>;onRenameSession: (sessionId: string, title: string) => Promise<void>;+ onArchiveSession: (sessionId: string) => Promise<void>;}> = ({project,expanded,@@ -351,6 +382,7 @@ const ProjectRow: React.FC<{onRename,onArchive,onRenameSession,+ onArchiveSession,}) => {const { t } = useTranslation();const Chevron = expanded ? ChevronDown : ChevronRight;@@ -530,6 +562,7 @@ const ProjectRow: React.FC<{unread={unreadBySession[session.id] || 0}onSessionMarkRead={onSessionMarkRead}onRenameSession={onRenameSession}+ onArchiveSession={onArchiveSession}/>))}{hasMore && (@@ -579,6 +612,7 @@ export const WorkbenchSidebar: React.FC = () => {renameProject,archiveProject,renameSession,+ archiveSession,upsertProjectToTop,} = useWorkbenchProjectsTree();const [popoverOpen, setPopoverOpen] = useState(false);@@ -775,6 +809,7 @@ export const WorkbenchSidebar: React.FC = () => {onRename={(next) => renameProject(project.id, next)}onArchive={() => archiveProject(project.id)}onRenameSession={(sessionId, title) => renameSession(project.id, sessionId, title)}+ onArchiveSession={(sessionId) => archiveSession(project.id, sessionId)}/>);})}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 0b72642fd..8bf27ecd8 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -178,6 +178,9 @@ export type ApiContextType = {getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;archiveSession: (sessionId: string) => Promise<WorkbenchSession>;+ /** Counts of resources permanently reclaimed when archiving this session+ * (bound tasks/watches + active runs) — drives the irreversible-confirm dialog. */+ getArchivePreview: (sessionId: string) => Promise<{ tasks: number; watches: number; runs: number; queued: number }>;listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;@@ -1672,6 +1675,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenreturn payloadJson;},archiveSession: (sessionId) => deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}`),+ getArchivePreview: (sessionId) =>+ getJson(`/api/sessions/${encodeURIComponent(sessionId)}/archive-preview`),listSessionMessages: (sessionId, params) => {const search = new URLSearchParams();if (params?.afterId) search.set('after_id', params.afterId);diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsxindex d5fd80f46..72b51dc3f 100644--- a/ui/src/context/WorkbenchInboxContext.tsx+++ b/ui/src/context/WorkbenchInboxContext.tsx@@ -200,6 +200,18 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>setUnreadBySession(data.unread_by_session);}},+ onSessionActivity: (data) => {+ // Terminal archive (here or in another tab) — drop the card + its unread+ // live, instead of waiting for the next reconnect/refresh to filter it.+ if (data.event !== 'archived') return;+ setInboxSessions((prev) => prev.filter((s) => s.session_id !== data.session_id));+ setUnreadBySession((prev) => {+ if (!(data.session_id in prev)) return prev;+ const next = { ...prev };+ delete next[data.session_id];+ return next;+ });+ },onError: (err) => {// Browser EventSource auto-reconnects on transient drops; the// visibility/online resync below covers what it can't — a frozen mobilediff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsxindex 045870dcb..90d46ff62 100644--- a/ui/src/context/WorkbenchProjectsContext.tsx+++ b/ui/src/context/WorkbenchProjectsContext.tsx@@ -62,6 +62,9 @@ export interface WorkbenchProjectsTree {archiveProject: (projectId: string) => Promise<void>;/** Throws on failure so the row's inline editor can fall back; patches title on success. */renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;+ /** Permanently archive a session: calls the API (which reclaims its bound+ * tasks/watches/runs) then drops the row from the tree. Throws on failure. */+ archiveSession: (projectId: string, sessionId: string) => Promise<void>;/** After NewProjectDialog: dedup-by-id, hoist to top, expand, fetch sessions if not loaded. */upsertProjectToTop: (project: WorkbenchProject) => void;}@@ -95,6 +98,31 @@ function patchSessionRow(return changed ? next : prev;}+// Drop a session id from every project's loaded rows — used when an archive+// broadcast (possibly from another tab) should remove the row live. Returns a+// new state only when a row was actually removed.+function removeSessionRow(+ prev: Record<string, ProjectSessionsState>,+ sessionId: string,+): Record<string, ProjectSessionsState> {+ let changed = false;+ const next: Record<string, ProjectSessionsState> = {};+ for (const [projectId, state] of Object.entries(prev)) {+ if (!state.sessions) {+ next[projectId] = state;+ continue;+ }+ const rows = state.sessions.filter((s) => s.id !== sessionId);+ if (rows.length !== state.sessions.length) {+ next[projectId] = { ...state, sessions: rows };+ changed = true;+ } else {+ next[projectId] = state;+ }+ }+ return changed ? next : prev;+}+const REORDER_ACTIVITY_EVENTS = new Set(['created', 'user_message', 'show_event']);const WorkbenchProjectsContext = createContext<WorkbenchProjectsTree | null>(null);@@ -354,6 +382,11 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cvoid reconcileProjectTree();},onSessionActivity: (data) => {+ if (data.event === 'archived') {+ // Terminal archive (here or in another tab) — drop the row live.+ setSessions((prev) => removeSessionRow(prev, data.session_id));+ return;+ }if (data.event === 'updated' && Object.prototype.hasOwnProperty.call(data, 'title')) {const nextTitle = data.title ?? null;setSessions((prev) =>@@ -502,6 +535,23 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c[api],);+ const archiveSession = useCallback(+ async (projectId: string, sessionId: string) => {+ // Archive is terminal — the API reclaims bound tasks/watches/runs server-side.+ // Drop the row from the tree on success; throw so the caller's dialog can react.+ await api.archiveSession(sessionId);+ setSessions((prev) => {+ const state = prev[projectId];+ if (!state?.sessions) return prev;+ return {+ ...prev,+ [projectId]: { ...state, sessions: state.sessions.filter((s) => s.id !== sessionId) },+ };+ });+ },+ [api],+ );+const upsertProjectToTop = useCallback((project: WorkbenchProject) => {// create_project is find-or-create by path: opening a tracked folder returns@@ -543,6 +593,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ csetProjectDefaultAgent,archiveProject,renameSession,+ archiveSession,upsertProjectToTop,}),[@@ -561,6 +612,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ csetProjectDefaultAgent,archiveProject,renameSession,+ archiveSession,upsertProjectToTop,],);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex ab91a7a7e..55f3911db 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -580,6 +580,20 @@"projectRenamePlaceholder": "New name","sessionRename": "Rename","sessionRenamePlaceholder": "Session name",+ "sessionArchive": "Archive session",+ "archiveSession": {+ "title": "Archive this session permanently?",+ "body": "“{{name}}” will be permanently archived and can't be restored.",+ "checking": "Checking linked resources…",+ "previewError": "Couldn't verify linked resources — they'll still be permanently deleted.",+ "reclaimIntro": "These linked resources will be permanently deleted:",+ "reclaimTasks": "{{n}} scheduled task(s)",+ "reclaimWatches": "{{n}} watch(es)",+ "reclaimRuns": "{{n}} in-progress run(s)",+ "reclaimQueued": "{{n}} queued message(s)",+ "noReclaim": "No scheduled tasks or watches are linked to this session.",+ "confirm": "Archive permanently"+ },"projectsEmpty": "No projects yet — add one to start a session.","projectsLoading": "Loading projects…","projectsLoadError": "Couldn't load projects.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex ae8ace684..76eb78f32 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -580,6 +580,20 @@"projectRenamePlaceholder": "新名字","sessionRename": "重命名","sessionRenamePlaceholder": "会话名称",+ "sessionArchive": "归档会话",+ "archiveSession": {+ "title": "永久归档此会话?",+ "body": "会话「{{name}}」将被永久归档,且无法恢复。",+ "checking": "正在检查关联资源…",+ "previewError": "无法确认关联资源——它们仍会被永久删除。",+ "reclaimIntro": "以下关联资源会被一并永久删除:",+ "reclaimTasks": "{{n}} 个定时任务",+ "reclaimWatches": "{{n}} 个 Watch",+ "reclaimRuns": "{{n}} 个进行中的任务",+ "reclaimQueued": "{{n}} 条排队中的消息",+ "noReclaim": "此会话没有关联的定时任务或 Watch。",+ "confirm": "永久归档"+ },"projectsEmpty": "还没有项目 — 添加一个就能开始会话。","projectsLoading": "加载项目中…","projectsLoadError": "项目加载失败。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 630a329f9..fe799e21a 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3711,9 +3711,48 @@ def sessions_update(session_id: str):return jsonify(session)[email protected]("/api/sessions/<session_id>/archive-preview", methods=["GET"])+def sessions_archive_preview(session_id: str):+ """Counts of resources archiving this session will permanently reclaim+ (bound tasks/watches + active runs) — powers the irreversible-confirm dialog."""+ from core.services import sessions as workbench_sessions_service++ engine = _projects_engine()+ try:+ with engine.connect() as conn:+ workbench_sessions_service.get_session(conn, session_id) # 404 if missing+ counts = workbench_sessions_service.count_bound_resources(conn, session_id)+ except LookupError as err:+ return jsonify({"error": str(err)}), 404+ return jsonify(counts)+++async def _archive_cancel_turn(session_id: str) -> None:+ """Best-effort, background cancel of an in-flight turn for a just-archived+ session — kept off the archive request path so a slow/refused backend+ interrupt never delays the response or broadcast."""+ from vibe import internal_client++ try:+ await internal_client.cancel_dispatch(session_id)+ except internal_client.InternalServerUnavailable:+ pass+ except Exception:+ logger.debug("archive: cancel in-flight turn failed for %s", session_id, exc_info=True)++@app.route("/api/sessions/<session_id>", methods=["DELETE"])-def sessions_archive(session_id: str):+async def sessions_archive(session_id: str):+ """Permanently archive a session and reclaim its bound resources.++ The DB-level teardown (status, tasks/watches, runs, Show Page) is atomic in+ ``archive_session``. Cancelling an in-flight chat turn lives in the controller+ process, so we fire it best-effort in the BACKGROUND after the commit — the+ session is already archived + guarded, so a turn that slips through just+ writes into hidden history rather than re-surfacing the session.+ """from core.services import sessions as workbench_sessions_service+ from vibe.sse_broker import brokerengine = _projects_engine()try:@@ -3721,6 +3760,20 @@ def sessions_archive(session_id: str):session = workbench_sessions_service.archive_session(conn, session_id)except LookupError as err:return jsonify({"error": str(err)}), 404++ # Broadcast + return immediately — the archive is already committed. Other+ # mounted clients (sidebars, tabs) drop the row live and leave the chat if+ # they're viewing it (mirrors the rename 'updated' event).+ broker.publish(+ "session.activity",+ {"session_id": session_id, "scope_id": session.get("scope_id"), "event": "archived"},+ )++ # Fire-and-forget the in-flight-turn cancel: the cancel client waits up to 30s+ # for the backend interrupt, so awaiting it here would hang the confirm dialog+ # and delay the broadcast for a teardown that has already committed.+ asyncio.get_running_loop().create_task(_archive_cancel_turn(session_id))+return jsonify(session)@@ -4060,6 +4113,11 @@ async def sessions_messages_create(session_id: str):try:with engine.connect() as conn:session = workbench_sessions_service.get_session(conn, session_id)+ # Archived sessions are terminal + inert: refuse to start a turn on one+ # even via a stale/direct request (the workbench hides them from the+ # list, so this only fires on a leftover tab or a hand-crafted call).+ if session.get("status") == "archived":+ return jsonify({"error": "session is archived", "code": "session_archived"}), 409# Idempotency: a stale or duplicate quick-reply submit (a second tab, or# one that missed the message.new event) must not start a second turn# for an already-answered group. The answer lives on the agent message.@@ -4090,14 +4148,20 @@ async def sessions_messages_create(session_id: str):conn, session_id=session_id, attachments=raw_attachments)- def _persist_user_row() -> dict:+ def _persist_user_row() -> dict | None:"""Reserve the user's row as ``pending`` (hidden from transcript/queue/inbox) + clear any saved draft, WITHOUT publishing. This locks the row's``(created_at, id)`` BEFORE the turn dispatches (so a fast reply can'tsort ahead of its prompt) yet keeps it invisible during the dispatchwindow, so another tab can't briefly see it as a sent prompt (Codex P2).- The caller promotes it (→ user / queued) once the outcome is known."""+ The caller promotes it (→ user / queued) once the outcome is known.+ Returns ``None`` if the session was archived in the meantime."""with engine.begin() as conn:+ # Re-check archive ATOMICALLY with the reservation: a concurrent archive+ # may have committed since the pre-flight check above, and the session+ # must stay terminal — no new row, no turn.+ if workbench_sessions_service.is_session_archived(conn, session_id):+ return Nonerow = messages_service.append(conn,scope_id=session["scope_id"],@@ -4155,6 +4219,9 @@ async def sessions_messages_create(session_id: str):# Reserve the row FIRST (pending), then decide by the dispatch outcome.message = _persist_user_row()+ if message is None:+ # Archived between the pre-flight check and the reservation — stay terminal.+ return jsonify({"error": "session is archived", "code": "session_archived"}), 409# No text AND no attachments: nothing for the agent to act on, so just# promote + publish the row, no turn. Attachments WITHOUT text still run a# turn (the agent reads the files), so they aren't caught here.@@ -4365,6 +4432,11 @@ def sessions_draft_set(session_id: str):try:with engine.begin() as conn:session = workbench_sessions_service.get_session(conn, session_id)+ # Archive is terminal: drop a late/debounced draft save (e.g. the+ # composer flushing as it unmounts right after archive) so it can't+ # recreate a draft on a session whose drafts were just reclaimed.+ if session.get("status") == "archived":+ return jsonify({"ok": True})messages_service.set_draft(conn, scope_id=session["scope_id"], session_id=session_id, text=text if isinstance(text, str) else None)