Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(permissions): preserve recovery state

Max466f7edabc9c
diff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.py
index 9d7e748ec..aaa1b2115 100644
--- a/tests/test_remote_authorization_revision.py
+++ b/tests/test_remote_authorization_revision.py
@@ -22,6 +22,7 @@ from storage import remote_access_authorization_service
from storage.lock import MigrationLockTimeout
from vibe import remote_access, ui_server
from vibe.authorization import context_from_session_payload
+from vibe.sse_broker import broker
from vibe.ui_compat import g
from vibe.ui_server import app
@@ -1059,6 +1060,82 @@ def test_authorization_revision_sync_rejects_an_unpersisted_watermark(
assert remote_access.current_authorization_revision(config) == 41
+ "malformed",
+ (
+ b"\xff",
+ b"{not-json",
+ b'{"schema_version":1,"instance_id":"inst_123","authorization_revision":"bad","source_updated_at":0}',
+ ),
+)
+def test_authorization_revision_read_treats_malformed_content_as_absent(
+ monkeypatch,
+ tmp_path,
+ malformed,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ remote_access._authorization_revision_state_path().write_bytes(malformed) # noqa: SLF001
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
+
+ assert remote_access.current_authorization_revision(config) is None
+
+
+ "malformed",
+ (
+ b"\xff",
+ b"{not-json",
+ b'{"schema_version":1,"instance_id":"inst_123","authorization_revision":"bad","source_updated_at":0}',
+ ),
+)
+def test_authorization_acknowledgement_keeps_memory_revision_when_rewrite_fails(
+ monkeypatch,
+ tmp_path,
+ malformed,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ state_path = remote_access._authorization_revision_state_path() # noqa: SLF001
+ state_path.write_bytes(malformed)
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
+ published = []
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+ )
+ monkeypatch.setattr(
+ broker,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+
+ assert remote_access.acknowledge_authorization_revision(config, 42) == 42
+ assert remote_access.current_authorization_revision(config) == 42
+ assert published == [
+ ("authorization.changed", {"instance_authorization_revision": 42})
+ ]
+
+
+def test_authorization_revision_sync_keeps_strict_write_after_malformed_read(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ remote_access._authorization_revision_state_path().write_bytes(b"\xff") # noqa: SLF001
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+ )
+
+ with pytest.raises(OSError, match="read-only state"):
+ remote_access._replace_authorization_revision(config, 42) # noqa: SLF001
+
+
def test_paired_session_requires_signed_current_revision(monkeypatch, tmp_path):
"""I1057-AC4: unsigned, missing, and stale authorization versions fail closed."""
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
index d79e69987..65dc44b7d 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
@@ -418,6 +418,59 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(api.updateResourceAccess).toHaveBeenCalledTimes(1);
});
+ it('preserves the draft when a failed PUT is recovered with Retry', async () => {
+ api.getPermissions.mockResolvedValueOnce(permissions()).mockResolvedValueOnce(permissions());
+ api.getResourceAccess
+ .mockResolvedValueOnce({ resource: resource() })
+ .mockResolvedValueOnce({ resource: resource() });
+ api.updateResourceAccess.mockRejectedValueOnce(new PermissionsApiError(503, {
+ error: 'permissions_backend_unavailable',
+ }));
+ const user = userEvent.setup();
+ renderControl();
+
+ await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
+ await user.click(screen.getByRole('checkbox', { name: 'Design' }));
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
+ expect(await screen.findByText('Workspace access could not be loaded.')).toBeTruthy();
+
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+ await screen.findByRole('checkbox', { name: 'Design' });
+ expect(screen.getByRole('radio', { name: 'Selected groups' }).getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');
+ expect(api.updateResourceAccess).toHaveBeenCalledOnce();
+ });
+
+ it('preserves the draft when the conflict refresh fails before a Retry', async () => {
+ api.getPermissions
+ .mockResolvedValueOnce(permissions())
+ .mockRejectedValueOnce(new PermissionsApiError(503, {
+ error: 'permissions_backend_unavailable',
+ }))
+ .mockResolvedValueOnce(permissions());
+ api.getResourceAccess
+ .mockResolvedValueOnce({ resource: resource() })
+ .mockResolvedValueOnce({ resource: resource() })
+ .mockResolvedValueOnce({ resource: resource() });
+ api.updateResourceAccess.mockRejectedValueOnce(new PermissionsApiError(409, {
+ error: 'permission_revision_conflict',
+ current_revision: 5,
+ }));
+ const user = userEvent.setup();
+ renderControl();
+
+ await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));
+ await user.click(screen.getByRole('checkbox', { name: 'Design' }));
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
+ expect(await screen.findByText('Workspace access could not be loaded.')).toBeTruthy();
+
+ await user.click(screen.getByRole('button', { name: 'Retry' }));
+ await screen.findByRole('checkbox', { name: 'Design' });
+ expect(screen.getByRole('radio', { name: 'Selected groups' }).getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');
+ expect(api.updateResourceAccess).toHaveBeenCalledOnce();
+ });
+
it('fails closed for personal, pending, and conflicting ownership without contacting Permissions', () => {
const personal = renderControl(showPageAccess({
mode: 'personal',
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
index cb541bdb5..16cf556c1 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
@@ -252,6 +252,10 @@ export function ShowPageWorkspaceAccessControl({
await commit();
};
+ const retryLoad = useCallback(() => {
+ void load('ready', resource ? draftRef.current : undefined);
+ }, [load, resource]);
+
return (
<section className="space-y-2.5" aria-label={t('chat.showPage.workspaceAccess')}>
<div>
@@ -392,7 +396,7 @@ export function ShowPageWorkspaceAccessControl({
size="icon"
variant="ghost"
className="size-7 shrink-0"
- onClick={() => void load()}
+ onClick={retryLoad}
aria-label={t('common.retry')}
>
<RefreshCw className="size-3.5" />
diff --git a/ui/src/features/permissions/PermissionsPage.test.tsx b/ui/src/features/permissions/PermissionsPage.test.tsx
index 70853db6f..e838edc5e 100644
--- a/ui/src/features/permissions/PermissionsPage.test.tsx
+++ b/ui/src/features/permissions/PermissionsPage.test.tsx
@@ -1215,6 +1215,68 @@ describe('PermissionsPage conflict handling', () => {
expect(api.replaceAuthorizedUsers).toHaveBeenCalledOnce();
});
+ it.each([
+ { draftRole: 'editor' as const, concurrentRole: 'viewer' as const },
+ { draftRole: 'viewer' as const, concurrentRole: 'editor' as const },
+ ])('rebases a principal replacement collision without duplicating the candidate', async ({
+ draftRole,
+ concurrentRole,
+ }) => {
+ const initial = response();
+ initial.projection.access.entries = [
+ { kind: 'email', value: '[email protected]', role: 'viewer' },
+ ];
+ const latest = response();
+ latest.projection.instance.authorization_revision = 5;
+ latest.projection.access.entries = [
+ { kind: 'email', value: '[email protected]', role: 'viewer' },
+ { kind: 'email', value: '[email protected]', role: concurrentRole },
+ ];
+ api.getPermissions
+ .mockResolvedValueOnce(initial)
+ .mockResolvedValueOnce(latest);
+ api.replaceAuthorizedUsers
+ .mockRejectedValueOnce(new PermissionsApiError(409, {
+ error: 'permission_revision_conflict',
+ current_revision: 5,
+ }))
+ .mockResolvedValueOnce({
+ ok: true,
+ instance_id: 'inst-123',
+ authorization_revision: 6,
+ entries: [{ kind: 'email', value: '[email protected]', role: draftRole }],
+ });
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(await screen.findByRole('button', { name: 'permissions.actions.editAccess' }));
+ await user.clear(screen.getByLabelText('permissions.fields.principal'));
+ await user.type(screen.getByLabelText('permissions.fields.principal'), '[email protected]');
+ if (draftRole === 'editor') {
+ await user.click(screen.getByRole('radio', { name: 'permissions.roles.editor' }));
+ }
+ await user.click(screen.getByRole('button', { name: 'permissions.actions.save' }));
+ const firstNarrowing = (await screen.findByText('permissions.access.narrowTitle')).closest('[role="dialog"]');
+ await user.click(within(firstNarrowing as HTMLElement).getByRole('button', {
+ name: 'permissions.actions.save',
+ }));
+
+ expect(await screen.findByText('permissions.states.conflictTitle')).toBeTruthy();
+ await user.click(screen.getByRole('button', { name: 'permissions.actions.retrySave' }));
+ const retryNarrowing = (await screen.findByText('permissions.access.narrowTitle')).closest('[role="dialog"]');
+ await user.click(within(retryNarrowing as HTMLElement).getByRole('button', {
+ name: 'permissions.actions.save',
+ }));
+
+ await waitFor(() => expect(api.replaceAuthorizedUsers).toHaveBeenCalledTimes(2));
+ expect(api.replaceAuthorizedUsers.mock.calls[1]).toEqual([
+ [{ kind: 'email', value: '[email protected]', role: draftRole }],
+ 5,
+ 'inst-123',
+ ]);
+ expect(screen.queryByText('permissions.errors.duplicate_access_principal')).toBeNull();
+ });
+
it('keeps an access draft mounted when the conflict refresh fails', async () => {
const initial = response();
initial.projection.access.entries = [
diff --git a/ui/src/features/permissions/PermissionsPage.tsx b/ui/src/features/permissions/PermissionsPage.tsx
index a2939255d..72539a5d6 100644
--- a/ui/src/features/permissions/PermissionsPage.tsx
+++ b/ui/src/features/permissions/PermissionsPage.tsx
@@ -351,12 +351,25 @@ function AccessEntryDialog({
: normalizePrincipal(kind, value);
const candidate: AccessEntry = { kind, value: resolvedValue, role };
const originalKey = originalEntry.current ? accessEntryKey(originalEntry.current) : null;
- const authoritativeIndex = originalKey === null
+ const candidateKey = accessEntryKey(candidate);
+ const originalIndex = originalKey === null
? -1
: entries.findIndex((entry) => accessEntryKey(entry) === originalKey);
- const nextEntries = originalKey === null || authoritativeIndex < 0
- ? [...entries, candidate]
- : entries.map((entry, index) => (index === authoritativeIndex ? candidate : entry));
+ const candidateIndex = entries.findIndex((entry) => accessEntryKey(entry) === candidateKey);
+ const nextEntries = (() => {
+ const filtered = entries.filter((entry) => {
+ const key = accessEntryKey(entry);
+ return key !== originalKey && key !== candidateKey;
+ });
+ if (candidateIndex >= 0) {
+ filtered.splice(Math.min(candidateIndex, filtered.length), 0, candidate);
+ } else if (originalIndex >= 0) {
+ filtered.splice(Math.min(originalIndex, filtered.length), 0, candidate);
+ } else {
+ filtered.push(candidate);
+ }
+ return filtered;
+ })();
const refreshConflict = async (): Promise<boolean> => {
const latest = await onRefresh();
@@ -376,11 +389,11 @@ function AccessEntryDialog({
? null
: latestEntries.find((entry) => accessEntryKey(entry) === originalKey) ?? null;
const latestCandidate = latestEntries.find(
- (entry) => accessEntryKey(entry) === accessEntryKey(candidate),
+ (entry) => accessEntryKey(entry) === candidateKey,
);
if (
latestCandidate?.role === candidate.role
- && (originalKey === null || originalKey === accessEntryKey(candidate) || latestOriginal === null)
+ && (originalKey === null || originalKey === candidateKey || latestOriginal === null)
) {
setConflict(false);
setRefreshRequired(false);
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index edbe04296..d149dcd94 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -696,6 +696,15 @@ def _authorization_revision_file_signature(path: Path) -> tuple[int, int, int, i
)
+def _read_authorization_revision_payload(path: Path) -> Any:
+ """Read the watermark payload, treating malformed content as absent."""
+
+ try:
+ return runtime.read_json(path)
+ except (OSError, TypeError, ValueError, UnicodeDecodeError):
+ return None
+
+
def _load_authorization_revision_snapshot(config: V2Config) -> tuple[int, float] | None:
global _AUTHORIZATION_REVISION_CACHE
@@ -713,8 +722,17 @@ def _load_authorization_revision_snapshot(config: V2Config) -> tuple[int, float]
)
if cache_matches and cached.file_signature == file_signature:
return cached.revision, cached.source_updated_at
- payload = runtime.read_json(state_path)
+ payload = _read_authorization_revision_payload(state_path)
if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ if cache_matches and cached is not None:
+ _AUTHORIZATION_REVISION_CACHE = _AuthorizationRevisionCache(
+ state_path=state_path,
+ instance_id=instance_id,
+ revision=cached.revision,
+ source_updated_at=cached.source_updated_at,
+ file_signature=file_signature,
+ )
+ return cached.revision, cached.source_updated_at
if cache_matches:
_AUTHORIZATION_REVISION_CACHE = None
return None
@@ -726,6 +744,15 @@ def _load_authorization_revision_snapshot(config: V2Config) -> tuple[int, float]
revision = _normalize_authorization_revision(payload.get("authorization_revision"))
source_updated_at = float(payload["source_updated_at"])
except (KeyError, TypeError, ValueError):
+ if cache_matches and cached is not None:
+ _AUTHORIZATION_REVISION_CACHE = _AuthorizationRevisionCache(
+ state_path=state_path,
+ instance_id=instance_id,
+ revision=cached.revision,
+ source_updated_at=cached.source_updated_at,
+ file_signature=file_signature,
+ )
+ return cached.revision, cached.source_updated_at
if cache_matches:
_AUTHORIZATION_REVISION_CACHE = None
return None
@@ -788,7 +815,7 @@ def _install_authorization_revision(
try:
state_path.parent.mkdir(parents=True, exist_ok=True)
with _authorization_revision_file_lock(state_path):
- persisted = runtime.read_json(state_path)
+ persisted = _read_authorization_revision_payload(state_path)
persisted_revision = None
if (
isinstance(persisted, dict)