Skip to content

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

Merge remote-tracking branch 'refs/remotes/upstream/main' into pr/6600

Steven Enamakel594bd338b273
diff --cc app/src/components/assistant-ui/lib/useDisclosure.ts
index 8d29c9072c,0000000000..f0b9b659d2
mode 100644,000000..100644
--- a/app/src/components/assistant-ui/lib/useDisclosure.ts
+++ b/app/src/components/assistant-ui/lib/useDisclosure.ts
@@@ -1,64 -1,0 +1,67 @@@
+import { useCallback, useState } from 'react';
+
+/**
+ * The user's open/closed choice for a disclosure, remembered by a stable key.
+ *
+ * Tool cards, delegation cards and reasoning blocks live inside assistant-ui's
+ * message tree, which unmounts and remounts them more often than it looks: a
+ * thread switch, the virtualised history, a message whose parts change shape.
+ * With the choice in local `useState` every remount reset it, so a card the
+ * user had opened snapped shut under them. Keyed by something that outlives the
+ * component (a tool-call id), the choice survives the remount.
+ *
+ * Only an explicit toggle is stored. Until the user touches a disclosure it
+ * follows `defaultOpen`, which callers derive from state that is the same live
+ * and on reload, so a streamed turn and the same turn reopened look alike.
+ *
+ * The store is module-scoped and deliberately not persisted: the choice matters
+ * for as long as the card is on screen in this session, not across launches.
+ * It is bounded so a long session cannot grow it without limit.
+ */
+const MAX_REMEMBERED = 500;
+const choices = new Map<string, boolean>();
+
+function remember(key: string, open: boolean): void {
+ // Re-insert so the Map's insertion order doubles as recency.
+ choices.delete(key);
+ choices.set(key, open);
+ if (choices.size > MAX_REMEMBERED) {
+ const oldest = choices.keys().next().value;
+ if (oldest !== undefined) choices.delete(oldest);
+ }
+}
+
+/** Read a remembered choice. Exposed for tests. */
+export function rememberedDisclosure(key: string): boolean | undefined {
+ return choices.get(key);
+}
+
+/** Forget every remembered choice. Exposed for tests. */
+export function resetRememberedDisclosures(): void {
+ choices.clear();
+}
+
+/**
+ * `[open, setOpen]` for a disclosure. With no `key` it is plain local state.
+ * The returned `open` is the user's choice when they made one, else
+ * `defaultOpen`.
+ */
+export function useDisclosure(
+ key: string | undefined,
+ defaultOpen: boolean
+): [boolean, (open: boolean) => void] {
- const [choice, setChoice] = useState<boolean | undefined>(() =>
- key === undefined ? undefined : choices.get(key)
++ // A virtualized card can stay mounted while its part changes identity. Keep
++ // the identity with the local value so card B never shows card A's choice.
++ const [local, setLocal] = useState<{ key: string | undefined; choice: boolean | undefined }>(
++ () => ({ key, choice: key === undefined ? undefined : choices.get(key) })
+ );
++ const choice = local.key === key ? local.choice : key === undefined ? undefined : choices.get(key);
+ const setOpen = useCallback(
+ (open: boolean) => {
+ if (key !== undefined) remember(key, open);
- setChoice(open);
++ setLocal({ key, choice: open });
+ },
+ [key]
+ );
+ return [choice ?? defaultOpen, setOpen];
+}
diff --cc app/src/components/assistant-ui/thread.tsx
index 26164ac9db,6fa034c896..0252237a61
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@@ -667,44 -648,15 +659,53 @@@ function useFollowBottom
// bottom" contract. Keying on `scrollTop` alone holds in both cases.
lastScrollTopRef.current = viewport.scrollTop;
+ // ...and the move up has to be the READER's. A falling `scrollTop` is not
+ // proof of that: a disclosure collapsing above the fold, content shrinking
+ // under a reply that swaps parts, and assistant-ui's `useScrollLock`
+ // (which writes the old `scrollTop` back on every scroll event while a
+ // disclosure animates) all lower it with nobody touching anything — and
+ // each used to switch following off mid-turn, leaving the reply streaming
+ // below the fold. So a decrease only counts within a short window after
+ // an input that can scroll: wheel, touch, a scroll key, or a press on the
+ // viewport itself (its scrollbar).
+ let userIntentAt = Number.NEGATIVE_INFINITY;
++ let scrollbarDragActive = false;
+ const markIntent = () => {
+ userIntentAt = window.performance.now();
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (SCROLL_KEYS.has(event.key)) markIntent();
+ };
+ const onPointerDown = (event: PointerEvent) => {
- if (event.target === viewport) markIntent();
++ if (event.target === viewport) {
++ scrollbarDragActive = true;
++ markIntent();
++ }
++ };
++ const clearScrollbarDrag = () => {
++ scrollbarDragActive = false;
+ };
+
const onScroll = () => {
if (distanceFromBottom() <= FOLLOW_BOTTOM_THRESHOLD_PX) {
followRef.current = true;
- } else if (viewport.scrollTop < lastScrollTopRef.current) {
+ } else if (
+ viewport.scrollTop < lastScrollTopRef.current &&
- window.performance.now() - userIntentAt <= USER_SCROLL_INTENT_WINDOW_MS
++ (scrollbarDragActive || window.performance.now() - userIntentAt <= USER_SCROLL_INTENT_WINDOW_MS)
+ ) {
followRef.current = false;
}
lastScrollTopRef.current = viewport.scrollTop;
};
viewport.addEventListener('scroll', onScroll, { passive: true });
+ viewport.addEventListener('wheel', markIntent, { passive: true });
+ viewport.addEventListener('touchmove', markIntent, { passive: true });
+ // Scroll keys are delivered to whatever has focus, not to the viewport.
+ const keyTarget = viewport.ownerDocument;
+ keyTarget.addEventListener('keydown', onKeyDown);
+ viewport.addEventListener('pointerdown', onPointerDown);
++ viewport.addEventListener('pointerup', clearScrollbarDrag);
++ viewport.addEventListener('pointercancel', clearScrollbarDrag);
const observer = new ResizeObserver(() => {
// Read the flag; do NOT recompute the distance here. By the time this
@@@ -746,10 -698,6 +747,12 @@@
return () => {
viewport.removeEventListener('scroll', onScroll);
+ viewport.removeEventListener('wheel', markIntent);
+ viewport.removeEventListener('touchmove', markIntent);
+ keyTarget.removeEventListener('keydown', onKeyDown);
+ viewport.removeEventListener('pointerdown', onPointerDown);
++ viewport.removeEventListener('pointerup', clearScrollbarDrag);
++ viewport.removeEventListener('pointercancel', clearScrollbarDrag);
observer.disconnect();
};
}, [contentRef, viewportRef]);
diff --cc app/src/features/conversations/components/AssistantUiChat.tsx
index cf32eec955,3018795343..5435349e6c
--- a/app/src/features/conversations/components/AssistantUiChat.tsx
+++ b/app/src/features/conversations/components/AssistantUiChat.tsx
@@@ -53,28 -32,16 +50,30 @@@ export function ComposerTextBridge(
const aui = useAui();
const composerText = useAuiState(selectComposerText);
const previousHostValue = useRef(value);
+ // Editor texts sent to the host that it has not echoed back yet.
+ const inFlight = useRef<string[]>([]);
useEffect(() => {
- // A host-side write (dictation, ESC restore, clear) wins for this pass.
if (previousHostValue.current !== value) {
previousHostValue.current = value;
- if (composerText !== value) aui.composer.setText(value);
- return;
+ const echoAt = inFlight.current.indexOf(value);
+ if (echoAt >= 0) {
+ // Our own write coming back (possibly behind newer typing): drop it and
+ // everything sent before it; the editor already holds newer text.
+ inFlight.current = inFlight.current.slice(echoAt + 1);
++ // Do not return: the editor may already contain text typed after this
++ // echo. Let the normal editor-to-host comparison forward it now.
++ } else {
++ // A host-side write (dictation, ESC restore, clear) wins for this pass.
++ inFlight.current = [];
++ if (composerText !== value) aui.composer.setText(value);
+ return;
+ }
- // A host-side write (dictation, ESC restore, clear) wins for this pass.
- inFlight.current = [];
- if (composerText !== value) aui.composer.setText(value);
- return;
}
- // Otherwise the editor changed and the host draft follows it.
- if (composerText !== value) onChange(composerText);
+ // Otherwise the editor changed and the host draft follows it, once per text.
+ if (composerText === value || inFlight.current.at(-1) === composerText) return;
+ inFlight.current.push(composerText);
+ startTransition(() => onChange(composerText));
}, [aui, composerText, onChange, value]);
return null;
diff --cc app/src/features/conversations/components/AssistantUiSubagentCall.tsx
index 7803f57abc,e978071fad..2448a2f3df
--- a/app/src/features/conversations/components/AssistantUiSubagentCall.tsx
+++ b/app/src/features/conversations/components/AssistantUiSubagentCall.tsx
@@@ -43,6 -42,6 +43,7 @@@ function ChildToolCallCard({ call }: {
detail={call.detail}
elapsedMs={call.elapsedMs}
failure={call.failure}
++ disclosureKey={call.callId}
/>
);
}
diff --cc app/src/providers/ChatRuntimeProvider.tsx
index 322a2206ba,7f9f2d9208..cf3f390387
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@@ -674,175 -664,480 +674,183 @@@ const ChatRuntimeProvider = ({ childre
};
rtLog('subscribe_chat_events', { socket: socketStatus });
- const cleanup = subscribeChatEvents({
- onInferenceStart: (event: ChatInferenceStartEvent) => {
- rtLog('inference_start', { thread: event.thread_id, request: event.request_id });
- // Fresh turn: drop the previous turn's live processing transcript so a
- // new turn's narration/steps don't append onto the old one.
- dispatch(clearProcessingForThread({ threadId: event.thread_id }));
- dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: { phase: 'thinking', iteration: 0, maxIterations: 0 },
- })
- );
- },
- onInferenceHeartbeat: (event: ChatInferenceHeartbeatEvent) => {
- // #4270: liveness beat — bump the per-thread counter so the
- // Conversations silence timer rearms even when the turn is in a long
- // prefill / buffered-reasoning phase that emits no other progress.
- rtLog('inference_heartbeat', { thread: event.thread_id, request: event.request_id });
- dispatch(bumpInferenceHeartbeatForThread({ threadId: event.thread_id }));
- },
- onIterationStart: (event: ChatIterationStartEvent) => {
- const prev = inferenceStatusRef.current[event.thread_id];
- rtLog('iteration_start', {
- thread: event.thread_id,
- request: event.request_id,
- iteration: event.round,
- });
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- phase: 'thinking',
- iteration: event.round,
- maxIterations: prev?.maxIterations ?? 0,
- },
- })
- );
- },
- onToolCall: (event: ChatToolCallEvent) => {
- const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- ...(prev ?? { iteration: event.round, maxIterations: 0 }),
- phase: 'tool_use',
- activeTool: event.tool_name,
- },
- })
- );
-
- const eventKey = `tool_call:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${toolEventIdentity(event)}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
-
- // Start (or extend) the tool-chain latency window for this turn (#4273).
- // Key by thread+request (same scheme as segment delivery) so parallel /
- // forked turns that share a thread_id keep independent chains (#4288).
- skillLatencyRef.current.noteToolCall(segmentDeliveryKey(event.thread_id, event.request_id));
-
- // Merge + processing-pointer are now a single reducer (Phase 3) — no
- // getState()/full-array rebuild in the provider.
- dispatch(
- toolCallReceived({
- threadId: event.thread_id,
- round: event.round,
- toolName: event.tool_name,
- toolCallId: event.tool_call_id,
- displayLabel: event.tool_display_label,
- displayDetail: event.tool_display_detail,
- })
- );
- },
- onToolResult: (event: ChatToolResultEvent) => {
- const eventKey = `tool_result:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.success}:${toolEventIdentity(event)}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
-
- // Settle the matching row in the reducer (Phase 3) — no getState() /
- // full-array rebuild. A no-op when no row matches.
- dispatch(
- toolResultReceived({
- threadId: event.thread_id,
- round: event.round,
- toolName: event.tool_name,
- toolCallId: event.tool_call_id,
- success: event.success,
- output: event.output,
- failure: event.failure,
- })
- );
-
- // Agent-first Workflow authoring (issue B4): a completed
- // `propose_workflow` call carries a `workflow_proposal` JSON payload
- // in `output` — surface it as a `WorkflowProposalCard` above the
- // composer. The tool only validates; only the card's "Save & enable"
- // action ever calls `flows_create`, so this dispatch alone can never
- // create a flow.
- const mainProposal = maybeParseWorkflowProposalTool(
- event.tool_name,
- event.success,
- event.output
- );
- if (mainProposal) {
- rtLog('workflow proposal parsed (main agent)', {
+ // Deltas are coalesced per frame; every other event flushes them first so
+ // ordering holds. See `chatDeltaCoalescer`.
+ const coalesced = withCoalescedDeltas<ChatTextDeltaEvent, ChatEventListeners>(
+ {
+ onInferenceStart: (event: ChatInferenceStartEvent) => {
+ rtLog('inference_start', { thread: event.thread_id, request: event.request_id });
+ // Fresh turn: drop the previous turn's live processing transcript so a
+ // new turn's narration/steps don't append onto the old one.
+ dispatch(clearProcessingForThread({ threadId: event.thread_id }));
++ // A queued primary follow-up starts with a clean timeline. Parallel
++ // branches have their own lane and must not erase the primary rows.
++ if (
++ !event.request_id ||
++ store.getState().chatRuntime.parallelRequestThreads[event.request_id] === undefined
++ ) {
++ dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries: [] }));
++ }
+ dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));
+ if (event.request_id) {
+ dispatch(liveTurnStarted({ threadId: event.thread_id, requestId: event.request_id }));
+ }
+ dispatch(
+ setInferenceStatusForThread({
+ threadId: event.thread_id,
+ status: { phase: 'thinking', iteration: 0, maxIterations: 0 },
+ })
+ );
+ },
+ onInferenceHeartbeat: (event: ChatInferenceHeartbeatEvent) => {
+ // #4270: liveness beat — bump the per-thread counter so the
+ // Conversations silence timer rearms even when the turn is in a long
+ // prefill / buffered-reasoning phase that emits no other progress.
+ rtLog('inference_heartbeat', { thread: event.thread_id, request: event.request_id });
+ // A parallel (forked) turn streams into its own lane and must NOT keep
+ // the thread's primary silence timer alive — otherwise a sibling branch
+ // would mask a stalled primary turn. Mirror the text/thinking-delta
+ // routing: ignore heartbeats owned by a parallel request.
+ if (store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined) {
+ return;
+ }
+ dispatch(bumpInferenceHeartbeatForThread({ threadId: event.thread_id }));
+ },
+ onIterationStart: (event: ChatIterationStartEvent) => {
+ const prev = inferenceStatusRef.current[event.thread_id];
+ rtLog('iteration_start', {
thread: event.thread_id,
- tool: event.tool_name,
- name: mainProposal.name,
+ request: event.request_id,
+ iteration: event.round,
});
dispatch(
- setWorkflowProposalForThread({ threadId: event.thread_id, proposal: mainProposal })
+ setInferenceStatusForThread({
+ threadId: event.thread_id,
+ status: {
+ phase: 'thinking',
+ iteration: event.round,
+ maxIterations: prev?.maxIterations ?? 0,
+ },
+ })
+ );
+ },
+ onToolCall: (event: ChatToolCallEvent) => {
+ const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
+ dispatch(
+ setInferenceStatusForThread({
+ threadId: event.thread_id,
+ status: {
+ ...(prev ?? { iteration: event.round, maxIterations: 0 }),
+ phase: 'tool_use',
+ activeTool: event.tool_name,
+ },
+ })
);
- }
- const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
- if (!current) return;
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: { ...current, phase: 'thinking', activeTool: undefined },
- })
- );
- },
- onSubagentSpawned: event => {
- // Event-seen guard, matching `onToolCall`/`onToolResult`. This socket
- // reconnects and redelivers freely (13+ times in one measured
- // session), and a replayed `subagent_spawned` that lands AFTER
- // `subagent_awaiting_user` looks exactly like `continue_subagent`
- // resuming the child — the reducer would clear the pause and the
- // question would vanish while the child was still blocked. `seq` is
- // the core's own answer to this: `(request_id, seq)` is stamped per
- // emission (`publish_seq_stamped`), so a redelivery repeats the pair
- // and a real resume never does. The reducer keeps its own durable
- // check for the case this bounded cache has already evicted.
- const eventKey = `subagent_spawned:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- ) {
- return;
- }
- const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- ...(prev ?? { iteration: event.round, maxIterations: 0 }),
- phase: 'subagent',
- activeSubagent: event.tool_name,
- },
- })
- );
+ const eventKey = `tool_call:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${toolEventIdentity(event)}`;
+ if (
+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
+ )
+ return;
- // Collapse the parent spawn/delegate row into the subagent row (one
- // entry per delegation) — merge now lives in the reducer (Phase 3).
- dispatch(
- subagentSpawned({
- threadId: event.thread_id,
- round: event.round,
- rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
- taskId: event.skill_id,
- agentId: event.tool_name,
- displayName: event.subagent?.display_name,
- workerThreadId: event.subagent?.worker_thread_id,
- mode: event.subagent?.mode,
- dedicatedThread: event.subagent?.dedicated_thread,
- // Identity of THIS emission, carried into the reducer so it can
- // tell a resume from a replay without depending on the cache above.
- spawnEventId: `${event.request_id ?? 'none'}:${event.seq ?? 'noseq'}`,
- })
- );
- },
- onSubagentAwaitingUser: (event: ChatSubagentDoneEvent) => {
- // Same guard, mirrored: a replayed `subagent_awaiting_user` arriving
- // after the child has resumed would re-park a running row.
- const eventKey = `subagent_awaiting_user:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- ) {
- return;
- }
- dispatch(
- subagentAwaitingUser({
- threadId: event.thread_id,
- rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
- // The core puts the child's `ask_user_clarification` question in
- // `message` (progress_bridge.rs:1055). It is the only copy of the
- // question the frontend ever receives.
- question: event.message,
- })
- );
- },
- onSubagentDone: (event: ChatSubagentDoneEvent) => {
- // Worktree isolation metadata (#3376) — present only for workers that ran
- // with `isolation = "worktree"`; drives the inline worktree row's
- // open/diff/remove affordances. Undefined fields leave the row untouched.
- dispatch(
- subagentDone({
- threadId: event.thread_id,
- rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
- success: event.success,
- iterations: event.subagent?.iterations,
- elapsedMs: event.subagent?.elapsed_ms,
- outputChars: event.subagent?.output_chars,
- worktreePath: event.subagent?.worktree_path,
- changedFiles: event.subagent?.changed_files,
- isDirty: event.subagent?.dirty_status,
- })
- );
+ // Start (or extend) the tool-chain latency window for this turn (#4273).
+ // Key by thread+request (same scheme as segment delivery) so parallel /
+ // forked turns that share a thread_id keep independent chains (#4288).
+ skillLatencyRef.current.noteToolCall(
+ segmentDeliveryKey(event.thread_id, event.request_id)
+ );
- // A detached sub-agent's spend reaches the composer here or nowhere.
- //
- // The parent turn's `chat_done` fired before this child finished, and
- // for a detached spawn the child's usage never entered the parent's
- // ledger — `detached_child()` sets `parent_subagent_usage` to `None` —
- // so `holistic_last_turn_usage` folded nothing and the reported totals
- // are parent-only. The core populates these fields ONLY when that is
- // the case, so adding them unconditionally is correct: for a blocking
- // spawn they are absent, because its spend is already inside the
- // `chat_done` figures (tokens AND cost). See #6459.
- const childInput = event.subagent?.input_tokens;
- const childOutput = event.subagent?.output_tokens;
- if (childInput !== undefined || childOutput !== undefined) {
+ // Merge + processing-pointer are now a single reducer (Phase 3) — no
+ // getState()/full-array rebuild in the provider.
dispatch(
- recordChatTurnUsage({
+ toolCallReceived({
threadId: event.thread_id,
- // The child's tokens go at the TOP level because that is what
- // `applyTurnUsage` folds into the thread totals the composer
- // shows — mirroring `chat_done`, whose top-level figures are
- // already parent+child. The `subAgents` entry below is the
- // per-agent breakdown, not the total.
- inputTokens: childInput ?? 0,
- outputTokens: childOutput ?? 0,
- cachedTokens: event.subagent?.cached_input_tokens ?? 0,
- costUsd: event.subagent?.cost_usd ?? 0,
- subAgentSpendOnly: true,
- subAgents: [
- {
- agentId: event.tool_name ?? 'subagent',
- inputTokens: childInput ?? 0,
- outputTokens: childOutput ?? 0,
- costUsd: event.subagent?.cost_usd ?? 0,
- },
- ],
+ round: event.round,
+ toolName: event.tool_name,
+ toolCallId: event.tool_call_id,
+ displayLabel: event.tool_display_label,
+ displayDetail: event.tool_display_detail,
+ args: event.args,
})
);
- }
+ },
+ onToolResult: (event: ChatToolResultEvent) => {
+ const eventKey = `tool_result:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.success}:${toolEventIdentity(event)}`;
+ if (
+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
+ )
+ return;
- const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
- if (!current) return;
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: { ...current, phase: 'thinking', activeSubagent: undefined },
- })
- );
- },
- onSubagentIterationStart: event => {
- const taskId = event.subagent?.task_id ?? event.skill_id;
- const agentId = event.subagent?.agent_id ?? event.tool_name;
- dispatch(
- subagentIterationStarted({
- threadId: event.thread_id,
- rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
- childIteration: event.subagent?.child_iteration,
- childMaxIterations: event.subagent?.child_max_iterations,
- })
- );
- },
- onSubagentToolCall: event => {
- const taskId = event.subagent?.task_id ?? event.skill_id;
- const agentId = event.subagent?.agent_id;
- if (!agentId) return;
- const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
- // Reducer owns the toolCalls upsert (dedup on call_id) — no getState().
- dispatch(
- subagentToolCallReceived({
- threadId: event.thread_id,
- rowId,
- callId: event.tool_call_id,
- toolName: event.tool_name,
- iteration: event.subagent?.child_iteration,
- args: event.args,
- displayName: event.tool_display_label,
- detail: event.tool_display_detail,
- })
- );
- // Mirror the call into the ordered transcript so the drawer renders it
- // right after the text that triggered it (self-guarded / self-deduped).
- dispatch(
- recordSubagentTranscriptTool({
- threadId: event.thread_id,
- rowId,
- callId: event.tool_call_id,
- toolName: event.tool_name,
- iteration: event.subagent?.child_iteration,
- args: event.args,
- displayName: event.tool_display_label,
- detail: event.tool_display_detail,
- })
- );
- },
- onSubagentToolResult: event => {
- // Phase 5c: the Flows prompt bar / canvas copilot route to the
- // `workflow_builder` specialist via delegation (`build_workflow`), so a
- // `propose_workflow`/`revise_workflow` proposal is produced INSIDE the
- // delegated worker and arrives here (not on `onToolResult`). This
- // extraction must run BEFORE the timeline-entry guards below: under
- // the workflow_builder subagent's heavy event volume, the progress
- // channel (bounded, `try_send`) can drop earlier events, so the
- // timeline row for this call may never have been created — gating
- // proposal extraction on finding that row silently drops the
- // proposal and the Accept/Reject card never renders (bug). The
- // extraction only needs `tool_name`/`success`/`output`, all present
- // directly on the event, with no timeline dependency. Surface it on
- // the PARENT thread (`event.thread_id`, which the progress bridge
- // always stamps with the parent request's thread, not the child's)
- // so the same `WorkflowProposalCard` the direct-tool path uses
- // renders it. Still validate-only — the card's explicit Save is the
- // sole persistence gate.
- const subagentProposal = maybeParseWorkflowProposalTool(
- event.tool_name,
- event.success,
- event.output
- );
- if (subagentProposal) {
- rtLog('workflow proposal parsed (delegated worker)', {
- thread: event.thread_id,
- tool: event.tool_name,
- name: subagentProposal.name,
- });
+ // Settle the matching row in the reducer (Phase 3) — no getState() /
+ // full-array rebuild. A no-op when no row matches.
dispatch(
- setWorkflowProposalForThread({ threadId: event.thread_id, proposal: subagentProposal })
+ toolResultReceived({
+ threadId: event.thread_id,
+ round: event.round,
+ toolName: event.tool_name,
+ toolCallId: event.tool_call_id,
+ success: event.success,
+ output: event.output,
+ failure: event.failure,
+ })
);
- }
- const taskId = event.subagent?.task_id ?? event.skill_id;
- const agentId = event.subagent?.agent_id;
- if (!agentId) return;
- const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
- // Reducer owns the nested toolCall settle (no-op if the call is absent).
- dispatch(
- subagentToolResultReceived({
- threadId: event.thread_id,
- rowId,
- callId: event.tool_call_id,
- success: event.success,
- elapsedMs: event.subagent?.elapsed_ms,
- outputChars: event.subagent?.output_chars,
- result: event.output,
- failure: event.failure,
- })
- );
- dispatch(
- resolveSubagentTranscriptTool({
- threadId: event.thread_id,
- rowId,
- callId: event.tool_call_id,
- success: event.success,
- elapsedMs: event.subagent?.elapsed_ms,
- outputChars: event.subagent?.output_chars,
- result: event.output,
- failure: event.success ? undefined : parseToolFailure(event.failure),
- })
- );
- },
- onSubagentTextDelta: (event: ChatSubagentTextDeltaEvent) => {
- const taskId = event.subagent?.task_id;
- const agentId = event.subagent?.agent_id;
- if (!taskId || !agentId || !event.delta) return;
- dispatch(
- appendSubagentStreamDelta({
- threadId: event.thread_id,
- rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
- kind: 'text',
- delta: event.delta,
- iteration: event.subagent?.child_iteration,
- })
- );
- },
- onSubagentThinkingDelta: (event: ChatSubagentThinkingDeltaEvent) => {
- const taskId = event.subagent?.task_id;
- const agentId = event.subagent?.agent_id;
- if (!taskId || !agentId || !event.delta) return;
- dispatch(
- appendSubagentStreamDelta({
- threadId: event.thread_id,
- rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
- kind: 'thinking',
- delta: event.delta,
- iteration: event.subagent?.child_iteration,
- })
- );
- },
- onSegment: (event: ChatSegmentEvent) => {
- const eventKey = `segment:${event.thread_id}:${event.request_id}:${event.segment_index}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
- const content = segmentText(event);
- const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
- const delivery = getOrCreateSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
- delivery.segments.set(event.segment_index, content);
- void dispatch(
- addInferenceResponse({
- content,
- threadId: event.thread_id,
- // Stamp the producing turn's request id so the timeline projection
- // can group this answer with its per-turn process trail (Phase 4
- // anchoring, Option B — see the companion plan). `citations` is
- // merged in when present.
- extraMetadata: {
- ...(event.citations?.length ? { citations: event.citations } : {}),
- ...(event.request_id ? { requestId: event.request_id } : {}),
- },
- })
- );
- },
- onInterim: (event: ChatInterimEvent) => {
- // One interim per round — `round` is a stable per-turn dedup key that
- // survives socket reconnect/replay (a re-delivered frame must not
- // append the narration bubble twice).
- const eventKey = `interim:${event.thread_id}:${event.request_id}:${event.round}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
- const content = event.full_response?.trim() ?? '';
- if (!content) return;
- // Narration is NOT promoted to a chat message any more.
- //
- // It used to be persisted here via `addInferenceResponse({ isInterim })`,
- // which gave it a lifetime no other progress signal has: thinking is
- // wiped at `chat_done`, tool rows collapse, but narration bubbles
- // ("Let me get the data for both.", "The HTML is hard to parse…")
- // stayed in the thread forever, wedged between the question and the
- // answer they were superseded by.
- //
- // It is already captured twice over without this: `streamDeltaReceived`
- // coalesces every `content` delta into `processingByThread` as a
- // `narration` transcript item (chatRuntimeSlice), and the core persists
- // the same thing server-side as `TranscriptItem::Narration`, kept after
- // completion so a reload replays it. The inline rail and the Agent
- // Process Source panel both render that transcript — so narration is
- // still fully visible while the turn runs, and still inspectable after,
- // just not as a permanent chat bubble.
- //
- // The event is still consumed (not dropped upstream) for its dedup key
- // and the preview reset below, both of which are round-scoped.
- rtLog('interim_narration_observed', {
- thread: event.thread_id,
- request: event.request_id,
- round: event.round,
- });
- // Drop the round's narration from the live streaming preview, which
- // accumulates across the whole turn under one request_id. This matters
- // MORE now: without it the same text renders both in the rail (as a
- // transcript item) and in the preview tail. Reset synchronously so the
- // next round's deltas start from an empty buffer.
- const cr = store.getState().chatRuntime;
- const existing = cr.streamingAssistantByThread[event.thread_id];
- if (existing && existing.requestId === event.request_id) {
+ // Agent-first Workflow authoring (issue B4): a completed
+ // `propose_workflow` call carries a `workflow_proposal` JSON payload
+ // in `output` — surface it as a `WorkflowProposalCard` above the
+ // composer. The tool only validates; only the card's "Save & enable"
+ // action ever calls `flows_create`, so this dispatch alone can never
+ // create a flow.
+ const mainProposal = maybeParseWorkflowProposalTool(
+ event.tool_name,
+ event.success,
+ event.output
+ );
+ if (mainProposal) {
+ rtLog('workflow proposal parsed (main agent)', {
+ thread: event.thread_id,
+ tool: event.tool_name,
+ name: mainProposal.name,
+ });
+ dispatch(
+ setWorkflowProposalForThread({ threadId: event.thread_id, proposal: mainProposal })
+ );
+ }
+
+ const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
+ if (!current) return;
dispatch(
- setStreamingAssistantForThread({
+ setInferenceStatusForThread({
threadId: event.thread_id,
- streaming: {
- requestId: existing.requestId,
- content: '',
- thinking: existing.thinking,
+ status: { ...current, phase: 'thinking', activeTool: undefined },
+ })
+ );
+ },
+ onSubagentSpawned: event => {
+ // Event-seen guard, matching `onToolCall`/`onToolResult`. This socket
+ // reconnects and redelivers freely (13+ times in one measured
+ // session), and a replayed `subagent_spawned` that lands AFTER
+ // `subagent_awaiting_user` looks exactly like `continue_subagent`
+ // resuming the child — the reducer would clear the pause and the
+ // question would vanish while the child was still blocked. `seq` is
+ // the core's own answer to this: `(request_id, seq)` is stamped per
+ // emission (`publish_seq_stamped`), so a redelivery repeats the pair
+ // and a real resume never does. The reducer keeps its own durable
+ // check for the case this bounded cache has already evicted.
+ const eventKey = `subagent_spawned:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
+ if (
+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
+ ) {
+ return;
+ }
+ const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
+ dispatch(
+ setInferenceStatusForThread({
+ threadId: event.thread_id,
+ status: {
+ ...(prev ?? { iteration: event.round, maxIterations: 0 }),
+ phase: 'subagent',
+ activeSubagent: event.tool_name,
},
})
);
diff --cc app/src/providers/useOpenHumanExternalStore.ts
index 56ba0d1ce2,fb5e01b75b..a4353764d4
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@@ -366,23 -339,11 +381,23 @@@ export function useOpenHumanExternalSto
pendingApproval,
turnTimelines: coreTranscript.timelines,
turnTranscripts: coreTranscript.transcripts,
+ settledTurns,
+ liveRequestId: tailRequestId,
}),
- [messages, streaming, isRunning, liveTimeline, liveTranscript, pendingApproval, coreTranscript]
+ [
+ messages,
+ streaming,
+ isRunning,
+ liveTimeline,
+ liveTranscript,
+ pendingApproval,
+ coreTranscript,
+ settledTurns,
+ tailRequestId,
+ ]
);
- const suggestions = useWelcomeSuggestions(runtimeMessages.length);
+ const suggestions = useWelcomeSuggestions(runtimeMessages.length, welcomeSuggestions);
// The status line titles its `tool_use` / `subagent` phases from the matching
// running timeline row (the same rows the surface renders as tool parts), so
diff --cc app/src/store/chatRuntimeSlice.ts
index 11df2a7dab,d52ecbda75..3aae1f3786
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@@ -886,6 -810,6 +886,23 @@@ const initialState: ChatRuntimeState =
queuedFollowupsByThread: {},
};
++/**
++ * A detached child can outlive its parent's reply. Keep its late progress in
++ * the frozen turn as well as the live timeline so the settled message remains
++ * current without changing its row identity.
++ */
++function subagentRows(
++ state: ChatRuntimeState,
++ threadId: string,
++ predicate: (entry: ToolTimelineEntry) => boolean
++): ToolTimelineEntry[] {
++ const rows = [
++ ...(state.toolTimelineByThread[threadId] ?? []),
++ ...Object.values(state.settledTurnsByThread[threadId] ?? {}).flatMap(turn => turn.timeline),
++ ].filter(predicate);
++ return rows.filter((row, index) => rows.indexOf(row) === index);
++}
++
/**
* Upsert a single artifact snapshot for a thread. New entries append
* in insertion order (matches the timeline ordering the UI expects);
@@@ -1734,12 -1565,12 +1751,14 @@@ const chatRuntimeSlice = createSlice(
state,
action: PayloadAction<{ threadId: string; rowId: string; question?: string }>
) => {
-- const entry = state.toolTimelineByThread[action.payload.threadId]?.find(
++ const entries = subagentRows(
++ state,
++ action.payload.threadId,
e => e.id === action.payload.rowId && e.status === 'running'
);
-- if (!entry) return;
-- entry.status = 'awaiting_user';
-- if (entry.subagent) {
++ for (const entry of entries) {
++ entry.status = 'awaiting_user';
++ if (!entry.subagent) continue;
entry.subagent.status = 'awaiting_user';
// The question is the whole point of the pause. Keep the previous one
// if this event carried none rather than blanking a readable prompt.
@@@ -1775,12 -1606,12 +1794,14 @@@
// Settle a still-in-flight row: `running`, or `awaiting_user` (a subagent
// paused for input that then completes must not stay stuck at
// awaiting_user). Already-terminal rows are left as-is.
-- const entry = state.toolTimelineByThread[threadId]?.find(
++ const entries = subagentRows(
++ state,
++ threadId,
e => e.id === rowId && (e.status === 'running' || e.status === 'awaiting_user')
);
-- if (!entry) return;
-- entry.status = success ? 'success' : 'error';
-- if (entry.subagent) {
++ for (const entry of entries) {
++ entry.status = success ? 'success' : 'error';
++ if (!entry.subagent) continue;
const s = entry.subagent;
if (iterations !== undefined) s.iterations = iterations;
if (elapsedMs !== undefined) s.elapsedMs = elapsedMs;
@@@ -1820,19 -1651,19 +1841,12 @@@
) => {
const { threadId, rowId, callId, toolName, iteration, args, displayName, detail } =
action.payload;
-- const entry = state.toolTimelineByThread[threadId]?.find(e => e.id === rowId);
-- if (!entry?.subagent) return;
-- // De-dupe on call_id — a redelivered event must not append twice.
-- if (entry.subagent.toolCalls.some(c => c.callId === callId)) return;
-- entry.subagent.toolCalls.push({
-- callId,
-- toolName,
-- status: 'running',
-- iteration,
-- args,
-- displayName,
-- detail,
-- });
++ for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
++ if (!entry.subagent || entry.subagent.toolCalls.some(c => c.callId === callId)) continue;
++ entry.subagent.toolCalls.push({
++ callId, toolName, status: 'running', iteration, args, displayName, detail,
++ });
++ }
},
subagentToolResultReceived: (
state,
@@@ -1849,16 -1680,16 +1863,16 @@@
) => {
const { threadId, rowId, callId, success, elapsedMs, outputChars, result, failure } =
action.payload;
-- const entry = state.toolTimelineByThread[threadId]?.find(e => e.id === rowId);
-- if (!entry?.subagent) return;
-- const call = entry.subagent.toolCalls.find(c => c.callId === callId);
-- if (!call) return;
-- call.status = success ? 'success' : 'error';
-- if (elapsedMs !== undefined) call.elapsedMs = elapsedMs;
-- if (outputChars !== undefined) call.outputChars = outputChars;
-- if (result !== undefined) call.result = result;
-- // A successful result clears any stale failure on the row.
-- call.failure = success ? undefined : parseToolFailure(failure);
++ for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
++ const call = entry.subagent?.toolCalls.find(c => c.callId === callId);
++ if (!call) continue;
++ call.status = success ? 'success' : 'error';
++ if (elapsedMs !== undefined) call.elapsedMs = elapsedMs;
++ if (outputChars !== undefined) call.outputChars = outputChars;
++ if (result !== undefined) call.result = result;
++ // A successful result clears any stale failure on the row.
++ call.failure = success ? undefined : parseToolFailure(failure);
++ }
},
/**
* Optimistically mark a detached background sub-agent as cancelled after the
@@@ -1868,10 -1699,10 +1882,10 @@@
*/
markSubagentCancelled: (state, action: PayloadAction<{ threadId: string; taskId: string }>) => {
const { threadId, taskId } = action.payload;
-- const entry = state.toolTimelineByThread[threadId]?.find(e => e.subagent?.taskId === taskId);
-- if (!entry) return;
-- entry.status = 'cancelled';
-- if (entry.subagent) entry.subagent.status = 'cancelled';
++ for (const entry of subagentRows(state, threadId, e => e.subagent?.taskId === taskId)) {
++ entry.status = 'cancelled';
++ if (entry.subagent) entry.subagent.status = 'cancelled';
++ }
},
/**
* Settle rows whose terminal turn snapshot could not be fetched.
@@@ -1917,22 -1748,22 +1931,23 @@@
}>
) => {
const { threadId, rowId, kind, delta, iteration } = action.payload;
-- const entry = state.toolTimelineByThread[threadId]?.find(e => e.id === rowId);
-- if (!entry?.subagent) return;
-- const transcript = (entry.subagent.transcript ??= []);
-- const last = transcript[transcript.length - 1];
++ for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
++ if (!entry.subagent) continue;
++ const transcript = (entry.subagent.transcript ??= []);
++ const last = transcript[transcript.length - 1];
// Extend the trailing item only when it's the same kind AND the same
// iteration — otherwise two same-kind chunks from different turns (with
// no tool call between them) would fuse into one transcript entry.
-- if (
-- last &&
-- (last.kind === 'text' || last.kind === 'thinking') &&
-- last.kind === kind &&
-- last.iteration === iteration
-- ) {
-- last.text += delta;
-- } else {
-- transcript.push({ kind, iteration, text: delta });
++ if (
++ last &&
++ (last.kind === 'text' || last.kind === 'thinking') &&
++ last.kind === kind &&
++ last.iteration === iteration
++ ) {
++ last.text += delta;
++ } else {
++ transcript.push({ kind, iteration, text: delta });
++ }
}
},
/**
diff --cc app/test/e2e/specs/chat-live-history-parity.spec.ts
index 54c8e433a7,0000000000..ac4591c0c6
mode 100644,000000..100644
--- a/app/test/e2e/specs/chat-live-history-parity.spec.ts
+++ b/app/test/e2e/specs/chat-live-history-parity.spec.ts
@@@ -1,247 -1,0 +1,247 @@@
+// @ts-nocheck
+/**
+ * Chat live/history parity — a streamed turn must render exactly like the same
+ * turn reopened from history, and must never reshape itself while it streams.
+ *
+ * The bug this guards: a live thread glitched (tool calls reordered, text
+ * restarted, cards collapsed, the view jumped away from the reply) while the
+ * same thread opened fresh looked right. The unit suite pins the projection
+ * (`providers/__tests__/liveHistoryParity.test.tsx`); this pins the real DOM.
+ *
+ * Scripted turn (three LLM rounds):
+ * 1. narration + file_read
+ * 2. narration + grep
+ * 3. a long final answer (taller than the viewport, so following matters)
+ *
+ * Verifies:
+ * P1 — while streaming, the reply's blocks are append-only: every sample's
+ * block list extends the previous one and text only grows
+ * P2 — at the end of the stream the viewport is still at the bottom
+ * P3 — the settled reply's blocks (kind, label, open/closed, text) equal the
+ * blocks of the same turn reopened from history
+ */
+import { waitForApp } from '../helpers/app-helpers';
+import {
+ chatMounted,
+ clickByTitle,
+ clickSend,
+ getSelectedThreadId,
+ typeIntoComposer,
+ waitForSocketConnected,
+} from '../helpers/chat-harness';
+import { callOpenhumanRpc } from '../helpers/core-rpc';
+import { textExists } from '../helpers/element-helpers';
+import { resetApp } from '../helpers/reset-app';
+import { navigateViaHash } from '../helpers/shared-flows';
+import { clearRequestLog, setMockBehavior, startMockServer, stopMockServer } from '../mock-server';
+
+const LOG_PREFIX = '[chat-live-history-parity]';
+const USER_ID = 'e2e-chat-live-history-parity';
+const PROMPT = 'Check the config, then search for the setting, then explain it.';
+const CANARY_FINAL = 'canary-parity-7c1e';
+const NARRATION_1 = 'Let me read the config first.';
+const NARRATION_2 = 'Now I will search for the setting.';
+const FINAL_ANSWER = [
+ `Here is what I found (${CANARY_FINAL}).`,
+ ...Array.from(
+ { length: 24 },
+ (_, n) => `Paragraph ${n + 1}: the setting controls how the agent behaves in this case.`
+ ),
+].join('\n\n');
+
+const FORCED_RESPONSES = [
+ {
+ content: NARRATION_1,
+ toolCalls: [
+ {
+ id: 'call_parity_read',
+ name: 'file_read',
+ arguments: JSON.stringify({ path: '/etc/openhuman/config.toml' }),
+ },
+ ],
+ },
+ {
+ content: NARRATION_2,
+ toolCalls: [
+ {
+ id: 'call_parity_grep',
+ name: 'grep',
+ arguments: JSON.stringify({ pattern: 'setting', path: '/etc/openhuman' }),
+ },
+ ],
+ },
+ { content: FINAL_ANSWER },
+];
+
+interface Block {
+ kind: string;
+ label: string;
+ state: string | null;
+ text: string;
+}
+
+/**
+ * The last assistant message's top-level blocks, in document order: activity
+ * groups, tool cards, delegation cards, reasoning disclosures and markdown text. Nested
+ * blocks (markdown inside a reasoning block) belong to their parent.
+ */
+async function replyBlocks(): Promise<Block[]> {
+ return (await browser.execute(() => {
+ const BLOCK = [
+ // An activity group (reasoning + tool calls of one run) is ONE block: it
+ // collapses once the answer leads, and its cards unmount with it.
+ '[data-slot="tool-group-root"]',
+ '[data-slot="aui_openhuman-tool-call"]',
+ '[data-slot="aui_subagent-call"]',
+ '[data-slot="reasoning-root"]',
+ '.aui-md',
+ ].join(',');
+ const messages = document.querySelectorAll('[data-testid="agent-message"]');
+ const last = messages[messages.length - 1];
+ if (!last) return [];
+ return Array.from(last.querySelectorAll(BLOCK))
+ .filter(node => !node.parentElement?.closest(BLOCK))
+ .map(node => {
+ const slot = node.getAttribute('data-slot');
+ const kind = slot ?? 'text';
+ const label =
+ slot === 'aui_openhuman-tool-call'
+ ? (node.querySelector('button .font-medium')?.textContent ?? '')
+ : '';
+ return {
+ kind,
+ label,
+ state: node.getAttribute('data-state'),
+ text: kind === 'text' ? (node.textContent ?? '').trim() : '',
+ };
+ });
+ })) as Block[];
+}
+
+async function distanceFromBottom(): Promise<number> {
+ return (await browser.execute(() => {
+ const viewport = document.querySelector('[data-slot="aui_thread-viewport"]');
+ if (!viewport) return Number.POSITIVE_INFINITY;
+ return viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
+ })) as number;
+}
+
+async function turnDrained(): Promise<boolean> {
+ const snap = await callOpenhumanRpc<{ result: { entries: Array<{ key: string }> } }>(
+ 'openhuman.test_support_in_flight_chats',
+ {}
+ );
+ return snap.ok && (snap.result?.result?.entries?.length ?? 0) === 0;
+}
+
+describe('Chat live/history parity', () => {
+ let threadId: string;
+ const samples: Block[][] = [];
+ let settled: Block[] = [];
+
+ before(async () => {
+ console.log(`${LOG_PREFIX} Starting mock server and resetting app`);
+ await startMockServer();
+ await waitForApp();
+ await resetApp(USER_ID);
+ setMockBehavior('llmForcedResponses', JSON.stringify(FORCED_RESPONSES));
+ setMockBehavior('llmStreamChunkDelayMs', '15');
+ clearRequestLog();
+ });
+
+ after(async () => {
+ setMockBehavior('llmForcedResponses', '');
+ setMockBehavior('llmStreamChunkDelayMs', '');
+ await stopMockServer();
+ });
+
+ it('P1 — the streaming reply is append-only', async () => {
+ await navigateViaHash('/chat');
+ await browser.waitUntil(async () => await chatMounted(), {
+ timeout: 15_000,
+ timeoutMsg: 'Conversations panel did not mount',
+ });
+ const priorThreadId = await getSelectedThreadId();
+ expect(await clickByTitle('New thread', 8_000)).toBe(true);
+ threadId = (await browser.waitUntil(
+ async () => {
+ const current = await getSelectedThreadId();
+ return current && current !== priorThreadId ? current : null;
+ },
+ { timeout: 8_000, timeoutMsg: 'new thread was never selected' }
+ )) as string;
+
+ await typeIntoComposer(PROMPT);
+ await waitForSocketConnected(30_000);
+ expect(
+ await browser.waitUntil(async () => await clickSend(), {
+ timeout: 5_000,
+ timeoutMsg: 'Send button never enabled',
+ })
+ ).toBe(true);
+
+ // Sample the reply while it streams, until the turn drains.
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ const blocks = await replyBlocks();
+ if (blocks.length > 0) samples.push(blocks);
+ if ((await textExists(CANARY_FINAL)) && (await turnDrained())) break;
+ await browser.pause(100);
+ }
+ expect(samples.length).toBeGreaterThan(3);
+
+ for (let at = 1; at < samples.length; at += 1) {
+ const before = samples[at - 1];
+ const after = samples[at];
+ expect(after.length).toBeGreaterThanOrEqual(before.length);
+ before.forEach((block, index) => {
+ const next = after[index];
+ expect(next.kind).toBe(block.kind);
+ expect(next.label).toBe(block.label);
+ if (block.kind === 'text') expect(next.text.startsWith(block.text)).toBe(true);
+ });
+ }
+ console.log(`${LOG_PREFIX} P1: ${samples.length} samples, all append-only`);
+ });
+
+ it('P2 — the viewport is still following the reply when it finishes', async () => {
+ await browser.waitUntil(async () => (await distanceFromBottom()) <= 80, {
+ timeout: 3_000,
+ timeoutMsg: 'viewport stopped following the streamed reply',
+ });
+ });
+
+ it('P3 — the settled reply equals the same turn reopened from history', async () => {
+ settled = await replyBlocks();
+ expect(settled.map(block => block.kind)).toEqual([
+ 'text',
+ 'tool-group-root',
+ 'text',
+ 'tool-group-root',
+ 'text',
+ ]);
+
+ // Reopen the thread as a fresh load: drop this session's runtime state for
+ // it (including the frozen trail) and select it from another thread, so it
+ // renders from the persisted messages plus the core transcript projection.
+ expect(await clickByTitle('New thread', 8_000)).toBe(true);
+ await browser.execute(tid => {
+ const store = (
+ window as unknown as { __OPENHUMAN_STORE__?: { dispatch: (a: unknown) => void } }
+ ).__OPENHUMAN_STORE__;
- store?.dispatch({ type: 'chatRuntime/clearRuntimeForThread', payload: { threadId: tid } });
++ store?.dispatch({ type: 'chatRuntime/clearAllChatRuntime' });
+ store?.dispatch({ type: 'thread/setSelectedThread', payload: tid });
+ }, threadId);
+
+ await browser.waitUntil(
+ async () => {
+ const blocks = await replyBlocks();
+ return blocks.length === settled.length && (await textExists(CANARY_FINAL));
+ },
+ { timeout: 15_000, timeoutMsg: 'reopened thread never rendered the full reply' }
+ );
+ const reopened = await replyBlocks();
+ expect(reopened).toEqual(settled);
+ console.log(`${LOG_PREFIX} P3: ${reopened.length} blocks identical live and reopened`);
+ });
+});