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
merge(pr1162): sync master into integration
Max4c3f9239bab1
diff --cc tests/test_ui_session_stream.pyindex f006ae748,c299392b0..545f86244--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@@ -218,9 -233,12 +223,12 @@@ def test_route_fire_and_forgets_dispatcpayload = response.get_json()assert payload["author"] == "user"assert payload["author_id"] == "remote:user-a"- assert payload["metadata"]["_web_push_user_key"] == "remote:user-a"+ assert "_web_push_user_key" not in payload["metadata"]assert payload["metadata"]["_memory_cli_admitted"] is Falseassert payload["text"] == "no stream"+ assert payload["draft_advanced"] is True+ assert payload["draft"]["text"] == ""+ assert payload["draft"]["updated_at"] not in (None, saved_draft["updated_at"])# The turn was kicked off fire-and-forget with the session + text.dispatch_mock.assert_awaited_once()sent = dispatch_mock.await_args.args[0]@@@ -1173,128 -1191,119 +1185,239 @@@ def test_chat_bootstrap_returns_first_sassert body["turn_state"]["connection"] == "connected"+def test_chat_bootstrap_filters_non_backend_activities_for_remote_context(isolated_state, tmp_path):+ from vibe.ui_server import app++ monkeypatch = pytest.MonkeyPatch()+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ from tests.test_ui_memory_routes import _save_remote_config++ config = _save_remote_config(tmp_path)+ _, session_id = _make_session(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 projected(_session_id):+ return {+ "status_code": 200,+ "body": {+ "in_flight": False,+ "foreground": "idle",+ "pending_input_count": 0,+ "background_activities": [+ {+ "id": "backend-1",+ "item_kind": "backend_activity",+ "label": "Waiting for approval",+ "status": "running",+ },+ {+ "id": "task-1",+ "item_kind": "task",+ "label": "private prompt head",+ "status": "scheduled",+ },+ ],+ "pending_activity_output_count": 1,+ "connection": "reconnecting",+ },+ }++ with (+ patch("vibe.internal_client.turn_state", projected),+ patch(+ "vibe.api.get_vibe_agents",+ return_value={+ "agents": [{"name": "worker", "backend": "claude", "enabled": True}],+ "default_agent_name": "worker",+ },+ ),+ ):+ response = client.get(+ f"/api/sessions/{session_id}/bootstrap",+ base_url="https://alex.avibe.bot",+ environ_base={"REMOTE_ADDR": "203.0.113.10"},+ )+ monkeypatch.undo()++ assert response.status_code == 200+ body = response.get_json()+ assert [item["id"] for item in body["turn_state"]["background_activities"]] == ["backend-1"]+ assert body["turn_state"]["background_activities"][0]["label"] == "Waiting for approval"+++def test_turn_state_route_filters_non_backend_activities_for_remote_context(isolated_state, tmp_path):+ from vibe.ui_server import app++ monkeypatch = pytest.MonkeyPatch()+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ from tests.test_ui_memory_routes import _save_remote_config++ config = _save_remote_config(tmp_path)+ _, session_id = _make_session(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 projected(session_id_inner):+ assert session_id_inner == session_id+ return {+ "status_code": 200,+ "body": {+ "in_flight": False,+ "foreground": "idle",+ "pending_input_count": 0,+ "background_activities": [+ {+ "id": "backend-1",+ "item_kind": "backend_activity",+ "label": "Waiting for approval",+ "status": "running",+ },+ {+ "id": "watch-1",+ "item_kind": "watch",+ "label": "private waiter prompt",+ "status": "enabled",+ },+ ],+ "pending_activity_output_count": 1,+ "connection": "reconnecting",+ },+ }++ with patch("vibe.internal_client.turn_state", projected):+ response = client.get(+ f"/api/sessions/{session_id}/turn-state",+ base_url="https://alex.avibe.bot",+ environ_base={"REMOTE_ADDR": "203.0.113.10"},+ )+ monkeypatch.undo()++ assert response.status_code == 200+ body = response.get_json()+ assert [item["id"] for item in body["background_activities"]] == ["backend-1"]+ assert body["background_activities"][0]["label"] == "Waiting for approval"++ def test_session_draft_compare_and_set_protects_newer_writes_and_clears(+ isolated_state,+ tmp_path,+ ):+ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)+ client = app.test_client()+ headers = csrf_headers(client)+ path = f"/api/sessions/{session_id}/draft"++ created = client.put(+ path,+ json={"text": "first", "expected_updated_at": None},+ headers=headers,+ )+ assert created.status_code == 200+ created_draft = created.get_json()["draft"]+ assert created_draft["text"] == "first"+ first_revision = created_draft["updated_at"]+ assert first_revision is not None++ fetched = client.get(path)+ assert fetched.status_code == 200+ assert fetched.get_json() == created_draft++ stale = client.put(+ path,+ json={"text": "stale", "expected_updated_at": None},+ headers=headers,+ )+ assert stale.status_code == 409+ assert stale.get_json() == {+ "ok": False,+ "code": "draft_conflict",+ "draft": created_draft,+ }++ revisionless = client.put(+ path,+ json={"text": "legacy overwrite"},+ headers=headers,+ )+ assert revisionless.status_code == 409+ assert revisionless.get_json() == {+ "ok": False,+ "code": "draft_conflict",+ "draft": created_draft,+ }++ updated = client.put(+ path,+ json={"text": "second", "expected_updated_at": first_revision},+ headers=headers,+ )+ assert updated.status_code == 200+ updated_draft = updated.get_json()["draft"]+ assert updated_draft["text"] == "second"+ second_revision = updated_draft["updated_at"]+ assert second_revision not in (None, first_revision)++ cleared = client.put(+ path,+ json={"text": "", "expected_updated_at": second_revision},+ headers=headers,+ )+ assert cleared.status_code == 200+ cleared_draft = cleared.get_json()["draft"]+ assert cleared_draft["text"] == ""+ assert cleared_draft["updated_at"] not in (None, second_revision)++ resurrect = client.put(+ path,+ json={"text": "resurrected", "expected_updated_at": second_revision},+ headers=headers,+ )+ assert resurrect.status_code == 409+ assert resurrect.get_json()["draft"] == cleared_draft+++ def test_session_draft_reserves_writer_before_cas_reads(isolated_state, tmp_path):+ from core.services import sessions as sessions_service+ from storage.agent_session_rows import reserve_write_lock as real_reserve_write_lock+ from vibe.ui_server import app++ real_get_session = sessions_service.get_session+ _, session_id = _make_session(tmp_path)+ client = app.test_client()+ headers = csrf_headers(client)+ calls = []++ def reserve_write_lock(conn):+ calls.append("write_lock")+ return real_reserve_write_lock(conn)++ def get_session(conn, target_session_id):+ calls.append("session_read")+ return real_get_session(conn, target_session_id)++ with (+ patch("storage.agent_session_rows.reserve_write_lock", reserve_write_lock),+ patch("core.services.sessions.get_session", get_session),+ ):+ response = client.put(+ f"/api/sessions/{session_id}/draft",+ json={"text": "serialized", "expected_updated_at": None},+ headers=headers,+ )++ assert response.status_code == 200+ assert calls[:2] == ["write_lock", "session_read"]-def test_queue_row_send_now_passes_the_exact_delivery_id(isolated_state, tmp_path):from vibe.ui_server import appdiff --cc ui/src/components/AppShell.tsxindex 06099e231,4a8bbae8b..fa1caa713--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@@ -1,6 -1,6 +1,6 @@@import React, { useEffect, useState } from 'react';-import { Link, NavLink, Outlet, useLocation } from 'react-router-dom';-import { AlertTriangle, ArrowLeft, Bot, Brain, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';+import { Link, Navigate, NavLink, Outlet, useLocation } from 'react-router-dom';- import { ArrowLeft, Bot, Brain, Building2, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';++import { AlertTriangle, ArrowLeft, Bot, Brain, Building2, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inbox, LayoutDashboard, LayoutGrid, Link as LinkIcon, Menu, MessageCircle, PlugZap, Plus, Settings, Sparkles, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';@@@ -364,35 -352,8 +394,35 @@@ export const AppShell: React.FC = () =const modelHubEnabled = modelHubEnabledFromConfig(config);const isRunning = status.state === 'running';+ const ownerOnlyPath =+ location.pathname === '/setup' ||+ (location.pathname.startsWith('/admin') && !location.pathname.startsWith('/admin/organization')) ||+ ['/agents', '/harness', '/apps/library'].some(+ (path) => location.pathname === path || location.pathname.startsWith(`${path}/`),+ );+ // Owner is not enough for these: `can_manage_instance` stays true for a remote+ // Instance owner, but every one of them runs on local-only routes. The list+ // and its rationale live in `isLocalSystemPath` so this redirect and the+ // navigation entries below cannot drift apart.+ const localSystemPath = isLocalSystemPath(location.pathname);+ const resourceUseDenied =+ (location.pathname.startsWith('/skills') && !capabilities.can_use_skills) ||+ (location.pathname.startsWith('/vaults') && !capabilities.can_use_vault_secrets);+ const fileOnlyPath =+ location.pathname.startsWith('/apps/files') || location.pathname.startsWith('/apps/editor');+ const terminalOnlyPath = location.pathname.startsWith('/apps/terminal');+ if (+ (ownerOnlyPath && !capabilities.can_manage_instance) ||+ (localSystemPath && !capabilities.can_use_system) ||+ resourceUseDenied ||+ (fileOnlyPath && !capabilities.can_use_files) ||+ (terminalOnlyPath && !capabilities.can_use_terminal)+ ) {+ return <Navigate to="/" replace />;+ }+if (location.pathname === '/setup') {- return <Outlet />;+ return <><ConfigRecoveryNotice config={config} /><Outlet /></>;}// Two shell modes share the same chrome (brand + bottom status):diff --cc ui/src/components/workbench/ChatPage.tsxindex 2d84055ec,307f776a0..51c04576d--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@@ -462,30 -440,7 +447,13 @@@ export const ChatPage: React.FC = () =// can still read the current transcript without listing ``messages`` as a dep.const messagesRef = useRef(messages);messagesRef.current = messages;- const vaultAnchorFetchesRef = useRef<Set<string>>(new Set());- const vaultAnchorRetryAttemptsRef = useRef<Map<string, number>>(new Map());- const vaultAnchorRetryExhaustedRef = useRef<Set<string>>(new Set());- const vaultAnchorRetryWaitingRef = useRef<Set<string>>(new Set());- const vaultAnchorInFlightRef = useRef(false);- const vaultAnchorMergeRef = useRef<{- anchorMessageId: string;- nextBeforeId: string | null;- result: ReturnType<typeof mergeAnchorWindow>;- } | null>(null);const deepLinkWindowHandledRef = useRef(false);- const [vaultAnchorCycle, setVaultAnchorCycle] = useState(0);- const markVaultRequestHidden = useCallback((requestId: string) => {- hiddenVaultRequestIdsRef.current.add(requestId);- // A user dismissal is an explicit retry boundary for deferred or exhausted- // anchors, so a later request can try again immediately.- vaultAnchorRetryAttemptsRef.current.clear();- vaultAnchorRetryExhaustedRef.current.clear();- vaultAnchorRetryWaitingRef.current.clear();- // A deferred request is intentionally left un-fetched while another card- // owns the visible historical window. Hiding that card is the state change- // that makes the deferred request eligible for its next anchor attempt.- setVaultAnchorCycle((cycle) => cycle + 1);++ const markVaultRequestHidden = useCallback((_requestId: string) => {++ // The merged provision flow keeps inline provision cards beside their++ // owning replies, so hiding a request no longer needs extra local anchor++ // bookkeeping. Keep the provider hook for compatibility and future++ // extension, but make the callback a stable no-op here.+ }, []);const denyVaultProvisionRequest = useCallback(async (requestId: string) => {try {@@@ -1468,16 -1154,8 +1171,9 @@@// while the URL is already on the new chat (Codex P2). Nulling it shows the// loading state until refresh() resolves the new session.setSession(null);+ setSessionCanChat(false);setMessages([]);- setVaultResolvedSourceIds(new Map());- vaultAnchorFetchesRef.current.clear();- vaultAnchorRetryAttemptsRef.current.clear();- vaultAnchorRetryExhaustedRef.current.clear();- vaultAnchorRetryWaitingRef.current.clear();- vaultAnchorInFlightRef.current = false;deepLinkWindowHandledRef.current = false;- hiddenVaultRequestIdsRef.current.clear();setOlderCursor(null);setHistoricalWindow(false);oldestLoadedIdRef.current = null;@@@ -1865,13 -1554,14 +1584,14 @@@void syncTurnStateRef.current?.();setWorking(false);setError(errorMessage(err) ?? String(err));- // Signal the composer the send didn't start so it restores the text +- // uploaded chips — the user can retry without re-uploading (Codex r5).- return false;}+ // Recovery belongs to the original session, while UI mutation is gated+ // above. Returning false also lets an unmounted old Composer persist its+ // submitted text after navigation.+ return false;}},- [sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages, convergeSessionArchived, t, writable],- [sessionId, api, appendMessage, refreshQueue, markWorking, reloadLatestMessages, t],++ [sessionId, api, appendMessage, refreshQueue, markWorking, reloadLatestMessages, t, writable],);// @ mention source: all enabled Agents, filtered client-side (the set is small@@@ -2695,9 -2369,11 +2411,11 @@@// 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 ? (+ sessionId && !readOnly && canManageShowPage ? (<VaultChatRequests- requests={transcriptTailVaultRequests}+ requests={pendingApprovals}onResolved={refreshVaultRequests}onOffscreenApprovalsChange={setOffscreenApprovals}/>diff --cc ui/src/context/ApiContext.tsxindex 0a46f5db8,24db38abd..dc81da79d--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@@ -14,9 -12,13 +14,15 @@@ import} from '../lib/workbenchEventConnection';import type { DockDoc } from './dockDoc';import { archivedConflictSessionId, selectApiErrorFields } from './apiErrorParse';+ import {+ SessionDraftPersistence,+ type SessionDraftSaveResult,+ type SessionDraftServerState,+ type SessionDraftWrite,+ } from '../lib/sessionDraftPersistence';+export type { InstanceCapabilities, SessionInfo };+// The workbench Dock API response shape ({ ok, dock }); the Dock document type// itself lives with the DockProvider that owns reconciliation.export type DockResponse = { ok: boolean; dock: DockDoc };@@@ -3584,10 -3706,10 +3770,10 @@@ export const ApiProvider: React.FC<{ chgetRemoteAccessNetworkInterfaces: () => getJson('/api/remote-access/network-interfaces'),saveRemoteAccessSettings: (settings) => postJson('/api/remote-access/settings', settings),diagnoseRemoteAccess: () => postJson('/api/remote-access/diagnostics', {}),- getAuthSession: () => getJson('/api/session'),+ getAuthSession: () => getJson('/api/session').then(normalizeSessionInfo),signOut: () => postJson('/auth/logout', {}),// eslint-disable-next-line react-hooks/exhaustive-deps- }), [showToast, t]);+ }), [sessionDraftPersistence, showToast, t]);return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;};diff --cc ui/src/context/WorkbenchInboxProvider.tsxindex 68f873176,62663e7ff..8339e1a6e--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@@ -113,21 -327,27 +327,34 @@@ 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.+ const operation = readOwnershipRef.current.beginRead(`inbox-mark-read:${sessionId}`);- const result = await api.markSessionRead(sessionId, untilMessageId);+ 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).- applySessionUnread(sessionId, result.unread_by_session?.[sessionId] ?? 0);+ if (!result?.unread_by_session) return;+ applyUnreadMap(result.unread_by_session);},- [api, applySessionUnread],+ [api, applyUnreadMap],);// Resume reconcile: re-read the feed WITHOUT collapsing pagination. A@@@ -214,10 -520,9 +527,12 @@@void reconcile();}const disconnect = api.connectWorkbenchEvents({+ onAuthorizationChanged: () => {+ void refresh();+ },onInboxSessionUpdated: (row) => {+ targetedSnapshotsRef.current.delete(row.session_id);+ acceptSessionMutation(row.session_id);setInboxSessions((prev) => upsertSession(prev, row));setUnreadBySession((prev) => {if ((prev[row.session_id] ?? 0) === row.unread_count) return prev;diff --cc ui/src/context/WorkbenchProjectsProvider.tsxindex abe21c755,53e80af68..7603b58eb--- a/ui/src/context/WorkbenchProjectsProvider.tsx+++ b/ui/src/context/WorkbenchProjectsProvider.tsx@@@ -118,23 -122,69 +122,85 @@@ export const WorkbenchProjectsProvider// reconcile per project so they can't race or truncate an append.const inFlightRef = useRef<Set<string>>(new Set());const pendingReconcileRef = useRef<Map<string, number>>(new Map());+ const sessionProjectRef = useRef<Map<string, string>>(new Map());+ const cachedRowRefreshInFlightRef = useRef<Set<string>>(new Set());+ const pendingCachedRowRefreshRef = useRef<Set<string>>(new Set());+ // All reads owned by this provider share one ordering fence. A bootstrap,+ // paginated read, or targeted row read that started before a newer mutation+ // must not commit its snapshot after that mutation is accepted.+ const readOwnershipRef = useRef(createWorkbenchSessionReadOwnership());+ // Initial/manual project fetches and reconnect bootstraps claim the same+ // global resources. Serialize them and retain trailing intents so a later+ // failed recovery cannot invalidate an earlier successful snapshot.+ const bootstrapReadInFlightRef = useRef(false);+ const fetchProjectsPendingRef = useRef<{ cache?: boolean } | null>(null);+ const projectTreePendingRef = useRef(false);+ const fetchProjectsRunnerRef = useRef<(options?: { cache?: boolean }) => void>(() => {});+ const projectTreeRunnerRef = useRef<() => void>(() => {});++ const flushBootstrapReadIntent = useCallback(() => {+ if (bootstrapReadInFlightRef.current) return;+ const pendingFetch = fetchProjectsPendingRef.current;+ if (pendingFetch) {+ fetchProjectsPendingRef.current = null;+ fetchProjectsRunnerRef.current(pendingFetch);+ return;+ }+ if (projectTreePendingRef.current) {+ projectTreePendingRef.current = false;+ projectTreeRunnerRef.current();+ }+ }, []);++ const queueFetchProjectsIntent = useCallback((options?: { cache?: boolean }) => {+ const pending = fetchProjectsPendingRef.current;+ fetchProjectsPendingRef.current =+ options?.cache === false || pending?.cache === false+ ? { cache: false }+ : pending ?? options ?? {};+ queueMicrotask(flushBootstrapReadIntent);+ }, [flushBootstrapReadIntent]);++ const queueProjectTreeIntent = useCallback(() => {+ projectTreePendingRef.current = true;+ queueMicrotask(flushBootstrapReadIntent);+ }, [flushBootstrapReadIntent]);++ const acceptSessionMutation = useCallback((projectId?: string | null, sessionId?: string) => {+ const resources = ['projects-bootstrap'];+ if (projectId) resources.push(`project:${projectId}`);+ if (sessionId) resources.push(`project-session:${sessionId}`);+ readOwnershipRef.current.acceptMutation(resources);+ }, []);++ const acceptProjectsMutation = useCallback(() => {+ readOwnershipRef.current.acceptMutation('projects');+ }, []);++ const projectIdForSession = useCallback((sessionId: string): string | null => {+ const known = sessionProjectRef.current.get(sessionId);+ if (known) return known;+ return Object.entries(sessionsRef.current).find(([, state]) =>+ state.sessions?.some((session) => session.id === sessionId),+ )?.[0] ?? null;+ }, []);+ const applyProjectsSnapshot = useCallback((nextProjects: WorkbenchProject[]) => {+ const accessibleIds = new Set(nextProjects.map((project) => project.id));+ projectsRef.current = nextProjects;+ setProjects(nextProjects);+ setSessions((prev) =>+ Object.fromEntries(+ Object.entries(prev).filter(([projectId]) => accessibleIds.has(projectId)),+ ),+ );+ setExpanded((prev) => new Set([...prev].filter((projectId) => accessibleIds.has(projectId))));+ setCreating((prev) => new Set([...prev].filter((projectId) => accessibleIds.has(projectId))));+ for (const projectId of [...pendingReconcileRef.current.keys()]) {+ if (!accessibleIds.has(projectId)) pendingReconcileRef.current.delete(projectId);+ }+ }, []);+const queueReconcile = useCallback((projectId: string, minCount = 0) => {const pending = pendingReconcileRef.current.get(projectId) ?? 0;pendingReconcileRef.current.set(projectId, Math.max(pending, minCount));@@@ -164,20 -230,52 +246,52 @@@}return changed ? next : prev;});- }, []);+ }, [acceptProjectRows]);const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {+ if (bootstrapReadInFlightRef.current) {+ queueFetchProjectsIntent(options);+ return;+ }+ bootstrapReadInFlightRef.current = true;+ const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);+ const retryAfterMutation = () => {+ if (readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) return;+ // Upgrade any already-pending cached fetch to the authoritative retry.+ queueFetchProjectsIntent({ cache: false });+ };try {const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });- applyProjectsSnapshot(result.projects);- applyBootstrapSessions(result.sessions ?? {});+ const projectsCurrent = readOwnershipRef.current.isCurrent(read, 'projects');- if (projectsCurrent) setProjects(result.projects);++ if (projectsCurrent) applyProjectsSnapshot(result.projects);+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {+ retryAfterMutation();+ return;+ }+ const pages = Object.fromEntries(+ Object.entries(result.sessions ?? {}).filter(([projectId]) =>+ readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]),+ ),+ );+ applyBootstrapSessions(read, pages);+ if (!projectsCurrent) {+ retryAfterMutation();+ return;+ }setProjectsError(null);} catch (err) {// Don't strand consumers on an empty-state for a transient failure — keep// any list we had and surface the error (mobile shows a retry).- setProjectsError(errorMessage(err) ?? String(err));+ if (readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) {+ setProjectsError(errorMessage(err) ?? String(err));+ } else {+ retryAfterMutation();+ }+ } finally {+ bootstrapReadInFlightRef.current = false;+ flushBootstrapReadIntent();}- }, [api, applyBootstrapSessions, applyProjectsSnapshot]);- }, [api, applyBootstrapSessions, flushBootstrapReadIntent, queueFetchProjectsIntent]);++ }, [api, applyBootstrapSessions, applyProjectsSnapshot, flushBootstrapReadIntent, queueFetchProjectsIntent]);useEffect(() => {void fetchProjects();@@@ -212,7 -312,10 +328,11 @@@beforeId: before,cache: false,});+ if (!projectsRef.current?.some((project) => project.id === projectId)) return;+ if (!readOwnershipRef.current.isCurrent(read, `project:${projectId}`)) {+ stale = true;+ break;+ }for (const s of res.sessions) {if (!seen.has(s.id)) {seen.add(s.id);@@@ -262,7 -379,7 +396,7 @@@const groups = Array.from(bootstrapGroups.entries());if (groups.length === 0) {const result = await api.getWorkbenchProjectsBootstrap({ cache: false });- applyProjectsSnapshot(result.projects);- if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjects(result.projects);++ if (readOwnershipRef.current.isCurrent(read, 'projects')) applyProjectsSnapshot(result.projects);} else {let nextProjects: WorkbenchProject[] | null = null;const pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null }> = {};@@@ -283,10 -409,19 +426,21 @@@}}}- if (nextProjects) applyProjectsSnapshot(nextProjects);- applyBootstrapSessions(pages);- if (readOwnershipRef.current.isCurrent(read, 'projects') && nextProjects) setProjects(nextProjects);++ if (readOwnershipRef.current.isCurrent(read, 'projects') && nextProjects) {++ applyProjectsSnapshot(nextProjects);++ }+ const currentPages = Object.fromEntries(+ Object.entries(pages).filter(([projectId]) =>+ readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]),+ ),+ );+ applyBootstrapSessions(read, currentPages);}- setProjectsError(null);+ if (!readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) {+ retryAfterInvalidation(read);+ return;+ }+ if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(null);for (const projectId of largeProjectIds) {void reconcileSessions(projectId);}@@@ -296,19 -435,51 +454,51 @@@for (const projectId of [...projectIds, ...largeProjectIds]) {void reconcileSessions(projectId);}+ } finally {+ bootstrapReadInFlightRef.current = false;+ flushBootstrapReadIntent();}- }, [api, applyBootstrapSessions, applyProjectsSnapshot, queueReconcile, reconcileSessions]);- }, [api, applyBootstrapSessions, flushBootstrapReadIntent, queueProjectTreeIntent, queueReconcile, reconcileSessions]);++ }, [api, applyBootstrapSessions, applyProjectsSnapshot, flushBootstrapReadIntent, queueProjectTreeIntent, queueReconcile, reconcileSessions]);- const refreshCachedSessionRow = useCallback(async (sessionId: string) => {- const needsRefresh = Object.values(sessionsRef.current).some((state) =>- state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),- );- if (!needsRefresh) return;+ fetchProjectsRunnerRef.current = (options) => void fetchProjects(options);+ projectTreeRunnerRef.current = () => void reconcileProjectTree();++ const refreshCachedSessionRow = useCallback(async function refreshCachedSessionRow(sessionId: string) {+ if (cachedRowRefreshInFlightRef.current.has(sessionId)) {+ pendingCachedRowRefreshRef.current.add(sessionId);+ return;+ }+ cachedRowRefreshInFlightRef.current.add(sessionId);try {- const updated = await api.getSession(sessionId, { cache: false });- setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));- } catch {- /* best-effort: reconnect reconcile will refresh the row later */+ while (true) {+ pendingCachedRowRefreshRef.current.delete(sessionId);+ const projectId = Object.entries(sessionsRef.current).find(([, state]) =>+ state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),+ )?.[0];+ if (!projectId) return;+ const resource = `project-session:${sessionId}`;+ const read = readOwnershipRef.current.beginRead(resource);+ let stale = false;+ try {+ const updated = await api.getSession(sessionId, { cache: false });+ stale = !readOwnershipRef.current.isCurrent(read, resource);+ if (!stale) {+ sessionProjectRef.current.set(updated.id, projectId);+ setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));+ return;+ }+ } catch {+ stale = !readOwnershipRef.current.isCurrent(read, resource);+ if (!stale && !pendingCachedRowRefreshRef.current.has(sessionId)) return;+ /* current best-effort failures are recovered by reconnect reconcile */+ }+ if (!stale && !pendingCachedRowRefreshRef.current.has(sessionId)) return;+ }+ } finally {+ cachedRowRefreshInFlightRef.current.delete(sessionId);+ if (pendingCachedRowRefreshRef.current.delete(sessionId)) {+ queueMicrotask(() => void refreshCachedSessionRow(sessionId));+ }}}, [api]);@@@ -327,12 -498,22 +517,23 @@@[projectId]: append ? { ...cur, loadingMore: true } : { ...cur, loading: true, error: false },};});+ const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;+ const read = readOwnershipRef.current.beginRead(`project:${projectId}`);+ let retryAfterInvalidation = false;try {- const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId });+ if (!projectsRef.current?.some((project) => project.id === projectId)) return;+ const currentRead = readOwnershipRef.current.isCurrent(read, `project:${projectId}`);+ retryAfterInvalidation = !currentRead && readOwnershipRef.current.isLatestRead(read);+ if (currentRead) acceptProjectRows(read, projectId, res.sessions);setSessions((prev) => {const cur = prev[projectId] ?? EMPTY_SESSIONS;+ if (!currentRead) {+ return {+ ...prev,+ [projectId]: append ? { ...cur, loadingMore: false } : { ...cur, loading: false },+ };+ }const existing = append ? cur.sessions ?? [] : [];// Cursor pages can overlap if a row's last_active_at shifts between// fetches (the cursor is just a row id resolved against current@@@ -374,11 -568,14 +588,17 @@@onConnected: () => {void reconcileProjectTree();},+ onAuthorizationChanged: () => {+ void reconcileProjectTree();+ },onSessionActivity: (data) => {+ const projectId =+ projectsRef.current?.find((project) => project.scope_id === data.scope_id)?.id ??+ projectIdForSession(data.session_id);+ if (projectId) sessionProjectRef.current.set(data.session_id, projectId);+ acceptSessionMutation(projectId, data.session_id);if (data.event === 'archived') {+ sessionProjectRef.current.delete(data.session_id);// Terminal archive (here or in another tab) — drop the row live.setSessions((prev) => removeSessionRow(prev, data.session_id));return;diff --cc ui/src/i18n/en.jsonindex aa36416a8,a3444f8b8..c558ac771--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@@ -2993,7 -3201,9 +3241,8 @@@"mode": "Mode","followUp": "Follow-up message","runtime": "Runtime",- "eventProcessing": "Event processing","lastError": "Last error",+ "pauseReason": "Pause reason","type": "Type","triggeredBy": "Triggered by","result": "Result",diff --cc ui/src/i18n/zh.jsonindex 6916c43ba,998d1161f..c3e40e1c6--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@@ -2993,7 -3201,9 +3241,8 @@@"mode": "模式","followUp": "跟进消息","runtime": "运行时",- "eventProcessing": "事件处理","lastError": "上次错误",+ "pauseReason": "暂停原因","type": "类型","triggeredBy": "触发来源","result": "结果",diff --cc vibe/i18n/en.jsonindex ba7ed3eff,b62c07abf..8ac1b5024--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@@ -68,7 -69,14 +68,8 @@@"task": {"resultNotRecorded": "The result of this run could not be recorded: the task was reclaimed, repointed or removed while it was running, so its stored state is unchanged."},- "queueCoalesced": {- "summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.",- "messagesLabel": "Coalesced callback messages:",- "latestLabel": "Latest callback message after {additional} additional trigger(s):",- "burstHint": "This callback source is firing frequently. Inspect the related watch/task and pause, remove, or update it if it is looping."- },"run": {+ "sessionTurnGateUnavailable": "This Agent Run could not be admitted because the Session turn gate is unavailable. Retry after the service finishes starting.","interrupted": {"noTerminalResult": "[Avibe Harness] This run ended without the Agent producing a result. The turn was released before the Agent replied, so no output was recorded. Check the Agent logs, then run it again if the work still needs doing.","stopped": "[Avibe Harness] This run was stopped before the Agent produced a result, so it has no final result. Any output the Agent had already sent is still kept on the run.",@@@ -707,12 -723,10 +717,12 @@@"flow_not_found": "Authorization flow not found.","flow_expired": "Authorization flow expired.","discovery_failed": "Could not validate or discover this source.",+ "invalid_priority_order": "Priority must include every source exactly once.",+ "invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source.",+ "mapping_target_unavailable": "The selected model is unavailable for this backend.","mode_switch_blocked": "This operation is blocked by the current supply mode or selection.",- "engine_down": "The local Model Hub runtime is unavailable.",- "consent_required": "Explicit consent is required for experimental subscription routing.",- "migration_item_conflict": "This migration item conflicts with current Model Hub state.",+ "engine_down": "The local model gateway is unavailable.",+ "migration_item_conflict": "This migration item conflicts with the current model gateway state.","stream_interrupted": "The upstream stream was interrupted.","upstream_protocol_error": "The upstream response did not match the expected protocol.","upstream_request_invalid": "The upstream service rejected the request.",@@@ -725,7 -738,10 +735,12 @@@"switch": "{from_source}: {reason} -> switched to {to_source}","cooldown": "{from_source}: {reason}; cooling down","recover": "{to_source}: recovered and available",+ "status": "{from_source}: {reason}",+ "skip": "{from_source}: {reason}; skipped",++ "mapping_applied": "{from_source} -> {model}: model mapping applied",+ "channel_switch": "{from_source}: supply channel changed",+ "needs_action": "{from_source}: {reason}; action required",+ "supply_interrupted": "{model}: {reason}; model supply interrupted","reason": {"quota_exhausted": "quota exhausted","rate_limited": "rate limited",diff --cc vibe/i18n/zh.jsonindex 56aa4bf59,a06f881f6..1cbb53926--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@@ -47,28 -75,8 +47,29 @@@"latestLabel": "后续又触发 {additional} 次后的最新 callback 消息:","burstHint": "这个 callback 来源正在频繁触发。请检查相关 watch/task;如果它在循环触发,请 pause、remove 或 update。"},+ "agentInitiatedContinuation": "Agent 主动发起的续接",+ "command": {+ "workdirMissing": "工作目录不存在:{cwd}",+ "supervisorExitedDuringStartup": "命令监控进程在启动期间退出。",+ "workerNotRecorded": "未启动命令:无法记录其监控进程。",+ "supervisorFailed": "命令监控进程失败:{detail}",+ "unknownSupervisorFailure": "未知的监控进程错误。",+ "protocolErrors": {+ "specTooLarge": "命令配置过大。",+ "invalidEncoding": "命令配置不是有效的 UTF-8。",+ "invalidJson": "命令配置不是有效的 JSON。",+ "unsupportedVersion": "不支持此命令配置版本。",+ "invalidCommand": "命令无效。"+ },+ "timedOut": "命令在 {seconds} 秒后超时。",+ "exited": "命令退出,状态码 {code}。",+ "exitedWithDetail": "命令退出,状态码 {code}:{detail}"+ },+ "task": {+ "resultNotRecorded": "无法记录本次运行的结果:任务在运行期间被回收、改绑或删除,其存储状态未发生变化。"+ },"run": {+ "sessionTurnGateUnavailable": "\u672c\u6b21 Agent Run \u65e0\u6cd5\u63a5\u5165\uff1aSession turn gate \u5f53\u524d\u4e0d\u53ef\u7528\u3002\u8bf7\u7b49\u5f85\u670d\u52a1\u542f\u52a8\u5b8c\u6210\u540e\u91cd\u8bd5\u3002","interrupted": {"noTerminalResult": "[Avibe Harness] 本次 run 结束时 Agent 没有产出结果。turn 在 Agent 回复前就被释放,因此没有记录任何输出。请检查 Agent 日志;如果这项工作仍需完成,请重新运行。","stopped": "[Avibe Harness] 本次 run 在 Agent 产出结果前被停止,因此没有最终结果。Agent 此前已经发出的输出仍会保留在这次 run 上。",@@@ -707,12 -723,10 +717,12 @@@"flow_not_found": "未找到授权流程。","flow_expired": "授权流程已过期。","discovery_failed": "无法验证或发现此来源。",+ "invalid_priority_order": "优先级必须完整且不重复地包含所有来源。",+ "invalid_source_order": "来源顺序包含不可用、不适用或重复的来源。",+ "mapping_target_unavailable": "所选模型无法用于此后端。","mode_switch_blocked": "当前供给模式或选择阻止了此操作。",- "engine_down": "本地模型中枢运行时不可用。",- "consent_required": "实验性订阅路由需要明确同意。",- "migration_item_conflict": "此迁移项与当前模型中枢状态冲突。",+ "engine_down": "本地模型网关不可用。",+ "migration_item_conflict": "此迁移项与当前模型网关状态冲突。","stream_interrupted": "上游流已中断。","upstream_protocol_error": "上游响应不符合预期协议。","upstream_request_invalid": "上游服务拒绝了请求。",@@@ -725,7 -738,10 +734,12 @@@"switch": "{from_source}:{reason} -> 已切到 {to_source}","cooldown": "{from_source}:{reason},暂时冷却","recover": "{to_source}:已恢复可用",+ "status": "{from_source}:{reason}",+ "skip": "{from_source}:{reason},已跳过",++ "mapping_applied": "{from_source} -> {model}:已应用模型映射",+ "channel_switch": "{from_source}:供给通道已切换",+ "needs_action": "{from_source}:{reason},需要处理",+ "supply_interrupted": "{model}:{reason},模型供给已中断","reason": {"quota_exhausted": "额度用完","rate_limited": "请求受限",diff --cc vibe/ui_server.pyindex 116df0e91,545733c3b..bbd366461--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@@ -4776,16 -4166,27 +4780,32 @@@ def _project_agent_unavailable_response)+ def _task_resume_blocked_response(exc):+ from core.services import settings as settings_service++ lang = settings_service.load_config_or_default().language+ return _coded_error_response(+ exc.code,+ t("error.taskOwnerUnavailable.message", lang),+ 409,+ hint=t("error.taskOwnerUnavailable.hint", lang, id=exc.definition_id),+ details={+ "task_id": exc.definition_id,+ "owner_session_id": exc.owner_session_id,+ },+ )++def _show_page_error_response(exc):code = getattr(exc, "code", "invalid_show_page_request")+ if code == "resource_access_forbidden":+ status = 403# A conflict (not a malformed request) when the page is in the wrong state or# the chosen suffix is already claimed.- status = 409 if code in {"not_public", "share_id_taken"} else 400+ elif code in {"not_public", "share_id_taken"}:+ status = 409+ else:+ status = 400return _coded_error_response(code, str(exc), status)@@@ -8414,43 -6804,21 +8434,47 @@@ async def sessions_bootstrap(session_id)from storage import message_deliveries- queued = message_deliveries.list_queued(conn, session_id)- draft = message_deliveries.get_draft_state(conn, session_id)+ queued = (+ [+ message_deliveries.public_delivery_payload(item)+ for item in message_deliveries.list_queued(conn, session_id)+ ]+ if can_chat+ else []+ )+ can_access_draft = can_chat and not bool(+ authorization_context and authorization_context.is_remote+ )- 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++ )- try:- agents_payload = vibe_api.get_vibe_agents(include_disabled=False, include_archived=True)- except Exception:- logger.exception("sessions_bootstrap: failed to load Vibe Agents")- agents_payload = {"agents": [], "default_agent_name": None}+ agents_payload = {"agents": [], "default_agent_name": None}+ if can_chat:+ try:+ agents_payload = vibe_api.get_vibe_agents(+ include_disabled=False,+ include_archived=True,+ )+ except Exception:+ logger.exception("sessions_bootstrap: failed to load Vibe Agents")try:- config_payload = vibe_api.client_config_payload(settings_service.load_config_or_default())+ config = settings_service.load_config_or_default()+ config_payload = (+ vibe_api.remote_config_payload(config)+ if authorization_context and authorization_context.is_remote+ else vibe_api.client_config_payload(config)+ )except Exception:logger.exception("sessions_bootstrap: failed to load config")config_payload = None- visible_queued = queued if can_chat else []- visible_draft = draft if can_access_draft else None++ visible_queued = queued++ visible_draft = draft+try:turn_result = await internal_client.turn_state(session_id)turn_body = turn_result.get("body") or {}@@@ -8484,8 -6848,8 +8508,8 @@@"messages": messages_result["messages"],"next_after_id": messages_result.get("next_after_id"),"next_before_id": messages_result.get("next_before_id"),- "queued": queued,- "draft": _session_draft_payload(draft),+ "queued": visible_queued,- "draft": {"text": (visible_draft or {}).get("text") or ""},++ "draft": _session_draft_payload(visible_draft),"turn_state": turn_state,})@@@ -10388,8 -8633,12 +10412,12 @@@ async def sessions_messages_create(sess)if not quick_reply_for:message_deliveries.set_draft(conn, session_id, None)+ draft = message_deliveries.get_draft_state(conn, session_id)workbench_sessions_service.touch_session(conn, session_id)- return message_deliveries.public_delivery_payload(row)- result = message_deliveries.delivery_payload(row)++ result = message_deliveries.public_delivery_payload(row)+ result["draft"] = _session_draft_payload(draft)+ result["draft_advanced"] = not bool(quick_reply_for)+ return result# Reserve the row FIRST (pending), then decide by the dispatch outcome.message = _persist_user_row()@@@ -10436,7 -8685,9 +10464,9 @@@current = message_deliveries.get_delivery(conn, str(message["id"]))if current is None:return dict(message)- payload = message_deliveries.delivery_payload(current)+ payload = message_deliveries.public_delivery_payload(current)+ payload["draft"] = message["draft"]+ payload["draft_advanced"] = message["draft_advanced"]if current["state"] == "queued":payload["type"] = "queued"payload["queued"] = True@@@ -10728,139 -8995,12 +10795,140 @@@ def sessions_draft_set(session_id: str)session_id,text if isinstance(text, str) else None,)+ saved = message_deliveries.get_draft_state(conn, session_id)except LookupError as err:return jsonify({"error": str(err)}), 404- return jsonify({"ok": True})+ return jsonify({"ok": True, "draft": _session_draft_payload(saved)})+def _workbench_event_data(payload: str) -> dict[str, Any] | None:+ try:+ envelope = json.loads(payload)+ except (TypeError, json.JSONDecodeError):+ return None+ data = envelope.get("data") if isinstance(envelope, dict) else None+ return data if isinstance(data, dict) else None+++def _workbench_event_visible_to_context(context, event_type: str, payload: str) -> bool:+ if context is None:+ return True+ if event_type == "show.event":+ # A Show Page carries its own resource ACL, and being the Instance owner+ # does not override it: a direct read of a page whose policy names+ # another subject is denied, so the workbench stream must not hand the+ # same page's annotation text and attachment metadata to that owner+ # either. Fail closed when the frame has no session to check.+ data = _workbench_event_data(payload)+ session_id = data.get("session_id") if data else None+ if not isinstance(session_id, str) or not session_id:+ return False+ if not _show_page_resource_access_allowed(context, session_id):+ return False+ if context.is_instance_owner:+ return True+ if event_type in {"authorization.changed", "workbench.events.bridge.status"}:+ return True+ data = _workbench_event_data(payload)+ if data is None:+ return False++ from storage import project_access_service++ engine = _projects_engine()+ with engine.connect() as conn:+ session_id = data.get("session_id")+ if isinstance(session_id, str) and session_id:+ return project_access_service.role_allows(+ project_access_service.get_effective_session_role(+ conn,+ context,+ session_id,+ ),+ "viewer",+ )+ project_id = project_access_service.project_id_from_scope_id(data.get("scope_id"))+ if project_id is not None:+ return project_access_service.can_read_project(conn, context, project_id)+ return False+++def _workbench_event_payload_for_context(context, event_type: str, payload: str) -> str | None:+ """Project-filter aggregate payloads whose values depend on the recipient.++ Returns ``None`` when the event cannot be projected safely for this+ recipient, in which case the caller drops the frame.+ """+ if event_type == "show.event" and context is not None and context.is_remote:+ # A Show annotation event carries the absolute host path of its+ # materialized screenshot. Remote subscribers read the image by+ # attachment id, so drop the path rather than stream the host layout —+ # and drop the whole frame if it cannot be projected.+ try:+ envelope = json.loads(payload)+ except (TypeError, json.JSONDecodeError):+ return None+ data = envelope.get("data") if isinstance(envelope, dict) else None+ if not isinstance(data, dict):+ return None+ return json.dumps(+ {**envelope, "data": _remote_safe_show_event_payload(data)},+ ensure_ascii=False,+ separators=(",", ":"),+ )+ if event_type == "vaults.updated" and context is not None and context.is_remote:+ try:+ envelope = json.loads(payload)+ except (TypeError, json.JSONDecodeError):+ return payload+ if isinstance(envelope, dict) and isinstance(envelope.get("data"), dict):+ return json.dumps(+ {+ **envelope,+ "data": {"scope": envelope["data"].get("scope", "")},+ },+ ensure_ascii=False,+ separators=(",", ":"),+ )+ if event_type != "inbox.unread.changed":+ return payload+ try:+ envelope = json.loads(payload)+ except (TypeError, json.JSONDecodeError):+ return payload+ data = envelope.get("data") if isinstance(envelope, dict) else None+ if not isinstance(data, dict):+ return payload++ from storage import messages_service++ engine = _projects_engine()+ with engine.connect() as conn:+ scope_ids = _accessible_project_scope_ids_for_context(conn, context)+ unread_counts = messages_service.unread_counts(+ conn,+ platform="avibe",+ scope_ids=scope_ids,+ )+ unread_by_session = messages_service.unread_counts_by_session(+ conn,+ platform="avibe",+ scope_ids=scope_ids,+ )+ return json.dumps(+ {+ **envelope,+ "data": {+ **data,+ "unread_counts": unread_counts,+ "unread_by_session": unread_by_session,+ },+ },+ ensure_ascii=False,+ separators=(",", ":"),+ )++@app.route("/api/events", methods=["GET"])async def workbench_events():"""Server-Sent Events stream for the workbench.@@@ -12010,18 -10073,29 +12083,39 @@@ def _sanitize_public_show_event_payloadreturn 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++ if not public:+ context = getattr(g, "authorization_context", None)+ if context is not None:+ if not context.has_role("editor"):+ return None+ if context.is_remote:+ return {"kind": "user", "email": context.email} if context.email else None+ return {"kind": "local"}config = _load_remote_access_config()if config is not None:@@@ -13566,23 -11431,16 +13666,27 @@@ async def serve_private_show_page(sessi# visibility still fall through to not-found.if page.visibility not in {"private", "public"}:return _show_page_not_found_response()- if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id):+ # A remote viewer is an untrusted viewer even on the private surface: keep+ # its asset reads inside the page workspace so an authored symlink cannot+ # serve out-of-Project disk files across the tunnel.+ if _is_show_page_runtime_denied_path(+ asset_path,+ session_id=page.session_id,+ confine_to_workspace=_is_remote_show_page_request(),+ ):return _show_page_file_not_found_response()+ show_author = _show_request_author()- can_annotate = show_author is not None++ can_annotate = _show_annotation_capability(++ author=show_author,++ page=page,++ )if asset_path.strip("/") == "__show/me":if request.method not in {"GET", "HEAD"}:return jsonify({"ok": False, "code": "method_not_allowed"}), 405- author = {"kind": "local"}return _show_me_response(- author,- can_annotate=_show_annotation_capability(author=author, page=page),- write_token=show_event_write_token(page.session_id),+ show_author,++ can_annotate=can_annotate,+ write_token=show_event_write_token(page.session_id) if can_annotate else None,)if asset_path.strip("/") in {"__show/events", "__events"}:return await _show_events_response(page.session_id)