Skip to content

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

fix(chat): handle assistant message errors without crashing

Steven Enamakel82f29aaad3cd
diff --git a/app/src/components/assistant-ui/markdown-text.tsx b/app/src/components/assistant-ui/markdown-text.tsx
index ab51b60b92..1aae9850f4 100644
--- a/app/src/components/assistant-ui/markdown-text.tsx
+++ b/app/src/components/assistant-ui/markdown-text.tsx
@@ -96,19 +96,29 @@ const MarkdownTextImpl = () => {
// renders: the gate must not flip mid-reveal.
const { text } = useMessagePartText();
const hasMath = hasLatexContent(text);
+ const sources = useAuiState(state => sourcePartsToCitations(state.message.parts));
+
+ const preprocess = (input: string): string => {
+ const withCitations = linkifyCitationMarkers(input, sources.length);
+ return hasMath ? normalizeLatexDelimiters(withCitations) : withCitations;
+ };
return (
- <MarkdownTextPrimitive
- remarkPlugins={hasMath ? MATH_REMARK_PLUGINS : GFM_REMARK_PLUGINS}
- rehypePlugins={hasMath ? MATH_REHYPE_PLUGINS : HIGHLIGHT_REHYPE_PLUGINS}
- // `\[ … \]` / `\( … \)` are what models actually emit; `remark-math`
- // only understands `$ … $`. Runs before the smooth reveal, so the text is
- // normalised once rather than per frame.
- preprocess={hasMath ? normalizeLatexDelimiters : undefined}
- className="aui-md"
- components={defaultComponents}
- defer
- />
+ <CitationSourcesContext.Provider value={sources}>
+ <MarkdownTextPrimitive
+ remarkPlugins={hasMath ? MATH_REMARK_PLUGINS : GFM_REMARK_PLUGINS}
+ rehypePlugins={hasMath ? MATH_REHYPE_PLUGINS : HIGHLIGHT_REHYPE_PLUGINS}
+ // `\[ … \]` / `\( … \)` are what models actually emit; `remark-math`
+ // only understands `$ … $`. Citation linkification always runs
+ // (a no-op when the message has no sources); LaTeX normalization is
+ // gated as before. Runs before the smooth reveal, so the text is
+ // normalised once rather than per frame.
+ preprocess={preprocess}
+ className="aui-md"
+ components={defaultComponents}
+ defer
+ />
+ </CitationSourcesContext.Provider>
);
};
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index 21f3c1aa97..e6daa805a1 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -8,16 +8,16 @@ import {
} from '@/components/assistant-ui/attachment';
import { ComposerTriggerPopover } from '@/components/assistant-ui/composer-trigger-popover';
import { DirectiveText } from '@/components/assistant-ui/directive-text';
-import { File } from '@/components/assistant-ui/file';
-import { ThreadFollowupSuggestions } from '@/components/assistant-ui/follow-up-suggestions';
import { ErrorState } from '@/components/assistant-ui/elements/error-state';
import { Image } from '@/components/assistant-ui/elements/image';
import { MessageTiming } from '@/components/assistant-ui/elements/message-timing.aui';
+import { ToolFallback } from '@/components/assistant-ui/elements/tool-fallback';
+import { File } from '@/components/assistant-ui/file';
+import { ThreadFollowupSuggestions } from '@/components/assistant-ui/follow-up-suggestions';
import { cn } from '@/components/assistant-ui/lib/utils';
import { MarkdownText } from '@/components/assistant-ui/markdown-text';
import { ComposerQuotePreview, SelectionToolbar } from '@/components/assistant-ui/quote';
import { Reasoning } from '@/components/assistant-ui/reasoning';
-import { ToolFallback } from '@/components/assistant-ui/elements/tool-fallback';
import { TooltipIconButton } from '@/components/assistant-ui/tooltip-icon-button';
import { Button } from '@/components/assistant-ui/ui/button';
import { Skeleton } from '@/components/assistant-ui/ui/skeleton';
@@ -28,6 +28,7 @@ import {
useAuiReloadCapability,
} from '@/features/conversations/components/aui/auiThreadState';
import { useAuiThreadId } from '@/providers/AssistantUiRuntimeProvider';
+import { useActionBarReload, useMessageError } from '@assistant-ui/core/react';
import {
ActionBarMorePrimitive,
ActionBarPrimitive,
@@ -47,7 +48,6 @@ import {
useAui,
useAuiState,
} from '@assistant-ui/react';
-import { useActionBarReload, useMessageError } from '@assistant-ui/core/react';
import { LexicalComposerInput } from '@assistant-ui/react-lexical';
import debugFactory from 'debug';
import {
@@ -1272,10 +1272,19 @@ const SourceGroupSlot: FC<{ Component: ComponentType<{ sources: readonly SourceI
const sources = parts.flatMap((part): SourceItemPart[] => {
if (part.type !== 'source') return [];
if (part.sourceType === 'url') {
- return [{ id: part.id, sourceType: 'url', url: part.url, ...(part.title ? { title: part.title } : {}) }];
+ return [
+ {
+ id: part.id,
+ sourceType: 'url',
+ url: part.url,
+ ...(part.title ? { title: part.title } : {}),
+ },
+ ];
}
if (part.sourceType === 'document') {
- return [{ id: part.id, sourceType: 'document', ...(part.title ? { title: part.title } : {}) }];
+ return [
+ { id: part.id, sourceType: 'document', ...(part.title ? { title: part.title } : {}) },
+ ];
}
return [];
});
diff --git a/app/src/features/conversations/aui/ChatErrorNotice.tsx b/app/src/features/conversations/aui/ChatErrorNotice.tsx
index 9ba72db3ee..01eb56ac3d 100644
--- a/app/src/features/conversations/aui/ChatErrorNotice.tsx
+++ b/app/src/features/conversations/aui/ChatErrorNotice.tsx
@@ -20,7 +20,9 @@ interface ChatErrorMetadata {
}
const selectChatError = (s: AssistantState): ChatErrorMetadata | undefined => {
- const custom = s.message.metadata?.custom as { extraMetadata?: Record<string, unknown> } | undefined;
+ const custom = s.message.metadata?.custom as
+ | { extraMetadata?: Record<string, unknown> }
+ | undefined;
return custom?.extraMetadata?.[CHAT_ERROR_METADATA_KEY] as ChatErrorMetadata | undefined;
};
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index b13b7262f8..d61f93dc3b 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -1,7 +1,7 @@
import {
+ type ThreadMessage as AuiThreadMessage,
fromThreadMessageLike,
type ThreadAssistantMessagePart,
- type ThreadMessage as AuiThreadMessage,
type ThreadMessageLike,
type ThreadUserMessagePart,
type ToolApprovalOption,
@@ -186,7 +186,9 @@ function toolArtifact(entry: ToolTimelineEntry): OpenHumanToolArtifact | undefin
* `parentCallId` (older history) pass through unchanged — those still rely on
* the reducer-side heuristic collapse.
*/
-function resolveSubagentTimeline(timeline: readonly ToolTimelineEntry[]): readonly ToolTimelineEntry[] {
+function resolveSubagentTimeline(
+ timeline: readonly ToolTimelineEntry[]
+): readonly ToolTimelineEntry[] {
const byParentCallId = new Map<string, ToolTimelineEntry>();
for (const entry of timeline) {
if (entry.subagent?.parentCallId) byParentCallId.set(entry.subagent.parentCallId, entry);
@@ -207,15 +209,15 @@ function resolveSubagentTimeline(timeline: readonly ToolTimelineEntry[]): readon
}
/** One item of a sub-agent's transcript, normalized to the `{kind:'tool', ...}` shape. */
-function subagentTranscriptItems(
- activity: SubagentActivity
-): readonly SubagentTranscriptItem[] {
+function subagentTranscriptItems(activity: SubagentActivity): readonly SubagentTranscriptItem[] {
if (activity.transcript && activity.transcript.length > 0) return activity.transcript;
return activity.toolCalls.map(call => ({ kind: 'tool' as const, ...call }));
}
/** A sub-agent's child tool call as a plain (non-nested) `tool-call` part. */
-function subagentChildToolPart(item: Extract<SubagentTranscriptItem, { kind: 'tool' }>): ToolCallMessagePart {
+function subagentChildToolPart(
+ item: Extract<SubagentTranscriptItem, { kind: 'tool' }>
+): ToolCallMessagePart {
const running = isActiveTimelineStatus(item.status);
const args = jsonObject(item.args);
return {
@@ -228,8 +230,12 @@ function subagentChildToolPart(item: Extract<SubagentTranscriptItem, { kind: 'to
? {
result:
item.status === 'error' || item.status === 'cancelled'
- ? { status: item.status, failure: item.failure, ...(item.result !== undefined ? { value: item.result } : {}) }
- : item.result ?? { status: item.status },
+ ? {
+ status: item.status,
+ failure: item.failure,
+ ...(item.result !== undefined ? { value: item.result } : {}),
+ }
+ : (item.result ?? { status: item.status }),
}
: {}),
};
@@ -302,7 +308,7 @@ function toolPart(entry: ToolTimelineEntry): ThreadAssistantMessagePart {
// it here (rather than this row's synthetic id) is what lets the part
// render as ONE task card on the exact call the model made, instead of two
// separate rows.
- const toolCallId = isSubagent ? entry.subagent?.parentCallId ?? entry.id : entry.id;
+ const toolCallId = isSubagent ? (entry.subagent?.parentCallId ?? entry.id) : entry.id;
const nestedMessages = isSubagent && entry.subagent ? subagentMessages(entry.subagent) : [];
return {
@@ -363,9 +369,7 @@ function approvalField(approval: PendingApproval): NonNullable<ToolCallMessagePa
return {
id: approval.requestId,
options: APPROVAL_DECISION_OPTIONS,
- ...(approval.resolution
- ? { resolution: approval.resolution, approved: false as const }
- : {}),
+ ...(approval.resolution ? { resolution: approval.resolution, approved: false as const } : {}),
};
}
@@ -418,7 +422,9 @@ function withApproval(
-1
);
if (index < 0) return [...parts, syntheticApprovalPart(approval)];
- return parts.map((part, at) => (at === index ? { ...part, approval: approvalField(approval) } : part));
+ return parts.map((part, at) =>
+ at === index ? { ...part, approval: approvalField(approval) } : part
+ );
}
/**
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 37121ad4f1..ffeab630f2 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -36,6 +36,7 @@ mod reply_persistence;
mod run_task;
mod schemas;
mod session;
+mod suggestions;
mod turn_timing;
mod types;
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index d7a99e30fc..b06bbd301c 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -349,6 +349,15 @@ pub(crate) fn spawn_progress_bridge(
// (it belongs to the terminal round, which ends with no tool call).
let mut pending_narration = String::new();
let mut timing = super::turn_timing::TurnTiming::start();
+ // Throttle for the live `turn_cost` socket event below: a multi-round
+ // turn can report a `TurnCostUpdated` on every model call, and a
+ // fast-tool-calling round can do that several times a second — far
+ // more often than a cost readout needs to repaint. Unconditionally
+ // `None` initially so the *first* update of a turn always emits
+ // immediately rather than waiting out the interval.
+ let mut last_turn_cost_emit: Option<std::time::Instant> = None;
+ const TURN_COST_EMIT_MIN_INTERVAL: std::time::Duration =
+ std::time::Duration::from_millis(750);
let mut events_seen: u64 = 0;
// Per-request monotonic ordering key stamped on every emitted
// web-channel event (see `publish_seq_stamped`). Unique per emission so