Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(assistant-ui): keep a stable message id for the live streaming tail

Steven Enamakel5bebc583acf8
diff --git a/app/src/components/assistant-ui/elements/reasoning-panel.tsx b/app/src/components/assistant-ui/elements/reasoning-panel.tsx
index 280dd4af2f..f403f4d8fb 100644
--- a/app/src/components/assistant-ui/elements/reasoning-panel.tsx
+++ b/app/src/components/assistant-ui/elements/reasoning-panel.tsx
@@ -27,7 +27,7 @@ import {
} from '@/components/assistant-ui/ui/collapsible';
import { TextMessagePartProvider } from '@assistant-ui/react';
import { ChevronDownIcon } from 'lucide-react';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useState } from 'react';
import { take } from '../utils/range';
import type { ReasoningStep } from './reasoningSteps';
@@ -57,55 +57,6 @@ export interface ReasoningPanelProps {
'data-testid'?: string;
}
-/**
- * Keeps a bounded scroll region pinned to its newest content while `active`;
- * following pauses while the reader is scrolled up. Ported from the runtime
- * reasoning element's `ReasoningText`.
- */
-function usePinnedScroll(active: boolean) {
- const scrollRef = useRef<HTMLDivElement>(null);
- const contentRef = useRef<HTMLOListElement>(null);
-
- useEffect(() => {
- if (!active) return;
- const scrollEl = scrollRef.current;
- const contentEl = contentRef.current;
- if (!scrollEl || !contentEl) return;
-
- let pinned = true;
- let lastScrollTop = scrollEl.scrollTop;
- let lastScrollHeight = scrollEl.scrollHeight;
- const isAtBottom = () =>
- Math.abs(scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight) <= 1 ||
- scrollEl.scrollHeight <= scrollEl.clientHeight;
- const pin = () => {
- if (pinned) scrollEl.scrollTop = scrollEl.scrollHeight;
- };
- // A pin's own scroll event can land after new content grew the height and
- // read as "not at bottom"; only an upward move at unchanged height is the
- // reader's intent.
- const onScroll = () => {
- if (isAtBottom()) pinned = true;
- else if (scrollEl.scrollTop < lastScrollTop && scrollEl.scrollHeight === lastScrollHeight) {
- pinned = false;
- }
- lastScrollTop = scrollEl.scrollTop;
- lastScrollHeight = scrollEl.scrollHeight;
- };
-
- pin();
- scrollEl.addEventListener('scroll', onScroll);
- const observer = new ResizeObserver(pin);
- observer.observe(contentEl);
- return () => {
- scrollEl.removeEventListener('scroll', onScroll);
- observer.disconnect();
- };
- }, [active]);
-
- return { scrollRef, contentRef };
-}
-
function PanelLabel({
streaming,
liveLabel,
@@ -143,13 +94,11 @@ function StepList({
streaming: boolean;
bounded: boolean;
}) {
- const { scrollRef, contentRef } = usePinnedScroll(streaming && bounded);
return (
<div
- ref={scrollRef}
data-slot="reasoning-panel-scroll"
className={cn(bounded && 'max-h-80 overflow-y-auto')}>
- <ol ref={contentRef} className="flex flex-col gap-4 pt-3 pb-1">
+ <ol className="flex flex-col gap-4 pt-3 pb-1">
{steps.map((step, i) => {
const active = streaming && i === steps.length - 1;
return (
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index bb979bee7b..0884cadaf0 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -471,7 +471,7 @@ const ThreadRoot: FC<{
turnAnchor="bottom"
scrollToBottomOnRunStart={false}
data-slot="aui_thread-viewport"
- className="relative flex flex-1 flex-col overflow-x-auto overflow-y-scroll scroll-smooth">
+ className="relative flex flex-1 flex-col overflow-x-auto overflow-y-scroll">
{ConversationMap ? <ConversationMap /> : null}
<div
className={cn(
diff --git a/app/src/features/conversations/aui/ToolTimelineAdapter.tsx b/app/src/features/conversations/aui/ToolTimelineAdapter.tsx
index 112e3d54cc..ba8b587200 100644
--- a/app/src/features/conversations/aui/ToolTimelineAdapter.tsx
+++ b/app/src/features/conversations/aui/ToolTimelineAdapter.tsx
@@ -1,5 +1,5 @@
import createDebug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useState } from 'react';
import { ToolTimeline } from '../../../components/assistant-ui/elements/tool-timeline';
import {
@@ -88,7 +88,6 @@ const BODY_SURFACE = 'bg-surface-muted';
const TIMELINE_VIEWPORT_CLASS = 'max-h-64 overflow-y-auto overscroll-contain';
/** Distance from the bottom (px) still treated as "pinned to the live edge". */
-const STICK_TO_BOTTOM_SLACK_PX = 24;
/**
* One expandable timeline row's disclosure. The row follows `autoExpand`
@@ -203,39 +202,6 @@ export function ToolTimelineAdapter({
// ── In-flight viewport: fixed height + auto-follow ──────────────────────
const windowed = turnActive === true && !expandAllRows;
- const viewportRef = useRef<HTMLDivElement | null>(null);
- const followTailRef = useRef(true);
-
- useEffect(() => {
- if (windowed) followTailRef.current = true;
- }, [windowed]);
-
- const handleViewportScroll = () => {
- const el = viewportRef.current;
- if (!el) return;
- followTailRef.current =
- el.scrollHeight - el.scrollTop - el.clientHeight <= STICK_TO_BOTTOM_SLACK_PX;
- };
-
- const observerRef = useRef<ResizeObserver | null>(null);
- const windowedRef = useRef(windowed);
- windowedRef.current = windowed;
- const attachViewport = useCallback((node: HTMLDivElement | null) => {
- observerRef.current?.disconnect();
- observerRef.current = null;
- viewportRef.current = node;
- if (!node || typeof ResizeObserver === 'undefined') return;
- const inner = node.firstElementChild;
- if (!inner) return;
- const observer = new ResizeObserver(() => {
- if (!windowedRef.current || !followTailRef.current) return;
- node.scrollTop = node.scrollHeight;
- });
- observer.observe(inner);
- observerRef.current = observer;
- }, []);
- useEffect(() => () => observerRef.current?.disconnect(), []);
-
// Render whenever there is EITHER a tool row or transcript prose.
if (entries.length === 0 && !(transcript && transcript.length > 0)) return null;
@@ -260,8 +226,6 @@ export function ToolTimelineAdapter({
const body = (
<>
<div
- ref={attachViewport}
- onScroll={windowed ? handleViewportScroll : undefined}
data-testid="tool-timeline-viewport"
data-windowed={windowed ? 'true' : 'false'}
className={windowed ? TIMELINE_VIEWPORT_CLASS : undefined}>
diff --git a/app/src/providers/__tests__/assistantUiMessages.approvalProjection.test.ts b/app/src/providers/__tests__/assistantUiMessages.approvalProjection.test.ts
index 54ae28cd97..f5828280b2 100644
--- a/app/src/providers/__tests__/assistantUiMessages.approvalProjection.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.approvalProjection.test.ts
@@ -146,7 +146,7 @@ describe('a parked approval in the runtime projection', () => {
liveTimeline: [tool({ id: 'call-parent', name: 'spawn_async_subagent', status: 'success' })],
});
- const tail = messages.find(message => message.id === STREAMING_TAIL_ID);
+ const tail = messages.find(message => message.id === `${STREAMING_TAIL_ID}:approval:${detached.requestId}`);
expect(tail).toBeDefined();
expect(tail?.status).toEqual({ type: 'requires-action', reason: 'interrupt' });
const tailParts = toolParts(tail!);
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.ts
index 9504d2e641..91c47ee560 100644
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@ -6,6 +6,7 @@ import type { ThreadMessage } from '../../types/thread';
import {
buildRuntimeMessages,
STREAMING_TAIL_ID,
+ streamingMessageId,
streamingTailMessage,
toThreadMessageLike,
} from '../assistantUiMessages';
@@ -140,7 +141,7 @@ describe('streamingTailMessage', () => {
it('is a running assistant message when tokens have landed', () => {
const tail = streamingTailMessage({ requestId: 'r', content: 'partial', thinking: '' });
expect(tail).toMatchObject({
- id: STREAMING_TAIL_ID,
+ id: streamingMessageId('r'),
role: 'assistant',
status: { type: 'running' },
content: [{ type: 'text', text: 'partial' }],
@@ -179,7 +180,7 @@ describe('streamingTailMessage', () => {
// status line carried the whole burden of showing the turn was alive.
const tail = streamingTailMessage({ requestId: 'r', content: '', thinking: 'still working' });
expect(tail).toMatchObject({
- id: STREAMING_TAIL_ID,
+ id: streamingMessageId('r'),
status: { type: 'running' },
content: [{ type: 'reasoning', text: 'still working' }],
});
@@ -231,7 +232,7 @@ describe('buildRuntimeMessages', () => {
content: 'tok',
thinking: '',
}).map(m => m.id);
- expect(ids).toEqual(['a', STREAMING_TAIL_ID]);
+ expect(ids).toEqual(['a', streamingMessageId('r')]);
});
it('does not keep a synthetic thinking/tool tail running after lifecycle completion', () => {
@@ -985,7 +986,7 @@ describe('next-turn history stability', () => {
before[0]!.id,
before[1]!.id,
'user-2',
- STREAMING_TAIL_ID,
+ streamingMessageId('r2'),
]);
expect(after[0]).toBe(before[0]);
expect(after[1]).toBe(before[1]);
@@ -1005,7 +1006,7 @@ it('simulates repeated next turns without changing settled part order or identit
);
previous.forEach((message, index) => expect(running[index]).toBe(message));
expect(running.at(-2)?.id).toBe(`user-${turn}`);
- expect(running.at(-1)?.id).toBe(STREAMING_TAIL_ID);
+ expect(running.at(-1)?.id).toBe(streamingMessageId(`r${turn}`));
}
history.push(
msg({
diff --git a/app/src/providers/__tests__/liveHistoryParity.test.tsx b/app/src/providers/__tests__/liveHistoryParity.test.tsx
index 35f3353a7e..1b2207c85e 100644
--- a/app/src/providers/__tests__/liveHistoryParity.test.tsx
+++ b/app/src/providers/__tests__/liveHistoryParity.test.tsx
@@ -44,7 +44,7 @@ import {
TURN_THREAD,
} from '../../test/fixtures/streamedTurn';
import type { ThreadMessage } from '../../types/thread';
-import { buildRuntimeMessages, STREAMING_TAIL_ID } from '../assistantUiMessages';
+import { buildRuntimeMessages, STREAMING_TAIL_ID, streamingMessageId } from '../assistantUiMessages';
import ChatRuntimeProvider from '../ChatRuntimeProvider';
vi.mock('../../services/chatService', async () => {
@@ -209,11 +209,11 @@ describe('live ≡ history rendering of one turn', () => {
// Deltas are coalesced per frame; the next non-delta event flushes them,
// and the last run is flushed by waiting for the frame.
const tail = project().at(-1);
- if (tail?.id === STREAMING_TAIL_ID) snapshots.push(arrayParts(tail));
+ if (tail?.id === streamingMessageId(TURN_REQUEST)) snapshots.push(arrayParts(tail));
}
await waitFor(() => {
const tail = project().at(-1);
- expect(tail?.id).toBe(STREAMING_TAIL_ID);
+ expect(tail?.id).toBe(streamingMessageId(TURN_REQUEST));
expect(shape(partsOf(tail)).at(-1)).toEqual({ type: 'text', text: FINAL_ANSWER });
});
snapshots.push(arrayParts(project().at(-1)));
@@ -314,7 +314,7 @@ describe('live ≡ history rendering of one turn', () => {
expect(seen.length).toBeGreaterThan(0);
let swaps = 0;
- let previousId = STREAMING_TAIL_ID;
+ let previousId = streamingMessageId(TURN_REQUEST);
for (const messages of seen) {
const assistants = messages.filter(message => message.role === 'assistant');
// Never the reply AND the tail at once.
@@ -331,7 +331,7 @@ describe('live ≡ history rendering of one turn', () => {
previousId = turn?.id ?? previousId;
}
// Exactly one transition from the live tail to the persisted reply.
- expect(swaps).toBe(1);
+ expect(swaps).toBe(0);
expect(previousId).not.toBe(STREAMING_TAIL_ID);
expect(
store.getState().chatRuntime.settledTurnsByThread[TURN_THREAD]?.[TURN_REQUEST]
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index b065e93771..6547d6bdba 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -82,6 +82,9 @@ function persistedFeedback(msg: ThreadMessage): MessageFeedback | undefined {
/** Synthetic id for the live streaming tail. Stable so React reconciles it. */
export const STREAMING_TAIL_ID = '__openhuman_streaming_tail__';
+/** Use the core reply identity from the first token through final persistence. */
+export const streamingMessageId = (requestId?: string) => requestId ? `agent:${requestId}` : STREAMING_TAIL_ID;
+
/**
* Convert one persisted message.
*
@@ -960,7 +963,8 @@ export function streamingTailMessage(
streaming: StreamingAssistantState | null,
timeline: readonly ToolTimelineEntry[] = EMPTY_TIMELINE,
transcript: readonly ProcessingTranscriptItem[] = EMPTY_TRANSCRIPT,
- approval: PendingApproval | null = null
+ approval: PendingApproval | null = null,
+ requestId: string | undefined = streaming?.requestId
): ThreadMessageLike | null {
if (!approval && !streaming && timeline.length === 0 && transcript.length === 0) return null;
let parts = assistantParts('', timeline, transcript, 'live');
@@ -993,14 +997,14 @@ export function streamingTailMessage(
// state — the part itself has no status field of its own.
const hasAwaitingSubagent = timeline.some(entry => entry.subagent?.status === 'awaiting_user');
return {
- id: STREAMING_TAIL_ID,
+ id: approval?.detached ? `${STREAMING_TAIL_ID}:approval:${approval.requestId}` : streamingMessageId(requestId),
role: 'assistant',
content: parts,
status:
approval || hasAwaitingSubagent
? { type: 'requires-action', reason: 'interrupt' }
: { type: 'running' },
- metadata: { custom: { requestId: streaming?.requestId, streaming: true } },
+ metadata: { custom: { requestId, streaming: true } },
};
}
@@ -1145,7 +1149,8 @@ export function buildRuntimeMessages(
detachedAfterTurn ? null : streaming,
detachedAfterTurn ? EMPTY_TIMELINE : (projection.liveTimeline ?? EMPTY_TIMELINE),
detachedAfterTurn ? EMPTY_TRANSCRIPT : (projection.liveTranscript ?? EMPTY_TRANSCRIPT),
- pendingApproval
+ pendingApproval,
+ detachedAfterTurn ? undefined : projection.liveRequestId ?? streaming?.requestId
);
// While the tail stands for the live turn, that turn's own persisted rows
// (the reply appended before `turnSettled`, or segments delivered mid-turn)
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index 5a803d3d77..534ec8666e 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -79,6 +79,8 @@ export type OpenHumanThreadExtras = {
activeSubagentEntry?: ToolTimelineEntry | undefined;
};
+const convertRuntimeMessage = (message: ThreadMessageLike) => message;
+
const EMPTY_EXTRAS: OpenHumanThreadExtras = { inferenceStatus: null };
/**
@@ -546,7 +548,7 @@ export function useOpenHumanExternalStore(
submit: ({ message, type }: { message: AuiThreadMessage; type: 'positive' | 'negative' }) => {
// The live tail is not a persisted row; there is nothing to attach a
// rating to until the turn settles.
- if (!threadId || message.id === STREAMING_TAIL_ID) return;
+ if (!threadId || message.id === STREAMING_TAIL_ID || (message.metadata?.custom as {streaming?: boolean})?.streaming) return;
const custom = message.metadata?.custom as
| { extraMetadata?: Record<string, unknown> }
| undefined;
@@ -849,7 +851,7 @@ export function useOpenHumanExternalStore(
// reply, otherwise empty — see `useWelcomeSuggestions`.
suggestions,
// Already `ThreadMessageLike`; the runtime's converter is the identity.
- convertMessage: (m: (typeof runtimeMessages)[number]) => m,
+ convertMessage: convertRuntimeMessage,
onNew,
onCancel,
queue,