Skip to content

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

Merge upstream/main into assistant-ui-elements

Steven Enamakel58407ea53b67
diff --cc app/src/features/conversations/aui/SubagentTaskCard.tsx
index c6abfd5bf9,0000000000..929b76b45f
mode 100644,000000..100644
--- a/app/src/features/conversations/aui/SubagentTaskCard.tsx
+++ b/app/src/features/conversations/aui/SubagentTaskCard.tsx
@@@ -1,274 -1,0 +1,294 @@@
+'use client';
+
+/**
+ * OpenHuman glue over the vendored `elements/task-card.tsx` for a sub-agent
+ * delegation (`task` toolkit entry — `features/conversations/aui/toolkit.tsx`).
+ *
+ * Replaces `AssistantUiSubagentCall.tsx` (deleted). The delegation's full
+ * transcript is no longer read through a host-supplied "View full processing"
+ * button into `SubagentDrawer` — assistant-ui's own `messages` part field
+ * (`providers/assistantUiMessages.ts`'s `subagentMessages`) carries it, and
+ * `TaskCardBase`'s built-in disclosure renders it inline as the nested
+ * transcript.
+ *
+ * Not the vendored `elements/task-card.aui.tsx`'s own `TaskCard` wrapper:
+ * that one derives its `actions` purely from `part.approval`/`part.interrupt`,
+ * which has no slot for the two OpenHuman-specific actions a delegation
+ * needs — the awaiting-user reply box and the worktree open/diff/remove row
+ * — so this adapter is built directly from the raw `TaskCard`
+ * (`elements/task-card.tsx`) + `utils/task.ts` pieces instead, with those
+ * actions supplied explicitly.
+ */
+import { type ToolCallMessagePartComponent, useAui } from '@assistant-ui/react';
+import { useCallback, useState } from 'react';
+
+import { TaskCard, type TaskCardState } from '../../../components/assistant-ui/elements/task-card';
+import { TaskTranscript } from '../../../components/assistant-ui/elements/task-card.aui';
++import { useDisclosure } from '../../../components/assistant-ui/lib/useDisclosure';
+import { formatElapsed } from '../../../components/assistant-ui/utils/task';
+import { Button } from '../../../components/ui';
+import Badge from '../../../components/ui/Badge';
+import WorktreeActions from '../../../components/worktree/WorktreeActions';
+import { useT } from '../../../lib/i18n/I18nContext';
+import { subagentMessages } from '../../../providers/assistantUiMessages';
+import { subagentApi } from '../../../services/api/subagentApi';
+import type { SubagentActivity } from '../../../store/chatRuntimeSlice';
+import { basename } from '../../../utils/pathUtils';
+
+function asSubagentActivity(value: unknown): SubagentActivity | undefined {
+ if (!value || typeof value !== 'object') return undefined;
+ const candidate = value as Partial<SubagentActivity>;
+ if (
+ typeof candidate.taskId !== 'string' ||
+ typeof candidate.agentId !== 'string' ||
+ !Array.isArray(candidate.toolCalls)
+ ) {
+ return undefined;
+ }
+ return candidate as SubagentActivity;
+}
+
+/**
+ * `providers/assistantUiMessages.ts`'s `toolPart` puts the live activity on
+ * `args.progress` while the delegation is running (mirroring `entry.subagent`)
+ * and the settled `{status, activity}` envelope on `result` once it is not —
+ * see that module's `toolPart`. Either shape yields the same
+ * {@link SubagentActivity}; only the outer row status differs in reliability
+ * (settled: the real {@link import('../../../store/chatRuntimeSlice').ToolTimelineEntryStatus};
+ * running: derived from the activity's own `status` field).
+ */
+function readSubagentCall(
+ args: unknown,
+ result: unknown
+): { activity: SubagentActivity | undefined; state: TaskCardState } {
+ if (result && typeof result === 'object' && 'activity' in (result as Record<string, unknown>)) {
+ const envelope = result as { status?: string; activity?: unknown };
+ const activity = asSubagentActivity(envelope.activity);
+ const status = envelope.status;
+ const state: TaskCardState =
+ status === 'error' ? 'failed' : status === 'cancelled' ? 'cancelled' : 'done';
+ return { activity, state };
+ }
+ const progress =
+ args && typeof args === 'object'
+ ? asSubagentActivity((args as { progress?: unknown }).progress)
+ : undefined;
+ return {
+ activity: progress,
+ state: progress?.status === 'awaiting_user' ? 'waiting' : 'working',
+ };
+}
+
+/** The child's question plus a reply box, sent via `aui.thread.append` — an ordinary new user turn. */
+function AwaitingUserActions({ activity }: { activity: SubagentActivity }) {
+ const { t } = useT();
+ const aui = useAui();
+ const [draft, setDraft] = useState('');
+ const [sent, setSent] = useState(false);
+
+ const submit = useCallback(() => {
+ const text = draft.trim();
+ if (!text) return;
+ void aui.thread.append({ role: 'user', content: [{ type: 'text', text }] });
+ setDraft('');
+ setSent(true);
+ }, [aui, draft]);
+
+ return (
+ <div data-testid="subagent-awaiting-user" className="flex flex-col gap-1.5">
+ <p className="text-[12px] font-medium text-amber-800 dark:text-amber-200">
+ {t('conversations.subagent.awaitingTitle')}
+ </p>
+ {activity.awaitingQuestion ? (
+ <p
+ data-testid="subagent-awaiting-question"
+ className="wrap-break-word whitespace-pre-wrap text-[12px] text-content-secondary">
+ {activity.awaitingQuestion}
+ </p>
+ ) : null}
+ {sent ? (
+ <p className="text-[11px] text-content-muted" data-testid="subagent-answer-sent">
+ {t('conversations.subagent.answerSent')}
+ </p>
+ ) : (
+ <div className="flex items-end gap-1.5">
+ <textarea
+ rows={1}
+ value={draft}
+ data-testid="subagent-answer-input"
+ aria-label={t('conversations.subagent.answerPlaceholder')}
+ placeholder={t('conversations.subagent.answerPlaceholder')}
+ onChange={event => setDraft(event.target.value)}
+ onKeyDown={event => {
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ submit();
+ }
+ }}
+ className="min-h-[28px] flex-1 resize-y rounded-md border border-line bg-surface px-2 py-1 text-[12px] text-content outline-none focus:border-primary-500"
+ />
+ <Button
+ type="button"
+ size="xs"
+ variant="primary"
+ analyticsId="subagent-answer-send"
+ data-testid="subagent-answer-send"
+ disabled={draft.trim().length === 0}
+ onClick={submit}>
+ {t('conversations.subagent.answerSend')}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The old drawer's "Cancel task" button, ported here as a `TaskCard` action:
+ * aborts a still-running (or awaiting-user) detached sub-agent via
+ * `openhuman.subagent_cancel`. Hidden once the delegation has settled
+ * (`done`/`failed`/`cancelled`) — there is nothing left to abort.
+ */
+function CancelTaskAction({ taskId }: { taskId: string }) {
+ const { t } = useT();
+ const [cancelling, setCancelling] = useState(false);
+ const [failed, setFailed] = useState(false);
+
+ const onCancel = useCallback(() => {
+ setFailed(false);
+ setCancelling(true);
+ void subagentApi
+ .cancel(taskId)
+ .catch(() => {
+ setFailed(true);
+ })
+ .finally(() => {
+ setCancelling(false);
+ });
+ }, [taskId]);
+
+ return (
+ <div className="flex flex-col gap-1">
+ <Button
+ type="button"
+ size="xs"
+ variant="secondary"
+ analyticsId="subagent-cancel-task"
+ data-testid="subagent-cancel-task"
+ disabled={cancelling}
+ onClick={onCancel}>
+ {cancelling ? t('conversations.subagent.cancelling') : t('conversations.subagent.cancel')}
+ </Button>
+ {failed ? (
+ <p className="text-[11px] text-red-600 dark:text-red-400">
+ {t('conversations.subagent.cancelFailed')}
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+function WorktreeRow({ activity }: { activity: SubagentActivity }) {
+ const { t } = useT();
+ if (!activity.worktreePath) return null;
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="font-medium text-content-secondary">{t('worktree.label')}</span>
+ <span
+ className="truncate font-mono text-[12px] text-content-muted"
+ title={activity.worktreePath}>
+ {basename(activity.worktreePath)}
+ </span>
+ <Badge variant={activity.isDirty ? 'warning' : 'success'} className="rounded-full">
+ {activity.isDirty ? t('worktree.dirty') : t('worktree.clean')}
+ </Badge>
+ </div>
+ <WorktreeActions path={activity.worktreePath} isDirty={activity.isDirty} compact />
+ </div>
+ );
+}
+
+/** Adapt an assistant-ui `task` part onto {@link TaskCard} for a sub-agent delegation. */
- export const SubagentTaskCard: ToolCallMessagePartComponent = ({ args, result, messages }) => {
++export const SubagentTaskCard: ToolCallMessagePartComponent = ({
++ args,
++ result,
++ messages,
++ toolCallId,
++}) => {
+ const { t } = useT();
+ const { activity, state } = readSubagentCall(args, result);
+ const fallbackAgent = (args as { subagent_type?: string } | undefined)?.subagent_type;
+ const resolved = activity ?? {
+ taskId: 'pending-subagent',
+ agentId: fallbackAgent ?? 'subagent',
+ toolCalls: [],
+ };
+ const name = resolved.displayName ?? resolved.agentId ?? 'subagent';
+ const elapsed = resolved.elapsedMs !== undefined ? formatElapsed(resolved.elapsedMs) : undefined;
+ const awaiting = state === 'waiting' && resolved.status === 'awaiting_user';
++ // The user's own open/closed choice, remembered by the part's tool-call id
++ // so it survives assistant-ui's remounts (a virtualized history, a thread
++ // switch, a part whose shape changes) — see `useDisclosure`. Pinned open
++ // for as long as the delegation is actually awaiting a reply, regardless of
++ // that choice: a question the user cannot see is a question they cannot
++ // answer, and the row is normally already mounted (and collapsed) by the
++ // time the pause arrives, so a one-time `defaultOpen` would be too late.
++ const [open, setOpen] = useDisclosure(
++ toolCallId ? `subagent:${toolCallId}` : undefined,
++ false
++ );
++ const disclosureOpen = open || awaiting;
+
+ const cancellable =
+ (state === 'working' || state === 'waiting') && resolved.taskId !== 'pending-subagent';
+
+ const actions =
+ awaiting || resolved.worktreePath || cancellable ? (
+ <div className="flex flex-col gap-2.5">
+ {awaiting ? <AwaitingUserActions activity={resolved} /> : null}
+ <WorktreeRow activity={resolved} />
+ {cancellable ? <CancelTaskAction taskId={resolved.taskId} /> : null}
+ </div>
+ ) : undefined;
+
+ const resultNode =
+ resolved.output && (state === 'done' || state === 'failed') ? (
+ <p className="m-0 whitespace-pre-wrap">{resolved.output}</p>
+ ) : undefined;
+
+ // `messages` (the part's own nested transcript, built by `subagentMessages`)
+ // is preferred over recomputing it here — it is the SAME data, but reusing
+ // the part's own field keeps this renderer correct for a replayed/settled
+ // part too, where `entry.subagent` is no longer live Redux state.
+ const nestedMessages = messages ?? subagentMessages(resolved);
+
+ return (
+ <TaskCard
+ data-testid="assistant-ui-subagent-call"
+ data-status={resolved.status ?? state}
+ label={`${t('conversations.tools.delegatedTo').replace('{agent}', name)}`}
+ meta={resolved.mode}
+ state={state}
+ elapsed={elapsed}
++ open={disclosureOpen}
++ onOpenChange={setOpen}
+ actions={actions}
+ result={resultNode}>
+ {nestedMessages.length > 0 ? (
+ <div data-testid="subagent-activity">
+ <TaskTranscript
+ messages={nestedMessages}
+ roleLabels={{
+ user: t('conversations.subagent.transcript.instruction'),
+ assistant: t('conversations.subagent.transcript.agent'),
+ system: t('conversations.subagent.transcript.system'),
+ }}
+ />
+ </div>
+ ) : undefined}
+ </TaskCard>
+ );
+};
+
+export default SubagentTaskCard;
diff --cc app/src/features/conversations/components/AssistantUiChat.tsx
index b899c64732,5435349e6c..f68ffb1dfc
--- a/app/src/features/conversations/components/AssistantUiChat.tsx
+++ b/app/src/features/conversations/components/AssistantUiChat.tsx
@@@ -11,16 -12,35 +11,34 @@@ import { AssistantUiRuntimeProvider } f
import { useAppSelector } from '../../../store/hooks';
import { DEFAULT_MASCOT_COLOR } from '../../../store/mascotSlice';
import { MascotChipAvatar } from '../../human/Mascot/MascotChipAvatar';
-import { AssistantUiInferenceStatus } from './AssistantUiInferenceStatus';
+import { AgentRunningStatus } from '../aui/AgentRunningStatus';
+import { ChatConversationMap } from '../aui/ChatConversationMap';
+import { ComposerTriggers } from '../aui/ComposerTriggers';
+import { ContextUsage } from '../aui/ContextUsage';
import { ChatSources } from './aui/ChatSources';
-import { SubagentDrawerHost } from './aui/subagentDrawerHost';
import { ChatToolFallback } from './ChatToolParts';
-import { contextUsageFromTokenUsage, ContextWindowPill } from './composer/ContextWindowPill';
-const EMPTY_TOKEN_USAGE = emptySessionTokenUsage();
const selectComposerText = (state: AssistantState) => state.composer.text;
- function ComposerTextBridge({
+ /**
+ * Keep the host's draft (`inputValue`) and assistant-ui's composer text in step.
+ *
+ * Two directions, and the one that fires on every keystroke is the dangerous
+ * one. Editor → host used to call `onChange` (a `useState` setter) inside this
+ * effect synchronously. A keystroke is a discrete event, so React flushes the
+ * effect — and the update it schedules — synchronously too, and a burst of
+ * keystrokes (key-repeat, fast typing, an automated driver) chained those sync
+ * updates past React's nested-update limit: "Maximum update depth exceeded",
+ * and the whole chat surface fell to the error boundary.
+ *
+ * So editor → host now runs as a transition, which is not a sync update. The
+ * host value then lags the editor by a render, and the other direction must
+ * not mistake that lag for a host write: a host value that is one we emitted
+ * ourselves is an echo and is never written back into the editor (doing so
+ * would overwrite what was typed since). Only a value we did not emit —
+ * dictation, ESC restore, clear after send — is a host write, and it wins.
+ */
+ export function ComposerTextBridge({
value,
onChange,
}: {
diff --cc app/src/features/conversations/components/AssistantUiToolCall.tsx
index 728e644099,364feaf00f..b3cde3a77f
--- a/app/src/features/conversations/components/AssistantUiToolCall.tsx
+++ b/app/src/features/conversations/components/AssistantUiToolCall.tsx
@@@ -1,12 -1,15 +1,13 @@@
import type { ToolCallMessagePart, ToolCallMessagePartProps } from '@assistant-ui/react';
-import { CheckIcon, ChevronDownIcon, CircleXIcon, Loader2Icon, WrenchIcon } from 'lucide-react';
import type { FC, ReactNode } from 'react';
+ import { useDisclosure } from '../../../components/assistant-ui/lib/useDisclosure';
-import { cn } from '../../../components/assistant-ui/lib/utils';
import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from '../../../components/assistant-ui/ui/collapsible';
-import type { ToolLabelArtifact } from '../../../providers/assistantUiMessages';
+ ToolCall,
+ type ToolCallOutcome,
+} from '../../../components/assistant-ui/elements/tool-call';
+import { useT } from '../../../lib/i18n/I18nContext';
+import { readOpenHumanToolArtifact } from '../../../providers/assistantUiMessages';
import type {
ToolFailureExplanation,
ToolTimelineEntryStatus,
@@@ -59,17 -119,14 +60,22 @@@ export interface AssistantUiToolCallCar
awaitingUser?: boolean;
/** Decision row / connect affordance, rendered under the call's header. */
footer?: ReactNode;
+ /**
+ * Stable identity (the tool-call id) under which the user's open/closed
+ * choice is remembered across remounts. See `useDisclosure`.
+ */
+ disclosureKey?: string;
}
-/** The single assistant-ui tool-call presentation used at every nesting level. */
+/**
+ * One tool call, rendered with assistant-ui's tool-call element.
+ *
+ * The icon, the label (in both tenses, which the element swaps between as
+ * the call settles) and the target chip all come from the presentation
+ * registry, so every surface names a call the same way. The panel expands
+ * into the tool's own assistant-ui element (search results, terminal, diff,
+ * page preview) or the generic Request / Result view.
+ */
export function AssistantUiToolCallCard({
toolName,
args,
@@@ -83,130 -139,113 +89,141 @@@
failure,
awaitingUser = false,
footer,
+ disclosureKey,
}: AssistantUiToolCallCardProps) {
- // Collapsed until the user opens it — running or settled, live or reloaded.
- // It used to be `defaultOpen={running}`: a card mounted mid-stream opened
- // and stayed open, the same card reloaded was closed, and any remount in
- // between flipped it. The header already says what the call is and whether
- // it is running; the body is detail on demand.
- const [open, setOpen] = useDisclosure(disclosureKey ? `tool:${disclosureKey}` : undefined, false);
+ const { t } = useT();
++ // Defaults open while the call is waiting on the user (an approval or a
++ // sub-agent question needs to be visible without an extra click); once the
++ // user has explicitly toggled it, that choice is remembered by
++ // `disclosureKey` (the tool-call id) so it survives assistant-ui's remounts
++ // — a virtualized history, a thread switch, a part whose shape changes.
++ const [open, setOpen] = useDisclosure(
++ disclosureKey ? `tool:${disclosureKey}` : undefined,
++ awaitingUser
++ );
const running =
awaitingUser ||
(status ? status === 'running' || status === 'awaiting_user' : result === undefined);
+ const effectiveStatus: ToolTimelineEntryStatus =
+ status ?? (awaitingUser ? 'awaiting_user' : running ? 'running' : 'success');
const input = hasDisplayValue(args) ? args : parsedValue(argsText ?? '');
- const output = result === '' && status && !running ? 'No output' : parsedValue(result);
- // The row's own label when it has one; otherwise the shared formatter keyed
- // on the tool's identity. Never a guess from the name's substrings or the
- // argument keys — see `toolCallLabel`.
- const suppliedLabel = displayName?.trim();
- const formatted =
- suppliedLabel && suppliedLabel.toLowerCase() !== 'tool'
- ? undefined
- : toolCallLabel(toolName, argsText || jsonText(args), jsonText(result));
- const label = suppliedLabel && !formatted ? suppliedLabel : (formatted?.title ?? toolName);
- const shownDetail = detail ?? formatted?.detail;
- // `awaiting input` was previously reachable only via `status`, which the
- // adapter forwards for `error` / `cancelled` alone — so the label could never
- // render for the case it was written for. A parked call now says so.
- const statusLabel =
- status === 'error'
- ? 'failed'
- : status === 'cancelled'
- ? 'cancelled'
- : awaitingUser || status === 'awaiting_user'
- ? 'awaiting input'
- : running
- ? 'running'
- : 'done';
+ const parsedArgs = parseToolArgs(input);
+ const output = result === '' && status && !running ? t('conversations.tools.noOutput') : result;
+ const presentation = describeToolCall({
+ name: toolName,
+ args: parsedArgs,
+ status: effectiveStatus,
+ serverLabel: displayName,
+ serverDetail: detail,
+ });
+ const activeLabel = toolLabel({ ...presentation, tense: 'active' }, t);
+ const doneLabel = toolLabel({ ...presentation, tense: 'done' }, t);
const failed = status === 'error';
- // `failed` gates the failure-explanation block, which only an `error` carries.
- // The icon is a wider question: a cancelled call did not succeed either, and
- // before the adapter forwarded a status this branch was unreachable, so the
- // check icon sat next to the word "cancelled".
- const terminalNonSuccess = failed || status === 'cancelled';
+ const awaiting = awaitingUser || status === 'awaiting_user';
+ const outcome: ToolCallOutcome = failed
+ ? 'error'
+ : status === 'cancelled'
+ ? 'cancelled'
+ : awaiting
+ ? 'awaiting'
+ : 'success';
+ const statusText =
+ outcome === 'error'
+ ? t('conversations.tools.status.failed')
+ : outcome === 'cancelled'
+ ? t('conversations.tools.status.cancelled')
+ : outcome === 'awaiting'
+ ? t('conversations.tools.status.awaiting')
+ : running
+ ? t('conversations.tools.status.running')
+ : t('conversations.tools.status.done');
+ // Running and done are carried by the spinner / check; they stay readable
+ // to a screen reader. The states that need attention are spelled out.
+ const statusVisible = outcome !== 'success';
+
+ const searchBody =
+ presentation.body === 'webSearch'
+ ? WebSearchBody({ args: parsedArgs, result: output, structured, searching: running, t })
+ : null;
+ const richBody = running
+ ? null
+ : presentation.body === 'shell'
+ ? ShellBody({ args: parsedArgs, result: output, failed, t })
+ : presentation.body === 'webFetch'
+ ? FetchBody({ args: parsedArgs, result: output, t, onOpenExternal: openExternal })
+ : presentation.body === 'file'
+ ? FileBody({ args: parsedArgs, result: output })
+ : null;
+ const showOutput = !searchBody && hasDisplayValue(parsedValue(output));
return (
- <Collapsible
- data-slot="aui_openhuman-tool-call"
+ <ToolCall
data-testid="assistant-ui-tool-call"
+ className="max-w-none"
+ label={doneLabel}
+ activeLabel={activeLabel}
+ // The web-search element shows the query as its own pill.
+ query={searchBody ? undefined : presentation.chip}
+ running={running}
+ outcome={outcome}
- defaultOpen={awaitingUser}
+ open={open}
+ onOpenChange={setOpen}
- data-awaiting-user={awaitingUser ? 'true' : undefined}
- className={cn(
- 'border-border/60 dark:border-muted-foreground/15 rounded-xl border',
- running && 'border-dashed'
- )}>
- <CollapsibleTrigger className="group/tool text-muted-foreground hover:text-foreground flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors">
- <WrenchIcon className="size-4 shrink-0" />
- <span className="text-foreground text-start font-medium">{label}</span>
- {shownDetail ? (
- <span className="bg-muted min-w-0 truncate rounded px-1.5 py-0.5 font-mono text-[11px]">
- {shownDetail}
+ icon={<ToolIcon presentation={presentation} className="text-foreground/45 size-3.5" />}
+ requestLabel={t('conversations.subagent.input')}
+ resultLabel={t('conversations.subagent.output')}
+ request={
+ !richBody && hasDisplayValue(input) ? (
+ <div data-testid="assistant-ui-tool-input">
+ <ToolDataView value={input} />
+ </div>
+ ) : undefined
+ }
+ result={
+ !richBody && showOutput ? (
+ <div data-testid="assistant-ui-tool-output">
+ <ToolDataView value={output} />
+ </div>
+ ) : undefined
+ }
+ meta={
+ <>
+ <span
+ data-testid="tool-call-status"
+ className={
+ !statusVisible || (running && outcome !== 'awaiting')
+ ? 'sr-only'
+ : outcome === 'awaiting'
+ ? 'text-amber-600 dark:text-amber-400'
+ : undefined
+ }>
+ {statusText}
</span>
- ) : null}
- <span className="flex shrink-0 items-center gap-1 text-[11px]">
- {running ? (
- <Loader2Icon className="size-3 animate-spin [animation-duration:0.6s]" />
- ) : terminalNonSuccess ? (
- <CircleXIcon className="size-3.5" />
- ) : (
- <CheckIcon className="size-3.5" />
- )}
- {statusLabel}
{elapsedMs != null && !running ? (
- <span className="tabular-nums">
- {elapsedMs >= 1000 ? `${(elapsedMs / 1000).toFixed(1)}s` : `${elapsedMs}ms`}
+ <span data-testid="tool-call-elapsed" className="tabular-nums">
+ {formatElapsed(elapsedMs)}
</span>
) : null}
- </span>
- <ChevronDownIcon className="ml-auto size-4 shrink-0 -rotate-90 transition-transform group-data-[state=open]/tool:rotate-0" />
- </CollapsibleTrigger>
- {failed && failure ? (
- <div className="px-3 pb-2">
- <ToolFailureLines failure={failure} />
- </div>
- ) : null}
- {/* Outside `CollapsibleContent` on purpose: a decision the turn is
- blocked on must not be hidden behind a disclosure the user has to
- find and open. */}
- {footer}
- <CollapsibleContent className="space-y-2 px-3 pb-3">
- {hasDisplayValue(input) ? (
- <div data-testid="assistant-ui-tool-input">
- <p className="text-muted-foreground mb-1 text-[11px] font-medium uppercase">Input</p>
- <div className="max-h-48 overflow-auto">
- <ToolDataView value={input} />
- </div>
- </div>
- ) : null}
- {hasDisplayValue(output) ? (
- <div data-testid="assistant-ui-tool-output">
- <p className="text-muted-foreground mb-1 text-[11px] font-medium uppercase">Output</p>
- <div className="max-h-64 overflow-auto">
- <ToolDataView value={output} />
+ </>
+ }
+ aside={
+ <>
+ {failed && failure ? (
+ <div className="ps-5.5 pt-1 pb-2">
+ <ToolFailureCard
+ toolName={toolName}
+ target={detail ?? displayName}
+ failure={failure}
+ />
</div>
- </div>
- ) : null}
- </CollapsibleContent>
- </Collapsible>
+ ) : null}
+ {footer ? <div className="ps-5.5">{footer}</div> : null}
+ {/* Search results are the call's whole point: visible without
+ opening the disclosure, as in assistant-ui's own web-search. */}
+ {searchBody ? <div className="ps-5.5 pt-1 pb-2">{searchBody}</div> : null}
+ </>
+ }>
+ {richBody ? <div className="mt-2 ps-5.5">{richBody}</div> : undefined}
+ </ToolCall>
);
}
@@@ -271,12 -314,9 +288,13 @@@ export const OpenHumanToolCall: FC
result={envelope ? envelope.value : props.result}
status={envelope?.status}
failure={envelope?.failure}
+ displayName={artifact?.displayName}
+ detail={artifact?.detail}
+ elapsedMs={artifact?.elapsedMs}
+ structured={artifact?.structured}
awaitingUser={isApprovalPending(props.approval)}
footer={props.approvalCard}
+ disclosureKey={props.toolCallId}
/>
);
};
diff --cc app/src/providers/ChatRuntimeProvider.tsx
index 8dca397f9f,cf3f390387..3f96b175a2
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@@ -720,843 -674,567 +723,577 @@@ 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,
- args: event.args,
- elapsedMs: event.elapsed_ms,
- structured: event.structured,
- displayLabel: event.tool_display_label,
- displayDetail: event.tool_display_detail,
- })
- );
-
- // 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'}`,
- // Real tool_call_id of the spawn/delegate call, when the core sent
- // one — lets the reducer attach this activity to that exact row
- // instead of guessing it heuristically.
- parentCallId: event.subagent?.parent_call_id,
- })
- );
- },
- 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,
- output: event.subagent?.output,
- 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,
++ args: event.args,
++ elapsedMs: event.elapsed_ms,
++ structured: event.structured,
++ displayLabel: event.tool_display_label,
++ displayDetail: event.tool_display_detail,
+ })
);
- }
- 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(
+ 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(
- setStreamingAssistantForThread({
+ setInferenceStatusForThread({
threadId: event.thread_id,
- streaming: {
- requestId: existing.requestId,
- content: '',
- thinking: existing.thinking,
+ status: {
+ ...(prev ?? { iteration: event.round, maxIterations: 0 }),
+ phase: 'subagent',
+ activeSubagent: event.tool_name,
},
})
);
- }
- },
- onTextDelta: event => {
- if (isReplayedDelta(event)) return;
- // Parallel-vs-primary routing + processing transcript now live in the
- // reducer (Phase 3) — no getState() in the provider.
- dispatch(
- streamDeltaReceived({
- threadId: event.thread_id,
- requestId: event.request_id,
- round: event.round,
- delta: event.delta,
- channel: 'content',
- })
- );
- },
- onThinkingDelta: event => {
- if (isReplayedDelta(event)) return;
- dispatch(
- streamDeltaReceived({
- threadId: event.thread_id,
- requestId: event.request_id,
- round: event.round,
- delta: event.delta,
- channel: 'thinking',
- at: Date.now(),
- })
- );
- },
- onToolArgsDelta: event => {
- // Match + append + decorate now live in the reducer (Phase 3).
- dispatch(
- toolArgsDeltaReceived({
- threadId: event.thread_id,
- round: event.round,
- delta: event.delta,
- toolName: event.tool_name,
- toolCallId: event.tool_call_id,
- })
- );
- },
- onProactiveMessage: (event: ProactiveMessageEvent) => {
- const messageDigest = proactiveMessageDigest(event.full_response ?? '');
- const eventKey = `proactive:${event.thread_id}:${event.request_id ?? 'none'}:${messageDigest}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
-
- proactiveDispatchQueueRef.current = proactiveDispatchQueueRef.current.then(async () => {
- try {
- const targetThreadId = await resolveVisibleThreadForProactive(event.thread_id);
- if (!targetThreadId) return;
- rtLog('proactive_message', {
- from: event.thread_id,
- to: targetThreadId,
- request: event.request_id,
- });
- await dispatch(
- addInferenceResponse({
- content: event.full_response,
- threadId: targetThreadId,
- // Stamp the producing turn's request id when present (Phase 4
- // anchoring); proactive events may omit it, in which case the
- // message falls back to the legacy single-anchor turn.
- extraMetadata: event.request_id ? { requestId: event.request_id } : undefined,
+
+ // 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'}`,
++ // Real tool_call_id of the spawn/delegate call, when the core sent
++ // one — lets the reducer attach this activity to that exact row
++ // instead of guessing it heuristically.
++ parentCallId: event.subagent?.parent_call_id,
+ })
+ );
+ },
+ 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,
++ output: event.subagent?.output,
+ worktreePath: event.subagent?.worktree_path,
+ changedFiles: event.subagent?.changed_files,
+ isDirty: event.subagent?.dirty_status,
+ })
+ );
+
+ // 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) {
+ dispatch(
+ recordChatTurnUsage({
+ 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,
+ },
+ ],
})
);
- } catch (error) {
- rtLog('proactive_dispatch_failed', {
- from: event.thread_id,
- request: event.request_id,
- error: error instanceof Error ? error.message : String(error),
- });
}
- });
- },
- onArtifactPending: event => {
- rtLog('artifact_pending', {
- thread: event.thread_id,
- artifact_id: event.artifact_id,
- kind: event.kind,
- });
- dispatch(
- upsertArtifactInProgressForThread({
- threadId: event.thread_id,
- artifactId: event.artifact_id,
- kind: event.kind,
- title: event.title,
- toolCallId: event.tool_call_id,
- })
- );
- },
- onArtifactReady: event => {
- rtLog('artifact_ready', {
- thread: event.thread_id,
- artifact_id: event.artifact_id,
- kind: event.kind,
- size_bytes: event.size_bytes,
- });
- dispatch(
- upsertArtifactReadyForThread({
- threadId: event.thread_id,
- artifactId: event.artifact_id,
- kind: event.kind,
- title: event.title,
- path: event.path,
- sizeBytes: event.size_bytes,
- toolCallId: event.tool_call_id,
- })
- );
- },
- onArtifactFailed: event => {
- // Defence-in-depth: producer is expected to pre-truncate the
- // reason, but cap again here so a leaky producer cannot dump
- // unbounded provider stderr into client telemetry.
- rtLog('artifact_failed', {
- thread: event.thread_id,
- artifact_id: event.artifact_id,
- kind: event.kind,
- error: event.error.slice(0, 80),
- });
- dispatch(
- upsertArtifactFailedForThread({
- threadId: event.thread_id,
- artifactId: event.artifact_id,
- kind: event.kind,
- title: event.title,
- error: event.error,
- toolCallId: event.tool_call_id,
- })
- );
- },
- onApprovalRequest: (event: ChatApprovalRequestEvent) => {
- rtLog('approval_request', {
- thread: event.thread_id,
- request: event.request_id,
- tool: event.tool_name,
- });
- // Pull the exact command/target out of the redacted args for display:
- // shell → command, file write/edit → path, network → url.
- const a = event.args ?? {};
- const firstString = (v: unknown): string | undefined =>
- typeof v === 'string' && v.length > 0 ? v : undefined;
- const command =
- firstString(a.command) ??
- firstString(a.path) ??
- firstString(a.url) ??
- firstString(a.target);
- // `composio_connect` carries the toolkit slug so the inline connect
- // card (#3993) knows which integration to authorize.
- const toolkit = firstString(a.toolkit);
- dispatch(
- setPendingApprovalForThread({
- threadId: event.thread_id,
- approval: {
- requestId: event.request_id,
- toolName: event.tool_name,
- message: event.message,
- command,
- toolkit,
- toolCallId: event.tool_call_id,
- expiresAt: event.expires_at,
- },
- })
- );
- },
- onApprovalDecided: (event: ChatApprovalDecidedEvent) => {
- rtLog('approval_decided', {
- thread: event.thread_id,
- request: event.request_id,
- resolution: event.resolution,
- });
- // Only a server-recorded TERMINAL non-decision (TTL expiry, an
- // external cancel) needs handling here: an interactive decision made
- // through THIS client already cleared the entry optimistically
- // (`useOpenHumanExternalStore`'s `onRespondToToolApproval` /
- // `ApprovalRequestCard`), and a decision made on another connected
- // client is covered by the existing turn-end handlers once that
- // client's turn settles. Clearing eagerly on every `approval_decided`
- // would race the optimistic clear and, worse, drop a card whose
- // decision the USER on this client is mid-click on when the event
- // for a DIFFERENT thread's request arrives.
- if (
- !event.thread_id ||
- (event.resolution !== 'expired' && event.resolution !== 'cancelled')
- ) {
- return;
- }
- dispatch(
- resolvePendingApprovalForThread({
- threadId: event.thread_id,
- requestId: event.request_id,
- resolution: event.resolution,
- })
- );
- },
- onPlanReviewRequest: (event: ChatPlanReviewRequestEvent) => {
- rtLog('plan_review_request', { thread: event.thread_id, request: event.request_id });
- const steps = Array.isArray(event.args?.steps)
- ? event.args.steps.filter((s): s is string => typeof s === 'string')
- : [];
- dispatch(
- setPendingPlanReviewForThread({
- threadId: event.thread_id,
- review: {
- requestId: event.request_id,
- summary: event.message,
- steps,
- toolCallId: event.tool_call_id,
- expiresAt: event.expires_at,
- },
- })
- );
- },
- onThreadTodosChanged: (event: ChatThreadTodosChangedEvent) => {
- rtLog('thread_todos_changed', { thread: event.thread_id, count: event.todos?.length ?? 0 });
- dispatch(setThreadTodos({ threadId: event.thread_id, todos: event.todos ?? [] }));
- },
- onThreadGoalUpdated: (event: ChatThreadGoalUpdatedEvent) => {
- rtLog('thread_goal_updated', { thread: event.thread_id, status: event.goal?.status });
- dispatch(setThreadGoal({ threadId: event.thread_id, goal: event.goal }));
- },
- onThreadGoalCleared: (event: ChatThreadGoalClearedEvent) => {
- rtLog('thread_goal_cleared', { thread: event.thread_id });
- dispatch(clearThreadGoal({ threadId: event.thread_id }));
- },
- onRunModeChanged: (event: ChatRunModeChangedEvent) => {
- rtLog('run_mode_changed', { thread: event.thread_id, mode: event.mode });
- dispatch(setRunMode({ threadId: event.thread_id, mode: event.mode }));
- },
- /**
- * `chat_cancelled` (wire-contract.md) — the core-authoritative sibling
- * of the local Stop path in `Conversations.tsx`'s `handleStopGeneration`
- * (which persists a `cancelReason: 'user_stop'` partial optimistically,
- * before the core confirms). This handler is what also covers a turn
- * the core cancels on its OWN initiative — `cancel_reason: 'superseded'`
- * when a newer send interrupts it — which has no local Stop click to
- * persist from.
- *
- * The core keeps emitting `chat_error{error_type:"cancelled"}`
- * alongside this for one release (that path appends no message — see
- * its own comment below), so this dedupes on `request_id` against
- * whatever `handleStopGeneration` already persisted rather than
- * assuming it is the only writer.
- */
- onCancelled: (event: ChatCancelledEvent) => {
- const eventKey = `cancelled:${event.thread_id}:${event.request_id ?? 'none'}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
-
- rtLog('chat_cancelled', {
- thread: event.thread_id,
- request: event.request_id,
- reason: event.cancel_reason,
- superseded_by: event.superseded_by,
- });
- // Read the live partial and the existing transcript BEFORE clearing
- // any runtime state below — those dispatches are what the partial and
- // the "already persisted?" check would otherwise be racing against.
- const stateBefore = store.getState();
- const partial =
- stateBefore.chatRuntime.streamingAssistantByThread[event.thread_id]?.content ?? '';
- const threadMessages = stateBefore.thread.messagesByThreadId[event.thread_id] ?? [];
- const alreadyStopped = event.request_id
- ? threadMessages.some(message => {
- const meta = message.extraMetadata as
- | { stopped?: boolean; requestId?: string }
- | undefined;
- return meta?.stopped === true && meta.requestId === event.request_id;
+ const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
+ if (!current) return;
+ dispatch(
+ setInferenceStatusForThread({
+ threadId: event.thread_id,
+ status: { ...current, phase: 'thinking', activeSubagent: undefined },
})
- : false;
-
- dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
- dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
- dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
- dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
+ );
+ },
+ 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,
+ });
+ dispatch(
+ setWorkflowProposalForThread({
+ threadId: event.thread_id,
+ proposal: subagentProposal,
+ })
+ );
+ }
- if (!alreadyStopped && partial.trim().length > 0) {
+ 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: partial,
+ content,
threadId: event.thread_id,
- extraMetadata: chatCancelledExtraMetadata(event),
+ // 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 } : {}),
+ },
})
);
- }
-
- dispatch(endInferenceTurn({ threadId: event.thread_id }));
- dispatch(clearThreadInferenceActive(event.thread_id));
- },
- onDone: event => {
- const eventKey = `done:${event.thread_id}:${event.request_id ?? 'none'}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
-
- rtLog('chat_done', {
- thread: event.thread_id,
- request: event.request_id,
- segments: event.segment_total,
- input_tokens: event.total_input_tokens,
- output_tokens: event.total_output_tokens,
- });
-
- // Close the tool-chain latency window and surface overruns of the 60s
- // target (#4273, AC3). Observability only — never blocks the turn.
- const latency = skillLatencyRef.current.finishChain(
- segmentDeliveryKey(event.thread_id, event.request_id),
- { ok: true }
- );
- if (latency) {
- rtLog('skill_tool_chain_latency', {
+ },
+ 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,
- elapsed_ms: latency.elapsedMs,
- tools: latency.toolCount,
- within_target: latency.withinTarget ? 'true' : 'false',
+ round: event.round,
});
- if (!latency.withinTarget) {
- console.warn(
- `[skill-latency] tool chain on thread ${event.thread_id} took ${latency.elapsedMs}ms ` +
- `across ${latency.toolCount} tool(s) — exceeds the ${SKILL_TOOL_CHAIN_TARGET_MS}ms target`
+ // 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) {
+ dispatch(
+ setStreamingAssistantForThread({
+ threadId: event.thread_id,
+ streaming: {
+ requestId: existing.requestId,
+ content: '',
+ thinking: existing.thinking,
+ },
+ })
);
}
- }
+ },
+ onTextDelta: event => {
+ // Redelivered frames are dropped before coalescing (`accept` below).
+ // Parallel-vs-primary routing + processing transcript now live in the
+ // reducer (Phase 3) — no getState() in the provider.
+ dispatch(
+ streamDeltaReceived({
+ threadId: event.thread_id,
+ requestId: event.request_id,
+ round: event.round,
+ delta: event.delta,
+ channel: 'content',
+ })
+ );
+ },
+ onThinkingDelta: event => {
+ dispatch(
+ streamDeltaReceived({
+ threadId: event.thread_id,
+ requestId: event.request_id,
+ round: event.round,
+ delta: event.delta,
+ channel: 'thinking',
+ at: Date.now(),
+ })
+ );
+ },
+ onToolArgsDelta: event => {
+ // Match + append + decorate now live in the reducer (Phase 3).
+ dispatch(
+ toolArgsDeltaReceived({
+ threadId: event.thread_id,
+ round: event.round,
+ delta: event.delta,
+ toolName: event.tool_name,
+ toolCallId: event.tool_call_id,
+ })
+ );
+ },
+ onProactiveMessage: (event: ProactiveMessageEvent) => {
+ const messageDigest = proactiveMessageDigest(event.full_response ?? '');
+ const eventKey = `proactive:${event.thread_id}:${event.request_id ?? 'none'}:${messageDigest}`;
+ if (
+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
+ )
+ return;
- const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
- const segmentDelivery = takeSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
- const completeSegmentDelivery = hasCompleteSegmentDelivery(event, segmentDelivery);
-
- dispatch(recordChatTurnUsage(chatTurnUsagePayload(event)));
- dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
- dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
- dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
- dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
-
- // Rows still `running` are NOT forced to `success` here. The core now
- // forwards every queued progress event before `chat_done`, so a row
- // still running at this point genuinely has no result — marking it
- // successful invented an outcome. The settled turn_state snapshot /
- // transcript projection settles it (to its real status, or
- // `cancelled`).
- if (!event.segment_total) {
- void (async () => {
+ proactiveDispatchQueueRef.current = proactiveDispatchQueueRef.current.then(async () => {
try {
+ const targetThreadId = await resolveVisibleThreadForProactive(event.thread_id);
+ if (!targetThreadId) return;
+ rtLog('proactive_message', {
+ from: event.thread_id,
+ to: targetThreadId,
+ request: event.request_id,
+ });
await dispatch(
addInferenceResponse({
content: event.full_response,
@@@ -1577,193 -1251,444 +1310,564 @@@
request: event.request_id,
error: error instanceof Error ? error.message : String(error),
});
- await recoverDeliveredReply(event, error);
}
- await finishChatDoneTurn(event, 'proactive');
- })();
- return;
- }
-
- if (!completeSegmentDelivery && event.full_response.length > 0) {
- rtLog('chat_done_segment_reconcile', {
+ });
+ },
+ onArtifactPending: event => {
+ rtLog('artifact_pending', {
+ thread: event.thread_id,
+ artifact_id: event.artifact_id,
+ kind: event.kind,
+ });
+ dispatch(
+ upsertArtifactInProgressForThread({
+ threadId: event.thread_id,
+ artifactId: event.artifact_id,
+ kind: event.kind,
+ title: event.title,
++ toolCallId: event.tool_call_id,
+ })
+ );
+ },
+ onArtifactReady: event => {
+ rtLog('artifact_ready', {
+ thread: event.thread_id,
+ artifact_id: event.artifact_id,
+ kind: event.kind,
+ size_bytes: event.size_bytes,
+ });
+ dispatch(
+ upsertArtifactReadyForThread({
+ threadId: event.thread_id,
+ artifactId: event.artifact_id,
+ kind: event.kind,
+ title: event.title,
+ path: event.path,
+ sizeBytes: event.size_bytes,
++ toolCallId: event.tool_call_id,
+ })
+ );
+ },
+ onArtifactFailed: event => {
+ // Defence-in-depth: producer is expected to pre-truncate the
+ // reason, but cap again here so a leaky producer cannot dump
+ // unbounded provider stderr into client telemetry.
+ rtLog('artifact_failed', {
+ thread: event.thread_id,
+ artifact_id: event.artifact_id,
+ kind: event.kind,
+ error: event.error.slice(0, 80),
+ });
+ dispatch(
+ upsertArtifactFailedForThread({
+ threadId: event.thread_id,
+ artifactId: event.artifact_id,
+ kind: event.kind,
+ title: event.title,
+ error: event.error,
+ })
+ );
+ },
+ onApprovalRequest: (event: ChatApprovalRequestEvent) => {
+ rtLog('approval_request', {
thread: event.thread_id,
request: event.request_id,
- expected: event.segment_total,
- received: segmentDelivery?.segments.size ?? 0,
- full_len: event.full_response.length,
+ tool: event.tool_name,
});
- void (async () => {
- try {
- await dispatch(
- addInferenceResponse({
- content: event.full_response,
- threadId: event.thread_id,
- messageId: corePersistedMessageId(event),
- extraMetadata: chatDoneExtraMetadata(event),
- })
- ).unwrap();
- void dispatch(
- generateThreadTitleIfNeeded({
- threadId: event.thread_id,
- assistantMessage: event.full_response,
- })
- );
- } catch (error) {
- rtLog('chat_done_reconcile_append_failed', {
- thread: event.thread_id,
- request: event.request_id,
- error: error instanceof Error ? error.message : String(error),
- });
- }
- await finishChatDoneTurn(event, 'segment_reconcile');
- })();
- return;
- }
-
- void dispatch(
- generateThreadTitleIfNeeded({
- threadId: event.thread_id,
- assistantMessage: event.full_response,
- })
- );
- void finishChatDoneTurn(event, 'ordinary');
- },
- onError: event => {
- const eventKey = `error:${event.thread_id}:${event.request_id ?? 'none'}:${event.error_type}`;
- if (
- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
- )
- return;
-
- rtLog('chat_error', {
- thread: event.thread_id,
- request: event.request_id,
- err: event.error_type,
- });
-
- // A failed turn still closes its latency window so the chain timer never
- // leaks into a later turn on the same thread (#4273, AC3).
- const errLatency = skillLatencyRef.current.finishChain(
- segmentDeliveryKey(event.thread_id, event.request_id),
- { ok: false }
- );
- if (errLatency) {
- rtLog('skill_tool_chain_latency', {
+ // Pull the exact command/target out of the redacted args for display:
+ // shell → command, file write/edit → path, network → url.
+ const a = event.args ?? {};
+ const firstString = (v: unknown): string | undefined =>
+ typeof v === 'string' && v.length > 0 ? v : undefined;
+ const command =
+ firstString(a.command) ??
+ firstString(a.path) ??
+ firstString(a.url) ??
+ firstString(a.target);
+ // `composio_connect` carries the toolkit slug so the inline connect
+ // card (#3993) knows which integration to authorize.
+ const toolkit = firstString(a.toolkit);
+ dispatch(
+ setPendingApprovalForThread({
+ threadId: event.thread_id,
+ approval: {
+ requestId: event.request_id,
+ toolName: event.tool_name,
+ message: event.message,
+ command,
+ toolkit,
++ toolCallId: event.tool_call_id,
++ expiresAt: event.expires_at,
+ },
+ })
+ );
+ },
++ onApprovalDecided: (event: ChatApprovalDecidedEvent) => {
++ rtLog('approval_decided', {
+ thread: event.thread_id,
+ request: event.request_id,
- elapsed_ms: errLatency.elapsedMs,
- tools: errLatency.toolCount,
- within_target: errLatency.withinTarget ? 'true' : 'false',
- ok: 'false',
++ resolution: event.resolution,
+ });
- }
++ // Only a server-recorded TERMINAL non-decision (TTL expiry, an
++ // external cancel) needs handling here: an interactive decision made
++ // through THIS client already cleared the entry optimistically
++ // (`useOpenHumanExternalStore`'s `onRespondToToolApproval` /
++ // `ApprovalRequestCard`), and a decision made on another connected
++ // client is covered by the existing turn-end handlers once that
++ // client's turn settles. Clearing eagerly on every `approval_decided`
++ // would race the optimistic clear and, worse, drop a card whose
++ // decision the USER on this client is mid-click on when the event
++ // for a DIFFERENT thread's request arrives.
++ if (
++ !event.thread_id ||
++ (event.resolution !== 'expired' && event.resolution !== 'cancelled')
++ ) {
++ return;
++ }
++ dispatch(
++ resolvePendingApprovalForThread({
++ threadId: event.thread_id,
++ requestId: event.request_id,
++ resolution: event.resolution,
++ })
++ );
++ },
+ onPlanReviewRequest: (event: ChatPlanReviewRequestEvent) => {
+ rtLog('plan_review_request', { thread: event.thread_id, request: event.request_id });
+ const steps = Array.isArray(event.args?.steps)
+ ? event.args.steps.filter((s): s is string => typeof s === 'string')
+ : [];
+ dispatch(
+ setPendingPlanReviewForThread({
+ threadId: event.thread_id,
- review: { requestId: event.request_id, summary: event.message, steps },
++ review: {
++ requestId: event.request_id,
++ summary: event.message,
++ steps,
++ toolCallId: event.tool_call_id,
++ expiresAt: event.expires_at,
++ },
+ })
+ );
+ },
++ onThreadTodosChanged: (event: ChatThreadTodosChangedEvent) => {
++ rtLog('thread_todos_changed', { thread: event.thread_id, count: event.todos?.length ?? 0 });
++ dispatch(setThreadTodos({ threadId: event.thread_id, todos: event.todos ?? [] }));
++ },
++ onThreadGoalUpdated: (event: ChatThreadGoalUpdatedEvent) => {
++ rtLog('thread_goal_updated', { thread: event.thread_id, status: event.goal?.status });
++ dispatch(setThreadGoal({ threadId: event.thread_id, goal: event.goal }));
++ },
++ onThreadGoalCleared: (event: ChatThreadGoalClearedEvent) => {
++ rtLog('thread_goal_cleared', { thread: event.thread_id });
++ dispatch(clearThreadGoal({ threadId: event.thread_id }));
++ },
++ onRunModeChanged: (event: ChatRunModeChangedEvent) => {
++ rtLog('run_mode_changed', { thread: event.thread_id, mode: event.mode });
++ dispatch(setRunMode({ threadId: event.thread_id, mode: event.mode }));
++ },
++ /**
++ * `chat_cancelled` (wire-contract.md) — the core-authoritative sibling
++ * of the local Stop path in `Conversations.tsx`'s `handleStopGeneration`
++ * (which persists a `cancelReason: 'user_stop'` partial optimistically,
++ * before the core confirms). This handler is what also covers a turn
++ * the core cancels on its OWN initiative — `cancel_reason: 'superseded'`
++ * when a newer send interrupts it — which has no local Stop click to
++ * persist from.
++ *
++ * The core keeps emitting `chat_error{error_type:"cancelled"}`
++ * alongside this for one release (that path appends no message — see
++ * its own comment below), so this dedupes on `request_id` against
++ * whatever `handleStopGeneration` already persisted rather than
++ * assuming it is the only writer.
++ */
++ onCancelled: (event: ChatCancelledEvent) => {
++ const eventKey = `cancelled:${event.thread_id}:${event.request_id ?? 'none'}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
+
- // #3931: surface expected, user-actionable provider/billing states
- // (insufficient BYO credits, managed-budget exhaustion) in the shell's
- // dedicated error panel — in ADDITION to the inline chat message below.
- // Additive + defensive: no-op for non-actionable errors, never throws.
- if (event.error_type !== 'cancelled') {
- ingestRuntimeErrorSignal(dispatch, {
- message: event.message,
- errorType: event.error_type,
- scope: 'chat',
- sourceDomain: 'chat',
++ rtLog('chat_cancelled', {
++ thread: event.thread_id,
++ request: event.request_id,
++ reason: event.cancel_reason,
++ superseded_by: event.superseded_by,
+ });
- // #5868: a session_expired chat error means the Rust core already
- // published DomainEvent::SessionExpired and set signed_out=true, but
- // the auth:session_expired socket event may have been suppressed
- // (isBootstrapping guard) or missed. Dispatch the same window event
- // socketService emits so CoreStateProvider's runReauth() fires the
- // clearSession() → login redirect path from this side too. The 10s
- // debounce in runReauth() ensures a concurrent socket event does not
- // cause a double-clear.
- if (event.error_type === 'session_expired') {
- // `reason: 'unconfirmed'` is load-bearing, not defensive. The core
- // classifies this error with `is_session_expired_message`, which
- // matches the LOCAL guards "no backend session token" and
- // "session jwt required" as well as a real backend expiry
- // (`core/observability.rs`). Those two fire transiently before the
- // on-disk auth profile has been read — #2758 is the bug where
- // treating them as definitive forced a re-login even though the
- // token had survived the restart. `unconfirmed` routes through
- // `confirmSessionTokenGone()` in `runReauth`, so a signal raised
- // while the token is still on disk stops short of the destructive
- // `clearSession()`. A genuine expiry still corroborates and signs
- // out; only the false positive is filtered.
- window.dispatchEvent(
- new CustomEvent('openhuman:session-expired', {
- detail: { source: 'chat-error', reason: 'unconfirmed' },
++
++ // Read the live partial and the existing transcript BEFORE clearing
++ // any runtime state below — those dispatches are what the partial and
++ // the "already persisted?" check would otherwise be racing against.
++ const stateBefore = store.getState();
++ const partial =
++ stateBefore.chatRuntime.streamingAssistantByThread[event.thread_id]?.content ?? '';
++ const threadMessages = stateBefore.thread.messagesByThreadId[event.thread_id] ?? [];
++ const alreadyStopped = event.request_id
++ ? threadMessages.some(message => {
++ const meta = message.extraMetadata as
++ | { stopped?: boolean; requestId?: string }
++ | undefined;
++ return meta?.stopped === true && meta.requestId === event.request_id;
+ })
- );
- }
- }
++ : false;
+
- deleteSegmentDelivery(
- segmentDeliveriesRef.current,
- segmentDeliveryKey(event.thread_id, event.request_id)
- );
- dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
- dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
- dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
- dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
-
- const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
- if (existing.length > 0) {
- const entries = existing.map(entry =>
- entry.status === 'running' ? { ...entry, status: 'error' as const } : entry
- );
- dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
- }
++ dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
++ dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
++ dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
++ dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
+
- if (event.error_type !== 'cancelled') {
- const currentState = store.getState();
- const threadMessages = currentState.thread.messagesByThreadId[event.thread_id] ?? [];
- const lastMsg = threadMessages[threadMessages.length - 1];
- // Every error_type — including the generic 'inference' fallback — carries a
- // user-facing `message` produced by classify_inference_error() in web_errors.rs.
- // For 'inference' that message is the friendly summary PLUS the real, sanitized
- // upstream provider error appended as a `> quote` block (secret-scrubbed and
- // length-capped server-side via with_provider_detail()/sanitize_api_error()), so
- // surfacing it tells the user *why* the turn failed instead of a blanket apology.
- // The hardcoded constant is only a last-resort fallback for an empty/missing message.
- const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
- // A core-owned failure carries a deterministic id, so dedupe on that
- // rather than on the text. Two runs can fail with byte-identical
- // content — the same upstream provider message, or the generic
- // fallback above — and a text check would then read the previous
- // run's row as this one and drop the current failure from the cache.
- // Interactive turns have no pre-persisted id and keep the text check.
- const errorMessageId = corePersistedMessageId(event);
- const alreadyPresent = errorMessageId
- ? threadMessages.some(message => message.id === errorMessageId)
- : lastMsg?.sender === 'agent' && lastMsg?.content === errorContent;
- if (!alreadyPresent) {
++ if (!alreadyStopped && partial.trim().length > 0) {
+ void dispatch(
+ addInferenceResponse({
- content: errorContent,
++ content: partial,
+ threadId: event.thread_id,
- messageId: errorMessageId,
- extraMetadata: chatErrorExtraMetadata(event),
++ extraMetadata: chatCancelledExtraMetadata(event),
+ })
+ );
+ }
+
- rtLog('refresh_usage_counter', {
++ dispatch(endInferenceTurn({ threadId: event.thread_id }));
++ dispatch(clearThreadInferenceActive(event.thread_id));
++ },
+ onDone: event => {
+ const eventKey = `done:${event.thread_id}:${event.request_id ?? 'none'}`;
+ if (
+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
+ )
+ return;
+
+ rtLog('chat_done', {
thread: event.thread_id,
request: event.request_id,
- reason: 'chat_error',
+ segments: event.segment_total,
+ input_tokens: event.total_input_tokens,
+ output_tokens: event.total_output_tokens,
});
- requestUsageRefresh();
- }
- // The backend drains + dispatches queued follow-ups even when the turn
- // errored, so flush them to the transcript here too (otherwise their
- // prompts are lost). Mirrors the done path (sequential internally).
- void flushQueuedFollowups(event.thread_id);
- dispatch(endInferenceTurn({ threadId: event.thread_id }));
- dispatch(clearThreadInferenceActive(event.thread_id));
+ // Close the tool-chain latency window and surface overruns of the 60s
+ // target (#4273, AC3). Observability only — never blocks the turn.
+ const latency = skillLatencyRef.current.finishChain(
+ segmentDeliveryKey(event.thread_id, event.request_id),
+ { ok: true }
+ );
+ if (latency) {
+ rtLog('skill_tool_chain_latency', {
+ thread: event.thread_id,
+ request: event.request_id,
+ elapsed_ms: latency.elapsedMs,
+ tools: latency.toolCount,
+ within_target: latency.withinTarget ? 'true' : 'false',
+ });
+ if (!latency.withinTarget) {
+ console.warn(
+ `[skill-latency] tool chain on thread ${event.thread_id} took ${latency.elapsedMs}ms ` +
+ `across ${latency.toolCount} tool(s) — exceeds the ${SKILL_TOOL_CHAIN_TARGET_MS}ms target`
+ );
+ }
+ }
+
+ // Parallel (forked) turn: resolve only its own lane. The primary turn's
+ // stream / status / lifecycle / active marker may still be running, so
+ // we must NOT clear them here. Segmented parallel turns already
+ // persisted via `onSegment` (keyed by thread+request); a single-bubble
+ // parallel turn persists its full response now.
+ if (
+ event.request_id !== undefined &&
+ store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
+ ) {
+ const parallelRequestId = event.request_id;
+ dispatch(recordChatTurnUsage(chatTurnUsagePayload(event)));
+ if (!event.segment_total && event.full_response.length > 0) {
+ void (async () => {
+ try {
+ await dispatch(
+ addInferenceResponse({
+ content: event.full_response,
+ threadId: event.thread_id,
+ messageId: deliveredReplyMessageId(event),
+ extraMetadata: chatDoneExtraMetadata(event),
+ })
+ ).unwrap();
+ void dispatch(
+ generateThreadTitleIfNeeded({
+ threadId: event.thread_id,
+ assistantMessage: event.full_response,
+ })
+ );
+ } catch (error) {
+ rtLog('parallel_chat_done_append_failed', {
+ thread: event.thread_id,
+ request: event.request_id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ await recoverDeliveredReply(event, error);
+ }
+ })();
+ }
+ dispatch(clearParallelRequest({ requestId: parallelRequestId }));
+ requestUsageRefresh();
+ return;
+ }
+
+ const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
+ const segmentDelivery = takeSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
+ const completeSegmentDelivery = hasCompleteSegmentDelivery(event, segmentDelivery);
+
+ dispatch(recordChatTurnUsage(chatTurnUsagePayload(event)));
+ // A parked gate cannot outlive its turn, so those go now.
+ dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
+ dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
+ // Nothing the turn RENDERED is cleared here. The streaming buffer, the
+ // status line and the running rows used to be torn down first, before
+ // the reply was even persisted, and every one of those was a render:
+ // the answer vanished, then reappeared above its own tools, then the
+ // tools moved back and remounted collapsed. The live tail now stays as
+ // it is until `finishChatDoneTurn` swaps it for the persisted reply in
+ // one `turnSettled` update (the reply row is hidden behind the tail
+ // until then — see `buildRuntimeMessages`).
+ //
+ // Rows still `running` are NOT forced to `success` here. The core now
+ // forwards every queued progress event before `chat_done`, so a row
+ // still running at this point genuinely has no result — marking it
+ // successful invented an outcome. The settled turn_state snapshot /
+ // transcript projection settles it (to its real status, or
+ // `cancelled`).
+ if (!event.segment_total) {
+ void (async () => {
+ try {
+ await dispatch(
+ addInferenceResponse({
+ content: event.full_response,
+ threadId: event.thread_id,
+ messageId: deliveredReplyMessageId(event),
+ extraMetadata: chatDoneExtraMetadata(event),
+ })
+ ).unwrap();
+ void dispatch(
+ generateThreadTitleIfNeeded({
+ threadId: event.thread_id,
+ assistantMessage: event.full_response,
+ })
+ );
+ } catch (error) {
+ rtLog('chat_done_append_failed', {
+ thread: event.thread_id,
+ request: event.request_id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ await recoverDeliveredReply(event, error);
+ }
+ await finishChatDoneTurn(event, 'proactive');
+ })();
+ return;
+ }
+
+ if (!completeSegmentDelivery && event.full_response.length > 0) {
+ rtLog('chat_done_segment_reconcile', {
+ thread: event.thread_id,
+ request: event.request_id,
+ expected: event.segment_total,
+ received: segmentDelivery?.segments.size ?? 0,
+ full_len: event.full_response.length,
+ });
+ void (async () => {
+ try {
+ await dispatch(
+ addInferenceResponse({
+ content: event.full_response,
+ threadId: event.thread_id,
+ messageId: corePersistedMessageId(event),
+ extraMetadata: chatDoneExtraMetadata(event),
+ })
+ ).unwrap();
+ void dispatch(
+ generateThreadTitleIfNeeded({
+ threadId: event.thread_id,
+ assistantMessage: event.full_response,
+ })
+ );
+ } catch (error) {
+ rtLog('chat_done_reconcile_append_failed', {
+ thread: event.thread_id,
+ request: event.request_id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ await finishChatDoneTurn(event, 'segment_reconcile');
+ })();
+ return;
+ }
+
+ void dispatch(
+ generateThreadTitleIfNeeded({
+ threadId: event.thread_id,
+ assistantMessage: event.full_response,
+ })
+ );
+ void finishChatDoneTurn(event, 'ordinary');
+ },
+ onError: event => {
+ const eventKey = `error:${event.thread_id}:${event.request_id ?? 'none'}:${event.error_type}`;
+ if (
+ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
+ )
+ return;
+
+ rtLog('chat_error', {
+ thread: event.thread_id,
+ request: event.request_id,
+ err: event.error_type,
+ });
+
+ // A failed turn still closes its latency window so the chain timer never
+ // leaks into a later turn on the same thread (#4273, AC3).
+ const errLatency = skillLatencyRef.current.finishChain(
+ segmentDeliveryKey(event.thread_id, event.request_id),
+ { ok: false }
+ );
+ if (errLatency) {
+ rtLog('skill_tool_chain_latency', {
+ thread: event.thread_id,
+ request: event.request_id,
+ elapsed_ms: errLatency.elapsedMs,
+ tools: errLatency.toolCount,
+ within_target: errLatency.withinTarget ? 'true' : 'false',
+ ok: 'false',
+ });
+ }
+
+ // #3931: surface expected, user-actionable provider/billing states
+ // (insufficient BYO credits, managed-budget exhaustion) in the shell's
+ // dedicated error panel — in ADDITION to the inline chat message below.
+ // Additive + defensive: no-op for non-actionable errors, never throws.
+ if (event.error_type !== 'cancelled') {
+ ingestRuntimeErrorSignal(dispatch, {
+ message: event.message,
+ errorType: event.error_type,
+ scope: 'chat',
+ sourceDomain: 'chat',
+ });
+ // #5868: a session_expired chat error means the Rust core already
+ // published DomainEvent::SessionExpired and set signed_out=true, but
+ // the auth:session_expired socket event may have been suppressed
+ // (isBootstrapping guard) or missed. Dispatch the same window event
+ // socketService emits so CoreStateProvider's runReauth() fires the
+ // clearSession() → login redirect path from this side too. The 10s
+ // debounce in runReauth() ensures a concurrent socket event does not
+ // cause a double-clear.
+ if (event.error_type === 'session_expired') {
+ // `reason: 'unconfirmed'` is load-bearing, not defensive. The core
+ // classifies this error with `is_session_expired_message`, which
+ // matches the LOCAL guards "no backend session token" and
+ // "session jwt required" as well as a real backend expiry
+ // (`core/observability.rs`). Those two fire transiently before the
+ // on-disk auth profile has been read — #2758 is the bug where
+ // treating them as definitive forced a re-login even though the
+ // token had survived the restart. `unconfirmed` routes through
+ // `confirmSessionTokenGone()` in `runReauth`, so a signal raised
+ // while the token is still on disk stops short of the destructive
+ // `clearSession()`. A genuine expiry still corroborates and signs
+ // out; only the false positive is filtered.
+ window.dispatchEvent(
+ new CustomEvent('openhuman:session-expired', {
+ detail: { source: 'chat-error', reason: 'unconfirmed' },
+ })
+ );
+ }
+ }
+
+ // Parallel (forked) turn error: resolve only its lane, leaving the
+ // primary turn untouched. Surface a non-cancellation error as a message
+ // so the failed branch is visible.
+ if (
+ event.request_id !== undefined &&
+ store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
+ ) {
+ deleteSegmentDelivery(
+ segmentDeliveriesRef.current,
+ segmentDeliveryKey(event.thread_id, event.request_id)
+ );
+ if (event.error_type !== 'cancelled') {
+ const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
+ void dispatch(
+ addInferenceResponse({ content: errorContent, threadId: event.thread_id })
+ );
+ requestUsageRefresh();
+ }
+ dispatch(clearParallelRequest({ requestId: event.request_id }));
+ return;
+ }
+
+ deleteSegmentDelivery(
+ segmentDeliveriesRef.current,
+ segmentDeliveryKey(event.thread_id, event.request_id)
+ );
+ dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
+ dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
+ dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
+ dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
+
+ const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
+ if (existing.length > 0) {
+ const entries = existing.map(entry =>
+ entry.status === 'running' ? { ...entry, status: 'error' as const } : entry
+ );
+ dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
+ }
+
+ if (event.error_type !== 'cancelled') {
+ const currentState = store.getState();
+ const threadMessages = currentState.thread.messagesByThreadId[event.thread_id] ?? [];
+ const lastMsg = threadMessages[threadMessages.length - 1];
+ // Every error_type — including the generic 'inference' fallback — carries a
+ // user-facing `message` produced by classify_inference_error() in web_errors.rs.
+ // For 'inference' that message is the friendly summary PLUS the real, sanitized
+ // upstream provider error appended as a `> quote` block (secret-scrubbed and
+ // length-capped server-side via with_provider_detail()/sanitize_api_error()), so
+ // surfacing it tells the user *why* the turn failed instead of a blanket apology.
+ // The hardcoded constant is only a last-resort fallback for an empty/missing message.
+ const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
+ // A core-owned failure carries a deterministic id, so dedupe on that
+ // rather than on the text. Two runs can fail with byte-identical
+ // content — the same upstream provider message, or the generic
+ // fallback above — and a text check would then read the previous
+ // run's row as this one and drop the current failure from the cache.
+ // Interactive turns have no pre-persisted id and keep the text check.
+ const errorMessageId = corePersistedMessageId(event);
+ const alreadyPresent = errorMessageId
+ ? threadMessages.some(message => message.id === errorMessageId)
+ : lastMsg?.sender === 'agent' && lastMsg?.content === errorContent;
+ if (!alreadyPresent) {
+ void dispatch(
+ addInferenceResponse({
+ content: errorContent,
+ threadId: event.thread_id,
+ messageId: errorMessageId,
++ extraMetadata: chatErrorExtraMetadata(event),
+ })
+ );
+ }
+
+ rtLog('refresh_usage_counter', {
+ thread: event.thread_id,
+ request: event.request_id,
+ reason: 'chat_error',
+ });
+ requestUsageRefresh();
+ }
+
+ // The backend drains + dispatches queued follow-ups even when the turn
+ // errored, so flush them to the transcript here too (otherwise their
+ // prompts are lost). Mirrors the done path (sequential internally).
+ void flushQueuedFollowups(event.thread_id);
+ dispatch(endInferenceTurn({ threadId: event.thread_id }));
+ dispatch(clearThreadInferenceActive(event.thread_id));
+ },
},
- });
+ // A redelivered frame must be dropped before it can be merged into text.
+ { accept: event => !isReplayedDelta(event) }
+ );
+ const cleanup = subscribeChatEvents(coalesced.listeners);
return () => {
rtLog('unsubscribe_chat_events');
diff --cc app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
index b80b61352d,cd4b0ad09d..3d022feec7
--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
@@@ -9,15 -9,14 +9,16 @@@ import { socketService } from '../../se
import { store } from '../../store';
import {
clearAllChatRuntime,
- enqueueFollowup,
findPendingDelegationContext,
+ registerParallelRequest,
resetSessionTokenUsage,
setPendingPlanReviewForThread,
+ setStreamingAssistantForThread,
} from '../../store/chatRuntimeSlice';
+import { pendingFollowupAdded } from '../../store/queueSlice';
import { setStatusForUser } from '../../store/socketSlice';
import {
+ addMessageLocal,
clearAllThreads,
loadThreads,
setActiveThread,
diff --cc app/src/providers/assistantUiMessages.ts
index d61f93dc3b,2c9d275446..4d576d496c
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@@ -449,21 -244,37 +449,36 @@@ export function reasoningPart
/**
* Project one assistant message into assistant-ui parts.
*
- * The surface carries the turn as it happened: the agent's reasoning as a
- * COLLAPSED disclosure, every tool row in issue order, then the answer.
+ * The surface carries the turn as it happened, in the order it happened:
+ * reasoning as a disclosure, what the agent said between tool rounds, every
+ * tool row where it was issued, then the answer.
*
- * ## What is here, and what stays in the rail
+ * ## One shape, live and settled
*
- * Reasoning (`kind: 'thinking'`) renders inline again, through the static
- * reasoning panel: collapsed by default to one "Thought for Ns" line, expanded
- * into titled steps while it streams, so a turn that thought for ten seconds
- * shows one quiet line rather than ten seconds of prose — which is what made it
- * clutter the first time round.
+ * The live tail and the settled message are the SAME projection of the same
+ * transcript, and that is the property everything else here serves. A live
+ * turn that projected differently from its settled self (text always last,
+ * narration shown then wiped, reasoning unshifted to the front) re-shaped on
+ * every event and again at completion — and assistant-ui keys text and
+ * reasoning parts by their INDEX, so each reshaping remounted the markdown,
+ * restarted its reveal from nothing, reset every disclosure and jumped the
+ * scroll. So:
*
- * Narration is deliberately NOT restored. It is the turn's running commentary,
- * it duplicates the answer on the final round, and it is the bulk of what made
- * the old surface a firehose. It stays in `processingByThread` and renders in
- * the process rail behind {@link TurnProcessTrail}, which is unchanged.
+ * - **Reasoning** (`kind: 'thinking'`) renders through the static reasoning
+ * panel: one "Thought for Ns" line once settled, titled steps while it
+ * streams.
- *
+ * - **Narration renders inline** where it was said, live and on reload. It is
+ * the agent explaining the call it is about to make; showing it and then
+ * wiping it was the flicker, never showing it on reload was the mismatch.
+ * - **Parts are append-only while a turn streams.** New events add parts at
+ * the end; nothing is inserted before an existing part.
+ * - **The answer takes the final narration's slot.** Live, the final round's
+ * text IS a narration item (`streamDeltaReceived` coalesces every content
+ * delta into one per round). Settled, the persisted `msg.content` is that
+ * same text, so narration after the turn's last tool call is replaced by the
+ * answer in place: same index, same key, no remount at completion. The core
+ * projection (`mapDisplayItems`) only emits interim narration, so a reloaded
+ * turn has no trailing narration and the answer lands in the same place.
*
* ## Ordering
*
@@@ -495,14 -299,13 +503,15 @@@
* carry colliding ones.
*/
function assistantParts(
- text: string,
+ answer: string,
timeline: readonly ToolTimelineEntry[],
transcript: readonly ProcessingTranscriptItem[],
- mode: 'live' | 'settled'
++ mode: 'live' | 'settled',
+ citations: readonly ChatCitation[] = EMPTY_CITATIONS
): ThreadAssistantMessagePart[] {
+ const resolvedTimeline = resolveSubagentTimeline(timeline);
const parts: ThreadAssistantMessagePart[] = [];
- const timelineById = new Map(timeline.map(entry => [entry.id, entry]));
+ const timelineById = new Map(resolvedTimeline.map(entry => [entry.id, entry]));
const emittedToolIds = new Set<string>();
const claim = (entry: ToolTimelineEntry): boolean => {
if (emittedToolIds.has(entry.id)) return false;
@@@ -544,8 -358,23 +564,24 @@@
}
continue;
}
- // Narration is the turn explaining itself; it stays in the rail.
+ if (item.kind === 'narration') {
+ if (item.text.trim().length === 0) continue;
+ if (replaceTrailingNarration && index > lastToolPointer) {
+ if (!answerEmitted) parts.push({ type: 'text', text: answerText });
+ answerEmitted = true;
+ continue;
+ }
+ // The answer is never narration, wherever a transcript puts it. A core
+ // that predates the prompt-guided projection fix records a text-mode
+ // turn's answer as an interim step (with the turn's calls after it); as
+ // narration it would render the answer twice.
+ if (mode === 'settled' && answerText.length > 0 && item.text.trim() === answerText.trim()) {
+ continue;
+ }
+ parts.push({ type: 'text', text: item.text });
+ continue;
+ }
+ if (item.kind !== 'toolCall') continue;
const entry = timelineById.get(item.callId);
if (!entry) continue;
drainBefore(entry.seq);
@@@ -553,30 -382,13 +589,36 @@@
}
drainBefore(null);
- if (text.length > 0) parts.push({ type: 'text', text });
+ // Settled with no trailing narration to stand in for (a reloaded turn, or a
+ // legacy trail): the answer closes the turn. Live, the text is the
+ // transcript's narration; `streamingTailMessage` handles the rare turn whose
+ // transcript recorded none.
+ if (mode === 'settled' && !answerEmitted && answerText.length > 0) {
+ parts.push({ type: 'text', text: answerText });
+ }
+ // `extractAgentSources` is the one place a model-supplied URL is admitted
+ // (http(s) only), so sources are derived through it rather than here.
+ for (const source of extractAgentSources([...timeline])) {
+ parts.push({
+ type: 'source',
+ sourceType: 'url',
+ id: source.id,
+ url: source.url,
+ title: source.title,
+ });
+ }
+ // Memory citations captured during retrieval for this turn
+ // (`ChatDoneEvent.citations` / `ChatSegmentEvent.citations`), surfaced as
+ // `document` source parts alongside the turn's `url` sources.
+ for (const citation of citations) {
+ parts.push({
+ type: 'source',
+ sourceType: 'document',
+ id: `memory:${citation.id}`,
+ title: citation.key,
+ mediaType: 'application/vnd.openhuman.memory-citation',
+ });
+ }
return parts;
}
@@@ -825,10 -616,9 +867,10 @@@ export function toThreadMessageLike
const converted: ThreadMessageLike = {
id: msg.id,
role: msg.sender === 'agent' ? 'assistant' : 'user',
- content:
- msg.sender === 'agent'
- ? assistantParts(text, effectiveTimeline, transcript, 'settled')
+ content: isGuardrailError
+ ? []
+ : msg.sender === 'agent'
- ? assistantParts(text, effectiveTimeline, transcript, messageCitations(msg))
++ ? assistantParts(text, effectiveTimeline, transcript, 'settled', messageCitations(msg))
: userParts(msg),
createdAt: new Date(msg.createdAt),
...(msg.sender === 'agent' && msg.extraMetadata?.stopped === true
@@@ -981,6 -846,19 +1097,15 @@@ export function buildRuntimeMessages
msg.sender === 'agent' && typeof msg.extraMetadata?.requestId === 'string'
? msg.extraMetadata.requestId
: undefined;
+ if (hiddenLiveRequestId !== undefined && requestId === hiddenLiveRequestId) continue;
+ const frozen = requestId ? projection.settledTurns?.[requestId] : undefined;
+ if (frozen) {
+ const settledRows = requestId ? projection.turnTimelines?.[requestId] : undefined;
+ out.push(
- toThreadMessageLike(
- msg,
- withSettledStatuses(frozen.timeline, settledRows),
- frozen.transcript
- )
++ toThreadMessageLike(msg, withSettledStatuses(frozen.timeline, settledRows), frozen.transcript)
+ );
+ continue;
+ }
const effectiveRequestId =
requestId ??
(msg.sender === 'agent' && pairOrphanTrails
diff --cc app/src/providers/useOpenHumanExternalStore.ts
index 1329a38cde,a4353764d4..59b0869f23
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@@ -373,20 -381,23 +415,32 @@@ 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, welcomeSuggestions);
+ // The two gates are disjoint (welcome needs an empty thread, follow-ups a
+ // settled reply), so at most one of these is ever non-empty.
+ const welcomeChips = useWelcomeSuggestions(runtimeMessages.length, welcomeSuggestions);
+ const followupChips = useFollowupSuggestions(
+ threadId,
+ runtimeMessages.length,
+ runtimeMessages.at(-1)?.role,
+ isRunning
+ );
+ const suggestions = welcomeChips.length > 0 ? welcomeChips : followupChips;
// 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 524172f857,3aae1f3786..b0dc2a6335
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@@ -904,8 -883,26 +980,25 @@@ const initialState: ChatRuntimeState =
sessionTokenUsage: emptySessionTokenUsage(),
usageByThread: {},
queueStatusByThread: {},
- 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);
@@@ -1634,57 -1699,53 +1805,97 @@@ const chatRuntimeSlice = createSlice(
}
return;
}
- const pending = findPendingDelegationContext(entries, round);
- // Collapse the parent spawn/delegate row into the subagent row so the
- // timeline shows one entry per delegation — IN PLACE. The row takes the
- // spawn row's slot, its `seq` and its transcript pointer, so the
- // delegation renders exactly where the agent issued it. Splicing it out
- // and appending a fresh row left the pointer dangling and the sub-agent
- // card sorted to the end of the turn, below text that came after it,
- // and every part after the old slot shifted index (and remounted).
- const spawnIdx = pending.spawnEntryId
- ? entries.findIndex(e => e.id === pending.spawnEntryId)
- : -1;
- const spawnSeq = spawnIdx >= 0 ? entries[spawnIdx].seq : undefined;
- let seq = spawnSeq;
- if (seq === undefined) {
+ // `parent_call_id` names the exact spawn/delegate tool-call row that
+ // started this delegation — no need to guess it from "the newest
+ // running spawn-shaped row in this round" (the heuristic below).
+ // `assistantUiMessages.ts` renders this activity directly on that row
+ // (keyed by `parentCallId`) and suppresses that row's own tool-call
- // part, so this reducer does not need to splice it away either.
++ // part, so this reducer does not need to collapse it away either; the
++ // spawn row is simply left in the timeline for `resolveSubagentTimeline`
++ // to substitute at render time.
+ //
+ // Fallback for cores/history that predate `parent_call_id`: locate the
- // running spawn/delegate row heuristically and collapse it away here so
- // the timeline still shows one entry per delegation.
++ // running spawn/delegate row heuristically and collapse the two IN
++ // PLACE — the row takes the spawn row's slot, its `seq` and its
++ // transcript pointer, so the delegation renders exactly where the agent
++ // issued it. Splicing the spawn row out and appending a fresh one left
++ // the pointer dangling and the sub-agent card sorted to the end of the
++ // turn, below text that came after it, with every part after the old
++ // slot shifting index (and remounting).
+ let prompt: string | undefined;
+ let sourceToolName: string | undefined;
++ let seq: number;
+ if (parentCallId) {
+ const spawnEntry = entries.find(e => e.id === parentCallId);
+ prompt = spawnEntry?.detail ?? promptFromArgsBuffer(spawnEntry?.argsBuffer);
+ sourceToolName = spawnEntry?.name;
+ seq = state.toolTimelineSeqByThread[threadId] ?? 0;
+ state.toolTimelineSeqByThread[threadId] = seq + 1;
- }
- const row = decorateEntry({
- id: rowId,
- name: `subagent:${agentId}`,
- round,
- seq,
- status: 'running',
- detail: pending.prompt,
- sourceToolName: pending.sourceToolName,
- subagent: {
- taskId,
- agentId,
- displayName,
- workerThreadId,
- spawnEventId,
- mode,
- dedicatedThread,
- prompt: pending.prompt,
- toolCalls: [],
- transcript: [],
- },
- });
- if (spawnIdx >= 0) {
- entries[spawnIdx] = row;
- const pointer = state.processingByThread[threadId]?.find(
- item => item.kind === 'toolCall' && item.callId === pending.spawnEntryId
++ entries.push(
++ decorateEntry({
++ id: rowId,
++ name: `subagent:${agentId}`,
++ round,
++ seq,
++ status: 'running',
++ detail: prompt,
++ sourceToolName,
++ subagent: {
++ taskId,
++ agentId,
++ displayName,
++ workerThreadId,
++ spawnEventId,
++ parentCallId,
++ mode,
++ dedicatedThread,
++ prompt,
++ toolCalls: [],
++ transcript: [],
++ },
++ })
+ );
- if (pointer && pointer.kind === 'toolCall') pointer.callId = rowId;
} else {
- entries.push(row);
+ const pending = findPendingDelegationContext(entries, round);
+ prompt = pending.prompt;
+ sourceToolName = pending.sourceToolName;
- if (pending.spawnEntryId) {
- const spawnIdx = entries.findIndex(e => e.id === pending.spawnEntryId);
- if (spawnIdx >= 0) entries.splice(spawnIdx, 1);
- }
- }
- const seq = state.toolTimelineSeqByThread[threadId] ?? 0;
- state.toolTimelineSeqByThread[threadId] = seq + 1;
- entries.push(
- decorateEntry({
++ const spawnIdx = pending.spawnEntryId
++ ? entries.findIndex(e => e.id === pending.spawnEntryId)
++ : -1;
++ const spawnSeq = spawnIdx >= 0 ? entries[spawnIdx].seq : undefined;
++ seq = spawnSeq ?? (state.toolTimelineSeqByThread[threadId] ?? 0);
++ if (spawnSeq === undefined) state.toolTimelineSeqByThread[threadId] = seq + 1;
++ const row = decorateEntry({
+ id: rowId,
+ name: `subagent:${agentId}`,
+ round,
+ seq,
+ status: 'running',
- detail: prompt,
- sourceToolName,
++ detail: pending.prompt,
++ sourceToolName: pending.sourceToolName,
+ subagent: {
+ taskId,
+ agentId,
+ displayName,
+ workerThreadId,
+ spawnEventId,
- parentCallId,
+ mode,
+ dedicatedThread,
- prompt,
++ prompt: pending.prompt,
+ toolCalls: [],
+ transcript: [],
+ },
- })
- );
++ });
++ if (spawnIdx >= 0) {
++ entries[spawnIdx] = row;
++ const pointer = state.processingByThread[threadId]?.find(
++ item => item.kind === 'toolCall' && item.callId === pending.spawnEntryId
++ );
++ if (pointer && pointer.kind === 'toolCall') pointer.callId = rowId;
++ } else {
++ entries.push(row);
++ }
+ }
},
subagentAwaitingUser: (
state,
@@@ -2177,16 -2198,128 +2386,103 @@@
clearQueueStatusForThread: (state, action: PayloadAction<{ threadId: string }>) => {
delete state.queueStatusByThread[action.payload.threadId];
},
- /** Append a follow-up the user queued while a turn was streaming. */
- enqueueFollowup: (
- state,
- action: PayloadAction<{ threadId: string; message: ThreadMessage; label: string }>
- ) => {
- const { threadId, message, label } = action.payload;
- const bucket = state.queuedFollowupsByThread[threadId] ?? [];
- bucket.push({ message, label });
- state.queuedFollowupsByThread[threadId] = bucket;
- },
- /** Drop a single queued follow-up by message id (e.g. the user removed it). */
- removeFollowup: (state, action: PayloadAction<{ threadId: string; id: string }>) => {
- const bucket = state.queuedFollowupsByThread[action.payload.threadId];
- if (!bucket) return;
- const next = bucket.filter(item => item.message.id !== action.payload.id);
- if (next.length) {
- state.queuedFollowupsByThread[action.payload.threadId] = next;
- } else {
- delete state.queuedFollowupsByThread[action.payload.threadId];
- }
- },
- /** Drop all queued follow-ups for a thread (turn end / explicit clear). */
- clearFollowupsForThread: (state, action: PayloadAction<{ threadId: string }>) => {
- delete state.queuedFollowupsByThread[action.payload.threadId];
- },
beginInferenceTurn: (state, action: PayloadAction<{ threadId: string }>) => {
state.inferenceTurnLifecycleByThread[action.payload.threadId] = 'started';
+ // The live transcript belongs to the previous turn until this one's
+ // `inference_start` resets it — and the tail is minted from the moment
+ // the lifecycle is `started`, so it would draw the last turn's narration
+ // and reasoning again under the new question. That turn is settled (its
+ // trail frozen, or served by the core projection); start this one clean.
+ delete state.processingByThread[action.payload.threadId];
+ delete state.liveRequestIdByThread[action.payload.threadId];
},
markInferenceTurnStreaming: (state, action: PayloadAction<{ threadId: string }>) => {
if (state.inferenceTurnLifecycleByThread[action.payload.threadId]) {
state.inferenceTurnLifecycleByThread[action.payload.threadId] = 'streaming';
}
},
+ /** Record the primary turn now live on a thread; see {@link ChatRuntimeState.liveRequestIdByThread}. */
+ liveTurnStarted: (state, action: PayloadAction<{ threadId: string; requestId: string }>) => {
+ const { threadId, requestId } = action.payload;
+ if (!requestId || state.parallelRequestThreads[requestId] !== undefined) return;
+ state.liveRequestIdByThread[threadId] = requestId;
+ },
+ /**
+ * Settle the live turn in ONE store transition.
+ *
+ * Before this existed `chat_done` settled a turn in four separate steps
+ * (clear the streaming buffer, settle the rows, append the reply after an
+ * RPC, then end the lifecycle after another), and each step was a render
+ * of an intermediate state nobody designed: the answer vanished, then
+ * appeared ABOVE its own tools while the tail was pushed one slot down and
+ * remounted, then the tools moved back and remounted again collapsed.
+ *
+ * Here the reply is already in the thread cache (appended while the tail
+ * still stood in for it — `buildRuntimeMessages` hides the live turn's own
+ * rows while its tail is minted), so ending the tail and revealing the row
+ * happen in the same render, at the same index, with the same parts:
+ *
+ * - the live rows and transcript are frozen under the turn's request id,
+ * which is what the settled message renders from;
+ * - the streaming buffer, status line, parked gates and live-turn id are
+ * cleared;
+ * - the lifecycle ends, so the tail is no longer minted.
+ *
+ * Queued follow-ups are deliberately left alone: they are flushed after the
+ * reply and dropped by {@link endInferenceTurn}, as before.
+ */
+ turnSettled: (state, action: PayloadAction<{ threadId: string; requestId?: string }>) => {
+ const { threadId } = action.payload;
+ const live = state.liveRequestIdByThread[threadId];
+ // A newer turn is already live on the thread (a queued follow-up the
+ // core started while this turn's reply was still being persisted). The
+ // live state is that turn's now: freezing or clearing it would erase the
+ // turn that is streaming. This turn's reply is already in the cache and
+ // its trail comes from the core projection.
+ if (action.payload.requestId && live && live !== action.payload.requestId) {
+ turnStateLog(
+ 'turn settle superseded thread=%s request=%s live=%s',
+ threadId,
+ action.payload.requestId,
+ live
+ );
+ return;
+ }
+ const requestId = action.payload.requestId ?? live;
+ if (requestId) {
+ // Rows are frozen as they are: one still running at `chat_done` has no
+ // result, and inventing `success` for it is the wrong answer. The core
+ // projection's terminal status for the same row id is overlaid at
+ // render (`buildRuntimeMessages`), which keeps the row's identity.
+ const timeline = [...(state.toolTimelineByThread[threadId] ?? [])];
+ const transcript = state.processingByThread[threadId] ?? [];
+ if (timeline.length > 0 || transcript.length > 0) {
+ const turns = (state.settledTurnsByThread[threadId] ??= {});
+ turns[requestId] = { timeline, transcript: [...transcript] };
+ // Bounded: only turns settled while this view was open need a frozen
+ // copy; older ones render from the core projection like any reload.
+ const keys = Object.keys(turns);
+ for (const stale of keys.slice(0, Math.max(0, keys.length - SETTLED_TURNS_KEPT))) {
+ delete turns[stale];
+ }
+ }
+ state.toolTimelineByThread[threadId] = timeline;
+ }
+ turnStateLog('turn settled thread=%s request=%s', threadId, requestId ?? 'none');
+ delete state.streamingAssistantByThread[threadId];
+ delete state.inferenceStatusByThread[threadId];
+ delete state.pendingApprovalByThread[threadId];
+ delete state.pendingPlanReviewByThread[threadId];
+ delete state.liveRequestIdByThread[threadId];
+ delete state.inferenceTurnLifecycleByThread[threadId];
+ },
endInferenceTurn: (state, action: PayloadAction<{ threadId: string }>) => {
delete state.inferenceTurnLifecycleByThread[action.payload.threadId];
+ delete state.liveRequestIdByThread[action.payload.threadId];
- // The turn finished, so any follow-ups queued behind it are now being
- // dispatched by the backend — drop the optimistic pills; the queued
- // texts reappear as real messages on their dispatched turns.
- delete state.queuedFollowupsByThread[action.payload.threadId];
++ // The turn finished. Any follow-ups queued behind it are now being
++ // dispatched by the backend — `queueSlice`'s own `endInferenceTurn`
++ // listener drops its optimistic pills there; the queued texts reappear
++ // as real messages on their dispatched turns.
},
clearRuntimeForThread: (state, action: PayloadAction<{ threadId: string }>) => {
delete state.inferenceStatusByThread[action.payload.threadId];
diff --cc crates/openhuman-core/src/threads/transcript_view/mod.rs
index 3ac807f937,c980e5ebc2..5efb409a1a
--- a/crates/openhuman-core/src/threads/transcript_view/mod.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/mod.rs
@@@ -105,10 -109,11 +109,14 @@@ mod subagent_anchor_tests
#[cfg(test)]
#[path = "transcript_view_tests.rs"]
mod tests;
+#[cfg(test)]
+#[path = "transcript_view_tool_round_tests.rs"]
+mod tool_round_tests;
+ #[cfg(test)]
+ #[path = "prompt_tools_tests.rs"]
+ mod prompt_tools_tests;
+
#[cfg(test)]
#[path = "transcript_ordering_tests.rs"]
mod ordering_tests;
diff --cc crates/openhuman-core/src/threads/transcript_view/project.rs
index 0c98ae31da,aa936fc137..e35aa99148
--- a/crates/openhuman-core/src/threads/transcript_view/project.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/project.rs
@@@ -10,10 -10,8 +10,11 @@@ use std::collections::{HashSet, VecDequ
use std::path::{Path, PathBuf};
use tinyagents_session::transcript::{self, CompactionMarker, DisplayMessage, DisplayRecord};
+use tinytools_agent::dialect::{parse_replayed_results, ToolResultEntry};
+
+use crate::agent::messages::TOOL_RESULT_FAILURES_METADATA_KEY;
+ use super::prompt_tools::{self, CallRegistry, PromptToolResult};
use super::resolve;
use super::subagents;
use super::types::{DisplayItem, ProjectedTranscript, ToolCallFailure, ToolCallStatus};
@@@ -223,12 -227,13 +241,19 @@@ impl Projector
log::debug!("{LOG_PREFIX} sanitize: dropped system line from projection");
}
"user" => {
+ if let Some(blocks) = prompt_tools::parse_tool_results(msg) {
+ // Tool plumbing, not something the user said.
+ for block in blocks {
+ self.pair_result(block.id, block.body, ToolCallStatus::Success, None);
+ }
+ return;
+ }
+ // A text dialect folds a round's results into one user turn; it
+ // is tool output, never the user's words.
+ if let Some(results) = parse_replayed_results(&msg.message.content) {
+ self.text_tool_results(msg, results);
+ return;
+ }
// A legacy turn without request ids still restarts the step
// count at its prompt.
self.step = 0;