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
chore(org): sync master and enforce conservative remote boundary
Max06cc07e75596
diff --cc docs/CLI.mdindex eef511f52,ae6413a64..15e9f2925--- a/docs/CLI.md+++ b/docs/CLI.md@@@ -173,12 -148,6 +173,12 @@@ Start the guided Avibe Cloud remote-accvibe remote```+In the conservative Organization release, the remote Workbench remains+available for Organization management and authorized Project, Session, message,- and history reads. Agent turns, Harness definition changes and autonomous++and history reads. Agent turns and runtime controls, Harness definition changes and autonomous+execution, terminal access, and file operations remain trusted-local only; open+Avibe on the machine to perform those actions.+**Flow:**- The CLI explains what remote access does before asking for anything.- Open `https://avibe.bot`, sign up or log in, create a new remote-access bot, claim your personal domain, and copy the one-time pairing key.diff --cc docs/CLI_ZH.mdindex 45a8df55a,799f0a0e1..5032afea7--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@@ -154,10 -132,6 +154,10 @@@ vibe doctor repair tmux --yevibe remote```+在 Organization 的保守发布版本中,远程工作台仍可用于 Organization 管理,以及按权限- 查看 Project、Session、消息和历史记录。Agent 对话、Harness 定义修改与自主执行、++查看 Project、Session、消息和历史记录。Agent 对话与运行控制、Harness 定义修改与自主执行、+终端和文件操作仅允许可信本机调用;如需执行这些操作,请在运行 Avibe 的机器上打开。+**流程:**- CLI 会先解释远程访问的作用,不会一上来就要求输入配对码。- 打开 `https://avibe.bot`,注册或登录,创建新的 remote-access bot,领取自己的个人域名,然后复制一次性 pairing key。diff --cc tests/test_terminal_backend.pyindex f5bfaf9d1,330ec6de6..1276cd659--- a/tests/test_terminal_backend.py+++ b/tests/test_terminal_backend.py@@@ -1428,39 -1428,6 +1428,36 @@@ def test_terminal_websocket_unsupportedassert websocket.calls == [("accept", None), ("close", 1008)]- def test_terminal_websocket_closes_at_authorization_refresh_deadline(monkeypatch):++def test_remote_terminal_websocket_is_rejected_before_authorization_refresh(monkeypatch):+ from vibe import remote_access++ class BlockingTerminalService:+ def start_reaper(self) -> None:+ pass++ async def handle_websocket(self, websocket, session_id, *, initial_cwd=None):+ await asyncio.Event().wait()++ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)+ monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda websocket: True)+ monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)+ monkeypatch.setattr(+ ui_server,+ "_remote_access_websocket_session_claims",+ lambda websocket, config: {"sub": "remote-owner", "claims_issued_at": 1},+ )+ monkeypatch.setattr(remote_access, "session_authorization_refresh_deadline", lambda payload: 0)+ monkeypatch.setattr(ui_server, "get_terminal_service", lambda: BlockingTerminalService())+ websocket = _RecordingWebSocket()+ websocket.client = None+ websocket.query_params = {}++ asyncio.run(ui_server.terminal_websocket(websocket, "test"))+- assert websocket.calls == [- ("accept", None),- ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),- ]++ assert websocket.calls == [("close", 1008)]++def test_terminal_websocket_rejects_forwarded_request(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")monkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@@ -1644,7 -1611,7 +1641,7 @@@ def test_terminal_delete_rejects_forwarassert terminated == []--def test_terminal_delete_scopes_remote_subject_and_rejects_cross_subject(monkeypatch, tmp_path):++def test_remote_terminal_delete_is_rejected_before_service_access(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")monkeypatch.setenv("AVIBE_HOME", str(tmp_path))monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)@@@ -1679,13 -1646,13 +1676,11 @@@environ_base={"REMOTE_ADDR": "203.0.113.10"},)-- assert response.status_code == 404-- assert malicious_response.status_code == 404-- assert terminated == [-- ui_server._terminal_effective_session_id("shared-session", "user-2"),-- ui_server._terminal_effective_session_id(user_one_effective, "user-2"),-- ]-- assert user_one_effective not in terminated++ assert response.status_code == 403++ assert response.get_json()["code"] == "remote_execution_disabled"++ assert malicious_response.status_code == 403++ assert malicious_response.get_json()["code"] == "remote_execution_disabled"++ assert terminated == []def test_terminal_service_ignores_invalid_limit_env(monkeypatch):diff --cc tests/test_ui_project_access.pyindex 0c15c2fb6,000000000..dc2c61640mode 100644,000000..100644--- a/tests/test_ui_project_access.py+++ b/tests/test_ui_project_access.py@@@ -1,673 -1,0 +1,628 @@@+from __future__ import annotations++import json+from types import SimpleNamespace+- from sqlalchemy import select-+from config.v2_config import (+ AgentsConfig,+ PlatformsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ UiConfig,+ V2Config,+)- from core.vibe_agents import VibeAgentStore+from storage import (+ media_service,+ message_deliveries,+ messages_service,+ project_access_service,+ projects_service,- resource_access_service,+)+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state- from storage.models import media_object_references, media_objects, messages, scopes- from storage.workbench_sessions_service import create_session, update_session++from storage.models import media_object_references, media_objects, scopes++from storage.workbench_sessions_service import create_session+from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie- from tests.test_ui_session_stream import _settle_reserved_delivery+from vibe import api, internal_client, remote_access, ui_server+from vibe.authorization import AuthorizationContext+from vibe.sse_broker import broker+from vibe.ui_server import app+++REMOTE_ORIGIN = "https://alex.avibe.bot"+REMOTE_PEER = {"REMOTE_ADDR": "203.0.113.10"}+++def _save_config() -> V2Config:+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.public_url = REMOTE_ORIGIN+ cloud.client_id = "vr_client_123"+ cloud.instance_id = "inst_123"+ cloud.session_secret = "session-secret"+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"+ cloud.redirect_uri = f"{REMOTE_ORIGIN}/auth/callback"+ config.save()+ return config+++def _intent(project_id: str, email: str, role: str = "editor") -> dict:+ return {+ "project_id": project_id,+ "revision": 1,+ "mode": "restricted",+ "bindings": [+ {+ "principal_kind": "email",+ "principal_value": email,+ "access_role": role,+ }+ ],+ }+++def _group_intent(project_id: str, group_id: str, role: str = "editor") -> dict:+ return {+ "project_id": project_id,+ "revision": 1,+ "mode": "restricted",+ "bindings": [+ {+ "principal_kind": "organization_group",+ "principal_value": group_id,+ "access_role": role,+ }+ ],+ }+++def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:+ config = _save_config()+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ project_a_dir = tmp_path / "project-a"+ project_b_dir = tmp_path / "project-b"+ project_a_dir.mkdir()+ project_b_dir.mkdir()+ shared_media = tmp_path / "shared.txt"+ shared_media.write_text("shared media", encoding="utf-8")+ with engine.begin() as conn:+ project_a = projects_service.create_project(conn, str(project_a_dir), display_name="A")+ project_b = projects_service.create_project(conn, str(project_b_dir), display_name="B")+ session_a = create_session(conn, scope_id=project_a["scope_id"], agent_backend="codex")+ session_b = create_session(conn, scope_id=project_b["scope_id"], agent_backend="codex")+ unscoped = create_session(conn, scope_id=None, agent_backend="codex")+ for project, session in ((project_a, session_a), (project_b, session_b)):+ messages_service.append(+ conn,+ scope_id=project["scope_id"],+ session_id=session["id"],+ platform="avibe",+ author="agent",+ message_type="result",+ text="shared needle",+ )+ media_a_token = media_service.register(+ conn,+ scope_id=project_a["scope_id"],+ session_id=session_a["id"],+ kind="file",+ source="agent_reply",+ local_path=str(shared_media.resolve()),+ )+ media_b_token = media_service.register(+ conn,+ scope_id=project_b["scope_id"],+ session_id=session_b["id"],+ kind="file",+ source="agent_reply",+ local_path=str(shared_media.resolve()),+ )+ assert media_a_token != media_b_token+ project_access_service.apply_project_access_intent(+ conn,+ _intent(project_a["id"], "[email protected]"),+ )+ project_access_service.apply_project_access_intent(+ conn,+ _group_intent(project_b["id"], "grp_beta"),+ )+ engine.dispose()+ return config, {+ "project_a": project_a["id"],+ "project_b": project_b["id"],+ "session_a": session_a["id"],+ "session_b": session_b["id"],+ "unscoped": unscoped["id"],+ "media_a": media_a_token,+ "media_b": media_b_token,+ }+++def _remote_client(config: V2Config, *, role: str, email: str):+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, email, f"user-{role}-{email}", role=role),+ domain="alex.avibe.bot",+ )+ return client+++def _get(client, path: str):+ return client.get(path, base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER)+++def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ conn.execute(+ scopes.update()+ .where(scopes.c.native_id == ids["project_a"])+ .values(metadata_json=json.dumps({"host_path_hint": "/private/host"}))+ )+ client = _remote_client(config, role="editor", email="[email protected]")+ monkeypatch.setattr(+ api,+ "list_show_pages",+ lambda: {+ "ok": True,+ "count": 3,+ "pages": [+ {"session_id": ids["session_a"]},+ {"session_id": ids["session_b"]},+ {"session_id": ids["unscoped"]},+ ],+ },+ )++ project_rows = _get(client, "/api/projects").get_json()["projects"]+ assert [row["id"] for row in project_rows] == [ids["project_a"]]+ assert project_rows[0]["folder_path"] == ""+ assert project_rows[0]["metadata"] == {}+ assert project_rows[0]["capabilities"] == {"can_chat": True}+ sessions = _get(client, "/api/sessions?status=active").get_json()["sessions"]+ assert {row["id"] for row in sessions} == {ids["session_a"]}+ assert sessions[0]["workdir"] is None+ assert sessions[0]["metadata"] == {}+ assert _get(client, f"/api/projects/{ids['project_a']}").status_code == 200+ assert _get(client, f"/api/projects/{ids['project_b']}").status_code == 404+ session = _get(client, f"/api/sessions/{ids['session_a']}").get_json()+ assert session["workdir"] is None+ assert session["metadata"] == {}+ assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 200+ assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 404+ assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 404++ search = _get(client, "/api/search/messages?q=needle").get_json()+ assert [row["session_id"] for row in search["sessions"]] == [ids["session_a"]]+ inbox = _get(client, "/api/inbox").get_json()+ assert [row["session_id"] for row in inbox["sessions"]] == [ids["session_a"]]+ assert set(inbox["unread_by_session"]) == {ids["session_a"]}+ media_response = _get(client, f"/api/media/{ids['media_a']}")+ assert media_response.status_code == 200+ assert media_response.headers["Cache-Control"] == "private, no-store"+ assert _get(client, f"/api/media/{ids['media_b']}").status_code == 404+ show_pages = _get(client, "/api/show-pages").get_json()+ assert show_pages["pages"] == [{"session_id": ids["session_a"]}]+ assert show_pages["count"] == 1++ published = []+ monkeypatch.setattr(broker, "publish", lambda event_type, data: published.append((event_type, data)))+ headers = csrf_headers(client, REMOTE_ORIGIN)+ mark_read = client.post(+ f"/api/sessions/{ids['session_a']}/mark-read",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=headers,+ json={},+ )+ assert mark_read.status_code == 200+ assert mark_read.get_json()["unread_counts"] == {}+ assert mark_read.get_json()["unread_by_session"] == {}+ event_type, event_data = published[-1]+ assert event_type == "inbox.unread.changed"+ raw_payload = json.dumps({"type": event_type, "data": event_data})+ alice_context = AuthorizationContext(+ instance_role="editor",+ email="[email protected]",+ is_remote=True,+ )+ alice_payload = json.loads(+ ui_server._workbench_event_payload_for_context(+ alice_context,+ event_type,+ raw_payload,+ )+ )+ assert alice_payload["data"]["unread_counts"] == {}+ assert alice_payload["data"]["unread_by_session"] == {}++ owner_payload = json.loads(+ ui_server._workbench_event_payload_for_context(None, event_type, raw_payload)+ )+ assert owner_payload["data"]["unread_counts"] == {+ project_access_service.project_scope_id(ids["project_b"]): 1,+ }+ assert owner_payload["data"]["unread_by_session"] == {ids["session_b"]: 1}+ filtered_owner_payload = json.loads(+ ui_server._workbench_event_payload_for_context(+ alice_context,+ event_type,+ json.dumps(owner_payload),+ )+ )+ assert filtered_owner_payload["data"]["unread_counts"] == {}+ assert filtered_owner_payload["data"]["unread_by_session"] == {}++ allowed_action = client.post(+ f"/api/sessions/{ids['session_a']}/attachments",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=headers,+ json={},+ )+ hidden_action = client.post(+ f"/api/sessions/{ids['session_b']}/attachments",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=headers,+ json={},+ )- assert allowed_action.status_code == 400- assert hidden_action.status_code == 404++ assert allowed_action.status_code == 403++ assert allowed_action.get_json()["code"] == "remote_execution_disabled"++ assert hidden_action.status_code == 403++ assert hidden_action.get_json()["code"] == "remote_execution_disabled"+++def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ project_access_service.apply_project_access_intent(+ conn,+ {+ **_intent(ids["project_a"], "[email protected]", role="viewer"),+ "revision": 2,+ },+ )+ scope_id = project_access_service.project_scope_id(ids["project_a"])+ message_deliveries.enqueue_queued(+ conn,+ scope_id=scope_id,+ session_id=ids["session_a"],+ text="editor-only queued prompt",+ )+ message_deliveries.set_draft(+ conn,+ ids["session_a"],+ "editor-only draft",+ )++ monkeypatch.setattr(+ api,+ "get_vibe_agents",+ lambda **kwargs: {+ "agents": [{"name": "editor-agent", "backend": "codex", "enabled": True}],+ "default_agent_name": "editor-agent",+ },+ )+ client = _remote_client(config, role="editor", email="[email protected]")++ viewer_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()+ assert viewer_project["capabilities"] == {"can_chat": False}++ viewer_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")++ assert viewer_bootstrap.status_code == 200+ viewer_payload = viewer_bootstrap.get_json()+ assert viewer_payload["capabilities"] == {"can_chat": False}+ assert viewer_payload["agents"] == []+ assert viewer_payload["default_agent_name"] is None+ assert viewer_payload["queued"] == []+ assert viewer_payload["draft"] == {"text": ""}+ assert [message["text"] for message in viewer_payload["messages"]] == ["shared needle"]+ assert viewer_payload["session"]["workdir"] is None+ assert viewer_payload["session"]["metadata"] == {}++ with engine.begin() as conn:+ project_access_service.apply_project_access_intent(+ conn,+ {+ **_intent(ids["project_a"], "[email protected]"),+ "revision": 3,+ },+ )++ editor_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")++ assert editor_bootstrap.status_code == 200+ editor_payload = editor_bootstrap.get_json()+ assert editor_payload["capabilities"] == {"can_chat": True}+ assert editor_payload["agents"][0]["name"] == "editor-agent"+ assert editor_payload["default_agent_name"] == "editor-agent"+ assert editor_payload["queued"][0]["text"] == "editor-only queued prompt"+ assert editor_payload["draft"] == {"text": "editor-only draft"}+ editor_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()+ assert editor_project["capabilities"] == {"can_chat": True}+++def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)+ published = []+ monkeypatch.setattr(+ broker,+ "publish",+ lambda event_type, data: published.append((event_type, data)),+ )+ owner = _remote_client(config, role="owner", email="[email protected]")+ archive = owner.delete(+ f"/api/projects/{ids['project_a']}",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=csrf_headers(owner, REMOTE_ORIGIN),+ )+ assert archive.status_code == 200+ assert (+ "authorization.changed",+ {"project_ids": [ids["project_a"]]},+ ) in published++ monkeypatch.setattr(+ api,+ "list_show_pages",+ lambda: {+ "ok": True,+ "count": 1,+ "pages": [{"session_id": ids["session_a"]}],+ },+ )+ client = _remote_client(config, role="editor", email="[email protected]")++ assert _get(client, "/api/projects").get_json()["projects"] == []+ assert _get(client, f"/api/projects/{ids['project_a']}").status_code == 404+ assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 404+ assert _get(client, f"/api/media/{ids['media_a']}").status_code == 404+ assert _get(client, "/api/show-pages").get_json()["pages"] == []++ response = client.post(+ f"/api/sessions/{ids['session_a']}/attachments",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=csrf_headers(client, REMOTE_ORIGIN),+ json={},+ )- assert response.status_code == 404++ assert response.status_code == 403++ assert response.get_json()["code"] == "remote_execution_disabled"+++def test_legacy_media_token_uses_all_migrated_session_references(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)+ engine = create_sqlite_engine()+ token = "legacy-shared-token"+ with engine.begin() as conn:+ original = media_service.get_by_token(conn, ids["media_a"])+ assert original is not None+ conn.execute(media_objects.insert().values(**{**original, "token": token}))+ conn.execute(+ media_object_references.insert(),+ [+ {+ "token": token,+ "session_id": ids["session_a"],+ "created_at": original["created_at"],+ },+ {+ "token": token,+ "session_id": ids["session_b"],+ "created_at": original["created_at"],+ },+ ],+ )++ alice = _remote_client(config, role="editor", email="[email protected]")+ beta = _remote_client(config, role="editor", email="[email protected]")+ beta.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(+ config,+ "[email protected]",+ "user-beta",+ role="editor",+ organization_id="org_beta",+ organization_member_id="member_beta",+ organization_role="member",+ group_ids=["grp_beta"],+ ),+ domain="alex.avibe.bot",+ )++ assert _get(alice, f"/api/media/{token}").status_code == 200+ assert _get(beta, f"/api/media/{token}").status_code == 200++- def test_remote_message_persists_trusted_web_push_authorization_context(++def test_remote_message_is_blocked_before_persistence_or_dispatch(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)+ engine = create_sqlite_engine()- agent_store = VibeAgentStore()- try:- agent = agent_store.create(name="project-access-agent", backend="codex")- finally:- agent_store.close()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="agent",- resource_id=agent.id,- organization_id=None,- owner_user_id="[email protected]",- access_level="private",- )- update_session(- conn,- ids["session_a"],- agent_id=agent.id,- agent_name=agent.name,- agent_backend=agent.backend,- )+ client = _remote_client(config, role="editor", email="[email protected]")+- async def dispatch_async(payload):- settled = _settle_reserved_delivery(payload, state="accepted")- return {- "status_code": 202,- "body": {- "ok": True,- "delivery_state": settled["state"],- "message_id": settled["message_id"],- },++ with engine.connect() as conn:++ before_ids = {++ row["id"]++ for row in messages_service.list_session_messages(++ conn,++ session_id=ids["session_a"],++ limit=500,++ )["messages"]+ }+++ async def dispatch_async(payload):++ raise AssertionError("remote message reached the local controller")+++ monkeypatch.setattr(internal_client, "dispatch_async", dispatch_async)+ response = client.post(+ f"/api/sessions/{ids['session_a']}/messages",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=csrf_headers(client, REMOTE_ORIGIN),+ json={+ "text": "Run it",+ "metadata": {+ "_web_push_authorization_contexts": [+ {"user_key": "remote:spoofed", "email": "[email protected]"}+ ],+ "resource_user_context": {+ "sub": "spoofed",+ "vibe_instance_role": "owner",+ "vibe_instance_access_source": "owner",+ },+ },+ },+ )+- assert response.status_code == 201- payload = response.get_json()- assert not any(key.startswith("_web_push_") for key in payload["metadata"])- assert "resource_user_context" not in payload["metadata"]-++ assert response.status_code == 403++ assert response.get_json()["code"] == "remote_execution_disabled"+ with engine.connect() as conn:- metadata_json = conn.execute(- select(messages.c.metadata_json).where(messages.c.id == payload["id"])- ).scalar_one()- persisted_metadata = json.loads(metadata_json)- assert persisted_metadata["_web_push_user_key"].startswith("remote:")- records = persisted_metadata["_web_push_authorization_contexts"]- claims_issued_at = records[0].pop("claims_issued_at")- assert isinstance(claims_issued_at, int) and claims_issued_at > 0- assert records == [- {- "email": "[email protected]",- "sub": persisted_metadata["_web_push_user_key"].removeprefix("remote:"),- "user_key": persisted_metadata["_web_push_user_key"],- "vibe_group_ids": [],- "vibe_instance_access_source": "owner",- "vibe_instance_id": "inst_123",- "vibe_instance_role": "editor",++ after_ids = {++ row["id"]++ for row in messages_service.list_session_messages(++ conn,++ session_id=ids["session_a"],++ limit=500,++ )["messages"]+ }- ]- resource_context = persisted_metadata["resource_user_context"]- assert resource_context["sub"] == persisted_metadata["_web_push_user_key"].removeprefix(- "remote:"- )- assert resource_context["vibe_instance_role"] == "editor"- assert resource_context["vibe_instance_access_source"] == "owner"- assert resource_context["authorization_expires_at"] > resource_context["claims_issued_at"]- transcript = _get(client, f"/api/sessions/{ids['session_a']}/messages").get_json()- stored_payload = next(row for row in transcript["messages"] if row["id"] == payload["id"])- assert not any(key.startswith("_web_push_") for key in stored_payload["metadata"])- assert "resource_user_context" not in stored_payload["metadata"]++ assert after_ids == before_ids+++def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)++ viewer = _remote_client(config, role="viewer", email="[email protected]")+ assert _get(viewer, f"/api/sessions/{ids['session_a']}").status_code == 200+ assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 404+ headers = csrf_headers(viewer, REMOTE_ORIGIN)+ assert viewer.post(+ "/api/sessions",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers=headers,+ json={"project_id": ids["project_a"]},+ ).status_code == 403++ no_match = _remote_client(config, role="editor", email="[email protected]")+ assert _get(no_match, "/api/projects").get_json()["projects"] == []+ assert _get(no_match, "/api/sessions").get_json()["sessions"] == []+ assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 404+ no_match_headers = csrf_headers(no_match, REMOTE_ORIGIN)+ denied = no_match.post(+ "/api/sessions",+ base_url=REMOTE_ORIGIN,+ environ_base=REMOTE_PEER,+ headers={**no_match_headers, "Accept-Language": "zh-CN,zh;q=0.9"},+ json={"project_id": ids["project_a"]},+ )+ assert denied.status_code == 403+ assert denied.get_json() == {+ "ok": False,+ "error": {+ "code": "project_access_denied",+ "message": "你没有权限在这个项目中创建会话。",+ },+ "code": "project_access_denied",+ "message": "你没有权限在这个项目中创建会话。",+ }++ organization_member = app.test_client()+ organization_member.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(+ config,+ "[email protected]",+ "user-org-member",+ role="editor",+ access_source="organization_group",+ organization_id="org_beta",+ organization_member_id="member_beta",+ organization_role="member",+ group_ids=["grp_beta"],+ ),+ domain="alex.avibe.bot",+ )+ assert [+ row["id"] for row in _get(organization_member, "/api/projects").get_json()["projects"]+ ] == [ids["project_b"]]+ assert _get(organization_member, f"/api/sessions/{ids['session_b']}").status_code == 200+ assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 404+ assert _get(organization_member, f"/api/media/{ids['media_b']}").status_code == 200+ assert _get(organization_member, f"/api/media/{ids['media_a']}").status_code == 404++ owner = _remote_client(config, role="owner", email="[email protected]")+ assert {row["id"] for row in _get(owner, "/api/projects").get_json()["projects"]} == {+ ids["project_a"],+ ids["project_b"],+ }+ assert _get(owner, f"/api/sessions/{ids['unscoped']}").status_code == 200++ local = app.test_client()+ local_projects = local.get("/api/projects", base_url="http://localhost").get_json()["projects"]+ assert {row["id"] for row in local_projects} == {ids["project_a"], ids["project_b"]}+ assert local.get(f"/api/sessions/{ids['unscoped']}", base_url="http://localhost").status_code == 200+++def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config, ids = _setup_state(tmp_path)+ context = AuthorizationContext(+ instance_role="editor",+ email="[email protected]",+ is_remote=True,+ )+ visible_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_a"]}})+ hidden_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_b"]}})+ assert ui_server._workbench_event_visible_to_context(context, "session.status", visible_payload) is True+ assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is False+ assert ui_server._workbench_event_visible_to_context(+ context,+ "authorization.changed",+ json.dumps({"type": "authorization.changed", "data": {"project_ids": []}}),+ ) is True++ cookie = remote_session_cookie(config, "[email protected]", "user-editor", role="editor")+ websocket = SimpleNamespace(+ client=SimpleNamespace(host="203.0.113.10"),+ headers={"host": "alex.avibe.bot"},+ cookies={remote_access.SESSION_COOKIE_NAME: cookie},+ url=SimpleNamespace(scheme="wss"),+ )+ assert ui_server._show_runtime_websocket_authorized(+ websocket,+ minimum_role="viewer",+ project_session_id=ids["session_a"],+ ) is True+ assert ui_server._show_runtime_websocket_authorized(+ websocket,+ minimum_role="viewer",+ project_session_id=ids["session_b"],+ ) is Falsediff --cc tests/test_ui_remote_access_auth.pyindex 1198abaa2,521fbed1a..6543315f5--- a/tests/test_ui_remote_access_auth.py+++ b/tests/test_ui_remote_access_auth.py@@@ -814,288 -634,6 +814,334 @@@ def test_remote_session_info_includes_a}+def test_remote_file_api_is_blocked_while_local_file_browsing_still_works(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, "[email protected]", "user-owner"),+ domain="alex.avibe.bot",+ )++ remote_response = client.get(+ "/api/files/list",+ params={"path": str(tmp_path)},+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ local_response = app.test_client().get(+ "/api/files/list",+ params={"path": str(tmp_path)},+ base_url="http://localhost",+ environ_base={"REMOTE_ADDR": "127.0.0.1"},+ )++ assert remote_response.status_code == 403+ assert remote_response.get_json()["code"] == "remote_execution_disabled"+ assert local_response.status_code == 200+ assert local_response.get_json()["path"] == str(tmp_path.resolve())+++ ("method", "path", "json_body"),+ [+ ("PATCH", "/api/harness/tasks/task-1", {"enabled": False}),+ ("DELETE", "/api/harness/tasks/task-1", None),+ ("PATCH", "/api/harness/watches/watch-1", {"enabled": False}),+ ("DELETE", "/api/harness/watches/watch-1", None),+ ],+)+def test_remote_harness_mutations_are_blocked_before_store_access(+ monkeypatch,+ tmp_path,+ method,+ path,+ json_body,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, "[email protected]", "user-owner"),+ domain="alex.avibe.bot",+ )++ response = client.request(+ method,+ path,+ json=json_body,+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )++ assert response.status_code == 403+ assert response.get_json()["code"] == "remote_execution_disabled"++++++ ("path", "json_body", "controller_method"),++ [++ ("/api/sessions/ses-local/cancel", {}, "cancel_dispatch"),++ (++ "/api/running-agents/end",++ {"backend": "codex", "base_session_id": "local-run"},++ "end_running_agent",++ ),++ ],++)++def test_remote_agent_termination_is_blocked_before_controller_access(++ monkeypatch,++ tmp_path,++ path,++ json_body,++ controller_method,++):++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ config = _save_config(tmp_path)++ client = app.test_client()++ client.set_cookie(++ remote_access.SESSION_COOKIE_NAME,++ remote_session_cookie(config, "[email protected]", "user-owner"),++ domain="alex.avibe.bot",++ )++++ async def unexpected_controller_call(*args, **kwargs):++ raise AssertionError("remote termination reached the local controller")++++ monkeypatch.setattr(++ f"vibe.internal_client.{controller_method}",++ unexpected_controller_call,++ )++ response = client.post(++ path,++ json=json_body,++ headers=csrf_headers(client, "https://alex.avibe.bot"),++ base_url="https://alex.avibe.bot",++ environ_base=_remote_peer(),++ )++++ assert response.status_code == 403++ assert response.get_json()["code"] == "remote_execution_disabled"+++def test_remote_show_dispatch_is_rejected_before_event_reservation(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, "[email protected]", "user-owner"),+ domain="alex.avibe.bot",+ )+ monkeypatch.setattr(ui_server, "_is_cli_show_event_request", lambda: True)++ def unexpected_store():+ raise AssertionError("remote Show dispatch must not reserve an event")++ monkeypatch.setattr(ui_server, "_show_session_event_store", unexpected_store)+ response = client.post(+ "/api/show/sessions/ses-remote/events",+ json={+ "type": "human.intent.submitted",+ "actor": "human",+ "payload": {"intent": "choose", "dispatch": True},+ },+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )++ assert response.status_code == 403+ assert response.get_json()["code"] == "remote_execution_disabled"+++def test_remote_owner_can_still_read_authorized_session_history(+ monkeypatch,+ tmp_path,+):+ from storage import messages_service, workbench_sessions_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_remote_history",+ now="2026-08-04T00:00:00Z",+ )+ session = workbench_sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="worker",+ )+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session["id"],+ platform="avibe",+ author="user",+ message_type="user",+ text="readable history",+ )++ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, "[email protected]", "user-owner"),+ domain="alex.avibe.bot",+ )+ response = client.get(+ f"/api/sessions/{session['id']}/messages",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )++ assert response.status_code == 200+ assert [row["text"] for row in response.get_json()["messages"]] == [+ "readable history"+ ]+++def test_remote_viewer_can_read_but_cannot_use_management_api(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(+ config,+ "[email protected]",+ "user-viewer",+ role="viewer",+ access_source="owner",+ ),+ domain="alex.avibe.bot",+ )++ read_response = client.get("/api/version", base_url="https://alex.avibe.bot")+ manage_response = client.get("/api/remote-access/status", base_url="https://alex.avibe.bot")+ session_response = client.get("/api/session", base_url="https://alex.avibe.bot")++ assert read_response.status_code == 200+ assert manage_response.status_code == 403+ assert manage_response.get_json()["error"] == "instance_access_forbidden"+ session_payload = session_response.get_json()+ assert session_payload["instance_role"] == "viewer"+ assert session_payload["capabilities"]["can_read_instance"] is True+ assert session_payload["capabilities"]["can_chat"] is False+ assert session_payload["capabilities"]["is_instance_owner"] is False+++ (+ "role",+ "agents_status",+ "skills_status",+ "vault_status",+ "show_pages_status",+ "conversation_status",+ "project_status",+ ),+ [+ ("viewer", 403, 403, 403, 200, 403, 403),+ ("editor", 200, 200, 200, 200, 400, 403),+ ("owner", 200, 200, 200, 200, 400, 400),+ ],+)+def test_remote_instance_role_route_matrix(+ monkeypatch,+ tmp_path,+ role,+ agents_status,+ skills_status,+ vault_status,+ show_pages_status,+ conversation_status,+ project_status,+):+ from storage.importer import ensure_sqlite_state++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ ensure_sqlite_state()+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(config, f"{role}@example.com", f"user-{role}", role=role),+ domain="alex.avibe.bot",+ )+ headers = csrf_headers(client, "https://alex.avibe.bot")++ read_response = client.get("/api/projects", base_url="https://alex.avibe.bot")+ agents_response = client.get("/api/agents", base_url="https://alex.avibe.bot")+ skills_response = client.get("/api/skills", base_url="https://alex.avibe.bot")+ vault_response = client.get("/api/vault/secrets", base_url="https://alex.avibe.bot")+ show_pages_response = client.get("/api/show-pages", base_url="https://alex.avibe.bot")+ config_response = client.get("/api/config", base_url="https://alex.avibe.bot")+ prefs_read_response = client.get("/api/workbench/prefs", base_url="https://alex.avibe.bot")+ prefs_write_response = client.put(+ "/api/workbench/prefs",+ base_url="https://alex.avibe.bot",+ headers=headers,+ json={"background_work_banner_enabled": False},+ )+ conversation_response = client.post(+ "/api/sessions",+ base_url="https://alex.avibe.bot",+ headers=headers,+ json={},+ )+ project_response = client.post(+ "/api/projects",+ base_url="https://alex.avibe.bot",+ headers=headers,+ json={},+ )++ assert read_response.status_code == 200+ assert agents_response.status_code == agents_status+ assert skills_response.status_code == skills_status+ assert vault_response.status_code == vault_status+ assert show_pages_response.status_code == show_pages_status+ assert config_response.status_code == 200+ assert prefs_read_response.status_code == 200+ assert prefs_read_response.get_json()["background_work_banner_enabled"] is True+ assert prefs_write_response.status_code == (200 if role == "owner" else 403)+ if role == "owner":+ assert "runtime" in config_response.get_json()+ else:+ assert set(config_response.get_json()) == {+ "capabilities",+ "language",+ "mode",+ "setup_state",+ "ui",+ "version",+ }+ assert conversation_response.status_code == conversation_status+ assert project_response.status_code == project_status+ if role == "viewer":+ assert conversation_response.get_json()["error"] == "instance_access_forbidden"+ if role != "owner":+ assert project_response.get_json()["error"] == "instance_access_forbidden"++def _forged_session_cookie(config: V2Config, exp: int, *, email: str = "[email protected]", subject: str = "user-1") -> str:import jsonimport urllib.parsediff --cc ui/src/components/workbench/ChatPage.tsxindex 167239b62,510c21ab6..1972f6b5d--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@@ -1890,6 -1899,63 +1920,64 @@@ export const ChatPage: React.FC = () =[api, session, t],);+ // Session-level actions (pin / rename / fork / hide / archive) — the same model+ // the sidebar rows and the mobile projects rows render, so the chat no longer+ // sends the user back to the tree to act on the session they're reading. A+ // read-only session yields no actions and an inert requestArchive: every one of+ // them is refused server-side (409 archived / 403 reserved_session), so the+ // header withdraws the ⋯ rather than offering guaranteed failures.+ const titleFieldRef = useRef<TitleFieldHandle | null>(null);+ const {+ actions: sessionActions,+ archiveDialog: sessionArchiveDialog,+ requestArchive,+ canArchive,+ } = useSessionActions({- session: readOnly ? null : session,++ session,++ writable,+ // Rename focuses the header's existing click-to-edit title instead of adding+ // a second editor for the same field.+ onRenameStart: () => titleFieldRef.current?.startEditing(),+ onOpenSession: (id) => navigate(`/chat/${encodeURIComponent(id)}`),+ onArchived: () => navigate('/inbox'),+ // The provider cache feeds the sidebar, not this page's own session copy. The+ // write resolves after an await, so only patch if we're still on that session.+ onSessionPatched: (changes, sessionId) =>+ setSession((prev) => (prev && prev.id === sessionId ? { ...prev, ...changes } : prev)),+ archiveHint: ARCHIVE_SHORTCUT_LABEL,+ });++ // ⌘⇧D / Ctrl+Shift+D archives the session being read. It OPENS THE CONFIRM+ // DIALOG — a destructive action never fires straight off a keystroke — and like+ // the shell's ⌘K it wins from inside the composer, because it's a command, not+ // text.+ //+ // Bound only while there IS something to archive: preventDefault on a read-only+ // or still-loading chat would swallow the browser's own ⌘⇧D (bookmark all tabs)+ // and do nothing in return. And "ChatPage is mounted" is not "chat owns the+ // keyboard" — it stays mounted under app windows and dialogs — so a keystroke+ // belonging to a foreground surface is left to that surface (Codex).+ useEffect(() => {+ if (!canArchive) return;+ const onKeyDown = (e: KeyboardEvent) => {+ if (!isArchiveSessionKeydown(e, e.target as Element | null)) return;+ e.preventDefault();+ requestArchive();+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [canArchive, requestArchive]);++ // A keydown inside the Show Page iframe never reaches this window, so the same+ // chord is bound to the frame's own document while it is mounted — otherwise the+ // shortcut silently dies as soon as the user clicks into the page they asked for.+ useEffect(() => {+ if (!canArchive) return;+ const frame = showPageFrameRef.current;+ if (!frame) return;+ return bindFrameChord(frame, (event) => isArchiveSessionChord(event), requestArchive);+ }, [canArchive, requestArchive, showPageActive, showPageUrl]);+// Ordered media-proxy image URLs across the whole session — feeds the lightbox// so it pages left/right through every image, in render order (each message's// attachments first, then any inline images in its text).@@@ -2080,8 -2146,8 +2168,10 @@@annotation={annotation}onAnnotateOpenChange={setAnnotateOpen}readOnlyReason={readOnlyReason}+ writable={writable}+ canManageShowPage={canManageShowPage}+ sessionActions={sessionActions}+ titleFieldRef={titleFieldRef}/>{showPageActive && showPageUrl && (@@@ -2204,8 -2271,11 +2294,11 @@@onSearchAgents={searchAgents}onSearchSessions={searchSessions}readOnlyReason={readOnlyReason}- />+ />}</div>+ {/* Archive confirm — mounted at the chat surface (not inside the header's+ popover) so the ⌘⇧D chord can open it in Show Page mode too. */}+ {sessionArchiveDialog}</div></VaultProvisionDialogProvider></FileViewerProvider>@@@ -2646,19 -2722,27 +2745,27 @@@ interface ChatHeaderBarProps// cluster is withdrawn entirely (see showPageControlActions). The REASON, not a// boolean, because it also picks the badge: a runtime-owned row is not "Archived".readOnlyReason: SessionReadOnlyReason | null;+ writable?: boolean;+ canManageShowPage?: boolean;+ // Shared session actions (pin / rename / fork / hide / archive), rendered behind+ // the ⋯ at the far right. Empty (or absent) withdraws the trigger — which is what+ // a read-only session yields, since every one of those writes is refused.+ sessionActions?: SessionActionDescriptor[];+ // Lets the menu's Rename row focus the title field that already lives here.+ titleFieldRef?: React.Ref<TitleFieldHandle>;}// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),// which renders the header alone rather than mounting the whole page. Note the// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the// read-only rendering is reachable without an ApiProvider.- export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, canManageShowPage = true }) => {-export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, sessionActions, titleFieldRef }) => {++export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, canManageShowPage = true, sessionActions, titleFieldRef }) => {const { t } = useTranslation();- const readOnly = readOnlyReason !== null;- const showPageActions = showPageControlActions(readOnly, showPageMode);+ const readOnly = !writable;+ const sessionReadOnly = readOnlyReason !== null;+ const showPageActions = showPageControlActions(sessionReadOnly, showPageMode);+ const [actionsOpen, setActionsOpen] = useState(false);- // ``!readOnly`` twice over: useSessionActions already yields an empty list for a- // read-only session, and the withdrawal is re-stated here so this header cannot- // grow a ⋯ full of guaranteed-409 rows if a future caller passes actions anyway.- const hasSessionActions = !readOnly && (sessionActions?.length ?? 0) > 0;++ const hasSessionActions = writable && (sessionActions?.length ?? 0) > 0;const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;const sessionAgentLabel = sessionAgentDisplayName(session, agents);// Backend locks once a NATIVE conversation exists — a native can only be@@@ -2772,9 -2860,9 +2885,9 @@@the three can do anything but 409 or frame a dead page. There is noread-only page-serving path to offer instead; seeshowPageControlActions for the per-control reasoning. */}- {showPageActions.visualize && (showPageMode || canManageShowPage) && (- {(showPageActions.visualize || hasSessionActions) && (++ {((showPageActions.visualize && (showPageMode || canManageShowPage)) || hasSessionActions) && (<div className="ml-auto flex items-center gap-1.5">- {showPageActions.annotate && (+ {showPageActions.annotate && writable && (<ShowPageAnnotateControlstate={annotation.state}onEnable={annotation.enable}@@@ -2783,15 -2871,17 +2896,17 @@@onPopoverOpenChange={onAnnotateOpenChange}/>)}- <ShowPageLaunchControl- sessionId={session.id}- title={session.title}- showPageMode={showPageMode}- busy={showPageBusy}- onToggle={onToggleShowPage}- onPrepareLaunch={onPrepareShowPageLaunch}- />- {showPageActions.visualize && (++ {showPageActions.visualize && (showPageMode || canManageShowPage) && (+ <ShowPageLaunchControl+ sessionId={session.id}+ title={session.title}+ showPageMode={showPageMode}+ busy={showPageBusy}+ onToggle={onToggleShowPage}+ onPrepareLaunch={onPrepareShowPageLaunch}+ />+ )}- {showPageActions.share && (+ {showPageActions.share && canManageShowPage && (<ShowPageShareControlsessionId={session.id}onPayloadChange={onShowPageVisibilityChange}diff --cc ui/src/components/workbench/ProjectsPage.tsxindex 87e1a26ee,43332f962..0ab6730ef--- a/ui/src/components/workbench/ProjectsPage.tsx+++ b/ui/src/components/workbench/ProjectsPage.tsx@@@ -25,14 -21,9 +21,10 @@@ import clsx from 'clsx'import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';- import { SessionPinAction } from './SessionPinAction';import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';- import { useApi } from '../../context/ApiContext';import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';- import { useToast } from '../../context/ToastContext';import { formatRelativeTime } from '../../lib/relativeTime';- import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { Input } from '../ui/input';@@@ -260,23 -245,27 +254,29 @@@ const MobileSessionRow: React.FC<projectId: string;session: WorkbenchSession;unread: number;+ canChat: boolean;onOpen: () => void;-}> = ({ projectId, session, unread, onOpen }) => {+}> = ({ projectId, session, unread, canChat, onOpen }) => {const { t } = useTranslation();- const api = useApi();- const { showToast } = useToast();- const { renameSession, setSessionPinned, archiveSession, forkSession } = useWorkbenchProjectsTree();+ const { renameSession } = useWorkbenchProjectsTree();const navigate = useNavigate();const [menuOpen, setMenuOpen] = useState(false);- const [archiveOpen, setArchiveOpen] = useState(false);const [renaming, setRenaming] = useState(false);- const [pinning, setPinning] = useState(false);const [draft, setDraft] = useState(session.title ?? '');const inputRef = useRef<HTMLInputElement | null>(null);const handledRef = useRef(false);- const forkingRef = useRef(false);- const pinningRef = useRef(false);++ const { actions, archiveDialog } = useSessionActions({+ session,++ writable: canChat,+ projectId,+ onRenameStart: () => {+ setDraft(session.title ?? '');+ handledRef.current = false;+ setRenaming(true);+ },+ onOpenSession: (sessionId) => navigate(`/chat/${encodeURIComponent(sessionId)}`),+ });useEffect(() => {if (renaming) inputRef.current?.focus();@@@ -356,102 -331,23 +342,23 @@@</span>)}</button>- {canChat && <SessionPinAction- pinned={session.pinned}- pending={pinning}- pinLabel={t('workbench.sessionPin')}- unpinLabel={t('workbench.sessionUnpin')}- onToggle={() => void togglePinned()}- />}- <Popover open={menuOpen} onOpenChange={setMenuOpen}>+ {canChat && <Popover open={menuOpen} onOpenChange={setMenuOpen}><PopoverTrigger asChild>- <Button- type="button"- variant="ghost"- size="icon"- aria-label={t('workbench.sessionActions')}- className="size-8 shrink-0 text-muted"- >- <Ellipsis className="size-3.5" />- </Button>+ <SessionActionsTrigger+ label={t('workbench.sessionActions')}+ open={menuOpen}+ variant="bar"+ className="size-8"+ /></PopoverTrigger>- <PopoverContent align="end" className="w-[176px] p-1">- <MenuItem- icon={session.pinned ? PinOff : Pin}- onClick={() => {- setMenuOpen(false);- void togglePinned();- }}- >- {t(session.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin')}- </MenuItem>- <MenuItem- icon={Pencil}- onClick={() => {- setMenuOpen(false);- setDraft(session.title ?? '');- handledRef.current = false;- setRenaming(true);- }}- >- {t('workbench.sessionRename')}- </MenuItem>- {/* Fork is hidden until the session has a native agent session to fork- (mirrors the desktop sidebar's fork gate). */}- {session.native_session_id && (- <MenuItem- icon={GitFork}- onClick={async () => {- setMenuOpen(false);- // The row stays mounted after the menu closes, so guard against a- // second tap (reopened menu) spawning a duplicate fork in flight.- if (forkingRef.current) return;- forkingRef.current = true;- try {- const forked = await forkSession(projectId, session.id);- if (forked) navigate(`/chat/${encodeURIComponent(forked.id)}`);- } finally {- forkingRef.current = false;- }- }}- >- {t('workbench.sessionFork')}- </MenuItem>- )}- <MenuItem- icon={EyeOff}- onClick={() => {- setMenuOpen(false);- void hideSessionToBackground({- sessionId: session.id,- setSessionVisibility: api.setSessionVisibility,- showToast,- hiddenMessage: t('workbench.sessionHiddenToast'),- undoLabel: t('common.undo'),- });- }}- >- {t('workbench.sessionHideToBackground')}- </MenuItem>- <MenuItem- icon={Archive}- danger- onClick={() => {- setMenuOpen(false);- setArchiveOpen(true);- }}- >- {t('workbench.sessionArchive')}- </MenuItem>- </PopoverContent>+ <SessionActionMenuContent+ actions={actions}+ label={t('workbench.sessionActions')}+ align="end"+ onClose={() => setMenuOpen(false)}+ />- </Popover>+ </Popover>}- {canChat && <ArchiveSessionDialog- sessionId={archiveOpen ? session.id : null}- sessionTitle={session.title}- open={archiveOpen}- onOpenChange={setArchiveOpen}- onConfirm={() => archiveSession(projectId, session.id)}- />}+ {archiveDialog}</div>);};diff --cc ui/src/components/workbench/WorkbenchSidebar.tsxindex f83e55b40,09fe28f3a..7dc5356cc--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@@ -33,19 -28,15 +28,16 @@@ import type { LucideIcon } from 'lucideimport { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';import { useWindowManager } from '../../context/WindowManagerContext';- import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';- import { useApi } from '../../context/ApiContext';import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';- import { useToast } from '../../context/ToastContext';- import { SessionPinAction } from './SessionPinAction';- import { sessionPinRowPaddingClass } from './sessionPinLayout';+ import { SessionPinIndicator } from './SessionPinIndicator';+ import { sessionRowActionPaddingClass } from './sessionRowLayout';+ import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';+ import { useSessionActions } from './useSessionActions';import { formatRelativeTime } from '../../lib/relativeTime';- import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';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';@@@ -120,21 -109,19 +112,19 @@@ const InboxHoverPopover: React.FC<{t('workbench.inbox.headerCount', { unread: unreadSessions, total: sessions.length })}</div></div>- {canMarkRead && (- <button- type="button"- onClick={onMarkAllRead}- disabled={totalUnread === 0}- className={clsx(- 'rounded-md border px-2 py-1 text-[10px] font-medium transition',- totalUnread === 0- ? 'cursor-not-allowed border-border bg-foreground/[0.02] text-muted'- : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',- )}- >- {t('workbench.inbox.markAllRead')}- </button>- )}- <button++ {canMarkRead && <button+ type="button"+ onClick={onMarkAllRead}+ disabled={totalUnread === 0}+ className={clsx(+ 'rounded-md border px-2 py-1 text-[10px] font-medium transition',+ totalUnread === 0+ ? 'cursor-not-allowed border-border bg-foreground/[0.02] text-muted'+ : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',+ )}+ >+ {t('workbench.inbox.markAllRead')}- </button>++ </button>}</div>{shown.length === 0 ? (@@@ -210,35 -197,22 +200,23 @@@ const STATUS_DOT_CLASS: Record<string,idle: 'bg-muted',};- // One session row under a project. Left-click opens the chat; right-click opens- // the session action menu. Rename calls api.updateSession({ title }); the live- // session.activity 'updated' event then patches the title in this list (see the- // onSessionActivity handler in WorkbenchSidebar), so no manual local patch here.+ // One session row under a project. Left-click opens the chat; the hover-revealed+ // ⋯ (and right-click anywhere on the row) opens the shared session action menu —+ // see sessionActions.tsx, which owns the items and the writes for every surface.+ // Rename is inline here: the commit calls the provider, whose session.activity+ // 'updated' event patches the title in this list, so no manual local patch.const SessionRow: React.FC<{+ projectId: string;session: WorkbenchSession;unread: number;-}> = ({ projectId, session, unread }) => {+ canChat: boolean;- onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;- onSetPinned: (sessionId: string, pinned: boolean) => Promise<void>;- onRenameSession: (sessionId: string, title: string) => Promise<void>;- onArchiveSession: (sessionId: string) => Promise<void>;- }> = ({ session, unread, canChat, onForkSession, onSetPinned, onRenameSession, onArchiveSession }) => {++}> = ({ projectId, session, unread, canChat }) => {const { t } = useTranslation();const navigate = useNavigate();- const api = useApi();- const { showToast } = useToast();- const authorizeRouteAction = useUnsavedChangesActionGuard();+ const { renameSession } = useWorkbenchProjectsTree();const location = useLocation();const active = location.pathname === `/chat/${session.id}`;- // "Reference this session" shows only when a chat composer is mounted (a chat- // is open) AND this row isn't that open session — you can't reference yourself.- const insertTarget = useComposerInsertTarget();- const canReference = canChat && insertTarget != null && insertTarget.sessionId !== session.id;const [menuOpen, setMenuOpen] = useState(false);- const [archiveOpen, setArchiveOpen] = useState(false);- const [forking, setForking] = useState(false);- const [pinning, setPinning] = useState(false);- const pinningRef = useRef(false);const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState(session.title ?? '');const inputRef = useRef<HTMLInputElement | null>(null);@@@ -247,6 -221,24 +225,25 @@@// must NOT let that trailing blur commit the stale draft (Codex P2).const handledRef = useRef(false);+ const { actions, archiveDialog } = useSessionActions({+ session,++ writable: canChat,+ projectId,+ onRenameStart: () => {+ setDraft(session.title ?? '');+ handledRef.current = false;+ setRenaming(true);+ },+ // Forking navigates, and useSessionActions runs the unsaved-changes guard+ // itself — before the fork request, so a cancelled prompt writes nothing.+ onOpenSession: (sessionId) => navigate(`/chat/${encodeURIComponent(sessionId)}`),+ // Archiving the chat we are currently viewing leaves it directly — don't rely+ // solely on the replay-less SSE 'archived' event to navigate away.+ onArchived: () => {+ if (active) navigate('/inbox');+ },+ });+useEffect(() => {if (renaming) inputRef.current?.focus();}, [renaming]);@@@ -296,23 -288,9 +293,9 @@@}const displayName = session.title?.trim() || t('workbench.untitledSession');- const canFork = !!session.native_session_id && !forking;- const togglePinned = async () => {- if (pinningRef.current) return;- pinningRef.current = true;- setPinning(true);- try {- await onSetPinned(session.id, !session.pinned);- } catch {- // apiFetch already surfaced the error toast.- } finally {- pinningRef.current = false;- setPinning(false);- }- };return (<>- <Popover open={menuOpen} onOpenChange={setMenuOpen}>+ <Popover open={canChat && menuOpen} onOpenChange={(open) => canChat && setMenuOpen(open)}><PopoverAnchor asChild><divonContextMenu={(e) => {@@@ -354,130 -335,21 +341,21 @@@</span>)}</button>- {canChat && (- <SessionPinAction- pinned={session.pinned}- pending={pinning}- pinLabel={t('workbench.sessionPin')}- unpinLabel={t('workbench.sessionUnpin')}- onToggle={() => void togglePinned()}- />- )}- <span className="absolute inset-y-0 right-2 flex items-center">++ {canChat && <span className="absolute inset-y-0 right-2 flex items-center">+ <PopoverTrigger asChild>+ <SessionActionsTrigger label={t('workbench.sessionActions')} open={menuOpen} />+ </PopoverTrigger>- </span>++ </span>}</div></PopoverAnchor>- <PopoverContent align="start" className="w-[176px] p-1">- <button- type="button"- disabled={pinning}- onClick={() => {- setMenuOpen(false);- void togglePinned();- }}- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04] disabled:cursor-not-allowed disabled:text-muted"- >- {pinning ? (- <Loader2 className="size-3 animate-spin text-muted" />- ) : session.pinned ? (- <PinOff className="size-3 text-muted" />- ) : (- <Pin className="size-3 text-muted" />- )}- {t(session.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin')}- </button>- {canReference && (- <button- type="button"- onClick={() => {- setMenuOpen(false);- insertTarget?.insertSessionReference(session.id, session.title);- }}- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"- >- <Hash className="size-3 text-muted" />- {t('workbench.sessionReference')}- </button>- )}- <button- type="button"- disabled={!canFork}- title={!session.native_session_id ? t('workbench.sessionForkUnavailable') : undefined}- onClick={async () => {- if (!canFork) return;- const authorization = authorizeRouteAction();- if (!authorization) return;- setMenuOpen(false);- setForking(true);- try {- const forked = await onForkSession(session.id);- if (forked) {- authorization.runNavigation(() => navigate(`/chat/${encodeURIComponent(forked.id)}`));- }- } finally {- setForking(false);- }- }}- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04] disabled:cursor-not-allowed disabled:text-muted disabled:hover:bg-transparent"- >- {forking ? <Loader2 className="size-3 animate-spin text-muted" /> : <GitFork className="size-3 text-muted" />}- {t('workbench.sessionFork')}- </button>- <button- type="button"- onClick={() => {- setMenuOpen(false);- setDraft(session.title ?? '');- handledRef.current = false;- setRenaming(true);- }}- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"- >- <Pencil className="size-3 text-muted" />- {t('workbench.sessionRename')}- </button>- <button- type="button"- onClick={() => {- setMenuOpen(false);- void hideSessionToBackground({- sessionId: session.id,- setSessionVisibility: api.setSessionVisibility,- showToast,- hiddenMessage: t('workbench.sessionHiddenToast'),- undoLabel: t('common.undo'),- });- }}- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"- >- <EyeOff className="size-3 text-muted" />- {t('workbench.sessionHideToBackground')}- </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>+ <SessionActionMenuContent+ actions={actions}+ label={t('workbench.sessionActions')}+ align="start"+ onClose={() => setMenuOpen(false)}+ /></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');- }}- />+ {archiveDialog}</>);};@@@ -715,13 -575,9 +585,10 @@@ const ProjectRow: React.FC<sessions.map((session) => (<SessionRowkey={session.id}+ projectId={project.id}session={session}unread={unreadBySession[session.id] || 0}+ canChat={canChat}- onForkSession={onForkSession}- onSetPinned={onSetPinned}- onRenameSession={onRenameSession}- onArchiveSession={onArchiveSession}/>))}{hasMore && (@@@ -957,7 -797,7 +820,7 @@@ export const WorkbenchSidebar: React.FCrow above to reclaim that space for the Projects list; ⌘K stillworks. Both are roomy 28px tap targets. */}<div className="flex items-center gap-0.5">-- <Button++ {capabilities.can_manage_projects && <Buttontype="button"variant="ghost"size="icon"@@@ -966,19 -806,17 +829,17 @@@onClick={onOpenSearch}><Search className="size-4" />- </Button>++ </Button>}+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-7 shrink-0 text-muted hover:text-foreground"+ aria-label={t('workbench.addProject')}+ onClick={() => setShowNewProject(true)}+ >+ <FolderPlus className="size-4" /></Button>- {capabilities.can_manage_projects && (- <Button- type="button"- variant="ghost"- size="icon"- className="size-7 shrink-0 text-muted hover:text-foreground"- aria-label={t('workbench.addProject')}- onClick={() => setShowNewProject(true)}- >- <FolderPlus className="size-4" />- </Button>- )}</div></div>diff --cc ui/src/components/workbench/useSessionActions.test.tsxindex 000000000,a65a0a5a1..18eb7c55emode 000000,100644..100644--- a/ui/src/components/workbench/useSessionActions.test.tsx+++ b/ui/src/components/workbench/useSessionActions.test.tsx@@@ -1,0 -1,238 +1,243 @@@+ import type { ReactElement } from 'react';+ import { renderToStaticMarkup } from 'react-dom/server';+ import { beforeEach, describe, expect, it, vi } from 'vitest';++ import type { WorkbenchSession } from '../../context/ApiContext';+ import type { UnsavedChangesActionAuthorization } from '../../lib/unsavedChangesRegistry';+ import type { ArchiveSessionDialogProps } from './ArchiveSessionDialog';+ import { useSessionActions, type SessionActionsHandle, type SessionActionsOptions } from './useSessionActions';++ // The hook only needs four contexts and `t`. Mocking them (rather than mounting the+ // real providers) keeps this a jsdom-free unit test of the WRITES — which project id+ // reaches the provider, in what order the unsaved-changes guard runs, and which+ // session id a resolved write reports.+ const mocks = vi.hoisted(() => ({+ forkSession: vi.fn<(projectId: string | null, sessionId: string) => Promise<WorkbenchSession | null>>(),+ setSessionPinned: vi.fn<(projectId: string | null, sessionId: string, pinned: boolean) => Promise<void>>(),+ archiveSession: vi.fn<(projectId: string | null, sessionId: string) => Promise<void>>(),+ setSessionVisibility: vi.fn(),+ showToast: vi.fn(),+ authorizeRouteAction: vi.fn<() => UnsavedChangesActionAuthorization | null>(),+ }));++ vi.mock('../../context/ApiContext', () => ({+ useApi: () => ({ setSessionVisibility: mocks.setSessionVisibility }),+ }));+ vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mocks.showToast }) }));+ vi.mock('../../context/ComposerBridgeContext', () => ({ useComposerInsertTarget: () => null }));+ vi.mock('../../context/WorkbenchProjectsContext', () => ({+ useWorkbenchProjectsTree: () => ({+ forkSession: mocks.forkSession,+ setSessionPinned: mocks.setSessionPinned,+ archiveSession: mocks.archiveSession,+ }),+ }));+ vi.mock('../../context/useUnsavedChangesActionGuard', () => ({+ useUnsavedChangesActionGuard: () => mocks.authorizeRouteAction,+ }));+ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++ const session = (over: Partial<WorkbenchSession> = {}): WorkbenchSession =>+ ({+ id: 'ses_standalone',+ scope_id: 'scope-1',+ project_id: null, // standalone: no project-bound scope, so no project row+ title: 'Standalone',+ status: 'active',+ pinned: false,+ agent_status: 'idle',+ native_session_id: 'native-1',+ ...over,+ }) as WorkbenchSession;++ // renderToStaticMarkup runs the hook body once and never re-renders, which is all+ // this needs: the returned descriptors close over refs and callbacks, so calling+ // them afterwards exercises the real write paths (the pending state updates are+ // no-ops on the server, and are covered by the presentation test instead).+ const Probe = ({+ options,+ capture,+ }: {+ options: SessionActionsOptions;+ capture: (handle: SessionActionsHandle) => void;+ }) => {+ capture(useSessionActions(options));+ return null;+ };+ const mount = (options: SessionActionsOptions): SessionActionsHandle => {+ let handle: SessionActionsHandle | null = null;+ renderToStaticMarkup(+ <Probe+ options={options}+ capture={(captured) => {+ handle = captured;+ }}+ />,+ );+ if (!handle) throw new Error('hook did not run');+ return handle;+ };++ const select = (h: SessionActionsHandle, id: string) => {+ const action = h.actions.find((candidate) => candidate.id === id);+ if (!action) throw new Error(`no ${id} action`);+ action.onSelect();+ };+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));+ const confirmArchive = (h: SessionActionsHandle) =>+ (h.archiveDialog as ReactElement<ArchiveSessionDialogProps>).props.onConfirm();++ const options = (over: Partial<SessionActionsOptions> = {}): SessionActionsOptions => ({+ session: session(),+ onRenameStart: vi.fn(),+ onOpenSession: vi.fn(),+ ...over,+ });++ /** What the real gate returns when there is nothing unsaved to warn about: an+ * authorization that runs the navigation straight through. */+ const grantedAuthorization = (): UnsavedChangesActionAuthorization => ({+ runNavigation: vi.fn((navigation: () => void) => navigation()),+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.forkSession.mockResolvedValue(session({ id: 'ses_forked' }));+ mocks.setSessionPinned.mockResolvedValue(undefined);+ mocks.archiveSession.mockResolvedValue(undefined);+ mocks.authorizeRouteAction.mockImplementation(grantedAuthorization);+ });++ // ── Codex review (useSessionActions.tsx:81) ──────────────────────────────────+ // `project_id` is the `proj_*` suffix of the scope id, so it is NULL for every+ // session outside a project. The hook used to bail out of pin / fork when it was+ // null, and archive CONFIRMED SUCCESSFULLY without archiving anything: the dialog+ // closed, the row stayed. The project id is a cache address, not a permission.+ describe('a session with no project (project_id: null)', () => {+ it('pins through to the API and reports the write', () => {+ const onSessionPatched = vi.fn();+ const h = mount(options({ onSessionPatched }));++ select(h, 'pin');++ expect(mocks.setSessionPinned).toHaveBeenCalledWith(null, 'ses_standalone', true);+ return flush().then(() => {+ // The id travels with the patch: the write resolves after an await, and the+ // surface may have navigated to another session by then.+ expect(onSessionPatched).toHaveBeenCalledWith({ pinned: true }, 'ses_standalone');+ });+ });++ it('forks and opens the fork', async () => {+ const onOpenSession = vi.fn();+ const h = mount(options({ onOpenSession }));++ select(h, 'fork');+ await flush();++ expect(mocks.forkSession).toHaveBeenCalledWith(null, 'ses_standalone');+ expect(onOpenSession).toHaveBeenCalledWith('ses_forked');+ });++ it('actually archives when the dialog is confirmed', async () => {+ const onArchived = vi.fn();+ const h = mount(options({ onArchived }));++ // The dialog is closed and bound to nothing until it is asked for — the hook+ // instance is reused across sessions, so an inherited `open` is the bug class+ // `archiveRequestIsLive` exists to prevent.+ const dialog = (h.archiveDialog as ReactElement<ArchiveSessionDialogProps>).props;+ expect(dialog.open).toBe(false);+ expect(dialog.sessionId).toBeNull();++ await confirmArchive(h);++ expect(mocks.archiveSession).toHaveBeenCalledWith(null, 'ses_standalone');+ expect(onArchived).toHaveBeenCalledTimes(1);+ });++ it('still routes a project-owned session through its project', () => {+ const h = mount(options({ session: session({ project_id: 'proj-1' }) }));+ select(h, 'pin');+ expect(mocks.setSessionPinned).toHaveBeenCalledWith('proj-1', 'ses_standalone', true);++ // An explicit projectId (what the sidebar rows pass) wins over the row's own.+ const owned = mount(options({ session: session({ project_id: 'proj-1' }), projectId: 'proj-2' }));+ select(owned, 'pin');+ expect(mocks.setSessionPinned).toHaveBeenLastCalledWith('proj-2', 'ses_standalone', true);+ });+ });++ // ── Codex review (useSessionActions.tsx:139) ─────────────────────────────────+ // The sidebar's unsaved-changes prompt used to run inside `onOpenSession`, i.e.+ // AFTER the fork request had already been sent: cancelling the prompt left an orphan+ // forked session behind. The guard is a pre-flight now — and the hook asks for it+ // ITSELF rather than taking it as an option, so a surface cannot forget to pass it+ // (the chat header and the mobile projects row both had).+ describe('fork under the unsaved-changes guard', () => {+ it('consults the router guard without being handed one', () => {+ mount(options());+ expect(mocks.authorizeRouteAction).not.toHaveBeenCalled(); // asked per action, not per render+ });++ it('writes nothing when the user cancels the prompt', async () => {+ mocks.authorizeRouteAction.mockReturnValue(null);+ const onOpenSession = vi.fn();+ const h = mount(options({ onOpenSession }));++ select(h, 'fork');+ await flush();++ expect(mocks.authorizeRouteAction).toHaveBeenCalledTimes(1);+ expect(mocks.forkSession).not.toHaveBeenCalled();+ expect(onOpenSession).not.toHaveBeenCalled();+ });++ it('carries the granted authorization into the navigation', async () => {+ const granted = grantedAuthorization();+ mocks.authorizeRouteAction.mockReturnValue(granted);+ const onOpenSession = vi.fn();+ const h = mount(options({ onOpenSession }));++ select(h, 'fork');+ await flush();++ expect(mocks.forkSession).toHaveBeenCalledTimes(1);+ // Navigating THROUGH runNavigation is what stops the guard prompting twice for+ // one action; calling navigate() directly would re-block it.+ expect(granted.runNavigation).toHaveBeenCalledTimes(1);+ expect(onOpenSession).toHaveBeenCalledWith('ses_forked');+ });++ it('never forks twice from a double click', async () => {+ const h = mount(options());++ select(h, 'fork');+ select(h, 'fork'); // before any re-render could disable the row++ await flush();+ expect(mocks.forkSession).toHaveBeenCalledTimes(1);+ });+ });++ describe('a read-only session', () => {+ it('offers nothing to click, no dialog, and an inert shortcut', () => {+ for (const readOnly of [session({ status: 'archived' }), session({ visibility: 'system' }), null]) {+ const h = mount(options({ session: readOnly }));++ expect(h.actions).toEqual([]);+ expect(h.archiveDialog).toBeNull();+ // canArchive is what ChatPage binds ⌘⇧D on, so the chord is not swallowed.+ expect(h.canArchive).toBe(false);+ h.requestArchive();+ expect(mocks.archiveSession).not.toHaveBeenCalled();+ }+++ const capabilityBlocked = mount(options({ writable: false }));++ expect(capabilityBlocked.actions).toEqual([]);++ expect(capabilityBlocked.archiveDialog).toBeNull();++ expect(capabilityBlocked.canArchive).toBe(false);+++ expect(mount(options()).canArchive).toBe(true);+ });+ });diff --cc ui/src/components/workbench/useSessionActions.tsxindex 000000000,0bb353375..bb31ba944mode 000000,100644..100644--- a/ui/src/components/workbench/useSessionActions.tsx+++ b/ui/src/components/workbench/useSessionActions.tsx@@@ -1,0 -1,260 +1,264 @@@+ import type * as React from 'react';+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+ import { useTranslation } from 'react-i18next';+ import { Archive, EyeOff, GitFork, Hash, Pencil, Pin, PinOff } from 'lucide-react';++ import { useApi } from '../../context/ApiContext';+ import type { WorkbenchSession } from '../../context/ApiContext';+ import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';+ import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';+ import { useToast } from '../../context/ToastContext';+ import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';+ import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';+ import { archiveRequestIsLive, isSessionReadOnly } from './sessionArchived';+ import { ArchiveSessionDialog } from './ArchiveSessionDialog';+ import type { SessionActionDescriptor } from './sessionActions';++ // ── One session action model, four render sites ───────────────────────────────+ // The desktop sidebar row, its right-click menu, the mobile projects row and the+ // chat header all offer the SAME six actions. They used to be written out three+ // times (and had already drifted: fork was disabled-with-tooltip on desktop but+ // hidden on mobile, and "reference" existed only on desktop). This hook owns the+ // list, the writes and the pending state; each surface owns only where the+ // trigger sits and what "rename" / "open" / "archived" mean locally. The rows+ // themselves render through SessionActionMenu (sessionActions.tsx).++ export interface SessionActionsOptions {+ /** ``null`` (no session yet, or a read-only one) yields no actions and an inert+ * archive request, so callers can invoke the hook unconditionally. */+ session: WorkbenchSession | null;++ /** Capability gate for otherwise-live sessions. Remote Organization readers++ * can inspect a session but must not receive local write actions. */++ writable?: boolean;+ /** Project whose cached list holds the row — a CACHE address, not a permission.+ * Defaults to ``session.project_id``, which is ``null`` for a standalone session+ * (no project-bound scope); the writes run either way. */+ projectId?: string | null;+ /** Start the surface's own rename editor (inline input / chat header title). */+ onRenameStart: () => void;+ /** Navigate to a session (the fork target). Always called inside the+ * unsaved-changes authorization's runner (see below). */+ onOpenSession: (sessionId: string) => void;+ /** After a successful archive — the chat leaves the dead session, rows just drop. */+ onArchived?: () => void;+ /** Mirror a write into a surface-local copy of the session (the chat page holds+ * its own ``session`` state, which the provider cache doesn't feed). The session+ * id is passed back so a surface that has since moved on can ignore it. */+ onSessionPatched?: (changes: Partial<WorkbenchSession>, sessionId: string) => void;+ /** Keyboard hint for the archive row (see chatShortcuts). */+ archiveHint?: string;+ }++ export interface SessionActionsHandle {+ actions: SessionActionDescriptor[];+ /** Render this next to the menu — it carries its own open state. */+ archiveDialog: React.ReactNode;+ /** Open the archive confirm dialog (menu row, or the ⌘⇧D shortcut). */+ requestArchive: () => void;+ /** ``requestArchive`` can actually do something — i.e. there is a writable+ * session. The keyboard shortcut binds only while this is true, so it never+ * swallows the browser's own ⌘⇧D on a read-only or still-loading chat. */+ canArchive: boolean;+ }++ export const useSessionActions = ({+ session,++ writable = true,+ projectId,+ onRenameStart,+ onOpenSession,+ onArchived,+ onSessionPatched,+ archiveHint,+ }: SessionActionsOptions): SessionActionsHandle => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();+ const { forkSession, setSessionPinned, archiveSession } = useWorkbenchProjectsTree();+ // Owned HERE, not passed in per surface: the unsaved-changes blocker is mounted on+ // the ROUTER, so any surface that navigates after a write — sidebar, mobile row,+ // chat header — is prompted only once the fork already exists, and cancelling+ // orphans it. Asking inside the hook means a new surface inherits the pre-flight+ // instead of having to remember an option (Codex found the chat header missing it).+ const authorizeNavigation = useUnsavedChangesActionGuard();+ const insertTarget = useComposerInsertTarget();+ // The session an archive request was made FOR, not a bare "open" flag: this hook+ // instance outlives any one session (ChatPage is reused across ids), so a boolean+ // would be inherited by the next session — see archiveRequestIsLive.+ const [archiveRequestId, setArchiveRequestId] = useState<string | null>(null);+ const [pinning, setPinning] = useState(false);+ const [forking, setForking] = useState(false);+ // Refs, not the state above: a second click can land before React re-renders+ // with the disabled row (a double fork spawns two sessions).+ const pinningRef = useRef(false);+ const forkingRef = useRef(false);++ // A read-only session (archived, or a runtime-owned ``system`` row) refuses every+ // one of these server-side — 409 archived / 403 reserved_session — so the whole+ // menu is withdrawn rather than offered as a list of guaranteed failures. Same+ // reasoning showPageControlActions already applies to the Show Page cluster.- const target = session && !isSessionReadOnly(session) ? session : null;++ const target = writable && session && !isSessionReadOnly(session) ? session : null;+ const targetId = target?.id ?? null;+ const ownerProjectId = projectId ?? target?.project_id ?? null;++ // Derived, so a target that moved or went read-only closes the dialog in the SAME+ // render rather than a frame later.+ const archiveOpen = archiveRequestIsLive(archiveRequestId, targetId);+ // ...and forget the request once it is stale, so coming back to that session later+ // does not resurrect a dialog the user has long since walked away from.+ useEffect(() => {+ setArchiveRequestId(null);+ }, [targetId]);++ const requestArchive = useCallback(() => {+ if (!targetId) return;+ setArchiveRequestId(targetId);+ }, [targetId]);++ const togglePinned = useCallback(async () => {+ if (!target || pinningRef.current) return;+ pinningRef.current = true;+ setPinning(true);+ const next = !target.pinned;+ const pinnedId = target.id;+ try {+ await setSessionPinned(ownerProjectId, pinnedId, next);+ // Carry the id: this resolves after an await, and the surface may have moved+ // to another session by then (patching it would flip the wrong row).+ onSessionPatched?.({ pinned: next }, pinnedId);+ } catch {+ // apiFetch already surfaced the error toast.+ } finally {+ pinningRef.current = false;+ setPinning(false);+ }+ }, [target, ownerProjectId, setSessionPinned, onSessionPatched]);++ const fork = useCallback(async () => {+ if (!target || forkingRef.current) return;+ // Ask FIRST (the prompt is synchronous), write second: a cancelled+ // unsaved-changes prompt must not leave a forked session nobody navigated to.+ // ``null`` is the user cancelling; with nothing unsaved the gate authorizes+ // straight through.+ const authorization = authorizeNavigation();+ if (!authorization) return;+ forkingRef.current = true;+ setForking(true);+ try {+ const forked = await forkSession(ownerProjectId, target.id);+ if (!forked) return;+ // runNavigation carries the already-granted authorization into the route+ // change, so the router blocker doesn't prompt a second time for one action.+ authorization.runNavigation(() => onOpenSession(forked.id));+ } finally {+ forkingRef.current = false;+ setForking(false);+ }+ }, [target, ownerProjectId, forkSession, onOpenSession, authorizeNavigation]);++ const hide = useCallback(() => {+ if (!target) return;+ void hideSessionToBackground({+ sessionId: target.id,+ setSessionVisibility: api.setSessionVisibility,+ showToast,+ hiddenMessage: t('workbench.sessionHiddenToast'),+ undoLabel: t('common.undo'),+ });+ }, [target, api.setSessionVisibility, showToast, t]);++ const actions = useMemo<SessionActionDescriptor[]>(() => {+ if (!target) return [];+ const canFork = Boolean(target.native_session_id);+ // "Reference this session" needs a chat composer mounted somewhere else — you+ // cannot reference the session you are already typing in, which is also why+ // the chat header never shows this row for its own session.+ const canReference = insertTarget != null && insertTarget.sessionId !== target.id;+ const rows: SessionActionDescriptor[] = [+ {+ id: 'pin',+ group: 'organize',+ icon: target.pinned ? PinOff : Pin,+ label: t(target.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin'),+ pending: pinning,+ disabled: pinning,+ onSelect: () => void togglePinned(),+ },+ {+ id: 'rename',+ group: 'organize',+ icon: Pencil,+ label: t('workbench.sessionRename'),+ onSelect: onRenameStart,+ },+ ];+ if (canReference) {+ rows.push({+ id: 'reference',+ group: 'continue',+ icon: Hash,+ label: t('workbench.sessionReference'),+ onSelect: () => insertTarget?.insertSessionReference(target.id, target.title),+ });+ }+ rows.push(+ {+ id: 'fork',+ group: 'continue',+ icon: GitFork,+ label: t('workbench.sessionFork'),+ // Disabled-with-a-reason on every surface: a session with no native+ // conversation has nothing to fork, and hiding the row (what mobile used+ // to do) teaches the user nothing.+ disabled: !canFork || forking,+ pending: forking,+ title: canFork ? undefined : t('workbench.sessionForkUnavailable'),+ onSelect: () => void fork(),+ },+ {+ id: 'hide',+ group: 'continue',+ icon: EyeOff,+ label: t('workbench.sessionHideToBackground'),+ onSelect: hide,+ },+ {+ id: 'archive',+ group: 'lifecycle',+ icon: Archive,+ label: t('workbench.sessionArchive'),+ hint: archiveHint,+ danger: true,+ onSelect: requestArchive,+ },+ );+ return rows;+ }, [+ target,+ insertTarget,+ t,+ pinning,+ forking,+ togglePinned,+ onRenameStart,+ fork,+ hide,+ requestArchive,+ archiveHint,+ ]);++ const archiveDialog = target ? (+ <ArchiveSessionDialog+ sessionId={archiveOpen ? archiveRequestId : null}+ sessionTitle={target.title}+ open={archiveOpen}+ onOpenChange={(open) => setArchiveRequestId(open ? targetId : null)}+ onConfirm={async () => {+ await archiveSession(ownerProjectId, target.id);+ onArchived?.();+ }}+ />+ ) : null;++ return { actions, archiveDialog, requestArchive, canArchive: target != null };+ };diff --cc vibe/ui_server.pyindex 48568659c,4f7e490cb..235f55a0d--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@@ -2212,111 -2127,6 +2212,113 @@@ def enforce_remote_access_cookie()return jsonify({"ok": False, "error": "remote_access_login_required"}), 401[email protected]_request+def enforce_instance_role_capabilities():+ if _remote_auth_exempt_path():+ return None+ from vibe.authorization import required_instance_role++ minimum_role = required_instance_role(request.method, request.path)+ if minimum_role is None:+ return None+ context = getattr(g, "authorization_context", None)+ if context is None or not context.has_role(minimum_role):+ return jsonify(+ {+ "ok": False,+ "error": "instance_access_forbidden",+ "required_role": minimum_role,+ }+ ), 403+ return None+++def _is_remote_local_execution_request(method: str, path: str) -> bool:+ normalized_method = method.upper()+ if path.startswith(("/api/files/", "/api/browse")):+ return True+ if path.startswith("/api/terminal/"):+ return True+ if path.startswith("/api/harness/") and normalized_method not in {+ "GET",+ "HEAD",+ "OPTIONS",+ }:+ return True++ if normalized_method == "POST" and path == "/api/running-agents/end":++ return True+ return normalized_method == "POST" and bool(+ re.fullmatch(- r"/api/sessions/[^/]+/(?:messages|attachments|queue/[^/]+/send-now)",++ r"/api/sessions/[^/]+/(?:messages|attachments|cancel|queue/[^/]+/send-now)",+ path,+ )+ )++[email protected]_request+def enforce_remote_local_execution_boundary():+ """Keep shell-capable Workbench surfaces on the trusted-local origin."""++ context = getattr(g, "authorization_context", None)+ if (+ context is None+ or not context.is_remote+ or not _is_remote_local_execution_request(request.method, request.path)+ ):+ return None+ return _remote_execution_disabled_response()+++_PROJECT_RESOURCE_PATHS = (+ ("project", re.compile(r"^/api/projects/([^/]+)(?:/agents-md)?$")),+ ("session", re.compile(r"^/api/sessions/([^/]+)(?:/.*)?$")),+ ("session", re.compile(r"^/api/show-pages/([^/]+)(?:/.*)?$")),+ ("session", re.compile(r"^/api/show/sessions/([^/]+)(?:/.*)?$")),+ ("session", re.compile(r"^/show/([^/]+)(?:/.*)?$")),+)+++def _project_access_resource(path: str) -> tuple[str, str] | None:+ for kind, pattern in _PROJECT_RESOURCE_PATHS:+ match = pattern.fullmatch(path)+ if match is not None:+ return kind, unquote(match.group(1))+ return None++[email protected]_request+def enforce_project_role_capabilities():+ """Narrow remote non-owner Project/session routes through applied Project ACLs."""+ if _remote_auth_exempt_path():+ return None+ context = getattr(g, "authorization_context", None)+ if context is None or context.is_instance_owner:+ return None++ from storage import project_access_service+ from storage.db import create_sqlite_engine+ from vibe.authorization import required_instance_role++ minimum_instance_role = required_instance_role(request.method, request.path)+ if minimum_instance_role not in {"viewer", "editor"}:+ return None+ resource = _project_access_resource(request.path)+ if resource is None:+ return None++ kind, resource_id = resource+ engine = create_sqlite_engine()+ with engine.connect() as conn:+ role = (+ project_access_service.get_effective_project_role(conn, context, resource_id)+ if kind == "project"+ else project_access_service.get_effective_session_role(conn, context, resource_id)+ )+ if not project_access_service.role_allows(role, minimum_instance_role):+ return jsonify({"ok": False, "error": "not_found"}), 404+ return None++@app.before_requestdef protect_mutating_ui_requests():if request.method not in MUTATING_METHODS: