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(chat): wait for transcript hydration before rendering (#1438)
Call Whiteddbbcd465d1c
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsxnew file mode 100644index 000000000..1824b562c--- /dev/null+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx@@ -0,0 +1,239 @@+/** @vitest-environment jsdom */++import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { MemoryRouter, Route, Routes } from 'react-router-dom';++const mocks = vi.hoisted(() => ({+ api: {+ connectWorkbenchEvents: vi.fn(),+ getCachedSessionDraft: vi.fn(),+ getSession: vi.fn(),+ getSessionBootstrap: vi.fn(),+ getTurnState: vi.fn(),+ getWorkbenchPrefs: vi.fn(),+ listSessionMessages: vi.fn(),+ listSessionQueue: vi.fn(),+ onSessionArchived: vi.fn(),+ },+ events: null as null | {+ onConnected: () => void;+ onAuthorizationChanged: (data: { resource_kinds?: string[] }) => void;+ },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('../../context/ApiContext', () => ({+ useApi: () => mocks.api,+}));++vi.mock('../../context/ToastContext', () => ({+ useToast: () => ({ showToast: vi.fn() }),+}));++vi.mock('../../context/WorkbenchInboxContext', () => ({+ useWorkbenchInbox: () => ({ unreadBySession: {}, markRead: vi.fn() }),+}));++vi.mock('../../context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => ({+ capabilities: {+ can_chat: true,+ can_manage_instance: false,+ can_use_show_pages: false,+ can_use_vault_secrets: false,+ },+ }),+}));++vi.mock('../../context/ComposerBridgeContext', () => ({+ useRegisterComposerTarget: vi.fn(),+}));++vi.mock('../../context/WindowManagerContext', () => ({+ useWindowManager: () => ({ focusedId: null, focusCanvas: vi.fn() }),+}));++vi.mock('../../lib/useIsDesktop', () => ({+ isDesktopViewport: () => false,+ useIsDesktop: () => false,+}));++vi.mock('../../lib/useIosKeyboardInset', () => ({+ useIosKeyboardInset: vi.fn(),+}));++vi.mock('../../lib/useFileDrop', () => ({+ useFileDrop: () => ({ dragging: false, handlers: {} }),+}));++vi.mock('../../lib/usePendingVaultRequests', () => ({+ usePendingVaultRequests: () => ({ requests: [], refresh: vi.fn() }),+}));++vi.mock('./useSessionActions', () => ({+ useSessionActions: () => ({+ actions: [],+ archiveDialog: null,+ requestArchive: vi.fn(),+ canArchive: false,+ }),+}));++vi.mock('./useShowPageAnnotation', () => ({+ useShowPageAnnotation: () => ({+ state: { enabled: false, mode: 'smart' },+ setIframe: vi.fn(),+ handleIframeLoad: vi.fn(),+ enable: vi.fn(),+ disable: vi.fn(),+ setMode: vi.fn(),+ }),+}));++vi.mock('./Composer', () => ({+ Composer: () => null,+}));++import { ChatPage } from './ChatPage';++type Deferred<T> = {+ promise: Promise<T>;+ resolve: (value: T) => void;+ reject: (reason: unknown) => void;+};++const deferred = <T,>(): Deferred<T> => {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((done, fail) => {+ resolve = done;+ reject = fail;+ });+ return { promise, resolve, reject };+};++const idleTurnState = {+ foreground: 'idle',+ native_turn_started: false,+ pending_input_count: 0,+ background_activities: [],+ pending_activity_output_count: 0,+ connection: 'connected',+};++const bootstrapPayload = (sessionId: string) => ({+ session: { id: sessionId },+ capabilities: { can_chat: true },+ agents: [],+ default_agent_name: null,+ config: { ui: {} },+ messages: [],+ next_before_id: null,+ turn_state: idleTurnState,+ queued: [],+ draft: { text: '' },+});++describe('ChatPage transcript hydration', () => {+ let sessionRow: Deferred<{ id: string }>;+ let bootstrap: Deferred<never>;++ beforeEach(() => {+ sessionRow = deferred();+ bootstrap = deferred();+ mocks.events = null;+ vi.clearAllMocks();++ mocks.api.connectWorkbenchEvents.mockImplementation((events) => {+ mocks.events = events;+ return () => {};+ });+ mocks.api.getCachedSessionDraft.mockReturnValue(null);+ mocks.api.getSession.mockReturnValue(sessionRow.promise);+ mocks.api.getSessionBootstrap.mockReturnValue(bootstrap.promise);+ mocks.api.getTurnState.mockResolvedValue(idleTurnState);+ mocks.api.getWorkbenchPrefs.mockResolvedValue({});+ mocks.api.listSessionMessages.mockResolvedValue({ messages: [] });+ mocks.api.listSessionQueue.mockResolvedValue([]);+ mocks.api.onSessionArchived.mockReturnValue(() => {});+ });++ afterEach(cleanup);++ it('keeps the loading view when SSE Session-row recovery beats transcript bootstrap', async () => {+ render(+ <MemoryRouter initialEntries={['/chat/session-new']}>+ <Routes>+ <Route path="/chat/:sessionId" element={<ChatPage />} />+ </Routes>+ </MemoryRouter>,+ );++ await act(async () => Promise.resolve());+ expect(mocks.events).not.toBeNull();++ act(() => mocks.events?.onConnected());+ await act(async () => sessionRow.resolve({ id: 'session-new' }));++ expect(screen.getByText('common.loading')).toBeTruthy();+ expect(screen.queryByText('chat.transcriptEmpty')).toBeNull();+ });++ it('ignores a bootstrap failure after a newer same-route refresh starts', async () => {+ const staleBootstrap = deferred<never>();+ const currentBootstrap = deferred<never>();+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });+ mocks.api.getSessionBootstrap+ .mockReset()+ .mockReturnValueOnce(staleBootstrap.promise)+ .mockReturnValueOnce(currentBootstrap.promise);++ render(+ <MemoryRouter initialEntries={['/chat/session-new']}>+ <Routes>+ <Route path="/chat/:sessionId" element={<ChatPage />} />+ </Routes>+ </MemoryRouter>,+ );++ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(1));+ act(() => mocks.events?.onAuthorizationChanged({ resource_kinds: [] }));+ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(2));++ await act(async () => staleBootstrap.reject(new Error('stale bootstrap failed')));++ expect(screen.getByText('common.loading')).toBeTruthy();+ expect(screen.queryByText('stale bootstrap failed')).toBeNull();+ });++ it('ignores a bootstrap success after a newer same-route refresh starts', async () => {+ const staleBootstrap = deferred<ReturnType<typeof bootstrapPayload>>();+ const currentBootstrap = deferred<never>();+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });+ mocks.api.getSessionBootstrap+ .mockReset()+ .mockReturnValueOnce(staleBootstrap.promise)+ .mockReturnValueOnce(currentBootstrap.promise);++ render(+ <MemoryRouter initialEntries={['/chat/session-new']}>+ <Routes>+ <Route path="/chat/:sessionId" element={<ChatPage />} />+ </Routes>+ </MemoryRouter>,+ );++ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(1));+ act(() => mocks.events?.onAuthorizationChanged({ resource_kinds: [] }));+ await waitFor(() => expect(mocks.api.getSessionBootstrap).toHaveBeenCalledTimes(2));++ await act(async () => staleBootstrap.resolve(bootstrapPayload('session-new')));++ expect(screen.getByText('common.loading')).toBeTruthy();+ expect(screen.queryByText('chat.transcriptEmpty')).toBeNull();+ });+});diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 2a2064a75..90d71d063 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -493,6 +493,12 @@ export const ChatPage: React.FC = () => {const [agents, setAgents] = useState<VibeAgentBrief[]>([]);const [defaultAgentName, setDefaultAgentName] = useState<string | null>(null);const [messages, setMessages] = useState<WorkbenchMessage[]>([]);+ // A Session row can arrive from lightweight SSE recovery before the combined+ // bootstrap installs this route's messages. Keep that row from exposing the+ // reset empty array as a real empty transcript. The marker survives same-route+ // reconnect/auth refreshes so an already visible chat stays visible.+ const [hydratedTranscriptSessionId, setHydratedTranscriptSessionId] = useState<string | null>(null);+ const [failedBootstrapSessionId, setFailedBootstrapSessionId] = useState<string | null>(null);const provisionPlacement = useMemo(() => placeVaultProvisionRequests(messages, vaultRequests),[messages, vaultRequests],@@ -779,6 +785,10 @@ export const ChatPage: React.FC = () => {// session's rows into the current one (Codex P2).const sessionIdRef = useRef(sessionId);sessionIdRef.current = sessionId;+ // Same-route refreshes can overlap (for example, the initial load and an+ // authorization refresh). Only the latest bootstrap may commit state: a+ // superseded success or failure describes an older authorization snapshot.+ const bootstrapRequestGenerationRef = useRef(0);const appendMessage = useCallback((msg: WorkbenchMessage) => {setMessages((prev) => {@@ -1143,16 +1153,23 @@ export const ChatPage: React.FC = () => {const refresh = useCallback(async () => {if (!sessionId) return;+ const requestGeneration = ++bootstrapRequestGenerationRef.current;+ const requestIsCurrent = () => (+ sessionId === sessionIdRef.current+ && requestGeneration === bootstrapRequestGenerationRef.current+ );setLoading(true);setError(null);+ setFailedBootstrapSessionId((current) => current === sessionId ? null : current);try {// Initial chat open needs the same recent tail window, queue, draft,// route/config state, and current turn state. Fetch them as one bootstrap// payload so remote links don't pay a tunnel round-trip per widget.const bootstrapIsCurrent = await sessionRowRefreshGateRef.current.begin();const bootstrap = await api.getSessionBootstrap(sessionId);- // Dropped if the user switched chats while this load was in flight.- if (sessionId !== sessionIdRef.current) return;+ // Drop a response if the user switched chats or a newer bootstrap for+ // this route began while it was in flight.+ if (!requestIsCurrent()) return;if (bootstrapIsCurrent()) {setSession(bootstrap.session);} else {@@ -1186,6 +1203,8 @@ export const ChatPage: React.FC = () => {// as a delivered bubble *and* sat in the queue strip, the exact double// render the live path already rejects.setMessages((prev) => mergeById(bootstrap.messages.filter(isTranscriptMessage), prev));+ setHydratedTranscriptSessionId(sessionId);+ setFailedBootstrapSessionId(null);setOlderCursor(bootstrap.next_before_id ?? null);setHistoricalWindow(false);// Chat Activity chips for past turns: resync the per-turn summary (row text@@ -1206,13 +1225,16 @@ export const ChatPage: React.FC = () => {if (bootstrap.turn_state.foreground === 'running') markWorking();else if (bootstrap.turn_state.foreground === 'idle') setWorking(false);} catch (err) {- // Only surface the error if we're still on the session that failed — a- // stale failure must not stamp an error onto the chat the user moved to.- if (sessionId === sessionIdRef.current) setError(errorMessage(err) ?? String(err));+ // A superseded failure must not stamp an error onto the newer request's+ // loading state, even when both requests belong to the same route.+ if (requestIsCurrent()) {+ setError(errorMessage(err) ?? String(err));+ setFailedBootstrapSessionId(sessionId);+ }} finally {- // Same guard: a stale load finishing must not flip the new session out of- // its own loading state into a premature not-found / error view (Codex P2).- if (sessionId === sessionIdRef.current) setLoading(false);+ // Same guard: a stale load finishing must not flip the latest request out+ // of its own loading state into a premature not-found / error view.+ if (requestIsCurrent()) setLoading(false);}}, [api, sessionId, markWorking, scheduleActivityRefresh, refreshSessionRow]);@@ -1221,6 +1243,7 @@ export const ChatPage: React.FC = () => {// load/subscribe — so the previous conversation / queue / draft never leak in// and the merge in ``refresh`` only ever unions same-session rows.useEffect(() => {+ bootstrapRequestGenerationRef.current += 1;// The gate is session-scoped. A PATCH for the previous chat may still be// pending after navigation, but it must never hold the new chat's bootstrap// or recovery reads hostage.@@ -1233,6 +1256,8 @@ export const ChatPage: React.FC = () => {setSession(null);setSessionCanChat(false);setMessages([]);+ setHydratedTranscriptSessionId(null);+ setFailedBootstrapSessionId(null);deepLinkWindowHandledRef.current = false;setOlderCursor(null);setHistoricalWindow(false);@@ -2298,8 +2323,8 @@ export const ChatPage: React.FC = () => {const viewState = chatSessionViewState({routeSessionId: sessionId,loadedSessionId: session?.id ?? null,- loading,- error,+ hydratedTranscriptSessionId,+ failedBootstrapSessionId,});if (viewState === 'loading') {return (diff --git a/ui/src/components/workbench/chatSessionViewState.test.ts b/ui/src/components/workbench/chatSessionViewState.test.tsindex 4c717d2ee..e0cc306a2 100644--- a/ui/src/components/workbench/chatSessionViewState.test.ts+++ b/ui/src/components/workbench/chatSessionViewState.test.ts@@ -3,39 +3,74 @@ import { describe, expect, it } from 'vitest';import { chatSessionViewState } from './chatSessionViewState';describe('chatSessionViewState', () => {- it.each([true, false])(- 'keeps an empty error-free session in loading state when loading=%s',- (loading) => {- expect(chatSessionViewState({- routeSessionId: 'session-new',- loadedSessionId: null,- loading,- error: null,- })).toBe('loading');- },- );+ it('keeps an unhydrated Session in loading state', () => {+ expect(chatSessionViewState({+ routeSessionId: 'session-new',+ loadedSessionId: null,+ hydratedTranscriptSessionId: null,+ failedBootstrapSessionId: null,+ })).toBe('loading');+ });it('keeps a row from the previous route out of the new chat', () => {expect(chatSessionViewState({routeSessionId: 'session-new',loadedSessionId: 'session-old',- loading: false,- error: null,+ hydratedTranscriptSessionId: 'session-old',+ failedBootstrapSessionId: 'session-old',+ })).toBe('loading');+ });++ it('keeps the route loading when Session-row recovery wins the bootstrap race', () => {+ expect(chatSessionViewState({+ routeSessionId: 'session-new',+ loadedSessionId: 'session-new',+ hydratedTranscriptSessionId: null,+ failedBootstrapSessionId: null,})).toBe('loading');});- it('shows content only for the current route and failure only for an explicit error', () => {+ it('shows a successfully hydrated route even during a background refresh', () => {expect(chatSessionViewState({routeSessionId: 'session-new',loadedSessionId: 'session-new',- loading: true,- error: null,+ hydratedTranscriptSessionId: 'session-new',+ failedBootstrapSessionId: 'session-new',})).toBe('ready');+ });++ it('waits for both the current Session row and its transcript in either completion order', () => {+ const routeSessionId = 'session-new';+ const states = [+ chatSessionViewState({+ routeSessionId,+ loadedSessionId: routeSessionId,+ hydratedTranscriptSessionId: null,+ failedBootstrapSessionId: null,+ }),+ chatSessionViewState({+ routeSessionId,+ loadedSessionId: null,+ hydratedTranscriptSessionId: routeSessionId,+ failedBootstrapSessionId: null,+ }),+ chatSessionViewState({+ routeSessionId,+ loadedSessionId: routeSessionId,+ hydratedTranscriptSessionId: routeSessionId,+ failedBootstrapSessionId: null,+ }),+ ];++ expect(states).toEqual(['loading', 'loading', 'ready']);+ });++ it('shows a route-owned bootstrap failure even if Session-row recovery succeeded', () => {expect(chatSessionViewState({routeSessionId: 'session-new',- loadedSessionId: null,- loading: false,- error: 'Session unavailable',+ loadedSessionId: 'session-new',+ hydratedTranscriptSessionId: null,+ failedBootstrapSessionId: 'session-new',})).toBe('failed');});});diff --git a/ui/src/components/workbench/chatSessionViewState.ts b/ui/src/components/workbench/chatSessionViewState.tsindex 768645de2..948b2fe0d 100644--- a/ui/src/components/workbench/chatSessionViewState.ts+++ b/ui/src/components/workbench/chatSessionViewState.ts@@ -3,22 +3,26 @@ export type ChatSessionViewState = 'loading' | 'ready' | 'failed';type ChatSessionViewStateInput = {routeSessionId: string;loadedSessionId: string | null;- loading: boolean;- error: string | null;+ hydratedTranscriptSessionId: string | null;+ failedBootstrapSessionId: string | null;};export function chatSessionViewState({routeSessionId,loadedSessionId,- loading,- error,+ hydratedTranscriptSessionId,+ failedBootstrapSessionId,}: ChatSessionViewStateInput): ChatSessionViewState {- if (loadedSessionId === routeSessionId) return 'ready';+ if (+ loadedSessionId === routeSessionId+ && hydratedTranscriptSessionId === routeSessionId+ ) return 'ready';- // A row from the previous route and an empty row awaiting a newer refresh are- // both pending states. Absence becomes a failure only after a request records- // an explicit error; it is never evidence that the session does not exist.- if (loadedSessionId !== null || loading || error === null) return 'loading';+ if (failedBootstrapSessionId === routeSessionId) return 'failed';- return 'failed';+ // The lightweight Session-row recovery can beat the transcript bootstrap.+ // Neither that row nor an empty messages array proves the route is ready: only+ // the route-scoped hydration marker can distinguish a real empty transcript+ // from the reset state that exists while bootstrap is still in flight.+ return 'loading';}