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(workbench): constrain ActivityStrip and recover realtime (#947)

Call White842c97a03cdb
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 5bf13dd90..e29a488d2 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -321,6 +321,7 @@ export const ChatPage: React.FC = () => {
const workingRef = useRef(working);
workingRef.current = working;
const [runtimeState, setRuntimeState] = useState<SessionRuntimeState>(emptyRuntimeState);
+ const [eventStreamConnected, setEventStreamConnected] = useState(false);
// Global background-work banner toggle (spec req 2), persisted server-side.
// Tri-state: null = not yet known → suppress the banner so a stored "off"
// never flashes on first paint; resolves to the stored value (ON when absent),
@@ -384,10 +385,6 @@ export const ChatPage: React.FC = () => {
setLiveRows(next.rows);
setLiveStartedAt(next.startedAt);
}, []);
- // Bumped on resume (tab visible again / network back) to force the transcript
- // subscription effect to reopen a possibly-dead SSE stream — see the
- // visibility effect below.
- const [connectionEpoch, setConnectionEpoch] = useState(0);
// Lifecycle guards for ``syncTurnState``'s clear-on-idle (Codex P2):
// - ``turnEpochRef`` bumps every time a turn STARTS (local send / send-now /
// observed ``turn.start``). syncTurnState captures it before its request and
@@ -781,11 +778,11 @@ export const ChatPage: React.FC = () => {
// directions: sets Stop when a turn is live, and clears a stale Stop (a
// ``turn.end`` we missed while the socket was down) when the controller reports
// idle — guarded so it can't drop a turn that's genuinely starting.
- const syncTurnState = useCallback(async () => {
+ const syncTurnState = useCallback(async (options?: { quiet?: boolean }) => {
if (!sessionId) return;
const epochAtRequest = turnEpochRef.current;
try {
- const res = await api.getTurnState(sessionId);
+ const res = await api.getTurnState(sessionId, { handleError: !options?.quiet });
if (sessionId !== sessionIdRef.current) return;
if (res.foreground === 'unknown') return;
setRuntimeState(res);
@@ -1063,15 +1060,21 @@ export const ChatPage: React.FC = () => {
// a native bind whose turn.end we missed.
void reconcile();
void refreshQueue();
- void syncTurnState();
+ void syncTurnState({ quiet: true });
void refreshSessionRowUntilNativeBound();
},
+ onConnectionState: (state) => {
+ const connected = state === 'connected';
+ setEventStreamConnected(connected);
+ if (!connected) void syncTurnState({ quiet: true });
+ },
onError: () => {
- // Browser EventSource auto-reconnects; keep the page usable.
+ // ApiContext owns the explicit retry loop; keep the page usable while
+ // the turn-state fallback below reconciles durable activity data.
},
- }, { reconnect: connectionEpoch > 0 });
+ });
return disconnect;
- }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, refreshSessionRowUntilNativeBound, markWorking, connectionEpoch, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive]);
+ }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, refreshSessionRowUntilNativeBound, markWorking, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive]);
// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the
// SSE feed can be suspended without a clean reconnect, dropping the reply.
@@ -1079,32 +1082,21 @@ export const ChatPage: React.FC = () => {
// catch up to durable storage.
useEffect(() => {
if (!sessionId) return;
- const onVisible = () => {
+ const resync = () => {
if (document.visibilityState !== 'visible') return;
// A suspended tab can drop the reply AND the turn.end, so recover all
// three: missed rows, the queue, and the working/Stop state (Codex P2).
void reconcile();
void refreshQueue();
- void syncTurnState();
- // The immediate reconcile above only catches up to NOW; if the socket
- // itself is dead (iOS can leave EventSource in a zombie OPEN state that
- // never auto-reconnects), it would be the last update until the next
- // resume. Reopen the stream so live events keep flowing while the page
- // stays foregrounded — the reopen's onConnected re-runs reconcile
- // (idempotent).
- setConnectionEpoch((e) => e + 1);
- };
- document.addEventListener('visibilitychange', onVisible);
- // Network flaps (mobile handoff, sleep/wake) can kill the stream without a
- // visibility change; reopen it on ``online`` too (only while foregrounded —
- // a background resume is handled by visibilitychange).
- const onOnline = () => {
- if (document.visibilityState === 'visible') setConnectionEpoch((e) => e + 1);
+ void syncTurnState({ quiet: true });
};
- window.addEventListener('online', onOnline);
+ document.addEventListener('visibilitychange', resync);
+ window.addEventListener('online', resync);
+ window.addEventListener('focus', resync);
return () => {
- document.removeEventListener('visibilitychange', onVisible);
- window.removeEventListener('online', onOnline);
+ document.removeEventListener('visibilitychange', resync);
+ window.removeEventListener('online', resync);
+ window.removeEventListener('focus', resync);
};
}, [sessionId, reconcile, refreshQueue, syncTurnState]);
@@ -1126,13 +1118,14 @@ export const ChatPage: React.FC = () => {
runtimeState.background_activities.length > 0 ||
runtimeState.pending_activity_output_count > 0 ||
runtimeState.connection === 'reconnecting';
- if (!working && !hasBackgroundState) return;
+ const needsStreamFallback = !eventStreamConnected;
+ if (!working && !hasBackgroundState && !needsStreamFallback) return;
const interval = window.setInterval(() => {
if (document.visibilityState !== 'visible') return;
- void syncTurnState();
- }, hasBackgroundState ? ACTIVITY_RECONCILE_INTERVAL_MS : WORKING_RECONCILE_INTERVAL_MS);
+ void syncTurnState({ quiet: needsStreamFallback });
+ }, hasBackgroundState || needsStreamFallback ? ACTIVITY_RECONCILE_INTERVAL_MS : WORKING_RECONCILE_INTERVAL_MS);
return () => window.clearInterval(interval);
- }, [working, runtimeState.background_activities.length, runtimeState.pending_activity_output_count, runtimeState.connection, syncTurnState]);
+ }, [working, runtimeState.background_activities.length, runtimeState.pending_activity_output_count, runtimeState.connection, eventStreamConnected, syncTurnState]);
const sendMessage = useCallback(
async (
@@ -1889,7 +1882,11 @@ export const ChatPage: React.FC = () => {
) : null
}
/>
- <ActivityStrip state={runtimeState} sessionId={sessionId ?? ''} enabled={bannerEnabled === true} />
+ <ActivityStrip
+ state={runtimeState}
+ sessionId={sessionId ?? ''}
+ enabled={bannerEnabled === true}
+ />
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
{sessionId && pendingApprovals.length > 0 ? (
<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
@@ -2089,9 +2086,6 @@ const ActivityStrip: React.FC<{
const firstLabel = first
? resolveActivityLabel(first, t(`chat.activities.kind.${activityKindI18nKey(first)}`))
: '';
- const connectionVisible =
- active.length > 0 &&
- (state.connection === 'reconnecting' || state.connection === 'disconnected');
const expandable = active.length > 0;
const navigateTo = (path: string) => {
setOpen(false);
@@ -2104,7 +2098,7 @@ const ActivityStrip: React.FC<{
role="status"
aria-live="polite"
className={clsx(
- 'min-h-7 min-w-0 max-w-[420px] gap-2 px-3 py-1 text-[11px] font-normal shadow-sm shadow-mint/5',
+ 'min-h-7 min-w-0 max-w-full gap-2 px-3 py-1 text-[11px] font-normal shadow-sm shadow-mint/5',
expandable && 'cursor-pointer select-none',
)}
indicator={
@@ -2122,11 +2116,6 @@ const ActivityStrip: React.FC<{
: t('chat.activities.delivering', { count: pendingOutputs })}
{firstLabel ? ` · ${firstLabel}` : ''}
</span>
- {connectionVisible ? (
- <span className="shrink-0 border-l border-border-strong pl-2 text-gold">
- {t(`chat.activities.connection.${state.connection}`)}
- </span>
- ) : null}
{expandable ? (
<ChevronDown
className={clsx('size-3.5 shrink-0 text-muted transition-transform', open && 'rotate-180')}
@@ -2147,7 +2136,7 @@ const ActivityStrip: React.FC<{
<button
type="button"
aria-label={t('chat.activities.toggle')}
- className="block max-w-full rounded-full outline-none focus-visible:ring-2 focus-visible:ring-mint/40"
+ className="block w-fit max-w-[min(420px,100%)] rounded-full outline-none focus-visible:ring-2 focus-visible:ring-mint/40"
>
{pill}
</button>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 264be203e..30443a354 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1,9 +1,13 @@
-import React, { createContext, useContext, useMemo, useRef } from 'react';
+import React, { createContext, useContext, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
import { apiFetch } from '../lib/apiFetch';
import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
+import {
+ WorkbenchEventReconnectLoop,
+ type WorkbenchEventConnectionState,
+} from '../lib/workbenchEventConnection';
import type { DockDoc } from './DockContext';
// The workbench Dock API response shape ({ ok, dock }); the Dock document type
@@ -602,11 +606,11 @@ export type ApiContextType = {
listSessionQueue: (sessionId: string, options?: { cache?: boolean }) => Promise<{ queued: WorkbenchMessage[] }>;
removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;
sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
- getTurnState: (sessionId: string) => Promise<SessionRuntimeState>;
+ getTurnState: (sessionId: string, options?: { handleError?: boolean }) => Promise<SessionRuntimeState>;
getSessionDraft: (sessionId: string) => Promise<{ text: string }>;
setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;
- listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; cache?: boolean }) => Promise<InboxFeedResult>;
- connectWorkbenchEvents: (handlers: WorkbenchEventHandlers, options?: { reconnect?: boolean }) => () => void;
+ listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; cache?: boolean; handleError?: boolean }) => Promise<InboxFeedResult>;
+ connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;
getVibeAgent: (name: string) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;
createVibeAgent: (payload: VibeAgentCreatePayload) => Promise<{ ok: boolean; agent: VibeAgentFull }>;
@@ -914,6 +918,7 @@ export type WorkbenchEventEnvelope<T = unknown> = {
export type WorkbenchEventHandlers = {
onConnected?: (data: { sub_id: number; source?: 'browser' | 'controller' }) => void;
+ onConnectionState?: (state: WorkbenchEventConnectionState) => void;
onEventBridgeStatus?: (data: { connected: boolean }) => void;
onMessageNew?: (data: WorkbenchMessage) => void;
onSessionActivity?: (data: { session_id: string; scope_id: string | null; event: string; title?: string | null }) => void;
@@ -1769,6 +1774,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const eventHandlersRef = useRef(new Set<WorkbenchEventHandlers>());
const eventConnectionRef = useRef<{ sub_id: number; source?: 'browser' | 'controller' } | null>(null);
const eventBridgeConnectedRef = useRef(false);
+ const eventConnectionStateRef = useRef<WorkbenchEventConnectionState>('reconnecting');
+ const eventReconnectLoopRef = useRef<WorkbenchEventReconnectLoop | null>(null);
+ const wakeWorkbenchEventsRef = useRef<() => void>(() => {});
+ const stopWorkbenchEventsRef = useRef<() => void>(() => {});
const handleApiError = async (res: Response, path: string) => {
let errorMessage = `Request failed: ${path} (${res.status})`;
@@ -1868,6 +1877,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
};
+ const setWorkbenchEventConnectionState = (state: WorkbenchEventConnectionState) => {
+ if (eventConnectionStateRef.current === state) return;
+ eventConnectionStateRef.current = state;
+ dispatchToWorkbenchHandlers((handlers) => handlers.onConnectionState?.(state));
+ };
+
const parseWorkbenchEnvelope = <T,>(raw: string): WorkbenchEventEnvelope<T> | null => {
try {
return JSON.parse(raw) as WorkbenchEventEnvelope<T>;
@@ -1877,22 +1892,53 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
};
- const closeWorkbenchEventSource = () => {
- eventSourceRef.current?.close();
+ const closeActiveWorkbenchEventSource = () => {
+ const source = eventSourceRef.current;
eventSourceRef.current = null;
+ source?.close();
eventConnectionRef.current = null;
eventBridgeConnectedRef.current = false;
};
- const ensureWorkbenchEventSource = (options?: { reconnect?: boolean }) => {
- if (options?.reconnect) {
- closeWorkbenchEventSource();
+ function reconnectWorkbenchEventSource(): void {
+ if (eventHandlersRef.current.size === 0) return;
+ closeActiveWorkbenchEventSource();
+ openWorkbenchEventSource();
+ }
+
+ function getWorkbenchEventReconnectLoop(): WorkbenchEventReconnectLoop {
+ if (!eventReconnectLoopRef.current) {
+ eventReconnectLoopRef.current = new WorkbenchEventReconnectLoop({
+ reconnect: reconnectWorkbenchEventSource,
+ isVisible: () => document.visibilityState === 'visible',
+ });
+ }
+ return eventReconnectLoopRef.current;
+ }
+
+ function openWorkbenchEventSource(): void {
+ if (
+ eventSourceRef.current ||
+ eventHandlersRef.current.size === 0 ||
+ document.visibilityState !== 'visible'
+ ) return;
+
+ let source: EventSource;
+ try {
+ source = new EventSource('/api/events');
+ } catch (err) {
+ setWorkbenchEventConnectionState('reconnecting');
+ getWorkbenchEventReconnectLoop().failed();
+ const event = err instanceof Event ? err : new Event('error');
+ dispatchToWorkbenchHandlers((handlers) => handlers.onError?.(event));
+ return;
}
- if (eventSourceRef.current) return;
- const source = new EventSource('/api/events');
eventSourceRef.current = source;
+ setWorkbenchEventConnectionState('reconnecting');
+ getWorkbenchEventReconnectLoop().attemptStarted();
source.addEventListener('connected', (e: MessageEvent) => {
+ if (eventSourceRef.current !== source) return;
try {
const parsed = JSON.parse(e.data) as { sub_id?: number; type?: string; data?: unknown };
const sourceKind = typeof parsed.sub_id === 'number' ? 'browser' : 'controller';
@@ -1902,6 +1948,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
if (sourceKind === 'controller') {
eventBridgeConnectedRef.current = true;
+ setWorkbenchEventConnectionState('connected');
dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: true }));
}
} catch (err) {
@@ -1909,6 +1956,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
eventConnectionRef.current = null;
}
if (eventConnectionRef.current) {
+ getWorkbenchEventReconnectLoop().streamOpened();
const connected = eventConnectionRef.current;
dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.(connected));
}
@@ -2038,21 +2086,61 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
});
});
source.addEventListener('workbench.events.bridge.status', (e: MessageEvent) => {
+ if (eventSourceRef.current !== source) return;
const envelope = parseWorkbenchEnvelope<{ connected: boolean }>(e.data);
if (!envelope) return;
+ getWorkbenchEventReconnectLoop().streamOpened();
eventBridgeConnectedRef.current = envelope.data.connected;
+ setWorkbenchEventConnectionState(envelope.data.connected ? 'connected' : 'reconnecting');
dispatchToWorkbenchHandlers((handlers) => {
handlers.onAny?.(envelope);
handlers.onEventBridgeStatus?.(envelope.data);
});
});
source.onerror = (err) => {
- eventConnectionRef.current = null;
- eventBridgeConnectedRef.current = false;
+ if (eventSourceRef.current !== source) return;
+ closeActiveWorkbenchEventSource();
+ setWorkbenchEventConnectionState('reconnecting');
dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: false }));
dispatchToWorkbenchHandlers((handlers) => handlers.onError?.(err));
+ getWorkbenchEventReconnectLoop().failed();
};
+ }
+
+ const ensureWorkbenchEventSource = () => {
+ getWorkbenchEventReconnectLoop();
+ openWorkbenchEventSource();
+ };
+
+ const stopWorkbenchEventSource = () => {
+ closeActiveWorkbenchEventSource();
+ eventReconnectLoopRef.current?.stop();
+ eventReconnectLoopRef.current = null;
+ setWorkbenchEventConnectionState('reconnecting');
};
+ stopWorkbenchEventsRef.current = stopWorkbenchEventSource;
+
+ const wakeWorkbenchEvents = () => {
+ if (eventHandlersRef.current.size === 0 || document.visibilityState !== 'visible') return;
+ setWorkbenchEventConnectionState('reconnecting');
+ getWorkbenchEventReconnectLoop().wake();
+ };
+ wakeWorkbenchEventsRef.current = wakeWorkbenchEvents;
+
+ useEffect(() => {
+ const wakeIfVisible = () => {
+ if (document.visibilityState === 'visible') wakeWorkbenchEventsRef.current();
+ };
+ document.addEventListener('visibilitychange', wakeIfVisible);
+ window.addEventListener('online', wakeIfVisible);
+ window.addEventListener('focus', wakeIfVisible);
+ return () => {
+ document.removeEventListener('visibilitychange', wakeIfVisible);
+ window.removeEventListener('online', wakeIfVisible);
+ window.removeEventListener('focus', wakeIfVisible);
+ stopWorkbenchEventsRef.current();
+ };
+ }, []);
const requestJson = async (
path: string,
@@ -2499,7 +2587,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
);
return { ok: res.ok, ...payloadJson };
},
- getTurnState: async (sessionId) => {
+ getTurnState: async (sessionId, options) => {
const path = `/api/sessions/${encodeURIComponent(sessionId)}/turn-state`;
const res = await apiFetch(path);
if (res.status === 504) {
@@ -2515,6 +2603,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
}
if (!res.ok) {
+ if (options?.handleError === false) {
+ throw new ApiError(`Request failed: ${path} (${res.status})`, res.status, null);
+ }
await handleApiError(res, path);
}
return res.json();
@@ -2536,7 +2627,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.before) search.set('before', params.before);
const qs = search.toString();
const path = qs ? `/api/inbox?${qs}` : '/api/inbox';
- return params?.cache === false ? getJson(path) : getCachedJson(path);
+ const options = { handleError: params?.handleError };
+ return params?.cache === false ? getJson(path, options) : getCachedJson(path, 1500, options);
},
listVibeAgents: (params) => {
const search = new URLSearchParams();
@@ -2713,9 +2805,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return getCachedJson(qs ? `/api/harness/runs?${qs}` : '/api/harness/runs');
},
getHarnessRun: (runId) => getCachedJson(`/api/harness/runs/${encodeURIComponent(runId)}`),
- connectWorkbenchEvents: (handlers, options) => {
+ connectWorkbenchEvents: (handlers) => {
eventHandlersRef.current.add(handlers);
- ensureWorkbenchEventSource(options);
+ ensureWorkbenchEventSource();
+ queueMicrotask(() => {
+ if (eventHandlersRef.current.has(handlers)) {
+ handlers.onConnectionState?.(eventConnectionStateRef.current);
+ }
+ });
if (
eventConnectionRef.current &&
(eventConnectionRef.current.source !== 'controller' || eventBridgeConnectedRef.current)
@@ -2740,7 +2837,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return () => {
eventHandlersRef.current.delete(handlers);
if (eventHandlersRef.current.size === 0) {
- closeWorkbenchEventSource();
+ stopWorkbenchEventSource();
}
};
},
diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsx
index 0ab87b1a4..1c51aee75 100644
--- a/ui/src/context/WorkbenchInboxContext.tsx
+++ b/ui/src/context/WorkbenchInboxContext.tsx
@@ -56,8 +56,8 @@ const appendPage = (prev: InboxSession[], page: InboxSession[]): InboxSession[]
/** Provider that owns the Inbox state shared across WorkbenchSidebar + InboxPage.
*
- * Connects to ``/api/events`` (reopening the stream on resume — see the resync
- * effect) and updates the per-session feed in place: ``inbox.session.updated``
+ * Connects to ``/api/events`` and updates the per-session feed in place:
+ * ``inbox.session.updated``
* upserts + re-sorts a card (the realtime "bump to top"), ``inbox.unread.changed``
* refreshes the unread map after a mark-read elsewhere. Each (re)connect also
* does a full ``refresh()`` so events missed while the socket was down (the
@@ -79,10 +79,6 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const [nextCursor, setNextCursor] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
- // Bumped on resume (tab visible again / network back) to force the SSE
- // connection effect to tear down the (possibly dead) stream and reopen it.
- // See the resync effect below for why a frozen mobile PWA needs this.
- const [connectionEpoch, setConnectionEpoch] = useState(0);
// Mirror the cursor into a ref so ``loadMore`` can read the latest value
// without re-creating its identity (and the context value) on every page.
const cursorRef = useRef<string | null>(null);
@@ -92,9 +88,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const inboxSessionsRef = useRef<InboxSession[]>([]);
inboxSessionsRef.current = inboxSessions;
// Only the very first mount does the destructive first-page refresh; every
- // later effect rerun — an ``api`` identity change (e.g. a locale switch, which
- // ApiProvider documents as rebuilding the value) or a resume-driven
- // connectionEpoch bump — reconciles the loaded window instead, so a non-resume
+ // later effect rerun — such as an ``api`` identity change after a locale switch
+ // — reconciles the loaded window instead, so a non-resume
// rerun never collapses a multi-page feed back to page one.
const initialFetched = useRef(false);
@@ -160,7 +155,12 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const loadedIds = new Set(inboxSessionsRef.current.map((s) => s.session_id));
const limit = Math.min(Math.max(loadedIds.size, PAGE_SIZE), 100);
try {
- const result = await api.listInbox({ platform: 'avibe', limit, cache: false });
+ const result = await api.listInbox({
+ platform: 'avibe',
+ limit,
+ cache: false,
+ handleError: false,
+ });
setInboxSessions((prev) => {
const incoming = new Map(result.sessions.map((s) => [s.session_id, s]));
const merged = prev.map((s) => incoming.get(s.session_id) ?? s);
@@ -189,8 +189,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
useEffect(() => {
// First mount loads page one; every later rerun reconciles the loaded window
- // instead — whether the rerun is a resume-driven connectionEpoch bump or just
- // an ``api`` identity change (e.g. a locale switch rebuilding the value) — so
+ // instead when an ``api`` identity change rebuilds the value — so
// a non-resume rerun never collapses a multi-page feed back to page one. The
// broker fans events out live with no replay (sse_broker.py ``/api/events``),
// so anything missed while the socket was down must be re-read; plain HTTP,
@@ -230,37 +229,32 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
});
},
onError: (err) => {
- // Browser EventSource auto-reconnects on transient drops; the
- // visibility/online resync below covers what it can't — a frozen mobile
- // tab whose socket died without ever firing a clean error. Keep this a
- // log, not a crash, so the workbench stays usable.
+ // ApiContext owns the explicit reconnect loop. Keep this a log, not a
+ // crash, so the workbench stays usable during the HTTP fallback.
console.debug('[inbox] sse error', err);
},
- }, { reconnect: connectionEpoch > 0 });
+ });
return disconnect;
- }, [api, refresh, reconcile, connectionEpoch, applyUnreadMap]);
+ }, [api, refresh, reconcile, applyUnreadMap]);
// Recover after the OS suspended us. A backgrounded mobile PWA has its page
- // frozen and its SSE socket dropped, and the broker never replays the gap; on
- // iOS the stream frequently does NOT auto-reconnect (it can sit in a zombie
- // OPEN state that never fires onerror), so neither the live handlers nor the
- // refresh above re-fire on their own. Bump the connection epoch when the tab
- // becomes visible again or the network returns: the effect above tears the
- // dead stream down, reopens it, and re-reads the feed + unread map — so the
- // inbox cards and sidebar dots catch up to messages that arrived while away.
- // StatusContext (runtime status) and ChatPage (transcript) already resync on
- // visibility; the inbox feed was the surface missing it.
+ // frozen and its SSE socket dropped, and the broker never replays the gap;
+ // iOS can leave EventSource in a zombie OPEN state without onerror. ApiContext
+ // reopens the shared stream on visibility, online, and focus; independently
+ // reconcile the durable feed here so missed events never gate data freshness.
useEffect(() => {
const resync = () => {
- if (document.visibilityState === 'visible') setConnectionEpoch((e) => e + 1);
+ if (document.visibilityState === 'visible') void reconcile();
};
document.addEventListener('visibilitychange', resync);
window.addEventListener('online', resync);
+ window.addEventListener('focus', resync);
return () => {
document.removeEventListener('visibilitychange', resync);
window.removeEventListener('online', resync);
+ window.removeEventListener('focus', resync);
};
- }, []);
+ }, [reconcile]);
const totalUnread = useMemo(
() => Object.values(unreadBySession).reduce((sum, n) => sum + (n || 0), 0),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d18ffa08f..f9be93c45 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2361,10 +2361,6 @@
"taskOneShot": "One-time",
"taskRecurring": "Recurring",
"agentRun": "Agent run"
- },
- "connection": {
- "reconnecting": "Reconnecting",
- "disconnected": "Disconnected"
}
},
"agentActivity": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index be10bf019..9ddfba549 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2361,10 +2361,6 @@
"taskOneShot": "一次性",
"taskRecurring": "周期性",
"agentRun": "Agent 运行"
- },
- "connection": {
- "reconnecting": "重连中",
- "disconnected": "已断开"
}
},
"agentActivity": {
diff --git a/ui/src/lib/workbenchEventConnection.test.ts b/ui/src/lib/workbenchEventConnection.test.ts
new file mode 100644
index 000000000..832909834
--- /dev/null
+++ b/ui/src/lib/workbenchEventConnection.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ WorkbenchEventReconnectLoop,
+ WORKBENCH_EVENT_OPEN_TIMEOUT_MS,
+} from './workbenchEventConnection';
+
+describe('WorkbenchEventReconnectLoop', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('retries terminal failures forever with bounded backoff and resets after recovery', () => {
+ vi.useFakeTimers();
+ const reconnect = vi.fn();
+ const loop = new WorkbenchEventReconnectLoop({ reconnect, isVisible: () => true });
+
+ for (const delayMs of [1_000, 2_000, 4_000, 8_000, 15_000, 15_000]) {
+ loop.failed();
+ vi.advanceTimersByTime(delayMs - 1);
+ expect(reconnect).toHaveBeenCalledTimes(0);
+ vi.advanceTimersByTime(1);
+ expect(reconnect).toHaveBeenCalledTimes(1);
+ reconnect.mockClear();
+ }
+
+ loop.streamOpened();
+ loop.failed();
+ vi.advanceTimersByTime(999);
+ expect(reconnect).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(reconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('replaces a hung connection attempt and wakes immediately on foreground signals', () => {
+ vi.useFakeTimers();
+ let visible = true;
+ const reconnect = vi.fn();
+ const loop = new WorkbenchEventReconnectLoop({ reconnect, isVisible: () => visible });
+
+ loop.attemptStarted();
+ vi.advanceTimersByTime(WORKBENCH_EVENT_OPEN_TIMEOUT_MS - 1);
+ expect(reconnect).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(reconnect).toHaveBeenCalledTimes(1);
+
+ visible = false;
+ loop.failed();
+ vi.advanceTimersByTime(60_000);
+ expect(reconnect).toHaveBeenCalledTimes(1);
+
+ visible = true;
+ loop.wake();
+ expect(reconnect).toHaveBeenCalledTimes(2);
+
+ loop.stop();
+ loop.failed();
+ loop.wake();
+ vi.advanceTimersByTime(60_000);
+ expect(reconnect).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/ui/src/lib/workbenchEventConnection.ts b/ui/src/lib/workbenchEventConnection.ts
new file mode 100644
index 000000000..ff8498ee8
--- /dev/null
+++ b/ui/src/lib/workbenchEventConnection.ts
@@ -0,0 +1,85 @@
+export type WorkbenchEventConnectionState = 'connected' | 'reconnecting';
+
+export const WORKBENCH_EVENT_RETRY_INITIAL_MS = 1_000;
+export const WORKBENCH_EVENT_RETRY_MAX_MS = 15_000;
+export const WORKBENCH_EVENT_OPEN_TIMEOUT_MS = 20_000;
+
+type TimerHandle = ReturnType<typeof setTimeout>;
+
+interface WorkbenchEventReconnectLoopOptions {
+ reconnect: () => void;
+ isVisible: () => boolean;
+}
+
+/** Owns the retry policy; EventSource wiring stays in ApiContext. */
+export class WorkbenchEventReconnectLoop {
+ private readonly reconnect: () => void;
+ private readonly isVisible: () => boolean;
+ private retryTimer: TimerHandle | null = null;
+ private openTimer: TimerHandle | null = null;
+ private retryAttempt = 0;
+ private stopped = false;
+
+ constructor(options: WorkbenchEventReconnectLoopOptions) {
+ this.reconnect = options.reconnect;
+ this.isVisible = options.isVisible;
+ }
+
+ attemptStarted(): void {
+ if (this.stopped) return;
+ this.clearOpenTimer();
+ this.openTimer = setTimeout(() => {
+ this.openTimer = null;
+ if (!this.stopped && this.isVisible()) this.reconnect();
+ }, WORKBENCH_EVENT_OPEN_TIMEOUT_MS);
+ }
+
+ streamOpened(): void {
+ if (this.stopped) return;
+ this.retryAttempt = 0;
+ this.clearRetryTimer();
+ this.clearOpenTimer();
+ }
+
+ failed(): void {
+ if (this.stopped) return;
+ this.clearOpenTimer();
+ if (this.retryTimer !== null || !this.isVisible()) return;
+ const delayMs = Math.min(
+ WORKBENCH_EVENT_RETRY_INITIAL_MS * (2 ** this.retryAttempt),
+ WORKBENCH_EVENT_RETRY_MAX_MS,
+ );
+ if (delayMs < WORKBENCH_EVENT_RETRY_MAX_MS) this.retryAttempt += 1;
+ this.retryTimer = setTimeout(() => {
+ this.retryTimer = null;
+ if (!this.stopped && this.isVisible()) this.reconnect();
+ }, delayMs);
+ }
+
+ wake(): void {
+ if (this.stopped || !this.isVisible()) return;
+ this.retryAttempt = 0;
+ this.clearRetryTimer();
+ this.clearOpenTimer();
+ this.reconnect();
+ }
+
+ stop(): void {
+ this.stopped = true;
+ this.retryAttempt = 0;
+ this.clearRetryTimer();
+ this.clearOpenTimer();
+ }
+
+ private clearRetryTimer(): void {
+ if (this.retryTimer === null) return;
+ clearTimeout(this.retryTimer);
+ this.retryTimer = null;
+ }
+
+ private clearOpenTimer(): void {
+ if (this.openTimer === null) return;
+ clearTimeout(this.openTimer);
+ this.openTimer = null;
+ }
+}