Skip to content

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

fix(chat): handle missing tool call results in conversation history

Steven Enamakeldf6192472278
diff --git a/app/src/features/conversations/aui/MediaAndDocumentCalls.test.tsx b/app/src/features/conversations/aui/MediaAndDocumentCalls.test.tsx
new file mode 100644
index 0000000000..6b10c1806f
--- /dev/null
+++ b/app/src/features/conversations/aui/MediaAndDocumentCalls.test.tsx
@@ -0,0 +1,81 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { DocumentArtifactCall, MediaGenerationCall } from './MediaAndDocumentCalls';
+
+const baseProps = {
+ type: 'tool-call' as const,
+ toolCallId: 'call-1',
+ argsText: '{}',
+ addResult: () => {},
+ resume: () => {},
+ respondToApproval: () => {},
+};
+
+describe('MediaGenerationCall', () => {
+ it('shows the image-generation placeholder while the tool runs', () => {
+ render(
+ <MediaGenerationCall
+ {...baseProps}
+ toolName="media_generate_image"
+ args={{ prompt: 'a red fox in snow' } as never}
+ result={undefined}
+ status={{ type: 'running' }}
+ />
+ );
+
+ expect(screen.getByText('a red fox in snow')).toBeInTheDocument();
+ });
+
+ it('renders one image per produced artifact once the tool completes', () => {
+ render(
+ <MediaGenerationCall
+ {...baseProps}
+ toolName="media_generate_image"
+ args={{ prompt: 'a red fox in snow' } as never}
+ result={
+ {
+ artifacts: [
+ { type: 'image', source_url: 'https://example.com/fox.png', artifact_id: 'art-1' },
+ ],
+ } as never
+ }
+ status={{ type: 'complete' }}
+ />
+ );
+
+ expect(screen.getByTestId('assistant-ui-media-generation-result')).toBeInTheDocument();
+ });
+});
+
+describe('DocumentArtifactCall', () => {
+ it('shows the artifact card generating while the tool runs', () => {
+ render(
+ <DocumentArtifactCall
+ {...baseProps}
+ toolName="generate_document"
+ args={{ title: 'Q3 report' } as never}
+ result={undefined}
+ status={{ type: 'running' }}
+ />
+ );
+
+ expect(screen.getByText('Q3 report')).toBeInTheDocument();
+ expect(screen.getByText('Writing')).toBeInTheDocument();
+ });
+
+ it('shows the settled artifact once generation completes', () => {
+ render(
+ <DocumentArtifactCall
+ {...baseProps}
+ toolName="generate_presentation"
+ args={{} as never}
+ result={{ title: 'Board deck', path: '/artifacts/board-deck.pptx' } as never}
+ status={{ type: 'complete' }}
+ />
+ );
+
+ expect(screen.getByText('Board deck')).toBeInTheDocument();
+ expect(screen.getByText('/artifacts/board-deck.pptx')).toBeInTheDocument();
+ });
+});
diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsx
index 1ec0803851..3c479dd6be 100644
--- a/app/src/features/conversations/components/ChatToolParts.tsx
+++ b/app/src/features/conversations/components/ChatToolParts.tsx
@@ -211,6 +211,37 @@ const GatedToolCall: ToolCallMessagePartComponent = props => {
);
};
+/** The top-level clarification tool: never approval-gated, just waits on the user. */
+const ASK_USER_CLARIFICATION_TOOL = 'ask_user_clarification';
+
+/**
+ * A top-level `ask_user_clarification` call — the agent itself (not a
+ * delegated sub-agent, which `SubagentCall`/`AssistantUiSubagentCall` already
+ * render their own question UI for) needs a structured answer before the turn
+ * can continue. Answered the same way a sub-agent's clarification is: append
+ * an ordinary user turn through the runtime (see `ElicitationAdapter`'s doc
+ * comment for why there is no separate RPC to call instead).
+ */
+const ElicitationCall: ToolCallMessagePartComponent = ({ args, result }) => {
+ const aui = useAui();
+ const question = (args as { question?: string } | undefined)?.question ?? '';
+ const answer = useCallback(
+ (text: string) => {
+ void aui.thread.append({ role: 'user', content: [{ type: 'text', text }] });
+ },
+ [aui]
+ );
+ return (
+ <ElicitationAdapter
+ server="OpenHuman"
+ message={question}
+ pending={result === undefined}
+ onAnswer={answer}
+ testId="assistant-ui-elicitation"
+ />
+ );
+};
+
/**
* Route every call the toolkit does not own through an assistant-ui-native
* rich renderer.
@@ -220,9 +251,10 @@ const GatedToolCall: ToolCallMessagePartComponent = props => {
* assistant-ui resolves it before this fallback ever mounts. Every other tool
* name — the vast majority, since most are dynamic (shell, file ops, MCP,
* Composio, web search, ...) and cannot be enumerated in a static registry —
- * still comes through here, which is also where the approval gate and
- * `composio_connect` routing live: both are keyed on the part's `approval`
- * field, not on the tool's name, so no per-name registry entry could own them
+ * still comes through here, which is also where the approval gate,
+ * `composio_connect` routing, and the top-level clarification question live:
+ * all three are keyed on the part's own fields (`approval`, `toolName`), not
+ * on a static registry entry, so no per-name registry entry could own them
* without duplicating this same check in every entry.
*
* The gated branches are chosen on the part's own `approval` field, before any
@@ -231,7 +263,10 @@ const GatedToolCall: ToolCallMessagePartComponent = props => {
* that has no store at all, which is how most of the tool-card tests mount it.
*/
export const ChatToolFallback: ToolCallMessagePartComponent = props => {
- if (!isApprovalPending(props.approval)) return <OpenHumanToolCall {...props} />;
+ if (!isApprovalPending(props.approval)) {
+ if (props.toolName === ASK_USER_CLARIFICATION_TOOL) return <ElicitationCall {...props} />;
+ return <OpenHumanToolCall {...props} />;
+ }
if (props.toolName === COMPOSIO_CONNECT_TOOL) return <ComposioConnectCall {...props} />;
return <GatedToolCall {...props} />;
};
diff --git a/crates/openhuman-core/src/agent/plan_review/tool_tests.rs b/crates/openhuman-core/src/agent/plan_review/tool_tests.rs
index 1afa8e8b6b..376e6e0513 100644
--- a/crates/openhuman-core/src/agent/plan_review/tool_tests.rs
+++ b/crates/openhuman-core/src/agent/plan_review/tool_tests.rs
@@ -16,6 +16,13 @@ async fn non_interactive_origin_auto_approves() {
#[tokio::test]
async fn interactive_turn_parks_until_resolved() {
+ // The tool is inert (no-ops rather than parks) outside Plan mode — see
+ // `plan_mode_is_inert_outside_plan_mode` below — so this thread must be
+ // in Plan mode for the park to actually happen.
+ crate::agent::tinyagents::run_mode::set_mode(
+ "t-int",
+ tinyagents_harness::middleware::RunMode::Plan,
+ );
let tool = RequestPlanReviewTool::new();
let fut = with_origin(
AgentTurnOrigin::WebChat {
@@ -34,3 +41,22 @@ async fn interactive_turn_parks_until_resolved() {
"interactive turn should park, not resolve immediately"
);
}
+
+#[tokio::test]
+async fn plan_mode_is_inert_outside_plan_mode() {
+ // A thread that has never toggled plan mode defaults to Build — the
+ // tool must no-op (return immediately) rather than park.
+ let tool = RequestPlanReviewTool::new();
+ let out = with_origin(
+ AgentTurnOrigin::WebChat {
+ thread_id: "t-build-inert".into(),
+ client_id: "c-build-inert".into(),
+ request_id: Some("req-build-inert".into()),
+ },
+ tool.execute(json!({ "summary": "plan", "steps": ["one"] })),
+ )
+ .await
+ .unwrap();
+ assert!(!out.is_error);
+ assert!(out.output().starts_with("not applicable"));
+}
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index b198fbb09b..20911bd81e 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -25,6 +25,55 @@ use super::turn_guards::{
run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,
};
+/// `start_chat`'s error type.
+///
+/// `Guardrail` is a structured verdict from the prompt-injection/security
+/// guardrail (`security::prompt_injection::enforce_prompt_input`) — the
+/// frontend classifies on this variant (`chat_error.error_type == "guardrail"`
+/// + a `guardrail` payload) instead of pattern-matching the user-facing
+/// message string. Every other rejection (validation, a configured
+/// `beforeSubmitPrompt` hook block, an approval-routing failure) stays
+/// `Other`, which `Display`s exactly like the plain `String` errors this
+/// replaced — existing `.to_string()` / `{err}` call sites need no other
+/// change.
+#[derive(Debug, Clone)]
+pub enum StartChatError {
+ Guardrail {
+ verdict: String,
+ score: f64,
+ reasons: Vec<crate::core::socketio::GuardrailReason>,
+ },
+ Other(String),
+}
+
+impl std::fmt::Display for StartChatError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ StartChatError::Guardrail {
+ verdict, score, ..
+ } => write!(
+ f,
+ "blocked by guardrail (verdict={verdict} score={score:.2})"
+ ),
+ StartChatError::Other(message) => write!(f, "{message}"),
+ }
+ }
+}
+
+impl std::error::Error for StartChatError {}
+
+impl From<String> for StartChatError {
+ fn from(message: String) -> Self {
+ StartChatError::Other(message)
+ }
+}
+
+impl From<&str> for StartChatError {
+ fn from(message: &str) -> Self {
+ StartChatError::Other(message.to_string())
+ }
+}
+
fn prompt_guard_user_message(action: PromptEnforcementAction) -> &'static str {
match action {
PromptEnforcementAction::Allow => "Message accepted.",
@@ -46,7 +95,7 @@ pub async fn start_chat(
locale: Option<String>,
queue_mode: Option<String>,
metadata: ChatRequestMetadata,
-) -> Result<String, String> {
+) -> Result<String, StartChatError> {
let client_id = client_id.trim().to_string();
let thread_id = thread_id.trim().to_string();
let message = message.trim().to_string();