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
fix(show-pages): stop the share panel from creating pages it only reads (#1576)
Call Whitedab3f9857cc6
diff --git a/core/show_pages.py b/core/show_pages.pyindex a4d71a66b..4b8cc2b79 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -803,6 +803,64 @@ class ShowPageStore:owner_email=user_context.email,)+ @classmethod+ def _existing_page_for_use(+ cls,+ connection,+ session_id: str,+ user_context: Any,+ ownership: dict[str, Any],+ ) -> ShowPage | None:+ """Reconcile and authorize an ALREADY-EXISTING page; None when there is none.++ The single owner of "may this caller use this existing page". ``ensure`` /+ ``ensure_active`` take this branch before they consider creating anything,+ and ``get_for_use`` is only this branch — so a read can never drift from+ what the create path would have enforced for the same page.+ """+ existing = (+ connection.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))+ .mappings()+ .first()+ )+ if existing is None:+ return None+ cls._reconcile_resource_policy(connection, session_id, user_context, ownership)+ cls._require_project_edit_access(connection, session_id, user_context)+ cls._require_resource_access(connection, session_id, user_context)+ return _page_from_row(existing)++ def get_for_use(self, session_id: str, *, user_context: Any = None) -> ShowPage:+ """Read a page the caller may use, WITHOUT creating one.++ The read-only half of ``ensure_active``: identical reconcile-and-authorize+ enforcement for a page that exists, and ``show_page_not_found`` where+ ``ensure_active`` would have created one. Reading no longer requires taking+ the creation path, which is what keeps the one-shot ``created`` edge — and+ the "visualize this session" prompt it triggers — owned by the single+ caller that honors it.+ """+ session_id = validate_session_id(session_id)+ context = _resolve_resource_access_context(user_context)+ ownership = self._resolve_instance_ownership()+ with config_file_lock():+ with self.engine.begin() as conn:+ page = self._existing_page_for_use(conn, session_id, context, ownership)+ if page is None:+ # Absence is only reported to a caller allowed to work on the+ # project, exactly as ``ensure`` checks before it creates. The+ # route policy screens the Instance role alone, so skipping this+ # would let an Editor without project access tell a session that+ # HAS a page (forbidden) from one that does not (not found) —+ # turning a read into a page-existence oracle over arbitrary+ # session ids.+ self._require_project_edit_access(conn, session_id, context)+ raise ShowPageError(+ "This session has no Show Page.",+ code="show_page_not_found",+ )+ return page+def reconcile_resource_policy(self,session_id: str,@@ -849,16 +907,9 @@ class ShowPageStore:)with config_file_lock():with self.engine.begin() as conn:- existing = (- conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))- .mappings()- .first()- )+ existing = self._existing_page_for_use(conn, session_id, context, ownership)if existing is not None:- self._reconcile_resource_policy(conn, session_id, context, ownership)- self._require_project_edit_access(conn, session_id, context)- self._require_resource_access(conn, session_id, context)- return _page_from_row(existing)+ return existingself._require_project_edit_access(conn, session_id, context)self._require_create_access(context)conn.execute(@@ -891,16 +942,9 @@ class ShowPageStore:now = _utc_now_iso()with config_file_lock():with self.engine.begin() as conn:- existing = (- conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))- .mappings()- .first()- )+ existing = self._existing_page_for_use(conn, session_id, context, ownership)if existing is not None:- self._reconcile_resource_policy(conn, session_id, context, ownership)- self._require_project_edit_access(conn, session_id, context)- self._require_resource_access(conn, session_id, context)- return _page_from_row(existing), False+ return existing, Falseself._require_project_edit_access(conn, session_id, context)self._require_create_access(context)status = conn.execute(diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.pyindex 27fafb4a5..1c7d9dad3 100644--- a/tests/test_instance_authorization.py+++ b/tests/test_instance_authorization.py@@ -160,6 +160,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N("POST", "/api/sessions/session-1/messages"),("POST", "/api/sessions/session-1/attachments"),("POST", "/api/sessions/session-1/cancel"),+ ("GET", "/api/show-pages/session-1"),("POST", "/api/show-pages/session-1/ensure"),("POST", "/api/show-pages/session-1/availability"),("POST", "/api/show-pages/session-1/access-settings/read"),diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex bfa5ad74b..7375c5e9d 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -22,6 +22,8 @@ from starlette.websockets import WebSocketDisconnectfrom config import pathsfrom core.show_pages import (SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS,+ VISIBILITIES,+ ShowPageError,ShowPageStore,ensure_show_page_dir,show_cli_event_token,@@ -1828,6 +1830,114 @@ def test_remote_show_page_icon_is_not_persistently_cached(monkeypatch, tmp_path)assert response.headers["Cache-Control"] == "private, no-store"+def _show_page_rows() -> dict[str, dict]:+ from sqlalchemy import select++ from core.show_pages import show_pages++ store = ShowPageStore()+ try:+ with store.engine.connect() as connection:+ return {+ row["session_id"]: dict(row)+ for row in connection.execute(select(show_pages)).mappings()+ }+ finally:+ store.close()+++def test_show_page_read_returns_a_page_without_writing_the_table(monkeypatch, tmp_path):+ # `GET /api/show-pages/<sid>` is the read-only counterpart of `POST .../ensure`.+ # The property: reading a Show Page NEVER writes the show_pages table. It returns+ # an existing page byte-identical and reports show_page_not_found where ensure+ # would have created one — which is what leaves ensure's one-shot `existed` edge,+ # and the "visualize this session" prompt it triggers, to its single owner.+ # Seeded with one page of every visibility that exists, so a visibility added+ # later is covered here without editing this test.+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ seeded = sorted(VISIBILITIES)+ for index, visibility in enumerate(seeded):+ _create_show_page(f"ses{index}", visibility)+ before = _show_page_rows()+ assert len(before) == len(seeded)+ client = app.test_client()+ responses = []++ for index, visibility in enumerate(seeded):+ response = client.get(f"/api/show-pages/ses{index}", base_url="http://127.0.0.1:5123")+ responses.append(response)+ assert response.status_code == 200, visibility+ body = response.get_json()+ assert body["ok"] is True+ assert body["session_id"] == f"ses{index}"+ # The read reports no creation fact, so no caller can consume one.+ assert "existed" not in body++ missing = client.get("/api/show-pages/sesabsent", base_url="http://127.0.0.1:5123")+ responses.append(missing)+ assert missing.status_code == 404+ assert missing.get_json()["code"] == "show_page_not_found"++ # The ensure POST was uncacheable by method. This route is a GET, so caching is+ # opt-out — and the property is per route, not per status: EVERY response it+ # produces carries per-caller page state and must be marked. A 404 is+ # heuristically cacheable, so an unmarked "no page here" could outlive the+ # page's creation and leave the share panel empty until it expired.+ for response in responses:+ assert response.headers["Cache-Control"] == "no-store, private", response.status+ assert response.headers["Vary"] == "Cookie", response.status++ assert _show_page_rows() == before+++def test_show_page_read_hides_page_existence_without_project_access(monkeypatch, tmp_path):+ # The route policy screens the Instance role only, so an Editor still reaches this+ # read for sessions in projects they are not bound to. The property: to a caller+ # who fails the project check, a session that HAS a page and a session that has+ # none are indistinguishable. Without it the read is a page-existence oracle over+ # arbitrary session ids -- the create path already checks project access before it+ # acts, and a read must not be the cheaper way to learn what create would refuse.+ from storage import project_access_service+ from storage.db import create_sqlite_engine+ from vibe.authorization import AuthorizationContext++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ _create_agent_session("seswith")+ _create_agent_session("seswithout")+ _create_show_page("seswith", "private")+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ result = project_access_service.apply_project_access_intent(+ conn,+ {"project_id": "proj_show", "revision": 1, "mode": "restricted", "bindings": []},+ )+ assert result.changed is True+ engine.dispose()+ context = AuthorizationContext(+ instance_role="editor",+ subject="remote-editor",+ email="[email protected]",+ instance_access_source="email",+ is_remote=True,+ )++ store = ShowPageStore()+ try:+ codes = []+ for session_id in ("seswith", "seswithout"):+ with pytest.raises(ShowPageError) as excinfo:+ store.get_for_use(session_id, user_context=context)+ codes.append(excinfo.value.code)+ finally:+ store.close()++ # Which code the caller gets is not the property -- that one session cannot be+ # told from the other is. Normalizing the pair either way keeps this passing.+ assert len(set(codes)) == 1, codes++def test_remote_personal_owner_can_ensure_show_page(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)diff --git a/ui/src/components/workbench/ShowPageShareControl.test.tsx b/ui/src/components/workbench/ShowPageShareControl.test.tsxindex ac8baa287..0375da25d 100644--- a/ui/src/components/workbench/ShowPageShareControl.test.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.test.tsx@@ -23,6 +23,7 @@ vi.mock('@/features/permissions/api', async (importOriginal) => ({}));const api = {+ getShowPage: vi.fn(),ensureShowPage: vi.fn(),getShowPageAccess: vi.fn(),getShowAccessSettings: vi.fn(),@@ -142,7 +143,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_manage: false,can_publish_public: false,}));- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',active_url: '/show/ses-1/',@@ -160,7 +161,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {fireEvent.click(screen.getByRole('button', { name: 'Share' }));await waitFor(() => {- expect(api.ensureShowPage).toHaveBeenCalledWith('ses-1');+ expect(api.getShowPage).toHaveBeenCalledWith('ses-1');});await waitFor(() => {expect((screen.getByDisplayValue(/\/show\/ses-1\//) as HTMLInputElement).value).toContain('/show/ses-1/');@@ -181,7 +182,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {permissionsApi.getPermissions.mockReturnValue(pending);permissionsApi.getResourceAccess.mockReturnValue(pending);api.getShowPageAccess.mockResolvedValue(organizationAccess);- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',active_url: '/show/ses-1/',@@ -243,7 +244,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {// Metadata-only manager: no payload read is ever issued.await vi.waitFor(() => {- expect(api.ensureShowPage).not.toHaveBeenCalled();+ expect(api.getShowPage).not.toHaveBeenCalled();},{ timeout: 250 },);@@ -258,7 +259,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_manage: true,can_publish_public: true,}));- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',active_url: '/show/ses-1/',@@ -286,7 +287,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {expect(api.getShowPageAccess).toHaveBeenCalled();});await vi.waitFor(() => {- expect(api.ensureShowPage).toHaveBeenCalledTimes(1);+ expect(api.getShowPage).toHaveBeenCalledTimes(1);});});@@ -296,7 +297,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_manage: false,can_publish_public: false,}));- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'limited',active_url: null,@@ -327,7 +328,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_manage: false,can_publish_public: false,}));- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'limited',active_url: null,@@ -345,7 +346,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {);fireEvent.click(screen.getByRole('button', { name: 'Share' }));- await waitFor(() => expect(api.ensureShowPage).toHaveBeenCalledWith('ses-1'));+ await waitFor(() => expect(api.getShowPage).toHaveBeenCalledWith('ses-1'));expect((screen.getByRole('button', { name: 'Open' }) as HTMLButtonElement).disabled).toBe(true);expect((screen.getByRole('button', { name: 'Copy link' }) as HTMLButtonElement).disabled).toBe(true,@@ -368,7 +369,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {permissionsApi.getPermissions.mockReturnValue(pending);permissionsApi.getResourceAccess.mockReturnValue(pending);api.getShowPageAccess.mockResolvedValue(organizationAccess);- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',active_url: '/show/ses-1/',@@ -417,7 +418,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_publish_public: true,});api.getShowPageAccess.mockResolvedValue(personalAccess);- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',active_url: '/show/ses-1/',@@ -465,7 +466,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_publish_public: false,});api.getShowPageAccess.mockResolvedValue(conflict);- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',active_url: '/show/ses-1/',@@ -494,7 +495,7 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {can_manage: true,can_publish_public: true,}));- api.ensureShowPage.mockResolvedValue({+ api.getShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'public',active_url: '/p/stable-link/',@@ -586,3 +587,86 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {});});});++describe('ShowPageShareControl request surface', () => {+ // The property: opening this panel READS a Show Page, it never creates one.+ // `POST .../ensure` reports the first-creation edge exactly once, and only the+ // caller that sends the "visualize this session" prompt may consume it — so+ // this panel must stay off that endpoint no matter which branch it opens+ // through. Asserted as a subset check against the declared read-only surface+ // instead of a list of forbidden calls: an API this component starts calling+ // later fails here until someone declares it read-only, and one that is not+ // even on the mocked surface fails louder still.+ const READ_ONLY_ON_OPEN = new Set([+ 'getShowPage',+ 'getShowPageAccess',+ 'getShowAccessSettings',+ 'listOrganizationResources',+ 'listOrganizationGroups',+ ]);++ const mutatingCallsSoFar = () => Object.entries(api)+ .filter(([name, fn]) => !READ_ONLY_ON_OPEN.has(name) && fn.mock.calls.length > 0)+ .map(([name]) => name);++ const page = {+ session_id: 'ses-1',+ visibility: 'private',+ active_url: '/show/ses-1/',+ share_id: null,+ url_available: true,+ offline: false,+ title: null,+ };++ it.each([+ // Both mount shapes: ChatPage passes access it already has, AppWindow does+ // not and makes the panel resolve access first. They open through different+ // branches, so the property is asserted on each.+ ['with access already resolved', true],+ ['resolving access on open', false],+ ])('reaches only read-only APIs when opening %s', async (_label, seeded) => {+ const access = showPageAccess({ can_use: true, can_manage: true, can_publish_public: true });+ api.getShowPageAccess.mockResolvedValue(access);+ api.getShowPage.mockResolvedValue(page);+ api.getShowAccessSettings.mockResolvedValue({+ show_access: {+ page_id: 'ses-1',+ access_mode: 'private',+ share_id: null,+ revision: 1,+ normalized_emails: [],+ },+ });++ render(+ <I18nextProvider i18n={i18n}>+ <ShowPageShareControl sessionId="ses-1" initialAccess={seeded ? access : null} />+ </I18nextProvider>,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));++ await waitFor(() => expect(api.getShowPage).toHaveBeenCalledWith('ses-1'));+ await waitFor(() => {+ expect((screen.getByDisplayValue(/\/show\/ses-1\//) as HTMLInputElement).value).toContain('/show/ses-1/');+ });+ expect(mutatingCallsSoFar()).toEqual([]);+ });++ it('reaches only read-only APIs when the page it wants does not exist', async () => {+ // The case that used to CREATE one: a framed session whose page row is gone.+ // The read fails and the panel stays empty; it must not fall back to ensure.+ api.getShowPageAccess.mockResolvedValue(showPageAccess({ can_use: true, can_manage: true }));+ api.getShowPage.mockRejectedValue(new Error('show_page_not_found'));++ render(+ <I18nextProvider i18n={i18n}>+ <ShowPageShareControl sessionId="ses-1" />+ </I18nextProvider>,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));++ await waitFor(() => expect(api.getShowPage).toHaveBeenCalledWith('ses-1'));+ expect(mutatingCallsSoFar()).toEqual([]);+ });+});diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex 05ebe48e5..9a074bf97 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -11,19 +11,12 @@ import { useDock } from '../../context/DockContext';import { showDockId } from '../../context/dockDoc';import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';import type { ShowPageAccess } from '../../lib/showPageAccess';-import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';+import { copyHref, type ShowPageLinkInfo, type ShowPagePayload } from '../../lib/showPageLinks';import { copyTextToClipboard } from '../../lib/utils';import { useShowPageInventory, type ShowPage } from '../useShowPages';import { ShowPageSharingSettings } from './ShowPageSharingSettings';import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';-type ShowPagePayload = ShowPageLinkInfo & {- url_available: boolean;- url_guidance?: string | null;- offline: boolean;- title?: string | null;-};-export const ShowPageShareControl: React.FC<{sessionId: string;initialAccess?: ShowPageAccess | null;@@ -90,7 +83,7 @@ export const ShowPageShareControl: React.FC<{return;}try {- const next: ShowPagePayload = await api.ensureShowPage(sessionId);+ const next: ShowPagePayload = await api.getShowPage(sessionId);if (seq === reqSeq.current) applyPayload(next);} catch {reload();@@ -123,12 +116,14 @@ export const ShowPageShareControl: React.FC<{}setLoading(!payload);try {- const result: ShowPagePayload = await api.ensureShowPage(sessionId);+ const result: ShowPagePayload = await api.getShowPage(sessionId);if (seq !== reqSeq.current) return;applyPayload(result);if (!inventoryPage) reload();} catch {- // Archived pages can still expose access metadata, but cannot be ensured.+ // A page can expose access metadata and still not be readable here (no+ // page row yet, or use access revoked). Opening this panel must never+ // create one, so there is nothing to recover — leave the link empty.} finally {setLoading(false);}diff --git a/ui/src/context/ApiContext.expectedErrors.test.tsx b/ui/src/context/ApiContext.expectedErrors.test.tsxnew file mode 100644index 000000000..28e3d4893--- /dev/null+++ b/ui/src/context/ApiContext.expectedErrors.test.tsx@@ -0,0 +1,115 @@+/* @vitest-environment jsdom */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { useEffect } from 'react';+import { cleanup, render, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const apiFetch = vi.hoisted(() => vi.fn());+const showToast = vi.hoisted(() => vi.fn());++vi.mock('../lib/apiFetch', () => ({ apiFetch }));+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { defaultValue?: string }) => options?.defaultValue ?? key,+ }),+}));++import { ApiProvider, useApi } from './ApiContext';++let capturedApi: ReturnType<typeof useApi> | null = null;++const CaptureApi = () => {+ const api = useApi();+ useEffect(() => {+ capturedApi = api;+ }, [api]);+ return null;+};++// The nested-``error`` body every coded route answers with (``_coded_error_response``+// in ``vibe/ui_server.py``), so these tests exercise the same parse the real routes do.+const codedError = (code: string, status: number) => new Response(+ JSON.stringify({ ok: false, error: { code, message: `${code} message` }, code, message: `${code} message` }),+ { status, headers: { 'Content-Type': 'application/json' } },+);++let consoleError: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ capturedApi = null;+ window.localStorage.clear();+ apiFetch.mockReset();+ showToast.mockReset();+ consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ apiFetch.mockResolvedValue(new Response('{}', {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }));+});++afterEach(() => {+ cleanup();+ consoleError.mockRestore();+ window.localStorage.clear();+});++// Mount, then forget whatever the provider's own bootstrap did: these tests are about+// the single call each one makes afterwards.+const mountApi = async () => {+ render(<ApiProvider><CaptureApi /></ApiProvider>);+ await waitFor(() => expect(capturedApi).not.toBeNull());+ showToast.mockClear();+ consoleError.mockClear();+ return capturedApi!;+};++const apiContextSource = () => readFileSync(join(__dirname, 'ApiContext.tsx'), 'utf8');++describe('ApiProvider expected error codes', () => {+ it('answers an absent Show Page silently on every read that shares the owner', async () => {+ // The members are DERIVED from the product source rather than restated here, so a read+ // added to `readShowPageJson` later is covered without editing this test — the panel+ // fires several of these in parallel and the reviewer found the second one exactly+ // because the property had been declared per call site instead of owned once.+ // Both directions are asserted per member: an absent page still REJECTS (no caller can+ // mistake an error body for a payload) yet is neither toasted nor logged, while any+ // other failure of the very same read still reaches the user. That pairing is what+ // stops the shared owner from quietly becoming "these reads never report anything".+ const reads = [...apiContextSource().matchAll(/(\w+): \(sessionId\) => readShowPageJson\(/g)]+ .map(([, name]) => name);+ expect(reads.length).toBeGreaterThan(1);++ const api = await mountApi();+ for (const name of reads) {+ const read = api[name as keyof typeof api] as (sessionId: string) => Promise<unknown>;++ apiFetch.mockResolvedValue(codedError('show_page_not_found', 404));+ await expect(read('ses1')).rejects.toMatchObject({ code: 'show_page_not_found' });+ expect(showToast, name).not.toHaveBeenCalled();+ expect(consoleError, name).not.toHaveBeenCalled();++ apiFetch.mockResolvedValue(codedError('resource_access_forbidden', 403));+ await expect(read('ses1')).rejects.toMatchObject({ code: 'resource_access_forbidden' });+ expect(showToast, name).toHaveBeenCalledTimes(1);+ expect(consoleError, name).toHaveBeenCalledTimes(1);++ showToast.mockClear();+ consoleError.mockClear();+ }+ });++ it('keeps every single-session Show Page GET on that owner', () => {+ // The behavioural test above can only exercise reads that already went through the+ // owner. This is the half that makes a NEW one fail: a GET of one session's page+ // written against raw `getJson` is a violation by construction, whatever it is named.+ // The list read (`/api/show-pages`, no session segment) cannot report a missing page+ // and is excluded by the same shape.+ const violations = [...apiContextSource().matchAll(/^.*\bgetJson\(`\/api\/show-pages\/\$\{.*$/gm)]+ .map(([line]) => line.trim());++ expect(violations).toEqual([]);+ });+});diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 662e7f874..1b5613fdb 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -7,6 +7,7 @@ import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';import type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';import { onPageReactivated } from '../lib/pageActivity';+import type { ShowPagePayload } from '../lib/showPageLinks';import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';@@ -527,7 +528,15 @@ export type ApiContextType = {unsubscribeWebPush: (endpoint: string) => Promise<{ ok: boolean; disabled: boolean }>;sendWebPushTest: (payload?: { title?: string; body?: string; url?: string; endpoint?: string }) => Promise<WebPushTestResult>;setShowPageAvailability: (sessionId: string, offline: boolean) => Promise<any>;- /** Create the session's Show Page if absent; resolves to `{ existed, ... }`. */+ /** Read the session's Show Page without creating it; rejects with+ * `show_page_not_found` — silently, as an expected answer — when there is none.+ * Everything that only DISPLAYS the page uses this — `ensureShowPage` is reserved+ * for the one caller that owns the first-creation prompt. */+ getShowPage: (sessionId: string) => Promise<ShowPagePayload>;+ /** Create the session's Show Page if absent; resolves to `{ existed, ... }`. Callers+ * MUST honor `existed === false` by sending the visualize prompt: that edge is+ * reported once, so a caller that ignores it silently consumes it. To only read the+ * page, use `getShowPage`. */ensureShowPage: (sessionId: string) => Promise<any>;/** Upload an image as the page's workspace-root favicon (multipart); resolves to the* refreshed page payload carrying the fresh `icon_version` (§7.1j). */@@ -2621,10 +2630,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}};- const handleApiError = async (res: Response, path: string) => {+ const handleApiError = async (+ res: Response,+ path: string,+ { expectedCodes }: { expectedCodes?: readonly string[] } = {},+ ) => {let errorMessage = `Request failed: ${path} (${res.status})`;let errorCode: string | null = null;-+try {const data = await res.json();const parsed = selectApiErrorFields(data, errorMessage);@@ -2641,15 +2654,21 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenerrorMessage = `${path}: ${res.statusText || 'Unknown error'} (${res.status})`;}- // Log error details to console- console.error(`[API Error] ${path}`, {- status: res.status,- statusText: res.statusText,- error: errorMessage,- });+ // A code the caller declared EXPECTED is an answer, not a failure: it still+ // rejects, so no caller can mistake an error body for data, but it is neither+ // announced to the user nor logged as an error. Declared per call site, applied+ // here, so "expected" cannot mean two different things in two helpers.+ if (!(errorCode !== null && expectedCodes?.includes(errorCode))) {+ // Log error details to console+ console.error(`[API Error] ${path}`, {+ status: res.status,+ statusText: res.statusText,+ error: errorMessage,+ });- // Show toast to user- showToast(errorMessage, 'error');+ // Show toast to user+ showToast(errorMessage, 'error');+ }// Archive is TERMINAL, so this particular refusal is not a failure to retry// but a state change the client missed (a backgrounded/offline tab can drop@@ -2672,14 +2691,28 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children};};- const getJson = async (path: string, { handleError = true }: { handleError?: boolean } = {}) => {+ const getJson = async (+ path: string,+ { handleError = true, expectedCodes }: { handleError?: boolean; expectedCodes?: readonly string[] } = {},+ ) => {const res = await apiFetch(path);if (!res.ok && handleError) {- await handleApiError(res, path);+ await handleApiError(res, path, { expectedCodes });}return res.json();};+ // Absence is data for a GET of ONE session's Show Page, never an incident: the share+ // panel opens on sessions that have no page yet and renders that as an empty link.+ // The property is owned here instead of declared per call site because the panel fires+ // several of these reads at once — one of them forgetting is a toast the user sees for+ // the normal case, and the reader cannot tell which of the parallel reads produced it.+ // Mutations stay off this path deliberately: pinning or re-skinning a page that does+ // not exist IS a fault worth announcing. So is the POST-shaped access-settings read,+ // which only mounts once an access read has already proven the page exists, so an+ // absent page there means it vanished mid-session rather than never existed.+ const readShowPageJson = (path: string) => getJson(path, { expectedCodes: ['show_page_not_found'] });+const getCachedJson = (path: string, ttlMs = 1500, opts?: { handleError?: boolean }) => {// Best-effort callers (handleError: false) bypass the shared read cache so a// silently-failing request can't hand its suppressed-error promise to a@@ -3280,7 +3313,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenremoveUser: (userId, platform) =>deleteJson(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`),getShowPages: () => getJson('/api/show-pages'),- getShowPageAccess: (sessionId) => getJson(`/api/show-pages/${encodeURIComponent(sessionId)}/access`),+ getShowPageAccess: (sessionId) => readShowPageJson(`/api/show-pages/${encodeURIComponent(sessionId)}/access`),probeShowPageAccess: async (sessionId) => {try {const response = await apiFetch(`/api/show-pages/${encodeURIComponent(sessionId)}/access`);@@ -3319,6 +3352,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children`/api/show-pages/${encodeURIComponent(sessionId)}/availability`,{ offline },),+ getShowPage: (sessionId) => readShowPageJson(`/api/show-pages/${encodeURIComponent(sessionId)}`),ensureShowPage: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/ensure`, {}),uploadShowPageIcon: async (sessionId, file) => {// Multipart POST: the server names the on-disk file, so we send only the bytesdiff --git a/ui/src/lib/showPageLinks.ts b/ui/src/lib/showPageLinks.tsindex 3f5700430..d24735c41 100644--- a/ui/src/lib/showPageLinks.ts+++ b/ui/src/lib/showPageLinks.ts@@ -9,6 +9,17 @@ export type ShowPageLinkInfo = {share_id: string | null;};+// One session's page as the server reports it: the link fields above plus the+// serving state. Lives beside `ShowPageLinkInfo` because it is the same family —+// the API read and the components that render its result share this shape rather+// than restating it.+export type ShowPagePayload = ShowPageLinkInfo & {+ url_available: boolean;+ url_guidance?: string | null;+ offline: boolean;+ title?: string | null;+};+// Same-origin path a Show Page is served at locally. Limited and Public share// one stable /p route; the server decides whether to start identity admission// or serve the page anonymously.diff --git a/vibe/api.py b/vibe/api.pyindex 7fe37833f..3f4c29f2f 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1676,6 +1676,29 @@ def ensure_show_page(session_id: str, *, user_context: Any = None) -> dict:return {"ok": True, "existed": not created, **_apply_session_meta([payload])[0]}+def get_show_page(session_id: str, *, user_context: Any = None) -> dict:+ """Read one session's Show Page without creating it.++ The read-only counterpart of ``ensure_show_page``: same payload and the same+ access enforcement for a page that exists, and ``show_page_not_found`` where+ ensure would have created one. A caller that only needs to DISPLAY the page+ uses this, so ``ensure_show_page``'s one-shot ``existed`` edge stays with the+ single caller that owns the "visualize this session" prompt. The response+ deliberately carries no ``existed`` key: there is no creation fact to report,+ and none to accidentally consume.+ """+ from core.show_pages import ShowPageStore, show_page_payload++ config = V2Config.load()+ store = ShowPageStore()+ try:+ page = store.get_for_use(session_id, user_context=user_context)+ payload = show_page_payload(page, config=config)+ finally:+ store.close()+ return {"ok": True, **_apply_session_meta([payload])[0]}++def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:"""Return the applied authenticated audience and sharing authority."""diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 1ed264adb..c6062c750 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -403,6 +403,10 @@ _EDITOR_HTTP_RULES = tuple(("POST", r"^/api/config$"),("POST", r"^/api/show/sessions/[^/]+/events$"),("POST", r"^/api/show/sessions/[^/]+/prewarm$"),+ # Reading one page stays at the role its ensure POST already required, so+ # replacing that POST with this GET changes no caller's authorization+ # outcome. Widening to viewer would be a policy change, not a read.+ ("GET", r"^/api/show-pages/[^/]+$"),("POST", r"^/api/show-pages/[^/]+/icon$"),("POST", r"^/api/show-pages/[^/]+/(?:ensure|availability)$"),("POST", r"^/api/show-pages/[^/]+/access-settings/(?:read|apply)$"),diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 7c702306a..fd2b7cf5d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5759,6 +5759,32 @@ def show_page_availability_post(session_id):return _show_page_error_response(exc)[email protected]("/api/show-pages/<session_id>", methods=["GET"])+def show_page_get(session_id):+ from core.show_pages import ShowPageError+ from vibe import api++ status = 200+ try:+ context = _request_authorization_context()+ response = jsonify(+ _show_page_payload_for_request(+ api.get_show_page(session_id, user_context=context),+ context,+ )+ )+ except ShowPageError as exc:+ response, status = _show_page_error_response(exc)+ # Same per-caller page data the ensure POST returned, now over a method caches+ # are allowed to store by default — so EVERY outcome of this route is marked,+ # not just the success. A 404 is heuristically cacheable, and a cached "no page+ # here" would survive the page's creation and leave the share panel empty until+ # it expired.+ response.headers["Cache-Control"] = "no-store, private"+ response.headers["Vary"] = "Cookie"+ return response, status++@app.route("/api/show-pages/<session_id>/ensure", methods=["POST"])def show_page_ensure_post(session_id):from core.show_pages import ShowPageError