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-page): close mutation access races
Maxf3ae0c453201
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.pyindex 731a84a90..b3f1e9ab7 100644--- a/tests/test_resource_acl_show_pages.py+++ b/tests/test_resource_acl_show_pages.py@@ -716,6 +716,32 @@ def test_show_page_email_grants_report_unavailable_without_cloud_pairing(assert response.get_json()["code"] == "show_page_email_access_not_configured"+def test_show_page_email_grants_report_transient_device_failures_as_retryable(+ monkeypatch, tmp_path+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ store = ShowPageStore()+ try:+ store.ensure("ses-email-access-transient")+ finally:+ store.close()+ monkeypatch.setattr(+ remote_access,+ "get_show_page_authorized_emails",+ lambda _show_page_id: (_ for _ in ()).throw(+ RuntimeError("resource_acl_device_unavailable")+ ),+ )++ response = app.test_client().get(+ "/api/show-pages/ses-email-access-transient/authorized-emails"+ )++ assert response.status_code == 503+ assert response.get_json()["code"] == "show_page_email_access_transient"++def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)@@ -765,6 +791,27 @@ def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmassert revisions == [9]+def test_show_page_email_grant_change_requires_authorization_revision(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)+ monkeypatch.setattr(+ remote_access,+ "_device_json_request",+ lambda *_args, **_kwargs: {+ "emails": ["[email protected]"],+ "changed": True,+ },+ )++ with pytest.raises(RuntimeError, match="show_page_email_access_invalid_response"):+ remote_access.replace_show_page_authorized_emails(+ "session-one",+ ["[email protected]"],+ config,+ )++def test_remote_dock_filters_private_pins_and_authorizes_mutations(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex f4cf78606..97972fb66 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -561,6 +561,14 @@ def _machine_coded_error_builders():"show_page_not_found",404,),+ (+ "show_page_email_transient",+ lambda: ui_server._show_page_error_response(+ _Coded("temporary failure", "show_page_email_access_transient")+ ),+ "show_page_email_access_transient",+ 503,+ ),("dock", lambda: ui_server._dock_error_response(_Coded("nope", "show_page_not_found")), "show_page_not_found", 404),("show_page_icon",diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsxindex 88752d4dc..22834ff56 100644--- a/ui/src/components/ShowPagesPage.tsx+++ b/ui/src/components/ShowPagesPage.tsx@@ -23,7 +23,8 @@ import clsx from 'clsx';import { useDock } from '../context/DockContext';import { useWindowManager } from '../context/WindowManagerContext';import { copyTextToClipboard } from '../lib/utils';-import { copyHref, displayLink, type ShowPageLinkInfo } from '../lib/showPageLinks';+import { copyHref, displayLink } from '../lib/showPageLinks';+import type { ShowPageVisibilityResult } from '../lib/showPageAccess';import { type ShowPage, type ShowPagesController, type Visibility } from './useShowPages';import { appTabHref, isAppleContextClick, tabModifierLabel, type LaunchModifiers } from '../apps/appLaunch';import { filterShowPages, type ShowPageFilter } from '../apps/appLibrary';@@ -63,7 +64,7 @@ interface RowProps {onSetVisibility: (visibility: Visibility) => void;onRotate: () => void;onCopy: () => void;- onShareIdSaved: (payload: ShowPageLinkInfo) => void;+ onShareIdSaved: (payload: ShowPageVisibilityResult, sessionId: string) => void;}function ShowPageRow({diff --git a/ui/src/components/useShowPages.ts b/ui/src/components/useShowPages.tsindex 5061834de..ad562ee61 100644--- a/ui/src/components/useShowPages.ts+++ b/ui/src/components/useShowPages.ts@@ -3,8 +3,7 @@ import { useTranslation } from 'react-i18next';import { useApi } from '../context/ApiContext';import { useToast } from '../context/ToastContext';-import type { ShowPageLinkInfo } from '../lib/showPageLinks';-import { isShowPageVisibilityPayload } from '../lib/showPageAccess';+import { isShowPageVisibilityPayload, type ShowPageVisibilityResult } from '../lib/showPageAccess';import {getShowPagesInventoryStore,type ShowPage,@@ -84,7 +83,12 @@ export function useShowPages() {setBusyId(page.session_id);try {const res = await api.rotateShowPageShare(page.session_id);- mergePage(res);+ if (isShowPageVisibilityPayload(res)) {+ mergePage(res);+ } else {+ removePage(page.session_id);+ reload();+ }showToast(t('showPages.toast.rotated'));} catch {// handled by ApiContext@@ -95,8 +99,13 @@ export function useShowPages() {// The custom-link field owns its own request/validation; we only merge the// returned payload (new share_id, updated_at) and confirm.- const onShareIdSaved = (next: ShowPageLinkInfo) => {- mergePage(next as ShowPage);+ const onShareIdSaved = (next: ShowPageVisibilityResult, sessionId: string) => {+ if (isShowPageVisibilityPayload(next)) {+ mergePage(next as unknown as ShowPage);+ } else {+ removePage(sessionId);+ reload();+ }showToast(t('showPages.shareId.toast.saved'));};diff --git a/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx b/ui/src/components/workbench/ShowPageEmailAccessEditor.tsxindex 6ed14a56b..5559d5ff8 100644--- a/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx+++ b/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx@@ -26,10 +26,12 @@ export function ShowPageEmailAccessEditor({active,canManage,sessionId,+ onConfirmationOpenChange,}: {active: boolean;canManage: boolean;sessionId: string;+ onConfirmationOpenChange?: (open: boolean) => void;}) {const { t } = useTranslation();const api = useApi();@@ -41,6 +43,10 @@ export function ShowPageEmailAccessEditor({const [saving, setSaving] = useState(false);const [confirmNarrowing, setConfirmNarrowing] = useState(false);const generationRef = useRef(0);+ const setConfirmationOpen = useCallback((next: boolean) => {+ setConfirmNarrowing(next);+ onConfirmationOpenChange?.(next);+ }, [onConfirmationOpenChange]);const load = useCallback(async () => {const generation = ++generationRef.current;@@ -66,12 +72,12 @@ export function ShowPageEmailAccessEditor({setDraft('');setDraftInvalid(false);setSaving(false);- setConfirmNarrowing(false);+ setConfirmationOpen(false);if (active && canManage) void load();return () => {generationRef.current += 1;};- }, [active, canManage, load, sessionId]);+ }, [active, canManage, load, sessionId, setConfirmationOpen]);const dirty = useMemo(() => emails.join('\u0000') !== savedEmails.join('\u0000'),@@ -93,7 +99,7 @@ export function ShowPageEmailAccessEditor({const commit = async () => {if (!dirty || saving || draft.trim()) return;- setConfirmNarrowing(false);+ setConfirmationOpen(false);setSaving(true);try {const result = await api.replaceShowPageAuthorizedEmails(sessionId, emails);@@ -250,7 +256,7 @@ export function ShowPageEmailAccessEditor({</div><ConfirmDialogopen={confirmNarrowing}- onOpenChange={setConfirmNarrowing}+ onOpenChange={setConfirmationOpen}title={t('organization.resources.narrowTitle')}description={t('organization.resources.narrowBody')}confirmLabel={t('organization.actions.saveChanges')}diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex 046591db0..3e20aa08f 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -17,6 +17,7 @@ import {isShowPageVisibilityPayload,showPageShareCapabilities,type ShowPageAccess,+ type ShowPageVisibilityResult,} from '../../lib/showPageAccess';import { ShowPageShareIdField } from './ShowPageShareIdField';import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';@@ -104,6 +105,31 @@ export const ShowPageShareControl: React.FC<{mergePage(next as ShowPage);};+ const applyMutationResult = (+ result: ShowPageVisibilityResult<ShowPagePayload>,+ options: { publicLinkEnabled?: boolean } = {},+ ) => {+ const canReadResult = isShowPageVisibilityPayload(result);+ if (canReadResult) {+ applyPayload(result as ShowPagePayload);+ } else {+ // Access can change after this control renders. A metadata-only response+ // deliberately has no page identity or link, so withdraw every retained+ // copy before revalidating the inventory instead of merging malformed data.+ setLocalPayload(null);+ removePage(sessionId);+ reload();+ }+ setAccess((current) => current ? {+ ...current,+ can_use: canReadResult ? current.can_use : false,+ public_link_enabled: canReadResult+ ? options.publicLinkEnabled ?? current.public_link_enabled+ : result.public_link_enabled,+ } : current);+ reqSeq.current += 1;+ };+useEffect(() => {if (!payload) return;const hasFreshLocalPayload = localPayload?.session_id === sessionId;@@ -198,27 +224,9 @@ export const ShowPageShareControl: React.FC<{api.setShowPageVisibility<ShowPagePayload>(sessionId, next).then((res) => {- // Authoritative server state: always apply it, and invalidate any- // in-flight refresh read so a stale read can't revert us afterwards.- const canReadResult = isShowPageVisibilityPayload(res);- if (canReadResult) {- applyPayload(res);- } else {- // Access changed after this popover rendered. A metadata-only result- // intentionally carries no page path, link, share id, or session id;- // withdraw every retained copy before revalidating the inventory.- setLocalPayload(null);- removePage(sessionId);- reload();- }- setAccess((current) => current ? {- ...current,- can_use: canReadResult ? current.can_use : false,- public_link_enabled: canReadResult- ? next === 'public'- : res.public_link_enabled,- } : current);- reqSeq.current += 1;+ // Authoritative server state: apply it and invalidate any in-flight+ // refresh read so a stale read cannot revert us afterwards.+ applyMutationResult(res, { publicLinkEnabled: next === 'public' });}).catch(() => undefined).finally(() => setBusy(false));@@ -246,10 +254,7 @@ export const ShowPageShareControl: React.FC<{setBusy(true);api.rotateShowPageShare(sessionId)- .then((res: ShowPagePayload) => {- applyPayload(res);- reqSeq.current += 1;- })+ .then((res: ShowPageVisibilityResult<ShowPagePayload>) => applyMutationResult(res)).catch(() => undefined).finally(() => setBusy(false));};@@ -444,10 +449,9 @@ export const ShowPageShareControl: React.FC<{shareId={payload.share_id}disabled={busy || !access?.can_publish_public}onSaved={(res) => {- // Authoritative server state, same handling as a visibility- // change: apply it and invalidate any in-flight refresh read.- applyPayload(res as ShowPagePayload);- reqSeq.current += 1;+ // Custom-link updates can also return metadata only when+ // page-use access changed while the editor was open.+ applyMutationResult(res as ShowPageVisibilityResult<ShowPagePayload>);}}/></div>diff --git a/ui/src/components/workbench/ShowPageShareIdField.tsx b/ui/src/components/workbench/ShowPageShareIdField.tsxindex 7557c044d..e78f12252 100644--- a/ui/src/components/workbench/ShowPageShareIdField.tsx+++ b/ui/src/components/workbench/ShowPageShareIdField.tsx@@ -6,7 +6,8 @@ import clsx from 'clsx';import { Button } from '../ui/button';import { Input } from '../ui/input';import { ApiError, useApi } from '../../context/ApiContext';-import { isValidShareId, SHARE_ID_MAX_LENGTH, type ShowPageLinkInfo } from '../../lib/showPageLinks';+import { isValidShareId, SHARE_ID_MAX_LENGTH } from '../../lib/showPageLinks';+import type { ShowPageVisibilityResult } from '../../lib/showPageAccess';// Editable custom suffix for a public Show Page's /p/<share_id>/ URL. Shared by// the in-chat share popover and the admin Show Pages page so both surfaces get@@ -19,7 +20,7 @@ export const ShowPageShareIdField: React.FC<{// External busy (e.g. a visibility change in flight) disables the field.disabled?: boolean;// Receives the updated payload so the caller can refresh its link/iframe.- onSaved: (payload: ShowPageLinkInfo) => void;+ onSaved: (payload: ShowPageVisibilityResult, sessionId: string) => void;}> = ({ sessionId, shareId, disabled, onSaved }) => {const { t } = useTranslation();const api = useApi();@@ -58,7 +59,7 @@ export const ShowPageShareIdField: React.FC<{setError(null);try {const res = await api.setShowPageShareId(sessionId, trimmed);- onSaved(res);+ onSaved(res, sessionId);setSaved(true);if (savedTimer.current) window.clearTimeout(savedTimer.current);savedTimer.current = window.setTimeout(() => setSaved(false), 1600);diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsxindex 5d0a9d1cd..0df21bfa8 100644--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx@@ -437,6 +437,7 @@ export function ShowPageWorkspaceAccessControl({active={active}canManage={access.can_publish_public}sessionId={sessionId}+ onConfirmationOpenChange={onConfirmationOpenChange}/>) : null}</section>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9f8cabef5..54d32e445 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1269,6 +1269,7 @@"remote_access_public_url_invalid": "Remote access is misconfigured (the public URL is invalid). Re-pair this device or fix the remote-access settings.","remote_access_session_secret_missing": "Remote access is misconfigured (missing session secret). Re-pair this device to restore access.","remote_access_unknown": "The operation did not finish. Refresh the status and try again; if it still fails, check the remote access runtime logs.",+ "show_page_email_access_transient": "Email access is temporarily unavailable. Try again.","invalid_pairing_key": "This pairing key is invalid or expired. Create a new key at avibe.bot, then paste it here.","missing_pairing_key": "Paste the pairing key first.","invalid_pairing_backend_url": "The Avibe Cloud URL must be a valid HTTPS address.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 47373b711..467dbe689 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1269,6 +1269,7 @@"remote_access_public_url_invalid": "远程访问配置有误(公网地址无效)。请重新配对此设备或修正远程访问设置。","remote_access_session_secret_missing": "远程访问配置有误(缺少会话密钥)。请重新配对此设备以恢复访问。","remote_access_unknown": "操作没有完成。请刷新状态后再试一次;如果仍然失败,请查看远程访问运行日志。",+ "show_page_email_access_transient": "邮箱权限暂时不可用,请重试。","invalid_pairing_key": "这个 pairing key 无效或已过期。请回到 avibe.bot 重新生成一个 key,然后粘贴到这里。","missing_pairing_key": "请先粘贴 pairing key。","invalid_pairing_backend_url": "Avibe Cloud 地址必须是有效的 HTTPS 地址。",diff --git a/vibe/api.py b/vibe/api.pyindex eb2cd6ceb..ff23c2676 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1506,19 +1506,28 @@ def _show_page_email_access_error(exc: Exception):from core.show_pages import ShowPageErrorfrom vibe import remote_access- if isinstance(exc, ShowPageError):- return exc- if isinstance(exc, remote_access.BackendRequestError):- code = str(exc.payload.get("error") or "show_page_email_access_unavailable")- else:- code = str(exc) or "show_page_email_access_unavailable"- if code not in {+ known_codes = {"invalid_email","too_many_entries","show_page_email_access_not_configured","show_page_email_access_invalid_response",- }:- code = "show_page_email_access_unavailable"+ }+ transient_code = "show_page_email_access_transient"+ if isinstance(exc, ShowPageError):+ return exc+ if isinstance(exc, remote_access.BackendRequestError):+ raw_code = str(exc.payload.get("error") or "")+ code = raw_code if raw_code in known_codes else (+ transient_code if exc.status >= 500 else "show_page_email_access_unavailable"+ )+ else:+ raw_code = str(exc)+ code = transient_code if raw_code in {+ "resource_acl_device_unavailable",+ "show_page_email_access_invalid_response",+ } else raw_code or "show_page_email_access_unavailable"+ if code not in known_codes and code != transient_code:+ code = "show_page_email_access_unavailable"return ShowPageError(code, code=code)diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 40d60e199..c668af2ec 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -1539,11 +1539,17 @@ def replace_show_page_authorized_emails(not isinstance(email, str) for email in returned_emails):raise RuntimeError("show_page_email_access_invalid_response")+ changed = bool(result.get("changed"))+ if changed and "authorization_revision" not in result:+ raise RuntimeError("show_page_email_access_invalid_response")if result.get("authorization_revision") is not None:- _replace_authorization_revision(config, result["authorization_revision"])+ try:+ _replace_authorization_revision(config, result["authorization_revision"])+ except ValueError as exc:+ raise RuntimeError("show_page_email_access_invalid_response") from excreturn {"emails": returned_emails,- "changed": bool(result.get("changed")),+ "changed": changed,}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex f8308f42e..8aca05173 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4782,6 +4782,8 @@ def _show_page_error_response(exc):# the chosen suffix is already claimed.elif code in {"not_public", "share_id_taken"}:status = 409+ elif code == "show_page_email_access_transient":+ status = 503else:status = 400return _coded_error_response(code, str(exc), status)