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(auth): reauthorize remaining remote surfaces

Maxvintb99694b187ff
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 729fb3b32..d4b48ba99 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -4744,6 +4744,54 @@ def test_private_show_page_hmr_websocket_accepts_remote_session(monkeypatch, tmp
set_show_runtime_manager_for_tests(None)
+def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadline(monkeypatch, tmp_path):
+ class RecordingWebSocket:
+ def __init__(self):
+ self.calls = []
+
+ async def accept(self, *, subprotocol=None):
+ self.calls.append(("accept", subprotocol))
+
+ async def close(self, code=1000):
+ self.calls.append(("close", code))
+
+ proxy_calls = []
+
+ async def blocking_proxy(websocket, session_id):
+ proxy_calls.append(("started", session_id))
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ proxy_calls.append(("cancelled", session_id))
+ raise
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)
+ monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)
+ monkeypatch.setattr(
+ ui_server,
+ "_remote_access_websocket_session_claims",
+ lambda websocket, config: {"sub": "remote-viewer", "claims_issued_at": 1},
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "session_authorization_refresh_deadline",
+ lambda payload: ui_server.time.time() + 0.01,
+ )
+ monkeypatch.setattr(ui_server, "_proxy_show_runtime_websocket", blocking_proxy)
+ websocket = RecordingWebSocket()
+
+ asyncio.run(ui_server.show_runtime_hmr_websocket(websocket, "ses123"))
+
+ assert websocket.calls == [
+ ("accept", "vite-hmr"),
+ ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ]
+ assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]
+
+
def test_private_show_page_hmr_websocket_accepts_setup_host_local_peer(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index caf9b00fc..62c7e6ff9 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -424,7 +424,7 @@ export const AppShell: React.FC = () => {
// pans the locked page to lift the focused composer above the keyboard.
// Desktop: normal document flow.
<WindowManagerProvider>
- <DockProvider>
+ <DockProvider enabled={capabilities.can_use_system}>
<div className="flex h-[var(--app-shell-h)] flex-col overflow-hidden bg-background text-foreground md:block md:h-auto md:min-h-screen md:overflow-visible">
{/* The sidebar forms its own stacking context BELOW the window layer (aside z-10 < window
layer z-20), so a maximized window covers the WHOLE sidebar — including the Apps launcher.
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8d6913ca6..0712ffe61 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -2169,6 +2169,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
source.onerror = (err) => {
if (eventSourceRef.current !== source) return;
closeActiveWorkbenchEventSource();
+ // EventSource does not expose a failed response's status or JSON body.
+ // Probe the session through apiFetch so an authorization-refresh 401
+ // enters the same full-page/PWA login recovery path as ordinary APIs.
+ void apiFetch('/api/session', { cache: 'no-store' }).catch(() => undefined);
setWorkbenchEventConnectionState('reconnecting');
dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: false }));
dispatchToWorkbenchHandlers((handlers) => handlers.onError?.(err));
diff --git a/ui/src/context/DockContext.tsx b/ui/src/context/DockContext.tsx
index 166b0f077..b4c7660dd 100644
--- a/ui/src/context/DockContext.tsx
+++ b/ui/src/context/DockContext.tsx
@@ -136,7 +136,10 @@ const DockContext = createContext<DockValue | null>(null);
// server's fresh-instance seed; reconcileDock takes over once the GET resolves.
const DEFAULT_DOC: DockDoc = seedDefaultDock();
-export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+export const DockProvider: React.FC<{ children: React.ReactNode; enabled?: boolean }> = ({
+ children,
+ enabled = true,
+}) => {
const api = useApi();
const [doc, setDoc] = useState<DockDoc>(DEFAULT_DOC);
// Latest committed doc for the async actions' rollback (avoids stale closures).
@@ -157,6 +160,7 @@ export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children
const runMutation = useCallback(
(optimistic: DockDoc, request: () => Promise<{ ok?: boolean; dock?: DockDoc } | undefined>): Promise<void> => {
+ if (!enabled) return Promise.resolve();
const seq = (mutationSeqRef.current += 1);
apply(optimistic);
const task = async () => {
@@ -189,10 +193,17 @@ export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children
queueRef.current = next;
return next;
},
- [api, apply],
+ [api, apply, enabled],
);
useEffect(() => {
+ if (!enabled) {
+ // Nonowners cannot read or mutate the system Dock. Invalidate any
+ // in-flight owner snapshot and retain only the non-sensitive seed.
+ mutationSeqRef.current += 1;
+ setDoc(DEFAULT_DOC);
+ return;
+ }
let cancelled = false;
const loadSeq = mutationSeqRef.current;
api
@@ -208,7 +219,7 @@ export const DockProvider: React.FC<{ children: React.ReactNode }> = ({ children
return () => {
cancelled = true;
};
- }, [api]);
+ }, [api, enabled]);
const pin = useCallback(
(sessionId: string): Promise<void> => {
diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.ts
index be044baee..40cf36abd 100644
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@ -19,11 +19,14 @@ describe('apiFetch remote auth recovery', () => {
vi.clearAllMocks();
});
- it('hands an expired remote session to the PWA auth gate', async () => {
+ it.each([
+ 'remote_access_login_required',
+ 'remote_access_authorization_refresh_required',
+ ])('hands %s to the PWA auth gate', async (error) => {
vi.stubGlobal(
'fetch',
vi.fn(async () =>
- Response.json({ error: 'remote_access_login_required' }, { status: 401 }),
+ Response.json({ error }, { status: 401 }),
),
);
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
index 6936dba98..d93cd55b1 100644
--- a/ui/src/lib/apiFetch.ts
+++ b/ui/src/lib/apiFetch.ts
@@ -6,6 +6,11 @@ const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
let csrfTokenPromise: Promise<string> | null = null;
+const REMOTE_AUTH_RECOVERY_ERRORS = new Set([
+ 'remote_access_login_required',
+ 'remote_access_authorization_refresh_required',
+]);
+
function readCookie(name: string): string | null {
if (typeof document === 'undefined') {
return null;
@@ -73,9 +78,9 @@ export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {})
// once and then stops re-running on ordinary navigation (so it doesn't
// re-mount the shell on every sidebar click). If the Avibe Cloud cookie
// expires after that, no component re-checks auth — but the server starts
- // answering /api/* with 401 `remote_access_login_required`. Detect it here
- // and trigger the same full-page login redirect the guard uses, so the user
- // lands on the login flow instead of a wall of silently-failing fetches.
+ // answering /api/* with a remote login/authorization-refresh 401. Detect it
+ // here and trigger the same full-page login redirect the guard uses, so the
+ // user lands on the login flow instead of a wall of silently-failing fetches.
if (response.status === 401) {
void maybeRedirectOnRemoteAuthExpiry(response.clone());
}
@@ -95,7 +100,8 @@ async function maybeRedirectOnRemoteAuthExpiry(response: Response): Promise<void
// Non-JSON 401 — not the remote-access signal; let the caller handle it.
return;
}
- if ((payload as { error?: string } | null)?.error !== 'remote_access_login_required') {
+ const error = (payload as { error?: string } | null)?.error;
+ if (!error || !REMOTE_AUTH_RECOVERY_ERRORS.has(error)) {
return;
}
// A cross-origin OAuth redirect from an iOS Home-Screen app opens in a
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 004ffe0ec..3cc3ce99a 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2459,9 +2459,24 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
finally:
store.close()
+ authorization_refresh_at = None
+ remote_payload = _remote_access_websocket_session_claims(websocket, _load_remote_access_config())
+ if remote_payload is not None:
+ from vibe import remote_access
+
+ authorization_refresh_at = remote_access.session_authorization_refresh_deadline(remote_payload)
+
await websocket.accept(subprotocol="vite-hmr")
try:
- await _proxy_show_runtime_websocket(websocket, session_id)
+ proxy = _proxy_show_runtime_websocket(websocket, session_id)
+ if authorization_refresh_at is None:
+ await proxy
+ else:
+ timeout = max(0.0, authorization_refresh_at - time.time())
+ await asyncio.wait_for(proxy, timeout=timeout)
+ except asyncio.TimeoutError:
+ logger.info("show_runtime.authorization_refresh session=%s", session_id)
+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
except Exception:
logger.debug("Show runtime HMR websocket unavailable", exc_info=True)
await websocket.close(code=1011)