The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(chat): read settled transcripts directly from core
Steven Enamakel2f4cc97c34e0
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsxindex ac50f5db3d..5596868489 100644--- a/app/src/features/conversations/Conversations.tsx+++ b/app/src/features/conversations/Conversations.tsx@@ -81,7 +81,6 @@ import {clearRuntimeForThread,clearThreadSendPending,enqueueFollowup,- fetchAndHydrateDerivedTranscript,fetchAndHydrateTurnState,hydrateThreadUsage,markThreadSendPending,@@ -730,12 +729,6 @@ const Conversations = ({if (selectedThreadId) {void dispatch(loadThreadMessages(selectedThreadId));void dispatch(fetchAndHydrateTurnState(selectedThreadId));- // Per-turn history: each past answer's own process trail. Phase C derives- // this from the append-only transcript projection- // (`threads_transcript_get`), auto-falling back to the legacy- // `turn_state_history` hydration when the derived path is off, errors, or- // the thread has no persisted transcript (legacy thread).- void dispatch(fetchAndHydrateDerivedTranscript(selectedThreadId));void threadApi.getTaskBoard(selectedThreadId).then(board => {diff --git a/app/src/features/conversations/components/ChatThreadView.tsx b/app/src/features/conversations/components/ChatThreadView.tsxindex 1841ca7cac..003c384a0a 100644--- a/app/src/features/conversations/components/ChatThreadView.tsx+++ b/app/src/features/conversations/components/ChatThreadView.tsx@@ -13,6 +13,7 @@ import {import { Conversation, ConversationContent } from '../../../components/ai-elements';import { useStickToBottom } from '../../../hooks/useStickToBottom';+import { useCoreTranscriptProjection } from '../../../providers/useOpenHumanExternalStore';import type { ProcessingTranscriptItem, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';import { useAppDispatch, useAppSelector } from '../../../store/hooks';import { persistReaction } from '../../../store/threadSlice';@@ -196,10 +197,6 @@ export const ChatThreadView = forwardRef<ChatThreadViewHandle, ChatThreadViewProthreadId ? (state.thread.messagesByThreadId[threadId] ?? EMPTY_MESSAGES) : EMPTY_MESSAGES);const toolTimelineByThread = useAppSelector(state => state.chatRuntime.toolTimelineByThread);- const turnTimelinesByThread = useAppSelector(state => state.chatRuntime.turnTimelinesByThread);- const turnTranscriptsByThread = useAppSelector(- state => state.chatRuntime.turnTranscriptsByThread- );const interruptedAssistantByThread = useAppSelector(state => state.chatRuntime.interruptedAssistantByThread);@@ -347,14 +344,16 @@ export const ChatThreadView = forwardRef<ChatThreadViewHandle, ChatThreadViewPro// own collapsed process trail above it. The latest turn is excluded upstream// (it renders as the live "agent insights" anchor), so there is no double// render. Empty for legacy messages without a `requestId`.- const selectedThreadTurnTimelines = threadId- ? (turnTimelinesByThread[threadId] ?? EMPTY_TURN_TIMELINES)- : EMPTY_TURN_TIMELINES;+ const settledRevision = `${messages.at(-1)?.id ?? ''}:${messages.at(-1)?.content.length ?? 0}`;+ const coreTranscript = useCoreTranscriptProjection(+ threadId,+ settledRevision,+ threadId ? streamingAssistantByThread[threadId]?.requestId : undefined+ );+ const selectedThreadTurnTimelines = coreTranscript.timelines ?? EMPTY_TURN_TIMELINES;// Sibling map: each past turn's persisted reasoning/narration trail, so a// reopened turn replays its thoughts, not just its tool cards (fix 1).- const selectedThreadTurnTranscripts = threadId- ? (turnTranscriptsByThread[threadId] ?? EMPTY_TURN_TRANSCRIPTS)- : EMPTY_TURN_TRANSCRIPTS;+ const selectedThreadTurnTranscripts = coreTranscript.transcripts ?? EMPTY_TURN_TRANSCRIPTS;const pastTurnAnchors = useMemo(() => {const anchors: Record<string, PastTurnAnchor> = {};const seen = new Set<string>();diff --git a/app/src/pages/__tests__/Conversations.render.test.tsx b/app/src/pages/__tests__/Conversations.render.test.tsxindex aa391a27dd..15e9d02bc4 100644--- a/app/src/pages/__tests__/Conversations.render.test.tsx+++ b/app/src/pages/__tests__/Conversations.render.test.tsx@@ -25,7 +25,6 @@ import chatRuntimeReducer, {setInferenceStatusForThread,setStreamingAssistantForThread,setToolTimelineForThread,- setTurnTimelinesForThread,} from '../../store/chatRuntimeSlice';import layoutReducer from '../../store/layoutSlice';import socketReducer from '../../store/socketSlice';@@ -76,6 +75,15 @@ vi.mock('../../services/api/threadApi', () => ({getThreadMessages: mockGetThreadMessages,getTurnState: vi.fn().mockResolvedValue(null),getTurnStateHistory: vi.fn().mockResolvedValue([]),+ getDerivedTranscript: vi+ .fn()+ .mockResolvedValue({+ threadId: 'none',+ items: [],+ total: 0,+ hasMore: false,+ hasTranscript: false,+ }),getTaskBoard: vi.fn().mockResolvedValue({ threadId: 't-1', cards: [], updatedAt: '2026-05-04T10:00:00Z' }),@@ -641,9 +649,18 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {mockGetThreads.mockResolvedValue({ threads: [thread], count: 1 });mockGetThreadMessages.mockResolvedValue({ messages, count: messages.length });- let store: ReturnType<typeof buildStore> | undefined;+ vi.mocked(threadApi.getDerivedTranscript).mockResolvedValueOnce({+ threadId: thread.id,+ items: [+ { kind: 'toolCall', callId: 'tc-1', name: 'read_file', status: 'success' },+ { kind: 'turnBoundary', requestId: 'req-1' },+ ],+ total: 2,+ hasMore: false,+ hasTranscript: true,+ });await act(async () => {- store = await renderConversations({+ await renderConversations({thread: {...selectedThreadState(thread),messagesByThreadId: { [thread.id]: messages },@@ -653,22 +670,7 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {});});- // No past-turn tool call before hydration.- expect(screen.queryByTestId('assistant-ui-tool-call')).not.toBeInTheDocument();-- // Hydrate the older turn's timeline (as fetchAndHydrateTurnHistory would).- await act(async () => {- store!.dispatch(- setTurnTimelinesForThread({- threadId: thread.id,- timelines: {- 'req-1': [{ id: 'tc-1', name: 'read_file', round: 0, seq: 0, status: 'success' }],- },- })- );- });-- // The past turn's tool call is projected into assistant-ui exactly once.+ // The past turn's core transcript is projected into assistant-ui exactly once.expect(await screen.findByTestId('assistant-ui-tool-call')).toHaveTextContent('Read File');});diff --git a/app/src/providers/AssistantUiRuntimeProvider.tsx b/app/src/providers/AssistantUiRuntimeProvider.tsxindex b35c7ba023..d03eec2c9f 100644--- a/app/src/providers/AssistantUiRuntimeProvider.tsx+++ b/app/src/providers/AssistantUiRuntimeProvider.tsx@@ -8,15 +8,11 @@ import { useOpenHumanExternalStore } from './useOpenHumanExternalStore';const debug = debugFactory('openhuman:assistant-ui');/**- * Mounts assistant-ui's runtime over the existing Redux state, scoped to ONE- * thread.+ * Mounts assistant-ui's runtime over one OpenHuman thread.*- * This is additive by design. Nothing below it is required to consume the- * runtime — the transcript, composer and tool timeline still render from Redux- * exactly as before — so mounting it cannot regress a surface that ignores it.- * What it provides is the runtime *context*: any component under it may use- * assistant-ui's hooks and primitives, and the two views of the conversation- * are guaranteed to agree because both read the same store.+ * Settled process history (reasoning, tools and sub-agents) is read directly+ * from the core transcript RPC, whose Rust projection cache is authoritative.+ * Redux only supplies the existing message list and live socket deltas.** ## Why the thread is a prop*diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsxindex 59ee25f279..0565d8879a 100644--- a/app/src/providers/ChatRuntimeProvider.tsx+++ b/app/src/providers/ChatRuntimeProvider.tsx@@ -40,7 +40,6 @@ import {clearStreamingAssistantForThread,endInferenceTurn,fetchAndHydrateCompletedTurnState,- fetchAndHydrateDerivedTranscript,markInferenceTurnStreaming,parseToolFailure,recordChatTurnUsage,@@ -78,7 +77,7 @@ import {setActiveThread,setSelectedThread,} from '../store/threadSlice';-import { DERIVED_TRANSCRIPT_ENABLED, IS_PROD } from '../utils/config';+import { IS_PROD } from '../utils/config';import { AssistantUiRuntimeProvider } from './AssistantUiRuntimeProvider';import { isProactiveConversationSurface, proactiveThreadPins } from './proactiveThreadPins';@@ -481,14 +480,6 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {// ending the live lifecycle) matters: `hydrateRuntimeFromSnapshot`// intentionally refuses to overwrite an actively streaming turn.await dispatch(fetchAndHydrateCompletedTurnState(event.thread_id));- // Live-turn seam: the turn just settled and its line was appended to the- // append-only transcript. Invalidate/refresh the thread's derived- // settled-turn trails so the next reopen is fresh. The just-finished turn- // is the newest, so the derived hydration skips it — this never fights the- // live anchor, and it does not touch any socket delta handler.- if (DERIVED_TRANSCRIPT_ENABLED) {- void dispatch(fetchAndHydrateDerivedTranscript(event.thread_id));- }};rtLog('subscribe_chat_events', { socket: socketStatus });diff --git a/app/src/providers/__tests__/AssistantUiRuntimeProvider.test.tsx b/app/src/providers/__tests__/AssistantUiRuntimeProvider.test.tsxindex f2f8e8e7dd..6ccc714038 100644--- a/app/src/providers/__tests__/AssistantUiRuntimeProvider.test.tsx+++ b/app/src/providers/__tests__/AssistantUiRuntimeProvider.test.tsx@@ -9,16 +9,35 @@*/import { useAui, useAuiState } from '@assistant-ui/react';import { combineReducers, configureStore } from '@reduxjs/toolkit';-import { act, render, screen } from '@testing-library/react';+import { act, render, screen, waitFor } from '@testing-library/react';import { Provider } from 'react-redux';import { afterEach, describe, expect, it, vi } from 'vitest';-import chatRuntimeReducer, { streamDeltaReceived } from '../../store/chatRuntimeSlice';+import { threadApi } from '../../services/api/threadApi';+import chatRuntimeReducer, {+ beginInferenceTurn,+ markInferenceTurnStreaming,+ streamDeltaReceived,+} from '../../store/chatRuntimeSlice';import threadReducer from '../../store/threadSlice';import type { ThreadMessage } from '../../types/thread';import { AssistantUiRuntimeProvider } from '../AssistantUiRuntimeProvider';import { __resetChatSurfaces, registerChatSurface } from '../chatSurfaceHandlers';+vi.mock('../../services/api/threadApi', () => ({+ threadApi: {+ getDerivedTranscript: vi+ .fn()+ .mockResolvedValue({+ threadId: 't-aui',+ items: [],+ total: 0,+ hasMore: false,+ hasTranscript: false,+ }),+ },+}));+const THREAD_ID = 't-aui';function msg(id: string, sender: 'user' | 'agent', content: string): ThreadMessage {@@ -63,6 +82,15 @@ function RuntimeProbe() {.map(m => m.content.map(p => (p.type === 'text' ? p.text : '')).join('')).join('|')}</div>+ <div data-testid="tools">+ {thread.messages+ .flatMap(message =>+ message.role === 'assistant'+ ? message.content.flatMap(part => (part.type === 'tool-call' ? [part.toolName] : []))+ : []+ )+ .join('|')}+ </div></div>);}@@ -91,12 +119,14 @@ describe('AssistantUiRuntimeProvider', () => {expect(screen.getByTestId('count')).toHaveTextContent('0');});- it('surfaces the live stream as a running tail message', () => {+ it('surfaces the live stream as a running tail message', async () => {const store = buildStore([msg('a', 'user', 'question')]);renderWith(store);expect(screen.getByTestId('count')).toHaveTextContent('1');act(() => {+ store.dispatch(beginInferenceTurn({ threadId: THREAD_ID }));+ store.dispatch(markInferenceTurnStreaming({ threadId: THREAD_ID }));store.dispatch(streamDeltaReceived({threadId: THREAD_ID,@@ -108,10 +138,39 @@ describe('AssistantUiRuntimeProvider', () => {);});- expect(screen.getByTestId('count')).toHaveTextContent('2');+ await waitFor(() => expect(screen.getByTestId('count')).toHaveTextContent('2'));expect(screen.getByTestId('text')).toHaveTextContent('question|partial answer');});+ it('reads settled reasoning and tools directly from the core transcript RPC', async () => {+ vi.mocked(threadApi.getDerivedTranscript).mockResolvedValueOnce({+ threadId: THREAD_ID,+ // RPC pages are newest-first: reverse traversal sees the boundary first.+ items: [+ {+ kind: 'toolCall',+ callId: 'call-web',+ name: 'web_fetch',+ args: { url: 'https://example.com' },+ result: 'Example Domain',+ status: 'success',+ },+ { kind: 'reasoning', text: 'I should fetch the source.' },+ { kind: 'turnBoundary', requestId: 'req-core' },+ ],+ total: 3,+ hasMore: false,+ hasTranscript: true,+ });+ const answer = msg('answer', 'agent', 'done');+ answer.extraMetadata = { requestId: 'req-core' };++ renderWith(buildStore([msg('question', 'user', 'fetch it'), answer]));++ await waitFor(() => expect(screen.getByTestId('tools')).toHaveTextContent('web_fetch'));+ expect(threadApi.getDerivedTranscript).toHaveBeenCalledWith(THREAD_ID, { limit: 500 });+ });+it('forwards onNew to the surface that owns the thread', async () => {const send = vi.fn(async () => {});registerChatSurface(THREAD_ID, { send });diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.tsindex ac93161d73..aab1a80f00 100644--- a/app/src/providers/useOpenHumanExternalStore.ts+++ b/app/src/providers/useOpenHumanExternalStore.ts@@ -1,6 +1,8 @@import type { AppendMessage } from '@assistant-ui/react';-import { useCallback, useMemo } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { mapDisplayItems } from '../features/conversations/derived/mapDisplayItems';+import { threadApi } from '../services/api/threadApi';import { useAppSelector } from '../store/hooks';import type { ThreadMessage } from '../types/thread';import { buildRuntimeMessages } from './assistantUiMessages';@@ -11,6 +13,69 @@ const EMPTY_TIMELINE: never[] = [];const EMPTY_TRANSCRIPT: never[] = [];const EMPTY_TURN_MAP = {};+type CoreTranscriptProjection = {+ threadId: string | null;+ timelines: ReturnType<typeof mapDisplayItems>['timelines'];+ transcripts: ReturnType<typeof mapDisplayItems>['transcripts'];+};++const EMPTY_CORE_TRANSCRIPT: CoreTranscriptProjection = {+ threadId: null,+ timelines: EMPTY_TURN_MAP,+ transcripts: EMPTY_TURN_MAP,+};++/**+ * Read settled process history straight from the core's transcript projection.+ * The Rust side owns a bounded, mtime-keyed LRU, so this hook deliberately does+ * not establish a second Redux transcript store or duplicate cache policy.+ */+export function useCoreTranscriptProjection(+ threadId: string | null,+ revision: string,+ liveRequestId: string | undefined+): CoreTranscriptProjection {+ const [projection, setProjection] = useState<CoreTranscriptProjection>(EMPTY_CORE_TRANSCRIPT);++ useEffect(() => {+ if (!threadId) {+ setProjection(EMPTY_CORE_TRANSCRIPT);+ return;+ }+ // Defensive for narrow test/embedder shims that expose only a subset of+ // threadApi. Production builds always provide this method.+ if (typeof threadApi.getDerivedTranscript !== 'function') {+ setProjection({ threadId, timelines: EMPTY_TURN_MAP, transcripts: EMPTY_TURN_MAP });+ return;+ }+ let cancelled = false;+ void threadApi+ .getDerivedTranscript(threadId, { limit: 500 })+ .then(page => {+ if (cancelled) return;+ if (!page.hasTranscript) {+ setProjection({ threadId, timelines: EMPTY_TURN_MAP, transcripts: EMPTY_TURN_MAP });+ return;+ }+ const skipRequestIds = liveRequestId ? new Set([liveRequestId]) : undefined;+ const mapped = mapDisplayItems(page.items, { skipRequestIds });+ setProjection({ threadId, timelines: mapped.timelines, transcripts: mapped.transcripts });+ })+ .catch(() => {+ // A missing/older core has no settled process trail; message text and+ // the live socket projection remain usable. Navigation must not fail.+ if (!cancelled) {+ setProjection({ threadId, timelines: EMPTY_TURN_MAP, transcripts: EMPTY_TURN_MAP });+ }+ });+ return () => {+ cancelled = true;+ };+ }, [liveRequestId, revision, threadId]);++ return projection.threadId === threadId ? projection : EMPTY_CORE_TRANSCRIPT;+}+/** Flatten an assistant-ui append payload down to the plain text our core takes. */function appendMessageText(message: AppendMessage): string {return message.content@@ -22,10 +87,9 @@ function appendMessageText(message: AppendMessage): string {/*** Build the `ExternalStoreAdapter` that backs `useExternalStoreRuntime`.*- * Read side: a pure projection of Redux. Write side: forwarded to the surface- * that owns the thread (see `chatSurfaceHandlers`). The runtime therefore gets- * a faithful, live view of the conversation and a working action API without- * holding any state of its own.+ * Settled messages and live deltas remain in their existing UI stores, while+ * reasoning/tool/sub-agent history comes directly from the core transcript+ * projection. Redux is not a second transcript database.*/export function useOpenHumanExternalStore(threadId: string | null) {const messages = useAppSelector(state =>@@ -48,15 +112,11 @@ export function useOpenHumanExternalStore(threadId: string | null) {? (state.chatRuntime.processingByThread?.[threadId] ?? EMPTY_TRANSCRIPT): EMPTY_TRANSCRIPT);- const turnTimelines = useAppSelector(state =>- threadId- ? (state.chatRuntime.turnTimelinesByThread?.[threadId] ?? EMPTY_TURN_MAP)- : EMPTY_TURN_MAP- );- const turnTranscripts = useAppSelector(state =>- threadId- ? (state.chatRuntime.turnTranscriptsByThread?.[threadId] ?? EMPTY_TURN_MAP)- : EMPTY_TURN_MAP+ const settledRevision = `${messages.at(-1)?.id ?? ''}:${messages.at(-1)?.content.length ?? 0}:${lifecycle ?? ''}`;+ const coreTranscript = useCoreTranscriptProjection(+ threadId,+ settledRevision,+ streaming?.requestId);// `started` and `streaming` are both in-flight. A completed turn can retain@@ -73,10 +133,10 @@ export function useOpenHumanExternalStore(threadId: string | null) {isRunning,liveTimeline,liveTranscript,- turnTimelines,- turnTranscripts,+ turnTimelines: coreTranscript.timelines,+ turnTranscripts: coreTranscript.transcripts,}),- [messages, streaming, isRunning, liveTimeline, liveTranscript, turnTimelines, turnTranscripts]+ [messages, streaming, isRunning, liveTimeline, liveTranscript, coreTranscript]);const onNew = useCallback(