Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

add tool approval flow for chat-panel (#9507)

Shahmir Varqhaac6c618a60c1
diff --git a/frontend/package.json b/frontend/package.json
index f91118ec43..68db8438bf 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -21,7 +21,7 @@
"./unstable_internal/*": "./src/*"
},
"dependencies": {
- "@ai-sdk/react": "^3.0.131",
+ "@ai-sdk/react": "^3.0.176",
"@anywidget/types": "^0.2.0",
"@codemirror/autocomplete": "^6.20.1",
"@codemirror/commands": "^6.10.2",
@@ -93,7 +93,7 @@
"@xterm/addon-web-links": "^0.12.0",
"@xterm/xterm": "^5.5.0",
"@zed-industries/agent-client-protocol": "^0.4.5",
- "ai": "^6.0.129",
+ "ai": "^6.0.174",
"ansi_up": "^6.0.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/frontend/src/components/chat/chat-components.tsx b/frontend/src/components/chat/chat-components.tsx
index c76868ac23..965f6608e9 100644
--- a/frontend/src/components/chat/chat-components.tsx
+++ b/frontend/src/components/chat/chat-components.tsx
@@ -13,6 +13,7 @@ import {
} from "lucide-react";
import { useState } from "react";
import { cn } from "@/utils/cn";
+import { isUrl } from "@/utils/urls";
import { Spinner } from "../icons/spinner";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
@@ -182,3 +183,49 @@ function renderFileIcon(file: File): React.ReactNode {
return <FileIcon className={classNames} />;
}
+
+export const SourceChip = ({
+ icon,
+ title,
+ subtitle,
+ href,
+}: {
+ icon: React.ReactNode;
+ title: string;
+ subtitle?: string;
+ href?: string;
+}) => {
+ const content = (
+ <>
+ {icon}
+ <span className="truncate font-medium">{title}</span>
+ {subtitle && <span className="truncate opacity-70">({subtitle})</span>}
+ </>
+ );
+
+ const className =
+ "inline-flex max-w-full items-center gap-1.5 rounded-md border bg-muted/50 px-2 py-1 my-1 text-xs text-muted-foreground";
+
+ // Only treat absolute http(s) URLs as safe to render as a clickable link.
+ // Source URLs come from model output (e.g. citations) and could otherwise
+ // smuggle in `javascript:`/`data:` schemes.
+ if (href && isUrl(href)) {
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={subtitle ?? title}
+ className={`${className} hover:bg-muted hover:text-foreground transition-colors`}
+ >
+ {content}
+ </a>
+ );
+ }
+
+ return (
+ <div className={className} title={subtitle ?? title}>
+ {content}
+ </div>
+ );
+};
diff --git a/frontend/src/components/chat/chat-display.tsx b/frontend/src/components/chat/chat-display.tsx
index 02803142e4..13ef992279 100644
--- a/frontend/src/components/chat/chat-display.tsx
+++ b/frontend/src/components/chat/chat-display.tsx
@@ -1,23 +1,31 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type { DataUIPart, ToolUIPart, UIMessage } from "ai";
+import type {
+ ChatAddToolApproveResponseFunction,
+ DataUIPart,
+ ToolUIPart,
+ UIMessage,
+} from "ai";
+import { ExternalLinkIcon, FileTextIcon } from "lucide-react";
import React from "react";
import { renderHTML } from "@/plugins/core/RenderHTML";
import { logNever } from "@/utils/assertNever";
import { Logger } from "@/utils/Logger";
import { MarkdownRenderer } from "../markdown/markdown-renderer";
-import { AttachmentRenderer } from "./chat-components";
+import { AttachmentRenderer, SourceChip } from "./chat-components";
import { ReasoningAccordion } from "./reasoning-accordion";
-import { ToolCallAccordion } from "./tool-call-accordion";
+import { ToolCallView } from "./tool-call/tool-call-view";
export const renderUIMessage = ({
message,
isStreamingReasoning,
isLast,
+ addToolApprovalResponse,
}: {
message: UIMessage;
isStreamingReasoning: boolean;
isLast: boolean;
+ addToolApprovalResponse?: ChatAddToolApproveResponseFunction;
}) => {
return (
<>{message.parts.map((part, index) => renderUIMessagePart(part, index))}</>
@@ -29,14 +37,18 @@ export const renderUIMessage = ({
) {
if (isToolPart(part)) {
return (
- <ToolCallAccordion
+ <ToolCallView
key={index}
index={index}
toolName={part.type}
result={part.output}
+ errorText={part.state === "output-error" ? part.errorText : undefined}
className="my-2"
state={part.state}
input={part.input}
+ approval={part.approval}
+ onApprove={addToolApprovalResponse}
+ isLive={isLast}
/>
);
}
@@ -69,7 +81,7 @@ export const renderUIMessage = ({
isStreaming={
isStreamingReasoning &&
isLast &&
- // If there are multiple reasoning parts, only show the last one
+ // If there are multiple reasoning parts, only stream the last one
index === (message.parts.length || 0) - 1
}
/>
@@ -78,18 +90,40 @@ export const renderUIMessage = ({
return <AttachmentRenderer attachment={part} key={index} />;
case "dynamic-tool":
return (
- <ToolCallAccordion
+ <ToolCallView
key={index}
toolName={part.toolName}
result={part.output}
+ errorText={
+ part.state === "output-error" ? part.errorText : undefined
+ }
state={part.state}
input={part.input}
+ approval={part.approval}
+ onApprove={addToolApprovalResponse}
+ isLive={isLast}
/>
);
case "source-document":
+ return (
+ <SourceChip
+ key={index}
+ icon={<FileTextIcon className="h-3 w-3 shrink-0" />}
+ title={part.title}
+ subtitle={part.filename}
+ />
+ );
case "source-url":
+ return (
+ <SourceChip
+ key={index}
+ icon={<ExternalLinkIcon className="h-3 w-3 shrink-0" />}
+ title={part.title ?? part.url}
+ subtitle={part.title ? part.url : undefined}
+ href={part.url}
+ />
+ );
case "step-start":
- Logger.debug("Found non-renderable part", part);
return null;
default:
logNever(part);
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 40678773fc..6490051377 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -4,7 +4,13 @@ import type { UIMessage } from "@ai-sdk/react";
import { useChat } from "@ai-sdk/react";
import { storePrompt } from "@marimo-team/codemirror-ai";
import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";
-import { DefaultChatTransport, type FileUIPart, type TextUIPart } from "ai";
+import {
+ type ChatAddToolApproveResponseFunction,
+ DefaultChatTransport,
+ type FileUIPart,
+ safeValidateUIMessages,
+ type TextUIPart,
+} from "ai";
import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";
import {
BotMessageSquareIcon,
@@ -131,10 +137,18 @@ interface ChatMessageProps {
onEdit: (index: number, newValue: string) => void;
isStreamingReasoning: boolean;
isLast: boolean;
+ addToolApprovalResponse?: ChatAddToolApproveResponseFunction;
}
const ChatMessageDisplay: React.FC<ChatMessageProps> = memo(
- ({ message, index, onEdit, isStreamingReasoning, isLast }) => {
+ ({
+ message,
+ index,
+ onEdit,
+ isStreamingReasoning,
+ isLast,
+ addToolApprovalResponse,
+ }) => {
const renderUserMessage = (message: UIMessage) => {
const textParts = message.parts?.filter(
(p): p is TextUIPart => p.type === "text",
@@ -181,7 +195,12 @@ const ChatMessageDisplay: React.FC<ChatMessageProps> = memo(
<div className="absolute right-1 top-1 opacity-0 group-hover:opacity-100 transition-opacity">
<CopyClipboardIcon className="h-3 w-3" value={content || ""} />
</div>
- {renderUIMessage({ message, isStreamingReasoning, isLast })}
+ {renderUIMessage({
+ message,
+ isStreamingReasoning,
+ isLast,
+ addToolApprovalResponse,
+ })}
</div>
);
};
@@ -458,6 +477,7 @@ const ChatPanelBody = () => {
regenerate,
stop,
addToolOutput,
+ addToolApprovalResponse,
id: chatId,
} = useChat({
id: activeChatId,
@@ -467,6 +487,19 @@ const ChatPanelBody = () => {
api: runtimeManager.getAiURL("chat").toString(),
headers: () => runtimeManager.headers(),
prepareSendMessagesRequest: async (options) => {
+ // Canary: flag outgoing messages that don't match the AI SDK's own
+ // schema. The server-side sanitizer in `_pydantic_ai_utils.py` corrects these before validation;
+ // this log surfaces drift early without affecting the request.
+ const validation = await safeValidateUIMessages({
+ messages: options.messages,
+ });
+ if (!validation.success) {
+ Logger.debug(
+ "Outgoing chat messages failed AI SDK schema validation",
+ validation.error,
+ );
+ }
+
const completionBody = await buildCompletionRequestBody(
options.messages,
);
@@ -495,13 +528,6 @@ const ChatPanelBody = () => {
});
},
onToolCall: async ({ toolCall }) => {
- // Dynamic tool calls will throw an error for toolName
- // https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage#client-side-page
- if (toolCall.dynamic) {
- Logger.debug("Skipping dynamic tool call", toolCall);
- return;
- }
-
await handleToolCall({
invokeAiTool,
addToolOutput,
@@ -712,6 +738,7 @@ const ChatPanelBody = () => {
onEdit={handleMessageEdit}
isStreamingReasoning={isStreamingReasoning}
isLast={idx === messages.length - 1}
+ addToolApprovalResponse={addToolApprovalResponse}
/>
))}
diff --git a/frontend/src/components/chat/chat-utils.ts b/frontend/src/components/chat/chat-utils.ts
index 2d2b1cb9bd..fbb3552f30 100644
--- a/frontend/src/components/chat/chat-utils.ts
+++ b/frontend/src/components/chat/chat-utils.ts
@@ -1,11 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { components } from "@marimo-team/marimo-api";
-import type {
- ChatAddToolOutputFunction,
- FileUIPart,
- ToolUIPart,
- UIMessage,
+import {
+ type ChatAddToolOutputFunction,
+ type FileUIPart,
+ isToolUIPart,
+ type ToolUIPart,
+ type UIMessage,
} from "ai";
import { useState } from "react";
import useEvent from "react-use-event-hook";
@@ -16,6 +17,7 @@ import type {
InvokeAiToolRequest,
InvokeAiToolResponse,
} from "@/core/network/types";
+import { logNever } from "@/utils/assertNever";
import { blobToString } from "@/utils/fileToBase64";
import { Logger } from "@/utils/Logger";
import { getAICompletionBodyWithAttachments } from "../editor/ai/completion-utils";
@@ -134,11 +136,11 @@ export async function handleToolCall({
try {
if (FRONTEND_TOOL_REGISTRY.has(toolCall.toolName)) {
// Invoke the frontend tool
- const response = await FRONTEND_TOOL_REGISTRY.invoke(
- toolCall.toolName,
- toolCall.input,
- toolContext,
- );
+ const response = await FRONTEND_TOOL_REGISTRY.invoke({
+ toolName: toolCall.toolName,
+ rawArgs: toolCall.input,
+ toolContext: toolContext,
+ });
addToolOutput({
tool: toolCall.toolName,
toolCallId: toolCall.toolCallId,
@@ -166,9 +168,33 @@ export async function handleToolCall({
}
}
+/**
+ * Returns true if a tool call is "ready to be sent back to the server" — i.e.
+ * either it has reached a terminal output state, or the user has just supplied
+ * an approval response that the server hasn't seen yet.
+ */
+function isToolCallReadyToSend(state: ToolUIPart["state"]): boolean {
+ switch (state) {
+ case "output-available":
+ case "output-error":
+ case "output-denied":
+ case "approval-responded":
+ return true;
+ case "input-streaming":
+ case "input-available":
+ case "approval-requested":
+ return false;
+ default:
+ logNever(state);
+ return false;
+ }
+}
+
/**
* Checks if we should send a message automatically based on the messages.
- * We only want to send a message if all tool calls are completed and there is no reply yet.
+ * We auto-send when every tool call on the last assistant message has either
+ * finished (output-available/error/denied) or has just received a user
+ * approval response, and the assistant hasn't replied yet.
*/
export function hasPendingToolCalls(messages: UIMessage[]): boolean {
if (messages.length === 0) {
@@ -188,17 +214,14 @@ export function hasPendingToolCalls(messages: UIMessage[]): boolean {
return false;
}
- const toolParts = parts.filter((part) =>
- part.type.startsWith("tool-"),
- ) as ToolUIPart[];
+ const toolParts = parts.filter(isToolUIPart);
- // Guard against no tool parts
if (toolParts.length === 0) {
return false;
}
- const allToolCallsCompleted = toolParts.every(
- (part) => part.state === "output-available",
+ const allToolCallsReady = toolParts.every((part) =>
+ isToolCallReadyToSend(part.state),
);
// Check if the last part has any text content
@@ -206,10 +229,9 @@ export function hasPendingToolCalls(messages: UIMessage[]): boolean {
const hasTextContent =
lastPart.type === "text" && lastPart.text?.trim().length > 0;
- Logger.warn("All tool calls completed: %s", allToolCallsCompleted);
+ Logger.debug("All tool calls ready to send: %s", allToolCallsReady);
- // Only auto-send if we have completed tool calls and there is no reply yet
- return allToolCallsCompleted && !hasTextContent;
+ return allToolCallsReady && !hasTextContent;
}
export function useFileState() {
diff --git a/frontend/src/components/chat/reasoning-accordion.tsx b/frontend/src/components/chat/reasoning-accordion.tsx
index 4fa8723e74..404e98796b 100644
--- a/frontend/src/components/chat/reasoning-accordion.tsx
+++ b/frontend/src/components/chat/reasoning-accordion.tsx
@@ -21,20 +21,31 @@ export const ReasoningAccordion: React.FC<ReasoningAccordionProps> = ({
index = 0,
isStreaming = false,
}) => {
+ const [openItem, setOpenItem] = React.useState<string>("");
+
+ // Some reasoning models emit a reasoning part with no surfaced content
+ // (e.g. OpenAI's o-series, which hides chain-of-thought but still marks
+ // its boundaries on the wire). pydantic-ai's Vercel adapter forwards the
+ // empty start/end pair, producing a 0-char ReasoningUIPart. Skip it.
+ if (!reasoning && !isStreaming) {
+ return null;
+ }
+
return (
<Accordion
key={index}
type="single"
collapsible={true}
className="w-full mb-2"
- value={isStreaming ? "reasoning" : undefined}
+ value={isStreaming ? "reasoning" : openItem}
+ onValueChange={setOpenItem}
>
<AccordionItem value="reasoning" className="border-0">
<AccordionTrigger className="text-xs text-muted-foreground hover:bg-muted/50 px-2 py-1 h-auto rounded-sm [&[data-state=open]>svg]:rotate-180">
<span className="flex items-center gap-2">
<BotMessageSquareIcon className="h-3 w-3" />
- {isStreaming ? "Thinking" : "View reasoning"} ({reasoning.length}{" "}
- chars)
+ {isStreaming ? "Thinking" : "View reasoning"}
+ {reasoning.length > 0 && ` (${reasoning.length} chars)`}
</span>
</AccordionTrigger>
<AccordionContent className="pb-2 px-2">
diff --git a/frontend/src/components/chat/tool-call-accordion.tsx b/frontend/src/components/chat/tool-call-accordion.tsx
deleted file mode 100644
index 47ef7b3380..0000000000
--- a/frontend/src/components/chat/tool-call-accordion.tsx
+++ /dev/null
@@ -1,247 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import type { ToolUIPart } from "ai";
-import { isEmpty } from "lodash-es";
-import {
- CheckCircleIcon,
- InfoIcon,
- Loader2,
- WrenchIcon,
- XCircleIcon,
-} from "lucide-react";
-import React from "react";
-import { z } from "zod";
-import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
-} from "@/components/ui/accordion";
-import { cn } from "@/utils/cn";
-
-// Zod schema matching the Python SuccessResult dataclass
-const SuccessResultSchema = z
- .object({
- status: z.string().default("success"),
- auth_required: z.boolean().default(false),
- action_url: z.any(),
- next_steps: z.any(),
- meta: z.any(),
- message: z.string().nullish(),
- })
- .passthrough();
-
-type SuccessResult = z.infer<typeof SuccessResultSchema>;
-
-const PrettySuccessResult: React.FC<{ data: SuccessResult }> = ({ data }) => {
- const {
- status,
- auth_required,
- action_url: _action_url,
- meta: _meta,
- next_steps: _next_steps,
- message,
- ...rest
- } = data;
-
- return (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <h3 className="text-xs font-semibold text-muted-foreground">
- Tool Result
- </h3>
- <div className="flex items-center gap-2">
- <span className="text-xs px-2 py-0.5 bg-[var(--grass-2)] text-[var(--grass-11)] rounded-full font-medium capitalize">
- {status}
- </span>
- {auth_required && (
- <span className="text-xs px-2 py-0.5 bg-[var(--amber-2)] text-[var(--amber-11)] rounded-full">
- Auth Required
- </span>
- )}
- </div>
- </div>
-
- {/* Message */}
- {message && (
- <div className="flex items-start gap-2">
- <InfoIcon className="h-3 w-3 text-[var(--blue-11)] mt-0.5 flex-shrink-0" />
- <div className="text-xs text-foreground">{message}</div>
- </div>
- )}
-
- {/* Data */}
- {rest && (
- <div className="space-y-3">
- {Object.entries(rest).map(([key, value]) => {
- if (isEmpty(value)) {
- return null;
- }
- return (
- <div key={key} className="space-y-1.5">
- <div className="text-xs font-medium text-muted-foreground capitalize flex items-center gap-2">
- <div className="w-1.5 h-1.5 bg-[var(--blue-9)] rounded-full" />
- {key}
- </div>
- <pre className="bg-[var(--slate-2)] p-2 text-muted-foreground border border-[var(--slate-4)] rounded text-xs overflow-auto scrollbar-thin max-h-64">
- {JSON.stringify(value, null, 2)}
- </pre>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-};
-
-const ResultRenderer: React.FC<{ result: unknown }> = ({ result }) => {
- // Try to parse the result with our Zod schema
- const parseResult = SuccessResultSchema.safeParse(result);
-
- if (parseResult.success) {
- // If it matches the SuccessResult schema, show the pretty UI
- return <PrettySuccessResult data={parseResult.data} />;
- }
-
- // Otherwise, fall back to the current JSON viewer
- return (
- <div className="text-xs font-medium text-muted-foreground mb-1 max-h-64 overflow-y-auto scrollbar-thin">
- {typeof result === "string" ? result : JSON.stringify(result, null, 2)}
- </div>
- );
-};
-
-const ToolArgsRenderer: React.FC<{ input: unknown }> = ({ input }) => {
- const hasinput = input && input !== null;
-
- if (!hasinput) {
- return null;
- }
-
- const isEmptyInput = isEmpty(input);
-
- const isObject =
- typeof input === "object" &&
- !Array.isArray(input) &&
- Object.keys(input as Record<string, unknown>).length > 0;
-
- return (
- <div className="space-y-2">
- <h3 className="text-xs font-semibold text-muted-foreground">
- Tool Request
- </h3>
- <pre className="bg-[var(--slate-2)] p-2 text-muted-foreground border border-[var(--slate-4)] rounded text-xs overflow-auto scrollbar-thin max-h-64">
- {isEmptyInput
- ? "{}"
- : isObject
- ? JSON.stringify(input, null, 2)
- : String(input)}
- </pre>
- </div>
- );
-};
-
-interface ToolCallAccordionProps {
- toolName: string;
- result: unknown;
- error?: string;
- index?: number;
- state?: ToolUIPart["state"];
- className?: string;
- input?: unknown;
-}
-
-export const ToolCallAccordion: React.FC<ToolCallAccordionProps> = ({
- toolName,
- result,
- error,
- index = 0,
- state,
- className,
- input,
-}) => {
- const hasResult = state === "output-available" && (result || error);
- const status = error ? "error" : hasResult ? "success" : "loading";
-
- const getStatusIcon = () => {
- switch (status) {
- case "loading":
- return <Loader2 className="h-3 w-3 animate-spin" />;
- case "error":
- return <XCircleIcon className="h-3 w-3 text-[var(--red-11)]" />;
- case "success":
- return <CheckCircleIcon className="h-3 w-3 text-[var(--grass-11)]" />;
- default:
- return <WrenchIcon className="h-3 w-3" />;
- }
- };
-
- const getStatusText = () => {
- if (status === "loading") {
- return "Running";
- }
- if (error) {
- return "Failed";
- }
- if (hasResult) {
- return "Done";
- }
- return "Tool call";
- };
-
- return (
- <Accordion
- key={`tool-${index}`}
- type="single"
- collapsible={true}
- className={cn("w-full", className)}
- >
- <AccordionItem value="tool-call" className="border-0">
- <AccordionTrigger
- className={cn(
- "h-6 text-xs border-border shadow-none! ring-0! bg-muted/60 hover:bg-muted py-0 px-2 gap-1 rounded-sm [&[data-state=open]>svg]:rotate-180 hover:no-underline",
- status === "error" && "text-[var(--red-11)]/80",
- status === "success" && "text-[var(--grass-11)]/80",
- )}
- >
- <span className="flex items-center gap-1">
- {getStatusIcon()}
- {getStatusText()}:
- <code className="font-mono text-xs">
- {formatToolName(toolName)}
- </code>
- </span>
- </AccordionTrigger>
- <AccordionContent className="py-2 px-2">
- {/* Only show content when tool is complete */}
- {hasResult && (
- <div className="space-y-3">
- <ToolArgsRenderer input={input} />
- {result !== undefined && result !== null && (
- <ResultRenderer result={result} />
- )}
-
- {/* Error */}
- {error && (
- <div className="bg-[var(--red-2)] border border-[var(--red-6)] rounded-lg p-3">
- <div className="text-xs font-semibold text-[var(--red-11)] mb-2 flex items-center gap-2">
- <div className="w-1.5 h-1.5 bg-[var(--red-9)] rounded-full" />
- Error
- </div>
- <div className="text-sm text-[var(--red-11)] leading-relaxed">
- {error}
- </div>
- </div>
- )}
- </div>
- )}
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- );
-};
-
-function formatToolName(toolName: string) {
- return toolName.replace("tool-", "");
-}
diff --git a/frontend/src/components/chat/tool-call/shared.ts b/frontend/src/components/chat/tool-call/shared.ts
new file mode 100644
index 0000000000..e42dbc9820
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/shared.ts
@@ -0,0 +1,13 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { ToolUIPart } from "ai";
+
+export type ToolState = ToolUIPart["state"];
+
+// The AI SDK declares `approval` inline on every variant of `UIToolInvocation`
+// rather than exporting a named type, so we derive ours from there.
+export type ToolApproval = NonNullable<ToolUIPart["approval"]>;
+
+export function formatToolName(toolName: string): string {
+ return toolName.replace("tool-", "");
+}
diff --git a/frontend/src/components/chat/tool-call/tool-approval-card.tsx b/frontend/src/components/chat/tool-call/tool-approval-card.tsx
new file mode 100644
index 0000000000..58a267c6e8
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/tool-approval-card.tsx
@@ -0,0 +1,62 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { ChatAddToolApproveResponseFunction } from "ai";
+import { ShieldQuestionIcon } from "lucide-react";
+import React from "react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+import { formatToolName, type ToolApproval } from "./shared";
+import { ToolArgsRenderer } from "./tool-args";
+
+interface ToolApprovalCardProps {
+ toolName: string;
+ input: unknown;
+ approval: ToolApproval;
+ onApprove: ChatAddToolApproveResponseFunction;
+ className?: string;
+}
+
+export const ToolApprovalCard: React.FC<ToolApprovalCardProps> = ({
+ toolName,
+ input,
+ approval,
+ onApprove,
+ className,
+}) => {
+ return (
+ <div
+ className={cn(
+ "rounded-md border border-(--amber-6) bg-(--amber-2) p-3 space-y-3",
+ className,
+ )}
+ role="alertdialog"
+ aria-label={`Approval required for ${formatToolName(toolName)}`}
+ >
+ <div className="flex items-start gap-2">
+ <ShieldQuestionIcon className="h-4 w-4 text-(--amber-11) mt-0.5 shrink-0" />
+ <div className="text-xs text-(--amber-11) leading-relaxed">
+ <span className="font-semibold">Approval required:</span>{" "}
+ <code className="font-mono">{formatToolName(toolName)}</code>
+ </div>
+ </div>
+
+ <ToolArgsRenderer input={input} />
+
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => onApprove({ id: approval.id, approved: false })}
+ >
+ Deny
+ </Button>
+ <Button
+ size="xs"
+ onClick={() => onApprove({ id: approval.id, approved: true })}
+ >
+ Approve
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/chat/tool-call/tool-args.tsx b/frontend/src/components/chat/tool-call/tool-args.tsx
new file mode 100644
index 0000000000..3a5d64f8ad
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/tool-args.tsx
@@ -0,0 +1,26 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import React from "react";
+
+interface ToolArgsRendererProps {
+ input: unknown;
+ label?: string;
+}
+
+export const ToolArgsRenderer: React.FC<ToolArgsRendererProps> = ({
+ input,
+ label = "Tool Request",
+}) => {
+ if (input == null) {
+ return null;
+ }
+
+ return (
+ <div className="space-y-2">
+ <h3 className="text-xs font-semibold text-muted-foreground">{label}</h3>
+ <pre className="bg-(--slate-2) p-2 text-muted-foreground border border-(--slate-4) rounded text-xs overflow-auto scrollbar-thin max-h-64">
+ {JSON.stringify(input, null, 2)}
+ </pre>
+ </div>
+ );
+};
diff --git a/frontend/src/components/chat/tool-call/tool-call-view.tsx b/frontend/src/components/chat/tool-call/tool-call-view.tsx
new file mode 100644
index 0000000000..6aa9ecf48a
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/tool-call-view.tsx
@@ -0,0 +1,99 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { ChatAddToolApproveResponseFunction } from "ai";
+import React from "react";
+import { logNever } from "@/utils/assertNever";
+import type { ToolApproval, ToolState } from "./shared";
+import { ToolApprovalCard } from "./tool-approval-card";
+import { ToolErrorCard } from "./tool-error-card";
+import { ToolHistoryRow } from "./tool-history-row";
+
+interface ToolCallViewProps {
+ toolName: string;
+ state: ToolState;
+ result?: unknown;
+ errorText?: string;
+ input?: unknown;
+ approval?: ToolApproval;
+ onApprove?: ChatAddToolApproveResponseFunction;
+ index?: number;
+ className?: string;
+ /**
+ * Whether this tool call belongs to the latest message in the conversation.
+ * Used by error cards to decide whether to stay expanded (live) or collapse
+ * (the user has moved on).
+ */
+ isLive?: boolean;
+}
+
+export const ToolCallView: React.FC<ToolCallViewProps> = ({
+ toolName,
+ state,
+ result,
+ errorText,
+ input,
+ approval,
+ onApprove,
+ index,
+ className,
+ isLive = true,
+}) => {
+ switch (state) {
+ case "approval-requested":
+ // Approval is a live, blocking action — render it as a prominent card
+ // Fall back to history row if the wiring isn't
+ // available (shouldn't happen in practice).
+ if (approval != null && onApprove != null) {
+ return (
+ <ToolApprovalCard
+ toolName={toolName}
+ input={input}
+ approval={approval}
+ onApprove={onApprove}
+ className={className}
+ />
+ );
+ }
+ return (
+ <ToolHistoryRow
+ toolName={toolName}
+ state="input-available"
+ input={input}
+ index={index}
+ className={className}
+ />
+ );
+
+ case "output-error":
+ return (
+ <ToolErrorCard
+ toolName={toolName}
+ input={input}
+ errorText={errorText}
+ isLive={isLive}
+ className={className}
+ />
+ );
+
+ case "input-streaming":
+ case "input-available":
+ case "approval-responded":
+ case "output-available":
+ case "output-denied":
+ return (
+ <ToolHistoryRow
+ toolName={toolName}
+ state={state}
+ input={input}
+ result={result}
+ approval={approval}
+ index={index}
+ className={className}
+ />
+ );
+
+ default:
+ logNever(state);
+ return null;
+ }
+};
diff --git a/frontend/src/components/chat/tool-call/tool-error-card.tsx b/frontend/src/components/chat/tool-call/tool-error-card.tsx
new file mode 100644
index 0000000000..82e0e84d03
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/tool-error-card.tsx
@@ -0,0 +1,81 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { ChevronDownIcon, XCircleIcon } from "lucide-react";
+import React from "react";
+import { cn } from "@/utils/cn";
+import { formatToolName } from "./shared";
+import { ToolArgsRenderer } from "./tool-args";
+
+interface ToolErrorCardProps {
+ toolName: string;
+ input: unknown;
+ errorText?: string;
+ // When false, defaults to collapsed (the conversation has moved past this).
+ isLive: boolean;
+ className?: string;
+}
+
+export const ToolErrorCard: React.FC<ToolErrorCardProps> = ({
+ toolName,
+ input,
+ errorText,
+ isLive,
+ className,
+}) => {
+ const [open, setOpen] = React.useState(isLive);
+
+ // Auto-collapse once when the conversation moves past this turn.
+ // The user can still re-open manually afterwards; we only do this on the
+ // live → not-live transition, never the reverse.
+ const wasLive = React.useRef(isLive);
+ React.useEffect(() => {
+ if (wasLive.current && !isLive) {
+ setOpen(false);
+ }
+ wasLive.current = isLive;
+ }, [isLive]);
+
+ return (
+ <div
+ className={cn(
+ "rounded-md border border-(--red-6) bg-(--red-2)",
+ className,
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => setOpen((prev) => !prev)}
+ className="w-full flex items-center gap-2 px-3 py-2 text-xs text-(--red-11) hover:bg-(--red-3) rounded-md transition-colors"
+ aria-expanded={open}
+ >
+ <XCircleIcon className="h-3.5 w-3.5 shrink-0" />
+ <span className="flex-1 text-left">
+ <span className="font-semibold">Failed:</span>{" "}
+ <code className="font-mono">{formatToolName(toolName)}</code>
+ </span>
+ <ChevronDownIcon
+ className={cn(
+ "h-3.5 w-3.5 shrink-0 transition-transform",
+ open && "rotate-180",
+ )}
+ />
+ </button>
+
+ {open && (
+ <div className="px-3 pb-3 space-y-3 border-t border-(--red-6)/40 pt-3">
+ <ToolArgsRenderer input={input} />
+ {errorText && (
+ <div>
+ <h3 className="text-xs font-semibold text-(--red-11) mb-1">
+ Error
+ </h3>
+ <pre className="bg-(--red-2) border border-(--red-6) rounded p-2 text-xs text-(--red-11) leading-relaxed overflow-auto scrollbar-thin max-h-64 whitespace-pre-wrap">
+ {errorText}
+ </pre>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/chat/tool-call/tool-history-row.tsx b/frontend/src/components/chat/tool-call/tool-history-row.tsx
new file mode 100644
index 0000000000..a4a940ac9d
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/tool-history-row.tsx
@@ -0,0 +1,153 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { BanIcon, CheckCircleIcon, Loader2, WrenchIcon } from "lucide-react";
+import React from "react";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { logNever } from "@/utils/assertNever";
+import { cn } from "@/utils/cn";
+import { formatToolName, type ToolApproval, type ToolState } from "./shared";
+import { ToolArgsRenderer } from "./tool-args";
+import { ResultRenderer } from "./tool-result";
+
+// States considered "inert" — they represent past or background work that the
+// user does not need to act on.
+export type HistoryState = Exclude<
+ ToolState,
+ "approval-requested" | "output-error"
+>;
+
+const STATUS_LABEL: Record<HistoryState, string> = {
+ "input-streaming": "Generating",
+ "input-available": "Running",
+ "approval-responded": "Awaiting result",
+ "output-available": "Done",
+ "output-denied": "Denied",
+};
+
+const StatusIcon: React.FC<{ state: HistoryState }> = ({ state }) => {
+ switch (state) {
+ case "input-streaming":
+ case "input-available":
+ case "approval-responded":
+ return <Loader2 className="h-3 w-3 animate-spin" />;
+ case "output-available":
+ return <CheckCircleIcon className="h-3 w-3 text-(--grass-11)" />;
+ case "output-denied":
+ return <BanIcon className="h-3 w-3 text-muted-foreground" />;
+ default:
+ logNever(state);
+ return <WrenchIcon className="h-3 w-3" />;
+ }
+};
+
+function getTriggerToneClass(state: HistoryState): string {
+ switch (state) {
+ case "output-available":
+ return "text-(--grass-11)/80";
+ case "output-denied":
+ return "text-muted-foreground";
+ case "input-streaming":
+ case "input-available":
+ case "approval-responded":
+ return "";
+ default:
+ logNever(state);
+ return "";
+ }
+}
+
+interface ToolHistoryRowProps {
+ toolName: string;
+ state: HistoryState;
+ input: unknown;
+ result?: unknown;
+ approval?: ToolApproval;
+ index?: number;
+ className?: string;
+}
+
+export const ToolHistoryRow: React.FC<ToolHistoryRowProps> = ({
+ toolName,
+ state,
+ input,
+ result,
+ approval,
+ index = 0,
+ className,
+}) => {
+ return (
+ <Accordion
+ key={`tool-${index}`}
+ type="single"
+ collapsible={true}
+ className={cn("w-full", className)}
+ >
+ <AccordionItem value="tool-call" className="border-0">
+ <AccordionTrigger
+ className={cn(
+ "h-6 text-xs border-border shadow-none! ring-0! bg-muted/60 hover:bg-muted py-0 px-2 gap-1 rounded-sm [&[data-state=open]>svg]:rotate-180 hover:no-underline",
+ getTriggerToneClass(state),
+ )}
+ >
+ <span className="flex items-center gap-1">
+ <StatusIcon state={state} />
+ {STATUS_LABEL[state]}:
+ <code className="font-mono text-xs">
+ {formatToolName(toolName)}
+ </code>
+ </span>
+ </AccordionTrigger>
+ <AccordionContent className="py-2 px-2">
+ <HistoryContent
+ state={state}
+ input={input}
+ result={result}
+ approval={approval}
+ />
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ );
+};
+
+const HistoryContent: React.FC<{
+ state: HistoryState;
+ input: unknown;
+ result?: unknown;
+ approval?: ToolApproval;
+}> = ({ state, input, result, approval }) => {
+ switch (state) {
+ case "input-streaming":
+ case "input-available":
+ case "approval-responded":
+ return <ToolArgsRenderer input={input} />;
+
+ case "output-available":
+ return (
+ <div className="space-y-3">
+ <ToolArgsRenderer input={input} />
+ {result != null && <ResultRenderer result={result} />}
+ </div>
+ );
+
+ case "output-denied":
+ return (
+ <div className="space-y-3">
+ <ToolArgsRenderer input={input} />
+ <div className="bg-muted/40 border border-border rounded-md p-3 text-xs text-muted-foreground leading-relaxed">
+ Tool execution was denied
+ {approval?.reason ? `: ${approval.reason}` : "."}
+ </div>
+ </div>
+ );
+
+ default:
+ logNever(state);
+ return null;
+ }
+};
diff --git a/frontend/src/components/chat/tool-call/tool-result.tsx b/frontend/src/components/chat/tool-call/tool-result.tsx
new file mode 100644
index 0000000000..ee6dccd9d8
--- /dev/null
+++ b/frontend/src/components/chat/tool-call/tool-result.tsx
@@ -0,0 +1,101 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { isEmpty } from "lodash-es";
+import { InfoIcon } from "lucide-react";
+import React from "react";
+import { z } from "zod";
+
+// A value worth rendering: drop null/undefined and empty containers
+// (`{}`, `[]`), but keep meaningful primitives (`0`, `false`, `""`).
+function isUninformative(value: unknown): boolean {
+ if (value == null) {
+ return true;
+ }
+ if (typeof value === "object") {
+ return isEmpty(value);
+ }
+ return false;
+}
+
+// Zod schema matching the Python SuccessResult dataclass
+const SuccessResultSchema = z.looseObject({
+ status: z.string().default("success"),
+ auth_required: z.boolean().default(false),
+ action_url: z.any(),
+ next_steps: z.any(),
+ meta: z.any(),
+ message: z.string().nullish(),
+});
+
+type SuccessResult = z.infer<typeof SuccessResultSchema>;
+
+const PrettySuccessResult: React.FC<{ data: SuccessResult }> = ({ data }) => {
+ const {
+ status,
+ auth_required,
+ action_url: _action_url,
+ meta: _meta,
+ next_steps: _next_steps,
+ message,
+ ...rest
+ } = data;
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs font-semibold text-muted-foreground">
+ Tool Result
+ </h3>
+ <div className="flex items-center gap-2">
+ <span className="text-xs px-2 py-0.5 bg-(--grass-2) text-(--grass-11) rounded-full font-medium capitalize">
+ {status}
+ </span>
+ {auth_required && (
+ <span className="text-xs px-2 py-0.5 bg-(--amber-2) text-(--amber-11) rounded-full">
+ Auth Required
+ </span>
+ )}
+ </div>
+ </div>
+
+ {message && (
+ <div className="flex items-start gap-2">
+ <InfoIcon className="h-3 w-3 text-(--blue-11) mt-0.5 shrink-0" />
+ <div className="text-xs text-foreground">{message}</div>
+ </div>
+ )}
+
+ {rest && (
+ <div className="space-y-3">
+ {Object.entries(rest).map(([key, value]) => {
+ if (isUninformative(value)) {
+ return null;
+ }
+ return (
+ <div key={key} className="space-y-1.5">
+ <span className="text-xs text-muted-foreground">{key}</span>
+ <pre className="bg-(--slate-2) p-2 text-muted-foreground border border-(--slate-4) rounded text-xs overflow-auto scrollbar-thin max-h-64">
+ {JSON.stringify(value, null, 2)}
+ </pre>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export const ResultRenderer: React.FC<{ result: unknown }> = ({ result }) => {
+ const parseResult = SuccessResultSchema.safeParse(result);
+
+ if (parseResult.success) {
+ return <PrettySuccessResult data={parseResult.data} />;
+ }
+
+ return (
+ <div className="text-xs font-medium text-muted-foreground mb-1 max-h-64 overflow-y-auto scrollbar-thin">
+ {typeof result === "string" ? result : JSON.stringify(result, null, 2)}
+ </div>
+ );
+};
diff --git a/frontend/src/core/ai/tools/__tests__/registry.test.ts b/frontend/src/core/ai/tools/__tests__/registry.test.ts
index eb24f5a071..2747c5d9e7 100644
--- a/frontend/src/core/ai/tools/__tests__/registry.test.ts
+++ b/frontend/src/core/ai/tools/__tests__/registry.test.ts
@@ -18,13 +18,11 @@ describe("FrontendToolRegistry", () => {
it("invokes a tool with valid args and validates input/output", async () => {
const registry = new FrontendToolRegistry([new TestFrontendTool()]);
- const response = await registry.invoke(
- "test_frontend_tool",
- {
- name: "Alice",
- },
- {} as never,
- );
+ const response = await registry.invoke({
+ toolName: "test_frontend_tool",
+ rawArgs: { name: "Alice" },
+ toolContext: {} as never,
+ });
// Check InvokeResult wrapper
expect(response.tool_name).toBe("test_frontend_tool");
@@ -47,11 +45,11 @@ describe("FrontendToolRegistry", () => {
it("returns a structured error on invalid args", async () => {
const registry = new FrontendToolRegistry([new TestFrontendTool()]);
- const response = await registry.invoke(
- "test_frontend_tool",
- {},
- {} as never,
- );
+ const response = await registry.invoke({
+ toolName: "test_frontend_tool",
+ rawArgs: {},
+ toolContext: {} as never,
+ });
// Check InvokeResult wrapper
expect(response.tool_name).toBe("test_frontend_tool");
diff --git a/frontend/src/core/ai/tools/registry.ts b/frontend/src/core/ai/tools/registry.ts
index 56a09a6dd1..780041f1e3 100644
--- a/frontend/src/core/ai/tools/registry.ts
+++ b/frontend/src/core/ai/tools/registry.ts
@@ -52,11 +52,15 @@ export class FrontendToolRegistry {
return tool;
}
- async invoke<TName extends string>(
- toolName: TName,
- rawArgs: unknown,
- toolContext: ToolNotebookContext,
- ): Promise<InvokeResult<TName>> {
+ async invoke<TName extends string>({
+ toolName,
+ rawArgs,
+ toolContext,
+ }: {
+ toolName: TName;
+ rawArgs: unknown;
+ toolContext: ToolNotebookContext;
+ }): Promise<InvokeResult<TName>> {
const tool = this.getToolOrThrow(toolName);
const handler = tool.handler;
const inputSchema = tool.schema;
diff --git a/marimo/_ai/_pydantic_ai_utils.py b/marimo/_ai/_pydantic_ai_utils.py
index 795eb89ec3..c1653ad21d 100644
--- a/marimo/_ai/_pydantic_ai_utils.py
+++ b/marimo/_ai/_pydantic_ai_utils.py
@@ -2,7 +2,8 @@
from __future__ import annotations
import uuid
-from typing import TYPE_CHECKING, Any
+from functools import lru_cache
+from typing import TYPE_CHECKING, Any, get_args
from marimo import _loggers
from marimo._messaging.msgspec_encoder import asdict
@@ -97,7 +98,7 @@ def convert_to_pydantic_messages(
or generate_id("message")
)
role = message.get("role", "assistant")
- parts = message.get("parts", [])
+ parts = [_sanitize_part(part) for part in message.get("parts", [])]
metadata = message.get("metadata")
ui_message = UIMessage(
@@ -121,3 +122,56 @@ def create_simple_prompt(text: str) -> UIMessage:
parts: list[UIMessagePart] = [TextUIPart(text=text)] if text else []
return UIMessage(id=generate_id("message"), role="user", parts=parts)
+
+
+@lru_cache(maxsize=1)
+def _tool_part_allowed_fields() -> dict[tuple[bool, str], frozenset[str]]:
+ """Build a lookup of allowed camelCase keys per (is_dynamic_tool, state).
+
+ Reflects pydantic-ai's own tool-part models so we don't duplicate the
+ schema and auto-track field changes on upgrade.
+ """
+ from pydantic_ai.ui.vercel_ai.request_types import (
+ DynamicToolUIPart,
+ ToolUIPart,
+ )
+
+ result: dict[tuple[bool, str], frozenset[str]] = {}
+ for model in (*get_args(ToolUIPart), *get_args(DynamicToolUIPart)):
+ state = model.model_fields["state"].default
+ is_dynamic = model.model_fields["type"].default == "dynamic-tool"
+ aliases = frozenset(
+ (info.alias or name) for name, info in model.model_fields.items()
+ )
+ result[(is_dynamic, state)] = aliases
+ return result
+
+
+def _sanitize_part(part: Any) -> Any:
+ """Drop fields the AI SDK spread onto a tool part during a state transition.
+
+ The AI SDK transitions tool parts via `{ ...part, state, approval }`, which
+ can leak stale fields (e.g. `output`, `errorText`) from a prior state.
+ Pydantic-ai's `extra='forbid'` schema rightly rejects those leaks. We
+ mirror the AI SDK's own `z.never().optional()` intent by keeping only the
+ fields declared on the matching pydantic-ai model.
+
+ Non-tool parts (text, reasoning, source, file, step-start, data-*) pass
+ through unchanged.
+ """
+ if not isinstance(part, dict):
+ return part
+ part_type = part.get("type")
+ state = part.get("state")
+ if not isinstance(part_type, str) or not isinstance(state, str):
+ return part
+
+ is_dynamic = part_type == "dynamic-tool"
+ is_static_tool = part_type.startswith("tool-")
+ if not (is_dynamic or is_static_tool):
+ return part
+
+ allowed = _tool_part_allowed_fields().get((is_dynamic, state))
+ if not allowed:
+ return part
+ return {k: v for k, v in part.items() if k in allowed}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 579bc20a64..82e54a7e26 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -38,8 +38,8 @@ importers:
frontend:
dependencies:
'@ai-sdk/react':
- specifier: ^3.0.131
+ specifier: ^3.0.176
'@anywidget/types':
specifier: ^0.2.0
version: 0.2.0
@@ -254,8 +254,8 @@ importers:
specifier: ^0.4.5
version: 0.4.5
ai:
- specifier: ^6.0.129
- version: 6.0.129([email protected])
+ specifier: ^6.0.174
+ version: 6.0.174([email protected])
ansi_up:
specifier: ^6.0.6
version: 6.0.6
@@ -712,24 +712,24 @@ packages:
'@agentclientprotocol/[email protected]':
resolution: {integrity: sha512-ExwH828LaTGoTTjxuw49l+fwOLA+Yx0+qkWn1TcHMOsY5mVI9CUfkj7ZDhv2klgZ7mJeT+lxX/Dn/KINv1AkNQ==}
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-7Hwa0VdH+l85NFS7zqZhRRaiwZMStDxEwUoTPxPNEH6V0Vgw9wi9OGopIsYdywmfSOPfSAsPL8XXPAuaSLGchw==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-r6dOqThjODp1vOhGRJg2OCmyB/ZOQtGx1esZ2SDvwDX5XoX8dBqYaYjLg8MPXTzMGJSgOkJyCxWgUcZtAl16pw==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-gpUIj9uDhIGbuo9afKEgQ074BWmhvK4THJAAeBjRnroTy2yQYo6rbtGD7pQDMZM8ouXPYmT/SCdkWVJ0KcpX8A==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-CsKNLKsOpvPujRlIYvoz+Ybw+kGn7J4/fIZa/58+R7iWLLfwn6ifE2G6Yq8K9XvH/I/3bzaDAJ3NhRwEMsLBKQ==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw==}
engines: {node: '>=18'}
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-75CqZ84ELE2/xOYpNs3A0Ioxa8MVa3yJCp3n8Ru9dWEbwv3tL7/+5wZlcHI9bkoEAw1KeNbhBL80eD861mtFHw==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-8CKMdSJDAHHUYEJSsI+HGanP/75dOYtnLWQ5WtQMvdmsA4PUVy8Hv6Bn1npoZBcTh250ESsuSptvctxFuIJrYw==}
engines: {node: '>=18'}
peerDependencies:
react: ^19.2.4
@@ -4519,6 +4519,7 @@ packages:
resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
+ deprecated: Potential CWE-502 - Update to 1.3.1 or higher
'@uwdata/[email protected]':
resolution: {integrity: sha512-hhtAgXlJbibLIHHIyFJ2fcPQ/hAK43HtEirRgrb/v2xEQv4It/KcUOyMklaVPUv2Z7+agKjSWLAXGyAQglRPvQ==}
@@ -4530,8 +4531,8 @@ packages:
'@codemirror/state': ^6
'@codemirror/view': ^6
- '@vercel/[email protected]':
- resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==}
engines: {node: '>= 20'}
'@vitejs/[email protected]':
@@ -4686,8 +4687,8 @@ packages:
resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
engines: {node: '>= 14'}
- resolution: {integrity: sha512-5nGckqbzwUBZD7wV9jsA8qaoYRwGpU9LVMtXD+ZrxSi2H6QNjpbrhsuuEBKS9xcMYevCviVNoFzpmSUWzn45Hw==}
+ resolution: {integrity: sha512-bTrfLUWHWtkjzWyCY4bmyuk4Qvmj4S4NSNsXyNSVVqkmftQNtxRj7dzUoMeQDBBwlJO6fC7m2Q/lNOPqQQfAGA==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.25.76 || ^4.1.8
@@ -5966,8 +5967,8 @@ packages:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
- resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
+ resolution: {integrity: sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ==}
engines: {node: '>=18.0.0'}
@@ -9334,7 +9335,7 @@ packages:
resolution: {integrity: sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==}
- deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
hasBin: true
@@ -9914,28 +9915,28 @@ snapshots:
dependencies:
zod: 3.25.76
dependencies:
- '@ai-sdk/provider': 3.0.8
- '@ai-sdk/provider-utils': 4.0.20([email protected])
- '@vercel/oidc': 3.1.0
+ '@ai-sdk/provider': 3.0.10
+ '@ai-sdk/provider-utils': 4.0.26([email protected])
+ '@vercel/oidc': 3.2.0
zod: 4.3.6
dependencies:
- '@ai-sdk/provider': 3.0.8
+ '@ai-sdk/provider': 3.0.10
'@standard-schema/spec': 1.1.0
- eventsource-parser: 3.0.6
+ eventsource-parser: 3.0.8
zod: 4.3.6
- '@ai-sdk/[email protected]':
+ '@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
dependencies:
- '@ai-sdk/provider-utils': 4.0.20([email protected])
- ai: 6.0.129([email protected])
+ '@ai-sdk/provider-utils': 4.0.26([email protected])
+ ai: 6.0.174([email protected])
react: 19.2.4
swr: 2.3.4([email protected])
throttleit: 2.1.0
@@ -11257,7 +11258,7 @@ snapshots:
cors: 2.8.6
cross-spawn: 7.0.6
eventsource: 3.0.7
- eventsource-parser: 3.0.6
+ eventsource-parser: 3.0.8
express: 5.2.1
express-rate-limit: 7.5.1([email protected])
pkce-challenge: 5.0.1
@@ -14490,7 +14491,7 @@ snapshots:
'@connectrpc/connect': 1.6.1(@bufbuild/[email protected])
'@connectrpc/connect-web': 1.6.1(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))
- '@vercel/[email protected]': {}
+ '@vercel/[email protected]': {}
dependencies:
@@ -14710,11 +14711,11 @@ snapshots:
dependencies:
- '@ai-sdk/gateway': 3.0.75([email protected])
- '@ai-sdk/provider': 3.0.8
- '@ai-sdk/provider-utils': 4.0.20([email protected])
+ '@ai-sdk/gateway': 3.0.109([email protected])
+ '@ai-sdk/provider': 3.0.10
+ '@ai-sdk/provider-utils': 4.0.26([email protected])
'@opentelemetry/api': 1.9.0
zod: 4.3.6
@@ -16037,11 +16038,11 @@ snapshots:
dependencies:
- eventsource-parser: 3.0.6
+ eventsource-parser: 3.0.8
diff --git a/tests/_ai/test_pydantic_utils.py b/tests/_ai/test_pydantic_utils.py
index a0a28a11a2..91a36600f9 100644
--- a/tests/_ai/test_pydantic_utils.py
+++ b/tests/_ai/test_pydantic_utils.py
@@ -9,6 +9,7 @@ import pytest
pytest.importorskip("pydantic_ai", reason="pydantic_ai not installed")
from marimo._ai._pydantic_ai_utils import (
+ _sanitize_part,
convert_to_pydantic_messages,
create_simple_prompt,
form_toolsets,
@@ -489,3 +490,148 @@ class TestCreateSimplePrompt:
assert result.id.startswith("message_")
assert result.role == "user"
assert result.parts == []
+
+
+class TestSanitizePart:
+ """Tests for the per-state field stripper for tool parts.
+
+ The AI SDK's `addToolApprovalResponse` spreads the previous part during
+ state transitions, which can leak stale fields like `output` or
+ `errorText`. pydantic-ai's `extra='forbid'` schema rejects those. The
+ sanitizer keeps only fields declared on the matching pydantic-ai model.
+ """
+
+ def test_strips_stale_fields_on_approval_responded(self):
+ """Reproduces the original 92-validation-errors bug.
+
+ Confirms both that stale fields are dropped and that the cleaned
+ part round-trips through pydantic-ai's strict schema.
+ """
+ from pydantic_ai.ui.vercel_ai.request_types import (
+ ToolApprovalRespondedPart,
+ UIMessage,
+ )
+
+ stale = {
+ "type": "tool-request_user_blessing",
+ "toolCallId": "call_abc",
+ "state": "approval-responded",
+ "input": {},
+ "approval": {"id": "call_abc", "approved": True},
+ "output": "Invalid arguments for tool request_user_blessing",
+ "errorText": "boom",
+ }
+ clean = _sanitize_part(stale)
+ assert "output" not in clean
+ assert "errorText" not in clean
+ assert clean["approval"] == {"id": "call_abc", "approved": True}
+
+ msg = UIMessage(id="m1", role="assistant", parts=[clean])
+ assert isinstance(msg.parts[0], ToolApprovalRespondedPart)
+
+ def test_preserves_real_fields_on_output_available(self):
+ part = {
+ "type": "tool-foo",
+ "toolCallId": "c1",
+ "state": "output-available",
+ "input": {"x": 1},
+ "output": {"ok": True},
+ "preliminary": False,
+ }
+ clean = _sanitize_part(part)
+ assert clean["output"] == {"ok": True}
+ assert clean["preliminary"] is False
+
+ def test_preserves_real_fields_on_output_error(self):
+ part = {
+ "type": "tool-foo",
+ "toolCallId": "c1",
+ "state": "output-error",
+ "input": {"x": 1},
+ "rawInput": {"x": 1},
+ "errorText": "boom",
+ }
+ clean = _sanitize_part(part)
+ assert clean["errorText"] == "boom"
+ assert clean["rawInput"] == {"x": 1}
+
+ def test_dynamic_tool_preserves_tool_name(self):
+ stale = {
+ "type": "dynamic-tool",
+ "toolName": "my_tool",
+ "toolCallId": "c1",
+ "state": "approval-responded",
+ "input": {"x": 1},
+ "approval": {"id": "c1", "approved": True},
+ "output": "stale",
+ }
+ clean = _sanitize_part(stale)
+ assert "output" not in clean
+ assert clean["toolName"] == "my_tool"
+
+ @pytest.mark.parametrize(
+ "part",
+ [
+ {"type": "text", "text": "hello"},
+ {"type": "reasoning", "text": "thinking..."},
+ {
+ "type": "source-url",
+ "sourceId": "s1",
+ "url": "https://example.com",
+ },
+ {"type": "step-start"},
+ {"type": "data-custom", "data": {"k": "v"}},
+ ],
+ )
+ def test_non_tool_parts_pass_through_unchanged(self, part):
+ assert _sanitize_part(part) is part
+
+ @pytest.mark.parametrize(
+ "part",
+ [
+ None,
+ "not a part",
+ 42,
+ # missing type
+ {"state": "approval-responded", "output": "stale"},
+ # missing state
+ {"type": "tool-foo", "toolCallId": "c1"},
+ # unknown future state
+ {
+ "type": "tool-foo",
+ "toolCallId": "c1",
+ "state": "future-state",
+ "output": "stale",
+ },
+ ],
+ )
+ def test_malformed_parts_pass_through_unchanged(self, part):
+ assert _sanitize_part(part) == part
+
+
+class TestConvertToPydanticMessagesSanitizes:
+ def test_stale_output_on_approval_responded_part_validates(self):
+ """Regression: server raised 92 errors when AI SDK leaked `output` onto an `approval-responded` part."""
+ from pydantic_ai.ui.vercel_ai.request_types import (
+ ToolApprovalRespondedPart,
+ )
+
+ messages = [
+ {
+ "id": "msg_1",
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "tool-request_user_blessing",
+ "toolCallId": "call_abc",
+ "state": "approval-responded",
+ "input": {},
+ "approval": {"id": "call_abc", "approved": True},
+ "output": "Invalid arguments for tool ...",
+ }
+ ],
+ }
+ ]
+ result = convert_to_pydantic_messages(messages)
+ assert len(result) == 1
+ assert isinstance(result[0].parts[0], ToolApprovalRespondedPart)