Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

merge(org): sync latest master into org

Maxf12cc679def5
diff --cc core/session_turns.py
index 4ca4cc0ed,42691b1e0..3f0039b0b
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@@ -3725,76 -3893,72 +3957,81 @@@ class SessionTurnManager
archived_before_dispatch = False
run_terminal_before_dispatch = False
invalid_delivery_ids: set[str] = set()
+ remote_authorization_denials: dict[str, str] = {}
- with self._sqlite_engine().begin() as conn:
- reserve_write_lock(conn)
- latest = delivery_store.get_turn(conn, turn_id)
- session_status = conn.execute(
- select(agent_sessions.c.status).where(
- agent_sessions.c.id == str(turn["session_id"])
- )
- ).scalar_one_or_none()
- fresh_deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
- fresh_delivery = fresh_deliveries[0] if fresh_deliveries else None
- if (
- latest is None
- or latest["state"] != "starting"
- or latest.get("start_attempt_id") != attempt_id
- or (
- expected_start_attempt_id is not None
- and str(latest.get("start_attempt_id") or "")
- != expected_start_attempt_id
- )
- or fresh_delivery is None
- or latest.get("initial_delivery_id") != fresh_delivery.get("id")
- or any(row["state"] != "claimed" for row in fresh_deliveries)
- ):
- return False
- turn = latest
- deliveries = fresh_deliveries
- delivery = fresh_delivery
- archived_before_dispatch = session_status != "active"
- invalid_delivery_ids = {
- str(row["id"])
- for row in deliveries
- if not self._has_resolvable_delivery_input(conn, row)
- }
- remote_authorization_denials = {
- str(row["id"]): reason
- for row in deliveries
- if (reason := self._remote_delivery_execution_denial(conn, row)) is not None
- }
- run_ids = list(
- dict.fromkeys(
- run_id
+ with release_lifecycle_admission_on_error():
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ latest = delivery_store.get_turn(conn, turn_id)
+ session_status = conn.execute(
+ select(agent_sessions.c.status).where(
+ agent_sessions.c.id == str(turn["session_id"])
+ )
+ ).scalar_one_or_none()
+ fresh_deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)
+ fresh_delivery = fresh_deliveries[0] if fresh_deliveries else None
+ if (
+ latest is None
+ or latest["state"] != "starting"
+ or latest.get("start_attempt_id") != attempt_id
+ or (
+ expected_start_attempt_id is not None
+ and str(latest.get("start_attempt_id") or "")
+ != expected_start_attempt_id
+ )
+ or fresh_delivery is None
+ or latest.get("initial_delivery_id") != fresh_delivery.get("id")
+ or any(row["state"] != "claimed" for row in fresh_deliveries)
+ ):
+ release_lifecycle_admission_if_owned()
+ return False
+ turn = latest
+ deliveries = fresh_deliveries
+ delivery = fresh_delivery
+ archived_before_dispatch = session_status != "active"
+ invalid_delivery_ids = {
+ str(row["id"])
for row in deliveries
- for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
- )
- )
- if not archived_before_dispatch and run_ids:
- run_rows = {
- str(row["id"]): row
- for row in conn.execute(
- select(
- agent_runs.c.id,
- agent_runs.c.status,
- agent_runs.c.cancel_requested,
- agent_runs.c.metadata_json,
- ).where(agent_runs.c.id.in_(run_ids))
- ).mappings()
+ if not self._has_resolvable_delivery_input(conn, row)
}
- for run_id in run_ids:
- run_row = run_rows.get(run_id)
- if run_row is None:
- continue
- run_status = normalize_run_status(run_row["status"])
- if bool(run_row["cancel_requested"]) or run_status not in {
- "queued",
- "running",
- }:
- run_terminal_before_dispatch = True
++ remote_authorization_denials = {
++ str(row["id"]): reason
++ for row in deliveries
++ if (
++ reason := self._remote_delivery_execution_denial(conn, row)
++ )
++ is not None
++ }
+ run_ids = list(
+ dict.fromkeys(
+ run_id
+ for row in deliveries
+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)
+ )
+ )
+ if not archived_before_dispatch and run_ids:
+ run_rows = {
+ str(row["id"]): row
+ for row in conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.status,
+ agent_runs.c.cancel_requested,
+ agent_runs.c.metadata_json,
+ ).where(agent_runs.c.id.in_(run_ids))
+ ).mappings()
+ }
+ for run_id in run_ids:
+ run_row = run_rows.get(run_id)
+ if run_row is None:
+ continue
+ run_status = normalize_run_status(run_row["status"])
+ if bool(run_row["cancel_requested"]) or run_status not in {
+ "queued",
+ "running",
+ }:
+ run_terminal_before_dispatch = True
if archived_before_dispatch:
- self._terminalize_durable_turn(
+ terminalize_and_release(
turn_id,
"not_written",
settled_by="session_archive",
@@@ -3811,27 -3975,6 +4048,27 @@@
if terminal.get("changed"):
await self._resume_post_terminal(str(turn["session_id"]))
return False
+ if remote_authorization_denials:
+ logger.warning(
+ "durable Turn=%s failed remote authorization before Agent dispatch: %s",
+ turn_id,
+ remote_authorization_denials,
+ )
- terminal = self._terminalize_durable_turn(
++ terminal = terminalize_and_release(
+ turn_id,
+ "not_written",
+ settled_by="remote_authorization_denied",
+ evidence_kind="remote_authorization_before_native_dispatch",
+ evidence={"denials": remote_authorization_denials},
+ retire_unwritten_delivery_ids={
+ str(row["id"])
+ for row in deliveries
+ },
+ )
+ if terminal.get("changed"):
+ self._publish_queue_update(str(turn["session_id"]))
+ await self._resume_post_terminal(str(turn["session_id"]))
+ return False
if invalid_delivery_ids:
logger.error(
"durable Turn=%s lost its resolvable input before native dispatch",
diff --cc tests/test_instance_authorization.py
index 0ce9bccfb,85b106c61..508baeb29
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@@ -164,156 -95,298 +164,163 @@@ def test_malformed_role_context_fails_c
assert context.can_read_instance is False
-def test_http_policy_defaults_unknown_api_to_owner() -> None:
- assert required_instance_role("GET", "/api/projects") == "viewer"
- assert required_instance_role("GET", "/api/projects/proj-1") == "viewer"
- assert required_instance_role("GET", "/api/projects/proj-1/agents-md") == "owner"
- assert required_instance_role("GET", "/api/agents") == "editor"
- assert required_instance_role("GET", "/api/skills") == "editor"
- assert required_instance_role("GET", "/api/vault/secrets") == "editor"
- assert required_instance_role("GET", "/api/vault/tags") == "editor"
- assert required_instance_role("POST", "/api/vault/requests/access") == "editor"
- assert required_instance_role("POST", "/api/vault/requests/sign") == "editor"
- assert required_instance_role("POST", "/api/vault/secrets") == "owner"
- assert required_instance_role("POST", "/api/skills") == "owner"
- assert required_instance_role("GET", "/api/show-pages") == "viewer"
- assert required_instance_role("GET", "/api/config") == "viewer"
- assert required_instance_role("GET", "/api/workbench/prefs") == "viewer"
- assert required_instance_role("PUT", "/api/workbench/prefs") == "owner"
- assert required_instance_role("GET", "/api/org/context") == "viewer"
- assert required_instance_role("GET", "/api/org/groups") == "viewer"
- assert required_instance_role("GET", "/api/resource-policies") == "viewer"
- assert required_instance_role("PUT", "/api/resource-policies/agent/agent-1") == "owner"
- assert required_instance_role("GET", "/api/sessions/ses-1/draft") == "editor"
- assert required_instance_role("POST", "/api/sessions/ses-1/messages") == "editor"
- assert required_instance_role("POST", "/api/sessions/ses-1/fork") == "editor"
- assert required_instance_role("POST", "/api/projects") == "owner"
- assert required_instance_role("GET", "/api/new-management-surface") == "owner"
- assert required_instance_role("GET", "/status") is None
- assert required_instance_role("GET", "/show/ses-1/") == "viewer"
- assert required_instance_role("POST", "/show/ses-1/api/action") == "editor"
- assert required_instance_role("GET", "/assets/app.js") is None
-
-
- ("method", "path"),
- [
- ("POST", "/api/show-pages/ses-1/visibility"),
- ("GET", "/api/backend/codex/runtime"),
- ("GET", "/api/backend/claude/auth"),
- ("GET", "/api/backend/codex/auth"),
- ("GET", "/api/opencode/permission-status"),
- ("GET", "/api/harness/tasks"),
- ("GET", "/api/harness/watches"),
- ("GET", "/api/global-prompts"),
- ("GET", "/api/harness/runs"),
- ("GET", "/api/harness/runs/run-1"),
+def test_show_page_email_context_requires_and_matches_one_exact_target() -> None:
+ context = context_from_session_payload(
+ {
+ "sub": "guest-1",
+ "email": "[email protected]",
+ "vibe_instance_id": "inst-1",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "session-one",
+ "vibe_instance_authorization_revision": 0,
+ }
+ )
+
+ assert context.can_use_show_page("session-one") is True
+ assert context.can_use_show_page("session-two") is False
+ assert context.show_page_id == "session-one"
+
+ missing_target = context_from_session_payload(
+ {
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ }
+ )
+ broader_target = context_from_session_payload(
+ {
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_show_page_id": "session-one",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "membership-1",
+ "vibe_organization_role": "member",
+ }
+ )
+ assert missing_target.can_read_instance is False
+ assert broader_target.can_read_instance is True
+ assert broader_target.can_chat is True
+ assert broader_target.can_use_show_page("session-one") is True
+ assert broader_target.can_use_show_page("session-two") is False
+
+ elevated_role = context_from_session_payload(
+ {
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "session-one",
+ }
+ )
+ assert elevated_role.can_read_instance is False
+ assert elevated_role.can_use_show_page("session-one") is False
+
+
+def test_http_policy_keeps_unknown_routes_fail_closed_and_runtime_matrix_explicit() -> None:
+ runtime_routes = (
("GET", "/api/harness/bootstrap"),
- ("GET", "/api/vault/pubkey"),
- ("GET", "/api/vault/agent/pubkey"),
- ("GET", "/api/vault/sandbox/root-metadata"),
- ("GET", "/api/vault/vmk"),
- ("GET", "/api/doctor"),
- ("POST", "/api/doctor"),
- ("POST", "/api/logs"),
- ("POST", "/api/ui/reload"),
- ("POST", "/api/opencode/options"),
- ("POST", "/api/opencode/setup-permission"),
- ("POST", "/api/vault/secrets"),
+ ("PATCH", "/api/harness/tasks/task-1"),
+ ("POST", "/api/agents"),
+ ("POST", "/api/skills"),
("PATCH", "/api/vault/secrets/secret-1"),
- ("DELETE", "/api/vault/grants/grant-1"),
- ("POST", "/api/vault/grants"),
- ("POST", "/api/vault/sign"),
- ("POST", "/api/skills/preview"),
- ("POST", "/api/users"),
+ ("PATCH", "/api/memory/settings"),
++ ("GET", "/api/memory/processing-record"),
++ ("GET", "/api/memory/maintenance"),
++ ("POST", "/api/memory/runtime/rebuild"),
++ ("POST", "/api/memory/runtime/factory-reset"),
++ ("POST", "/api/memory/runtime/repair"),
++ ("POST", "/api/memory/clear/resume"),
++ ("POST", "/api/memory/clear/abort"),
+ ("POST", "/api/control"),
+ ("POST", "/api/config"),
+ ("GET", "/api/models/sources"),
+ ("POST", "/api/models/runtime/start"),
+ ("POST", "/api/backend/codex/restart"),
+ ("POST", "/api/backend/claude/auth/oauth/start"),
+ ("GET", "/api/dependencies"),
+ ("POST", "/api/dependencies/avault/install"),
+ ("PUT", "/api/projects/proj-1/agents-md"),
+ ("POST", "/api/files/upload"),
+ ("DELETE", "/api/terminal/term-1"),
+ ("POST", "/api/show-pages/ses-1/icon"),
+ ("POST", "/show/ses-1/api/action"),
+ ("GET", "/api/users"),
("POST", "/api/users/user-1/admin"),
("DELETE", "/api/users/user-1"),
+ ("GET", "/api/bind-codes"),
("POST", "/api/bind-codes"),
("DELETE", "/api/bind-codes/code-1"),
- ("GET", "/api/vault/future-capability"),
- ("GET", "/api/dock/future-capability"),
- ("GET", "/api/web-push/future-capability"),
- ("GET", "/api/models/future-capability"),
- ("GET", "/api/harness/future-capability"),
- ("GET", "/api/users/future-capability"),
- ("GET", "/api/bind-codes/future-capability"),
+ ("GET", "/api/setup/first-bind-code"),
+ ("GET", "/status"),
+ )
+ for method, path in runtime_routes:
+ policy = http_authorization_policy(method, path)
+ assert policy.remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER, (method, path)
+
+ for method, path in (
("GET", "/api/future-owner-capability"),
- ("POST", "/api/future-owner-capability"),
- ("GET", "/api/memory/future-capability"),
- ("POST", "/api/memory/future-capability"),
- ],
-)
-def test_remote_http_policy_defaults_local_machine_and_unknown_routes_to_local_only(
- method,
- path,
-) -> None:
- policy = http_authorization_policy(method, path)
-
- assert policy.minimum_role == "owner"
- assert policy.remote_access == REMOTE_HTTP_LOCAL_ONLY
-
-
- ("method", "path", "expected"),
- [
- ("GET", "/api/projects", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/workbench/prefs", REMOTE_HTTP_ALLOWED),
- ("PUT", "/api/workbench/prefs", REMOTE_HTTP_LOCAL_ONLY),
- ("PUT", "/api/resource-policies/agent/agent-1", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/models/runtime/status", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/models/agents/codex/chain", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/models/turns/turn-1/provenance", REMOTE_HTTP_ALLOWED),
- # Only the local owner can start an OAuth flow, and a status poll hands
- # back that flow's authorization URL and device code - plus, once a Model
- # Hub flow succeeds, the credential and account payload `/api/models/
- # sources` keeps local. Polling follows its flow and stays local too.
- ("GET", "/api/models/oauth/status/oaf_test0001", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/backend/codex/auth/oauth/status/flow-1", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/backend/codex/runtime", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/opencode/permission-status", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/vault/audit", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/dock", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/dock/pins", REMOTE_HTTP_LOCAL_ONLY),
- ("PUT", "/api/dock/order", REMOTE_HTTP_LOCAL_ONLY),
- # A push endpoint is caller-supplied and `send_web_push()` fetches it
- # from this host, so registering or testing one from across the tunnel
- # would let a remote caller aim an outbound request at loopback, a
- # private LAN host or a rebinding name. Status reads stay remote: they
- # report the caller's own subscription and reach no endpoint.
- ("GET", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/web-push/vapid-public-key", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/web-push/subscriptions", REMOTE_HTTP_LOCAL_ONLY),
- ("DELETE", "/api/web-push/subscriptions", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/web-push/test", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/harness/runs/run-1", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/users", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/users", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/skills/check", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/skills/find", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/vault/requests/access", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/vault/requests/sign", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/show-pages/ses-1/rotate-share", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/show-pages/ses-1/share-id", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/sessions/ses-1/draft", REMOTE_HTTP_LOCAL_ONLY),
- ("PUT", "/api/sessions/ses-1/draft", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/sessions/ses-1/mark-read", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/status", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/status", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/show-pages/ses-1/ensure", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/memory/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/memory/failures", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/memory/log/entry", REMOTE_HTTP_LOCAL_ONLY),
- ("PATCH", "/api/memory/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/memory/search", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/memory/runtime/restart", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/memory/clear", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/projects/proj-1/agents-md", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/projects", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/show/ses-1/", REMOTE_HTTP_ALLOWED),
- ("POST", "/show/ses-1/__show/events", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/config", REMOTE_HTTP_PAYLOAD_FILTERED),
- ("PATCH", "/api/projects/proj-1", REMOTE_HTTP_PAYLOAD_FILTERED),
- ("PATCH", "/api/sessions/ses-1", REMOTE_HTTP_PAYLOAD_FILTERED),
- ("GET", "/api/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/settings/thread", REMOTE_HTTP_LOCAL_ONLY),
- ("DELETE", "/api/settings/thread", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/bind-codes", REMOTE_HTTP_LOCAL_ONLY),
- ("DELETE", "/api/projects/proj-1", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/sessions/ses-1/fork", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/show/ses-1/api/action", REMOTE_HTTP_LOCAL_ONLY),
- ],
-)
-def test_remote_http_policy_keeps_approved_management_and_read_surfaces(
- method,
- path,
- expected,
-) -> None:
- assert http_authorization_policy(method, path).remote_access == expected
-
-
- ("gate", "method", "path", "expected"),
- [
- # canManageSkills: read-only catalog remotely, every mutation local.
- ("canManageSkills", "GET", "/api/skills", REMOTE_HTTP_ALLOWED),
- ("canManageSkills", "POST", "/api/skills", REMOTE_HTTP_LOCAL_ONLY),
- ("canManageSkills", "POST", "/api/skills/askill/update", REMOTE_HTTP_LOCAL_ONLY),
- ("canManageSkills", "DELETE", "/api/skills/askill", REMOTE_HTTP_LOCAL_ONLY),
- (
- "canManageSkills",
- "POST",
- "/api/dependencies/askill/install",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- # canManageVaultSecrets: inventory and audit reads stay remote, mutations
- # and key material do not.
- ("canManageVaultSecrets", "GET", "/api/vault/secrets", REMOTE_HTTP_ALLOWED),
- ("canManageVaultSecrets", "GET", "/api/vault/settings", REMOTE_HTTP_ALLOWED),
- ("canManageVaultSecrets", "GET", "/api/vault/grants", REMOTE_HTTP_ALLOWED),
- ("canManageVaultSecrets", "POST", "/api/vault/secrets", REMOTE_HTTP_LOCAL_ONLY),
- (
- "canManageVaultSecrets",
- "PATCH",
- "/api/vault/secrets/prod",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- (
- "canManageVaultSecrets",
- "DELETE",
- "/api/vault/secrets/prod",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("canManageVaultSecrets", "POST", "/api/vault/vmk", REMOTE_HTTP_LOCAL_ONLY),
- # canUseHarness: the page cannot even bootstrap remotely.
- ("canUseHarness", "GET", "/api/harness/bootstrap", REMOTE_HTTP_LOCAL_ONLY),
- # canArchiveProjects: list and rename stay remote, archive does not.
- ("canArchiveProjects", "GET", "/api/projects", REMOTE_HTTP_ALLOWED),
- (
- "canArchiveProjects",
- "PATCH",
- "/api/projects/proj-1",
- REMOTE_HTTP_PAYLOAD_FILTERED,
- ),
- ("canArchiveProjects", "DELETE", "/api/projects/proj-1", REMOTE_HTTP_LOCAL_ONLY),
- # canEditProjectInstructions: local in both directions, because an
- # AGENTS.md / CLAUDE.md symlink can resolve outside the Project.
- (
- "canEditProjectInstructions",
- "GET",
- "/api/projects/proj-1/agents-md",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- (
- "canEditProjectInstructions",
- "PUT",
- "/api/projects/proj-1/agents-md",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- # canEditAgentDefinitions: catalog reads remotely, definition writes locally.
- ("canEditAgentDefinitions", "GET", "/api/agents", REMOTE_HTTP_ALLOWED),
- ("canEditAgentDefinitions", "POST", "/api/agents", REMOTE_HTTP_LOCAL_ONLY),
- # canAdministerMemory: principal-scoped reads and search stay remote,
- # the cross-principal admin log and the sidecar administration do not.
- ("canAdministerMemory", "GET", "/api/memory/status", REMOTE_HTTP_ALLOWED),
- ("canAdministerMemory", "GET", "/api/memory/profile", REMOTE_HTTP_ALLOWED),
- ("canAdministerMemory", "POST", "/api/memory/search", REMOTE_HTTP_ALLOWED),
- ("canAdministerMemory", "GET", "/api/memory/log", REMOTE_HTTP_LOCAL_ONLY),
- ("canAdministerMemory", "GET", "/api/memory/log/entry", REMOTE_HTTP_LOCAL_ONLY),
- ("canAdministerMemory", "PATCH", "/api/memory/settings", REMOTE_HTTP_LOCAL_ONLY),
- (
- "canAdministerMemory",
- "POST",
- "/api/memory/runtime/restart",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("canAdministerMemory", "POST", "/api/memory/clear", REMOTE_HTTP_LOCAL_ONLY),
- # Dock/Workbench prefs: the read is remote, the process-global writes
- # are local until the records are keyed by the authenticated subject.
- ("dockAndWorkbenchPrefs", "GET", "/api/dock", REMOTE_HTTP_ALLOWED),
- ("dockAndWorkbenchPrefs", "GET", "/api/workbench/prefs", REMOTE_HTTP_ALLOWED),
- ("dockAndWorkbenchPrefs", "POST", "/api/dock/pins", REMOTE_HTTP_LOCAL_ONLY),
- (
- "dockAndWorkbenchPrefs",
- "DELETE",
- "/api/dock/pins/ses-1",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("dockAndWorkbenchPrefs", "PUT", "/api/dock/order", REMOTE_HTTP_LOCAL_ONLY),
- ("dockAndWorkbenchPrefs", "PUT", "/api/workbench/prefs", REMOTE_HTTP_LOCAL_ONLY),
- # canRegisterWebPush: status reads stay remote, but registering or
- # testing an endpoint this host will call does not.
- ("canRegisterWebPush", "GET", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- ("canRegisterWebPush", "POST", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- (
- "canRegisterWebPush",
- "POST",
- "/api/web-push/subscriptions",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- (
- "canRegisterWebPush",
- "DELETE",
- "/api/web-push/subscriptions",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("canRegisterWebPush", "POST", "/api/web-push/test", REMOTE_HTTP_LOCAL_ONLY),
- ],
-)
-def test_local_only_workbench_gates_match_the_remote_http_policy(
- gate,
- method,
- path,
- expected,
-) -> None:
- """Pin the endpoint classifications the Workbench UI gates are derived from.
-
- `can_manage_instance` / `can_manage_agents` / `can_manage_projects` stay true
- for a remote Instance owner, so `ui/src/lib/remoteAuth.ts` adds a locality
- check for every control whose endpoint is local-only. If one of these routes
- is reclassified, that UI gate is stale and must be revisited with it.
- """
- assert http_authorization_policy(method, path).remote_access == expected, gate
+ ("POST", "/api/harness/future-capability"),
+ ("GET", "/api/opencode/future-capability"),
+ ("GET", "/api/backend/future/runtime"),
+ ("GET", "/api/users/user-1"),
+ ("POST", "/api/bind-codes/code-1"),
+ ):
+ policy = http_authorization_policy(method, path)
+ assert policy.minimum_role == "owner"
+ assert policy.remote_access == REMOTE_HTTP_LOCAL_ONLY
+
+ for method, path in (
+ ("POST", "/api/remote-access/vibe-cloud/pair"),
+ ("POST", "/api/remote-access/start"),
+ ("POST", "/api/remote-access/stop"),
+ ("POST", "/api/remote-access/optimize-route"),
+ ("POST", "/api/remote-access/settings"),
+ ("POST", "/api/remote-access/diagnostics"),
+ ("GET", "/api/remote-access/network-interfaces"),
+ ):
+ assert http_authorization_policy(method, path).remote_access == REMOTE_HTTP_LOCAL_ONLY
+
+
+def test_http_policy_preserves_safe_remote_reads_and_show_routes() -> None:
+ assert http_authorization_policy("GET", "/api/projects").remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER
+ assert http_authorization_policy("GET", "/api/org/context").remote_access == REMOTE_HTTP_ALLOWED
+ assert http_authorization_policy("GET", "/api/cloud-management/session").remote_access == REMOTE_HTTP_ALLOWED
+ assert http_authorization_policy("GET", "/show/ses-1/").remote_access == REMOTE_HTTP_ALLOWED
+ assert http_authorization_policy("POST", "/show/ses-1/__show/events").remote_access == REMOTE_HTTP_ALLOWED
+
+
+def test_temporary_runtime_signal_requires_membership_while_role_guard_uses_rank() -> None:
+ member = AuthorizationContext(
+ instance_role="viewer",
+ subject="member-1",
+ organization_id="org-1",
+ organization_member_id="membership-1",
+ organization_role="member",
+ instance_access_source="organization_group",
+ is_remote=True,
+ )
+ non_member = AuthorizationContext(
+ instance_role="owner",
+ subject="owner-1",
+ instance_access_source="owner",
+ is_remote=True,
+ )
+ assert has_temporary_unrestricted_org_access(member) is True
+ assert has_temporary_unrestricted_org_access(non_member) is False
+ assert require_instance_role(member, "owner") is member
+ assert require_instance_role(non_member, "owner") is non_member
+
+
+def test_temporary_runtime_route_matrix_is_not_a_capability_projection() -> None:
+ member = AuthorizationContext(
+ instance_role="viewer",
+ organization_id="org-1",
+ organization_member_id="membership-1",
+ organization_role="member",
+ instance_access_source="organization_group",
+ is_remote=True,
+ )
+ assert member.capability_projection()["can_use_system"] is False
+ assert member.capability_projection()["can_use_files"] is False
+ assert member.capability_projection()["can_use_terminal"] is False
def test_workbench_event_policy_filters_privileged_and_unknown_events() -> None:
diff --cc tests/test_internal_server.py
index b56821ca2,9aa4df8d5..0ca6d9bce
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@@ -17,14 -17,10 +17,11 @@@ from __future__ import annotation
import asyncio
import contextlib
- import errno
- import json
- import os
import socket
- import stat
import sys
import tempfile
+import time
+ import threading
import types
from pathlib import Path
from types import SimpleNamespace
@@@ -36,10 -32,10 +33,11 @@@ from sqlalchemy import selec
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
- from config import paths
from core import internal_server, session_turns
from core.message_context import build_context_turn_sink_key
+from core.vibe_agents import VibeAgentStore
+ from core.memory.maintenance import MemoryStoreUnavailableError
+ from core.memory.runtime import MemorySessionLifecycleBusyError
from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT
from core.services.agent_steering import SteerOutcome, result as steer_result
from core.services.dispatch import (
@@@ -1775,59 -1999,6 +2040,57 @@@ def test_dispatch_async_replay_of_queue
assert transcript == []
+def test_dispatch_async_starts_authorized_remote_reservation(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_remote_dispatch_reservation",
+ )
+ _seed_remote_worker()
+ with engine.begin() as conn:
+ remote = _reserve_submission(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="remote reserved input",
+ metadata=_authorized_remote_message_metadata(),
+ )
+
+ controller = None
+
+ async def handler(context, _text):
+ controller.mark_turn_complete(context)
+
+ controller = _build_controller_double(handler)
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session["id"],
+ "text": "remote reserved input",
+ "user_message_id": remote["id"],
+ },
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 202
+ assert response.json()["ok"] is True
+ controller.message_handler.handle_user_message.assert_awaited_once()
+ with engine.connect() as conn:
+ stored = message_deliveries.get_delivery(conn, remote["id"])
+ assert stored is not None
+ assert stored["state"] == "accepted"
-
-
def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(
monkeypatch,
tmp_path,
@@@ -5547,108 -6846,6 +6938,106 @@@ def _manager_accepting_runs()
return manager, runs
+def test_flush_runs_authorized_remote_fifo_head(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_remote_queue_retirement",
+ )
+ _seed_remote_worker()
+ with engine.begin() as conn:
+ remote = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="remote queued input",
+ metadata=_authorized_remote_message_metadata(),
+ )
+ local = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="local queued input",
+ metadata={
- session_turns.MEMORY_USER_ID_METADATA: "local",
- session_turns.MEMORY_ORDINARY_TEXT_METADATA: True,
++ message_deliveries.MEMORY_USER_ID_METADATA: "local",
++ message_deliveries.MEMORY_ORDINARY_TEXT_METADATA: True,
+ },
+ )
+
+ manager, runs = _manager_accepting_runs()
+ assert asyncio.run(manager.flush_queue(session["id"])) is True
+
+ assert [(text, source) for text, source, _context in runs] == [
+ ("remote queued input", SOURCE_HUMAN),
+ ]
+ with engine.connect() as conn:
+ remote_saved = message_deliveries.get_delivery(conn, remote["id"])
+ local_saved = message_deliveries.get_delivery(conn, local["id"])
+ assert remote_saved is not None
+ assert remote_saved["state"] == "accepted"
+ assert local_saved is not None
+ assert local_saved["state"] == "claimed"
+
+
+def test_claimed_authorized_remote_turn_reaches_native_dispatch(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ engine, session = _create_test_session(
+ tmp_path,
+ native_id="proj_remote_claimed_turn",
+ )
+ _seed_remote_worker()
+ turn_id = message_deliveries.new_turn_id()
+ with engine.begin() as conn:
+ queued = message_deliveries.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session["id"],
+ text="claimed remote input",
+ metadata=_authorized_remote_message_metadata(),
+ )
+ row = message_deliveries.get_delivery(conn, queued["id"])
+ assert row is not None
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session["id"],
+ backend="claude",
+ deliveries=[row],
+ dispatch_text="claimed remote input",
+ )
+
+ manager = session_turns.SessionTurnManager(
+ controller=types.SimpleNamespace(),
+ build_context=lambda sid: MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": sid},
+ ),
+ )
+
+ runs = []
+
+ async def capture_run(_session_id, _context, text, **_kwargs):
+ runs.append(text)
+
+ manager._run = capture_run
+ assert asyncio.run(manager._start_persisted_turn(turn_id)) is True
+ assert runs == ["claimed remote input"]
+
+ with engine.connect() as conn:
+ saved_turn = message_deliveries.get_turn(conn, turn_id)
+ saved_delivery = message_deliveries.get_delivery(conn, queued["id"])
+ assert saved_turn is not None
+ assert saved_turn["state"] == "starting"
+ assert saved_delivery is not None
+ assert saved_delivery["state"] == "claimed"
-
-
def test_flush_runs_scheduled_row_as_scheduled_with_provenance(tmp_path, monkeypatch):
"""A queued scheduled run flushes as its OWN SOURCE_SCHEDULED turn with its
delivery provenance restored — not merged into a plain user turn (#84)."""
diff --cc tests/test_ui_memory_routes.py
index d93987c4e,ccdd96216..534c4413f
--- a/tests/test_ui_memory_routes.py
+++ b/tests/test_ui_memory_routes.py
@@@ -16,11 -17,12 +17,26 @@@ from config.v2_config import
SlackConfig,
V2Config,
)
+ from core.memory.operation_lock import MemoryOperationLease
-from tests.ui_server_test_helpers import csrf_headers
+from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
from vibe import api, internal_client, remote_access, ui_memory_routes, ui_server
from vibe.ui_server import app
++def _active_org_member_cookie(config: V2Config, email: str, subject: str) -> str:
++ return remote_session_cookie(
++ config,
++ email,
++ subject,
++ role="viewer",
++ access_source="organization_group",
++ organization_id="org-1",
++ organization_member_id="member-1",
++ organization_role="member",
++ group_ids=[],
++ )
++
++
def _save_config(tmp_path) -> None:
V2Config(
mode="self_host",
@@@ -51,24 -62,20 +76,26 @@@ def _renewable_remote_session_cookie
email: str,
subject: str,
) -> str:
++ current = remote_session_cookie(
++ config,
++ email,
++ subject,
++ role="viewer",
++ access_source="organization_group",
++ organization_id="org-1",
++ organization_member_id=f"member-{subject}",
++ organization_role="member",
++ group_ids=[],
++ )
++ payload_text, _signature = current.rsplit(".", 1)
++ payload = json.loads(urllib.parse.unquote(payload_text))
expires_at = int(time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60
-- payload = {
-- "email": email,
-- "sub": subject,
-- "instance_id": config.remote_access.vibe_cloud.instance_id,
-- "iat": expires_at - remote_access.SESSION_TTL_SECONDS,
-- "exp": expires_at,
- "claims_issued_at": int(time.time()),
- "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,
- "vibe_instance_role": "owner",
- "vibe_instance_access_source": "owner",
-- }
-- payload_text = urllib.parse.quote(json.dumps(payload, separators=(",", ":")), safe="")
-- signature = remote_access._session_signature(
++ payload["iat"] = expires_at - remote_access.SESSION_TTL_SECONDS
++ payload["exp"] = expires_at
++ return remote_access._encode_session_cookie(
config.remote_access.vibe_cloud.session_secret,
-- payload_text,
++ payload,
)
-- return f"{payload_text}.{signature}"
def _local_headers() -> dict[str, str]:
@@@ -148,17 -489,7 +509,7 @@@ def test_memory_authenticated_avibe_clo
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(
- config,
- "user-1",
- role="viewer",
- access_source="organization_group",
- organization_id="org-1",
- organization_member_id="member-1",
- organization_role="member",
- group_ids=[],
- ),
- remote_access.make_session_cookie(config, "[email protected]", "user-1"),
++ _active_org_member_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
remote_headers = {"Origin": "https://alex.avibe.bot"}
@@@ -200,24 -540,13 +560,16 @@@
]
- def test_active_org_member_can_patch_memory_settings(monkeypatch, tmp_path) -> None:
-
-def test_memory_diagnostics_patch_is_rejected_for_remote_ui(monkeypatch, tmp_path) -> None:
++def test_active_org_member_memory_patch_rejects_retired_diagnostics_field(
++ monkeypatch,
++ tmp_path,
++) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_remote_config(tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(
- config,
- "user-1",
- role="viewer",
- access_source="organization_group",
- organization_id="org-1",
- organization_member_id="member-1",
- organization_role="member",
- group_ids=[],
- ),
- remote_access.make_session_cookie(config, "[email protected]", "user-1"),
++ _active_org_member_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
calls: list[bool] = []
@@@ -271,7 -601,7 +624,7 @@@ def test_memory_avibe_cloud_read_still_
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
- remote_access.make_session_cookie(config, "[email protected]", "user-1"),
++ _active_org_member_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
diff --cc ui/src/components/settings/SettingsMemoryPage.tsx
index 502ec2192,a0cd9575b..57eed6824
--- a/ui/src/components/settings/SettingsMemoryPage.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.tsx
@@@ -14,42 -15,28 +15,35 @@@ import { MemorySettingsPanel } from './
import { MemoryStatusPanel } from './memory/MemoryStatusPanel';
import { useMemoryResource } from './memory/useMemoryResource';
import { useApi } from '../../context/ApiContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import type {
- MemoryFailureLogEntry,
- MemoryFailureLogResult,
+ MemoryMaintenanceResult,
+ MemoryCascadeHealth,
+ MemoryProcessingRecordResult,
MemorySettingsResult,
MemoryStatus,
} from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
- import { memoryRuntimeRecoveryAvailable, memorySetupStage } from '../../lib/memorySettings';
import { memoryErrorMessage } from '../../lib/memoryRead';
+import { canAdministerMemory } from '../../lib/remoteAuth';
- type MemoryTab = 'status' | 'profile' | 'search' | 'log' | 'settings';
+ type MemoryTab = 'processingRecord' | 'profile' | 'search' | 'settings';
type MemorySettingsOk = Extract<MemorySettingsResult, { status: 'ok' }>;
- type MemoryFailureLogOk = Extract<MemoryFailureLogResult, { items: MemoryFailureLogEntry[] }>;
-
- const POLL_MS = 4000;
-
- const DEFAULT_FAILURE_RETENTION_DAYS = 90;
-
- // The failure log is the one Memory route that answers success untagged.
- const hasFailureItems = (value: unknown): boolean =>
- Array.isArray((value as { items?: unknown } | null | undefined)?.items);
+ type MemoryMaintenanceOk = Extract<MemoryMaintenanceResult, { status: 'ok' }>;
+ type MemoryProcessingRecordOk = Extract<MemoryProcessingRecordResult, { status: 'ok' }>;
export const SettingsMemoryPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
+ const { remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ const canAdminister = canAdministerMemory({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ });
- const [tab, setTab] = useState<MemoryTab>('status');
+ const [tab, setTab] = useState<MemoryTab>('processingRecord');
const [clearOpen, setClearOpen] = useState(false);
const [clearing, setClearing] = useState(false);
const [dependencyReady, setDependencyReady] = useState(true);
@@@ -170,32 -189,45 +196,48 @@@
}
};
+ const repairIndex = async () => {
+ if (settings?.enabled !== true || repairBusy || repairMutationBusy) return;
+ setRepairBusy(true);
+ setRepairError(null);
+ setRepairHealth(null);
+ try {
+ const res = await api.repairMemoryIndex();
+ if ('ok' in res && res.ok === true) {
+ setRepairHealth(res.health);
+ showToast(
+ res.result === 'completed'
+ ? t('memory.processingRecord.repair.completed')
+ : t('memory.processingRecord.repair.completedWithWarnings'),
+ res.result === 'completed' ? 'success' : 'warning',
+ );
+ await loadProcessingRecord();
+ } else {
+ setRepairError(memoryErrorMessage(t, 'error' in res ? res.error : undefined));
+ await loadProcessingRecord();
+ }
+ } catch {
+ setRepairError(t('memory.processingRecord.repair.failed'));
+ await loadProcessingRecord();
+ } finally {
+ setRepairBusy(false);
+ }
+ };
+
const tabs = useMemo(
() => [
- { id: 'status' as const, label: t('memory.tabs.status') },
+ { id: 'processingRecord' as const, label: t('memory.tabs.processingRecord') },
{ id: 'profile' as const, label: t('memory.tabs.profile') },
{ id: 'search' as const, label: t('memory.tabs.search') },
- { id: 'settings' as const, label: t('memory.tabs.settings') },
+ ...(canAdminister
- ? [
- { id: 'log' as const, label: t('memory.tabs.log') },
- { id: 'settings' as const, label: t('memory.tabs.settings') },
- ]
++ ? [{ id: 'settings' as const, label: t('memory.tabs.settings') }]
+ : []),
],
- [t],
+ [canAdminister, t],
);
++ const activeTab = tabs.some((entry) => entry.id === tab) ? tab : 'processingRecord';
- // A remote principal that deep-links to an administration tab lands on status
- // rather than on a panel whose reads and writes it cannot make.
- const activeTab = tabs.some((entry) => entry.id === tab) ? tab : 'status';
-
- const setupStage = memorySetupStage(runtimeInstalled, memoryEnabled);
- const runtimeRecoveryAvailable = memoryRuntimeRecoveryAvailable(runtimeInstalled, settings !== null);
- // Setup and runtime recovery exist to save settings, so they are unreachable
- // for a principal that cannot administer Memory at all.
- const administrationUnavailable =
- !canAdminister && (setupStage === 'runtime-required' || setupStage === 'setup');
-
+ const rebuildRequired = settings?.rebuild_required === true;
const settingsPanel = settings ? (
<MemorySettingsPanel
settings={settings}
@@@ -225,13 -264,7 +274,7 @@@
title={t('memory.title')}
subtitle={t('memory.subtitle')}
>
- {!remoteUnavailable &&
- canAdminister &&
- settings?.enabled === false &&
- status?.recorder?.reason === 'call_log_corrupt' ? (
- <MemoryRecorderFaultBanner status={status} onClearAll={() => setClearOpen(true)} />
- ) : null}
- {!remoteUnavailable && settings?.enabled === true ? (
+ {!remoteUnavailable && canAdminister && settings?.enabled === true ? (
<div className="flex justify-end">
<Button
variant="secondary"
@@@ -278,46 -294,79 +304,83 @@@
{t('memory.settings.loading')}
</div>
)
- ) : setupStage === 'setup' && settings ? (
- settingsPanel
) : (
<>
+ {runtimeInstalled === false ? (
+ <div className="flex flex-col items-start gap-3 rounded-lg border border-border bg-surface p-5">
+ <div className="flex items-center gap-2 text-[14px] font-semibold text-foreground">
+ <Brain className="size-4 text-violet" />
+ {t('memory.setup.runtimeRequired')}
+ </div>
+ <p className="text-[12.5px] text-muted">{t('memory.setup.runtimeRequiredHint')}</p>
+ <Button asChild variant="secondary" size="sm">
+ <Link to="/admin/settings/dependencies">
+ {t('memory.settings.goToDependencies')}
+ <ArrowUpRight className="size-3.5" />
+ </Link>
+ </Button>
+ </div>
+ ) : null}
<div data-testid="memory-tabs-scroll" className="max-w-full overflow-x-auto pb-1">
<div className="min-w-max">
- <SegmentedRadio value={tab} onChange={setTab} options={tabs} ariaLabel={t('memory.title')} tone="mint" />
+ <SegmentedRadio value={activeTab} onChange={setTab} options={tabs} ariaLabel={t('memory.title')} tone="mint" />
</div>
</div>
- {activeTab === 'status' && (
- <MemoryStatusPanel
- status={status}
- failures={failuresRead.data?.items ?? []}
- failureRetentionDays={failuresRead.data?.retention_days ?? DEFAULT_FAILURE_RETENTION_DAYS}
- failuresError={failuresRead.error}
- loading={!statusRead.loaded}
- error={statusRead.error}
- onRefresh={() => {
- void loadStatus();
- void loadFailures();
- }}
- onOpenSettings={canAdminister ? () => setTab('settings') : undefined}
- />
- )}
-
- {activeTab === 'profile' && <MemoryProfilePanel enabled={memoryEnabled} />}
- {tab === 'processingRecord' ? (
++ {activeTab === 'processingRecord' ? (
+ <div className="flex flex-col gap-6">
+ <MemoryStatusPanel
+ status={status}
+ failures={processingRecord?.anomalies.items ?? []}
+ recovery={processingRecord?.maintenance.clear_recovery ?? null}
+ logSections={processingRecord?.sources ?? null}
+ statusLoading={!processingRecordRead.loaded || processingRecordRead.loading}
+ failuresLoading={!processingRecordRead.loaded || processingRecordRead.loading}
+ statusError={processingRecordRead.error}
+ failuresError={
+ processingRecord?.anomalies.source.status === 'unavailable'
+ ? memoryErrorMessage(t, processingRecord.anomalies.source.reason)
+ : processingRecordRead.error
+ }
+ refreshPending={processingRecordRead.loading}
+ recoveryAction={recoveryAction}
+ onRefresh={refreshProcessingRecord}
- onResumeClear={(operationId) => void runClearRecovery('resume', operationId)}
- onAbortClear={(operationId) => void runClearRecovery('abort', operationId)}
- repairSupported={settings.enabled === true && settings.repair_available === true}
++ onResumeClear={(operationId) => {
++ if (canAdminister) void runClearRecovery('resume', operationId);
++ }}
++ onAbortClear={(operationId) => {
++ if (canAdminister) void runClearRecovery('abort', operationId);
++ }}
++ repairSupported={canAdminister && settings.enabled === true && settings.repair_available === true}
+ repairBusy={repairBusy}
+ mutationBusy={repairMutationBusy}
+ repairError={repairError}
+ repairHealth={repairHealth}
+ onRepair={() => void repairIndex()}
+ />
+ <section className="flex flex-col gap-2" aria-labelledby="memory-timeline-title">
+ <div className="flex items-center gap-1.5">
+ <h3 id="memory-timeline-title" className="text-[13px] font-semibold text-foreground">
+ {t('memory.processingRecord.timeline.title')}
+ </h3>
+ <InfoHint
+ label={t('memory.processingRecord.timeline.helpLabel')}
+ content={t('memory.processingRecord.timeline.help')}
+ />
+ </div>
+ <MemoryLogPanel
+ key={logGeneration}
+ refreshToken={logRefreshToken}
+ />
+ </section>
+ </div>
+ ) : null}
- {activeTab === 'search' && <MemorySearchPanel enabled={memoryEnabled} />}
- {tab === 'profile' && <MemoryProfilePanel enabled={!!settings?.enabled} />}
++ {activeTab === 'profile' && <MemoryProfilePanel enabled={!!settings?.enabled} />}
- {activeTab === 'log' && settings ? (
- <MemoryLogPanel
- key={logGeneration}
- enabled={settings.enabled}
- status={status}
- onClearAll={() => setClearOpen(true)}
- />
- ) : null}
- {tab === 'search' && <MemorySearchPanel enabled={!!settings?.enabled} />}
++ {activeTab === 'search' && <MemorySearchPanel enabled={!!settings?.enabled} />}
- {activeTab === 'settings' &&
- {tab === 'settings' &&
++ {canAdminister && activeTab === 'settings' &&
(!settingsRead.loaded && !settings ? (
<div className="flex items-center gap-2 px-1 text-sm text-muted">
<Loader2 className="size-4 animate-spin" />
diff --cc ui/src/components/workbench/ChatPage.tsx
index 03d37f4f8,51c04576d..42d1753b4
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@@ -28,18 -24,8 +28,14 @@@ import { isProxyMediaUrl } from '../../
import {
isVaultApprovalRequest,
placeVaultProvisionRequests,
- vaultRequestSourceMessageId,
- vaultRequestSourcePlatform,
- vaultRequestSourceRunId,
- vaultRequestSourceTurnId,
} from '../../lib/vaultRequestPlacement';
import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
+import {
+ showPageHeaderAccess,
+ showPageRestoreAccessDecision,
+ type ShowPageAccess,
+ type ShowPageAccessProbe,
+} from '../../lib/showPageAccess';
import { showPageEmbeddedPath } from '../../apps/showPageAvatar';
import { downloadFile, fileMeta } from '../../lib/filesApi';
import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/filePreview';
@@@ -347,9 -301,7 +339,8 @@@ export const ChatPage: React.FC = () =
// Derived rather than an effect on purpose: the fallback lands in the SAME
// render that flips ``readOnly``. An effect would first commit one frame with
// the chat surface still hidden and the iframe already gone — a blank chat.
- const showPageActive = isShowPageActive(readOnly, showPageMode);
+ const showPageAccessDenied = showPageRestoreAccess === 'deny';
+ const showPageActive = isShowPageActive(readOnly, showPageMode, showPageAccessDenied);
- const showPageActiveRef = useLatestRef(showPageActive);
// True while the share popover is open. The popover floats over the Show Page
// iframe; making the iframe inert lets an outside tap there reach the parent
// document so the (non-modal) popover dismisses, without modal-blocking the
@@@ -2779,9 -2411,11 +2495,9 @@@
// BEFORE the archive still holds them in state, though — the same
// stale-tab case that reaches the archived 409 — and their
// approve/deny buttons would write to a session that can't accept it.
- // Only access/sign approvals belong in this footer. Provision forms
- // are rendered next to their owning Agent message above.
- sessionId && !readOnly && canManageShowPage ? (
+ sessionId && !readOnly && (capabilities.can_manage_instance || canUseRuntime) ? (
<VaultChatRequests
- requests={transcriptTailVaultRequests}
+ requests={pendingApprovals}
onResolved={refreshVaultRequests}
onOffscreenApprovalsChange={setOffscreenApprovals}
/>
diff --cc ui/src/context/ApiContext.tsx
index 5ca70f911,766d67601..e54f53d5d
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@@ -22,9 -15,16 +23,17 @@@ import
} from '../lib/workbenchEventConnection';
import type { DockDoc } from './dockDoc';
import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';
+ import { parseMemoryFactoryResetResult } from '../lib/memoryFactoryReset';
+ import type { MemoryFactoryResetResult } from '../lib/memoryFactoryReset';
+ import {
+ SessionDraftPersistence,
+ type SessionDraftSaveResult,
+ type SessionDraftServerState,
+ type SessionDraftWrite,
+ } from '../lib/sessionDraftPersistence';
export type { InstanceCapabilities, SessionInfo };
+export type { ShowPageAccess };
// The workbench Dock API response shape ({ ok, dock }); the Dock document type
// itself lives with the DockProvider that owns reconciliation.
diff --cc ui/src/context/WorkbenchInboxProvider.tsx
index a2b457cc9,8339e1a6e..7d50335cf
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@@ -114,14 -328,29 +328,27 @@@ export const WorkbenchInboxProvider = (
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
// Clearing unread is best-effort, so a failure must not raise an error
- // toast: `POST /api/sessions/{id}/mark-read` is local-only, and a remote
- // viewer reading a session it is allowed to read auto-clears unread on
- // view. The mark-read CONTROLS are already trusted-local (`can_chat`);
- // this keeps the automatic write from surfacing
- // `remote_execution_disabled` to a legitimate remote reader.
+ // toast. Active Organization members are admitted by the temporary
+ // runtime policy; other remote principals can still read a permitted
+ // session without being allowed to mutate its unread state.
+ const operation = readOwnershipRef.current.beginRead(`inbox-mark-read:${sessionId}`);
const result = await api.markSessionRead(sessionId, untilMessageId, { handleError: false });
+ if (
+ !readOwnershipRef.current.isMutationCurrent(operation, `inbox-session:${sessionId}`)
+ ) {
+ return;
+ }
+ // A successful write commits after every read that was already in flight,
+ // even when one of those reads started later and returns last. The endpoint
+ // mutates only this session, so merge only that count; concurrent mark-read
+ // writes for other sessions remain independent.
+ readOwnershipRef.current.acceptMutation([
+ 'inbox-unread',
+ `inbox-unread-session:${sessionId}`,
+ ]);
// The unread map is authoritative for badges; the card's unread styling
// derives from it, so clearing here clears the dot without touching the
- // feed order (a read doesn't change last activity). A rejected write
- // carries no map — leave the badges as they are rather than blanking them.
+ // feed order (a read doesn't change last activity).
if (!result?.unread_by_session) return;
applyUnreadMap(result.unread_by_session);
},
diff --cc vibe/authorization.py
index 5bfb2bd5d,222a6a6f7..ec8f56f8d
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@@ -507,8 -355,9 +507,9 @@@ _REMOTE_LOCAL_ONLY_HTTP_RULES = tuple
("POST", r"^/api/sessions/[^/]+/mark-read$"),
(
"POST",
- r"^/api/sessions/[^/]+/(?:messages|attachments|cancel|queue/[^/]+/send-now)$",
+ r"^/api/sessions/[^/]+/(?:attachments|cancel|queue/[^/]+/send-now)$",
),
+ ("POST", r"^/api/projects$"),
("POST", r"^/api/asr/transcribe$"),
("POST", r"^/api/show/sessions/[^/]+/(?:events|prewarm)$"),
("GET", r"^/api/settings$"),
@@@ -545,103 -394,9 +543,106 @@@ _REMOTE_PAYLOAD_FILTERED_HTTP_RULES = t
)
)
-# Positive allowlist for remote-safe owner surfaces. Any route that mutates
-# local Agent, IM, Vault, or other execution state must stay absent here and
-# therefore use the fail-closed local-only default below.
+# Temporary unrestricted runtime surface for authenticated active Organization
+# members. This is deliberately an explicit route matrix: Organization auth,
+# membership, tunnel pairing, cloud-management, and unknown future API routes
+# still use their existing policy. The per-surface authorization model is
+# tracked in avibe#1313.
+_UNRESTRICTED_ORG_METHODS = frozenset({"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"})
+_TEMPORARY_UNRESTRICTED_ORG_HTTP_RULES = tuple(
+ (methods, re.compile(pattern))
+ for methods, pattern in (
+ # Settings, configuration, workbench preferences, and service control.
+ # Config responses use the local runtime projection with only the
+ # pairing/tunnel block removed.
+ (frozenset({"POST"}), r"^/api/config$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:settings|settings/thread|workbench/prefs|ui/reload)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:control|doctor|logs|upgrade)$"),
+ # The shell polls the process status and the setup pages use these
+ # local discovery/configuration helpers. They do not alter Organization
+ # identity, pairing, or tunnel state.
+ (_UNRESTRICTED_ORG_METHODS, r"^/status$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:cli/detect|slack/manifest)$"),
+ # Harness, Agent definitions, global prompts, and runtime diagnostics.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/harness/(?:counts|tasks|tasks/[^/]+|watches|watches/[^/]+|runs|runs/[^/]+|bootstrap)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/agents(?:/(?:default|import|[^/]+))?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:agent-backends|agents-graph|agent-onboarding|running-agents(?:/end)?)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/agent/[^/]+/install(?:/[^/]+)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/global-prompts$"),
+ # Skills mutations (read endpoints are viewer-allowed on origin/org).
+ (frozenset({"POST"}), r"^/api/skills$"),
+ (frozenset({"POST"}), r"^/api/skills/preview$"),
+ (frozenset({"POST", "DELETE"}), r"^/api/skills/(?:update|upload|[^/]+)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/dependencies(?:/[^/]+(?:/install(?:/[^/]+)?)?)?$"),
+ # Vault inventory, key material, secret CRUD, grants, approvals, and audit.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/vault/(?:secrets(?:/[^/]+(?:/reveal-context)?)?|tags|pubkey|agent/pubkey|sandbox/root-metadata|agent-bindings:batch|agent-binding|settings|vmk|authz/factors/webauthn(?:/options)?|signing-addresses|requests(?:/[^/]+(?:/(?:deny|fulfill-access))?)?|provision-requests(?:/(?:by-id/)?[^/]+)?|grants(?:/[^/]+)?|sign|pubkey-pin|audit)$"),
+ # Model Hub source/mapping/OAuth/runtime management.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/sources(?:/[^/]+(?:/(?:credential|reauth|refresh|models(?:/.*)?)?)?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/(?:agents|events)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/agents/(?:opencode/menu|[^/]+/(?:sources|mode|mappings|chain|probe))$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/turns/[^/]+/provenance$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/oauth/(?:start|status/[^/]+|submit|cancel)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/migration/(?:scan|apply)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/runtime/(?:status|start)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/sources/[^/]+/models(?:/.*)?$"),
+ # Memory administration.
- (_UNRESTRICTED_ORG_METHODS, r"^/api/memory/(?:settings|status|failures|profile|log|log/entry|search|runtime/restart|clear)$"),
++ (
++ _UNRESTRICTED_ORG_METHODS,
++ r"^/api/memory/(?:settings|status|processing-record|failures|maintenance|profile|log|log/entry|search|runtime/(?:restart|rebuild|factory-reset|repair)|clear(?:/(?:resume|abort))?)$",
++ ),
+ # Projects, sessions, chat execution, and ASR.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/projects(?:/[^/]+(?:/agents-md)?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/workbench/projects-bootstrap$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/sessions(?:/[^/]+(?:/(?:fork|cli-activity|cancel|mark-read|queue(?:/[^/]+(?:/send-now)?)?|draft|attachments))?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:search/messages|events|inbox)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/asr/(?:transcribe|telemetry|status)$"),
+ # Apps: Dock, Files, browse favorites, Terminal teardown, and Show Pages.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/dock(?:/pins(?:/[^/]+)?|/order)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/files/(?:list|meta|content|write|upload|mkdir|rename|move|copy|delete|delete/undo|search|search_names|search/replace|search/undo)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/media/[^/]+(?:/meta)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/browse(?:/favorites|/mkdir)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/terminal/[^/]+$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/show-pages(?:/[^/]+(?:/(?:visibility|ensure|access|authorized-emails|rotate-share|share-id|icon))?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/show/sessions/[^/]+/(?:events|prewarm)$"),
+ # Agent backends, provider setup, platform settings, and channel tools.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/backend/(?:codex|claude|opencode)/(?:runtime|restart)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/backend/(?:codex|claude)/auth$"),
+ (
+ _UNRESTRICTED_ORG_METHODS,
+ r"^/api/backend/(?:codex|claude|opencode)/auth/(?:oauth/(?:start|status/[^/]+|submit-code|cancel|remove)|api-key/remove|test)$",
+ ),
+ (
+ _UNRESTRICTED_ORG_METHODS,
+ r"^/api/backend/claude/auth/oauth/credentials/remove$",
+ ),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/backend/opencode/(?:providers|custom-provider(?:/[^/]+)?|default-provider|provider/[^/]+/(?:auth(?:/.*)?|test|models(?:/.*)?))$"),
+ (
+ _UNRESTRICTED_ORG_METHODS,
+ r"^/api/(?:opencode/(?:options|permission-status|setup-permission)|claude/(?:agents|models)|codex/(?:agents|models))$",
+ ),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:platforms|slack(?:/(?:auth_test|channels))?|discord/(?:auth_test|channels|guilds)|telegram/(?:auth_test|chats)|lark/(?:auth_test|chats|temp_ws/(?:start|stop))|wechat/qr_login/(?:start|poll)|channels/delete)$"),
+ # Push registration is a runtime notification surface.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/web-push/(?:status|vapid-public-key|subscriptions|test)$"),
+ # Local IM users and bind codes are part of the temporarily unrestricted
+ # runtime administration surface. This does not include Organization
+ # membership, Cloud pairing, or tunnel control routes.
+ (frozenset({"GET", "HEAD", "POST"}), r"^/api/users$"),
+ (frozenset({"POST"}), r"^/api/users/[^/]+/admin$"),
+ (frozenset({"DELETE"}), r"^/api/users/[^/]+$"),
+ (frozenset({"GET", "HEAD", "POST"}), r"^/api/bind-codes$"),
+ (frozenset({"DELETE"}), r"^/api/bind-codes/[^/]+$"),
+ (frozenset({"GET", "HEAD"}), r"^/api/setup/first-bind-code$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/resource-policies(?:/[^/]+/[^/]+)?$"),
+ )
+)
+
+# Compatibility name retained for callers/tests from the previous Apps-only
+# rollout. New code should use the unrestricted Organization matrix above.
+_TEMPORARY_ORGANIZATION_APP_HTTP_RULES = _TEMPORARY_UNRESTRICTED_ORG_HTTP_RULES
+
+# Compatibility allowlist for remote identities outside the temporary active
+# Organization rollout. The unrestricted active-member matrix is evaluated
+# first; unknown routes still use the fail-closed local-only default below.
_REMOTE_OWNER_ALLOWED_HTTP_RULES = tuple(
(methods, re.compile(pattern))
for methods, pattern in (
diff --cc vibe/ui_server.py
index 766d59f85,bb21b2028..e0bd22da0
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@@ -8964,14 -8447,14 +8989,18 @@@ async def sessions_bootstrap(session_id
if can_chat
else []
)
- can_access_draft = can_chat and not bool(
- authorization_context and authorization_context.is_remote
+ from vibe.authorization import has_temporary_unrestricted_runtime_access
+
+ can_access_draft = can_chat and not (
+ authorization_context
+ and authorization_context.is_remote
+ and not has_temporary_unrestricted_runtime_access(authorization_context)
)
- draft = message_deliveries.get_draft(conn, session_id) if can_access_draft else None
+ draft = (
+ message_deliveries.get_draft_state(conn, session_id)
+ if can_access_draft
+ else None
+ )
agents_payload = {"agents": [], "default_agent_name": None}
if can_chat:
@@@ -12596,12 -12173,30 +12759,33 @@@ def _sanitize_public_show_event_payload
return sanitized
+ def _show_annotation_capability(
+ *,
+ author: dict[str, str] | None,
+ page: ShowPage,
+ public_share_id: str | None = None,
+ ) -> bool:
+ """Return whether this request may write and dispatch Show annotations.
+
+ The current device-side authorization boundary is the validated Workbench
+ session (or trusted local access), represented by ``author``. Page
+ visibility and the share/session binding remain independent structural
+ checks so a future ACL can extend the author decision without changing the
+ event pipeline.
+ """
+ if author is None or page.visibility == VISIBILITY_OFFLINE:
+ return False
+ if public_share_id is not None:
+ return page.visibility == VISIBILITY_PUBLIC and page.share_id == public_share_id
+ return page.visibility in {VISIBILITY_PRIVATE, VISIBILITY_PUBLIC}
+
+
def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
from vibe import remote_access
- from vibe.authorization import context_from_session_payload
+ from vibe.authorization import (
+ context_from_session_payload,
+ has_temporary_unrestricted_runtime_access,
+ )
if not public:
context = getattr(g, "authorization_context", None)
@@@ -12685,23 -12277,10 +12875,14 @@@ async def _show_event_response_from_pay
# callers keep the full supported set.
event_type = str(payload.get("type") or "").strip()
if event_type not in HUMAN_EVENT_TYPES and event_type != "assistant.mark.resolved":
- return (
- jsonify(
- {
- "ok": False,
- "code": "unsupported_event_type",
- "error": "Remote Show Page writes require a supported human event or mark resolution type.",
- }
- ),
- 400,
- )
+ return _unsupported_show_event_type_response()
- # The echo of the stored event goes back to whoever posted it, so a remote
- # author must not learn the local screenshot path from its own response.
- remote = not public and _is_remote_show_page_request()
+ # Non-member remote readers keep the host-path redaction. Active
+ # Organization members receive the same runtime detail as local callers.
+ remote = (
+ not public
+ and _is_remote_show_page_request()
+ and not _has_temporary_runtime_access(context)
+ )
if show_event_payload_session_mismatch(session_id, payload):
return (
jsonify(