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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix interruption for pydantic-ai chatbot (#9620)
Shahmir Varqha143c13e61c7f
diff --git a/examples/ai/chat/pydantic-ai-chat.py b/examples/ai/chat/pydantic-ai-chat.pyindex b57b615faa..b3d740e706 100644--- a/examples/ai/chat/pydantic-ai-chat.py+++ b/examples/ai/chat/pydantic-ai-chat.py@@ -6,9 +6,10 @@# "pydantic==2.12.5",# ]# ///+import marimo-__generated_with = "0.21.1"+__generated_with = "0.23.6"app = marimo.App(width="medium")with app.setup(hide_code=True):@@ -16,7 +17,12 @@ with app.setup(hide_code=True):import osimport httpx- from pydantic_ai import Agent, RunContext, BinaryImage+ from pydantic_ai import (+ Agent,+ BinaryImage,+ DeferredToolRequests,+ RunContext,+ )from pydantic_ai.models.google import GoogleModel, GoogleModelSettingsfrom pydantic_ai.providers.google import GoogleProviderfrom pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings@@ -52,6 +58,7 @@ def _():structured = mo.ui.checkbox(label="Structured outputs")thinking = mo.ui.checkbox(label="Reasoning")fetch_dog_tool = mo.ui.checkbox(label="Fetch dog pics tool")+ delete_file_tool = mo.ui.checkbox(label="Delete file tool (requires approval)")models = mo.ui.dropdown(options={@@ -64,8 +71,8 @@ def _():label="Choose a model",)- mo.vstack([models, structured, thinking, fetch_dog_tool])- return fetch_dog_tool, models, structured, thinking+ mo.vstack([models, structured, thinking, fetch_dog_tool, delete_file_tool])+ return delete_file_tool, fetch_dog_tool, models, structured, thinking@app.cell(hide_code=True)@@ -129,6 +136,7 @@ def get_model(@app.cell(hide_code=True)def _(+ delete_file_tool,fetch_dog_tool,input_key,model_name,@@ -153,6 +161,15 @@ def _(elif structured.value:output_type = [CodeOutput, str]+ # Tools that pause for human approval require `DeferredToolRequests`+ # in the output type; pydantic-ai returns it whenever a tool flagged+ # `requires_approval=True` is called.+ if delete_file_tool.value:+ if isinstance(output_type, list):+ output_type = [*output_type, DeferredToolRequests]+ else:+ output_type = [output_type, DeferredToolRequests]+agent = Agent(model,output_type=output_type,@@ -172,6 +189,14 @@ def _(return response_json["message"]else:return "Error fetching dog URL"+++ if delete_file_tool.value:++ @agent.tool_plain(requires_approval=True)+ def delete_file(path: str) -> str:+ """Pretend to delete the file at `path`."""+ return f"File {path!r} deleted"return (agent,)@@ -184,6 +209,7 @@ def _(agent):"Who is Ada Lovelace?","What is marimo?","I need dogs (render as markdown)",+ "Delete the file at path 'secrets.env'",],allow_attachments=True,show_configuration_controls=True,@@ -198,52 +224,115 @@ def _(chatbot):return[email protected](hide_code=True)def _():- mo.md("""- ## Custom Model Sample+ mo.md(r"""+ ## Custom model sample++ `mo.ui.chat` accepts any async generator that yields Vercel AI SDK chunks.+ The model below is a hand-rolled showcase of every part the SDK knows+ about — reasoning, streamed tool input, file/source/data attachments,+ a deliberately failed tool, and a final tool that pauses for human+ approval.""")return[email protected](hide_code=True)def _():+ import asyncioimport uuid+import pydantic_ai.ui.vercel_ai.response_types as vercel+ def _new_id(prefix: str) -> str:+ return f"{prefix}_{uuid.uuid4().hex[:8]}"+++ def _pending_approval(messages) -> dict | None:+ """Find a tool part the user just approved or denied, if any.++ After Approve/Deny, the SDK transitions the tool part on the last+ assistant message to `approval-responded` and auto-resumes. We+ look for that state on the most recent assistant turn so we know+ whether to start a fresh showcase or finish the deletion.+ """+ for message in reversed(messages):+ if message.role != "assistant":+ continue+ for part in message.raw_or_dumped_parts():+ if not isinstance(part, dict):+ continue+ if not str(part.get("type", "")).startswith("tool-"):+ continue+ if part.get("state") == "approval-responded":+ return part+ return None+ return None++async def custom_model(messages, config):- # Generate unique IDs for message parts- reasoning_id = f"reasoning_{uuid.uuid4().hex}"- text_id = f"text_{uuid.uuid4().hex}"- tool_id = f"tool_{uuid.uuid4().hex}"+ del config++ pending = _pending_approval(messages)+ if pending is not None:+ async for chunk in _resume_after_approval(pending):+ yield chunk+ return++ async for chunk in _showcase_turn():+ yield chunk+++ async def _showcase_turn():+ reasoning_id = _new_id("reasoning")+ search_id = _new_id("tc")+ translate_id = _new_id("tc")+ delete_id = _new_id("tc")+ approval_id = _new_id("ap")+ intro_id = _new_id("text")+ followup_id = _new_id("text")+ error_text_id = _new_id("text")+ ask_id = _new_id("text")+ data_id = _new_id("data")++ # Message-level metadata round-trips on `message.metadata` in the UI.+ yield vercel.MessageMetadataChunk(+ message_metadata={"demo": "vercel-ai-sdk-showcase", "turn": 1}+ )- # --- Stream reasoning/thinking ---+ # ── Step 1: think + run a tool that succeeds ──────────────────yield vercel.StartStepChunk()+yield vercel.ReasoningStartChunk(id=reasoning_id)- yield vercel.ReasoningDeltaChunk(- id=reasoning_id,- delta="The user is asking about Van Gogh. I should fetch information about his famous works.",- )+ for chunk in [+ "The user wants the full tour. ",+ "I'll search for a famous painting, ",+ "compose an answer with citations and an image, ",+ "demonstrate an erroring tool, ",+ "and finally offer to clean up a temp file ",+ "behind a human-approval gate.",+ ]:+ yield vercel.ReasoningDeltaChunk(id=reasoning_id, delta=chunk)+ await asyncio.sleep(0.04)yield vercel.ReasoningEndChunk(id=reasoning_id)- # --- Stream tool call to fetch artwork information ---+ yield vercel.ToolInputStartChunk(+ tool_call_id=search_id, tool_name="search_artwork"+ )+ for delta in ['{"artist":', ' "Vincent van Gogh",', ' "limit": 1}']:+ yield vercel.ToolInputDeltaChunk(+ tool_call_id=search_id, input_text_delta=delta+ )+ await asyncio.sleep(0.04)yield vercel.ToolInputAvailableChunk(- tool_call_id=tool_id,+ tool_call_id=search_id,tool_name="search_artwork",input={"artist": "Vincent van Gogh", "limit": 1},)- yield vercel.ToolInputStartChunk(- tool_call_id=tool_id, tool_name="search_artwork"- )- yield vercel.ToolInputDeltaChunk(- tool_call_id=tool_id,- input_text_delta='{"artist": "Vincent van Gogh", "limit": 1}',- )-- # --- Tool output (simulated artwork search result) ---yield vercel.ToolOutputAvailableChunk(- tool_call_id=tool_id,+ tool_call_id=search_id,output={"title": "The Starry Night","year": 1889,@@ -251,28 +340,170 @@ def _():},)- # --- Stream text response ---- yield vercel.TextStartChunk(id=text_id)- yield vercel.TextDeltaChunk(- id=text_id,- delta="One of Vincent van Gogh's most iconic works is 'The Starry Night', painted in 1889. Here's the painting:\n\n",- )+ yield vercel.FinishStepChunk()++ # ── Step 2: compose the answer with rich media ────────────────+ yield vercel.StartStepChunk()++ yield vercel.TextStartChunk(id=intro_id)+ for delta in [+ "One of Vincent van Gogh's most iconic works is ",+ "**The Starry Night**, painted in 1889. ",+ "Here is the painting:",+ ]:+ yield vercel.TextDeltaChunk(id=intro_id, delta=delta)+ await asyncio.sleep(0.04)+ yield vercel.TextEndChunk(id=intro_id)- # --- Embed the artwork image ---yield vercel.FileChunk(- url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1280px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg",+ url=(+ "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/"+ "Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/"+ "1280px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg"+ ),media_type="image/jpeg",)++ yield vercel.SourceUrlChunk(+ source_id=_new_id("src"),+ url="https://www.moma.org/collection/works/79802",+ title="The Starry Night | MoMA",+ )+ yield vercel.SourceDocumentChunk(+ source_id=_new_id("src"),+ media_type="application/pdf",+ title="Faille catalogue raisonné, vol. III",+ filename="van-gogh-catalogue.pdf",+ )++ # Custom data-* parts let backends ship arbitrary structured+ # payloads to bespoke UI widgets without bending the text channel.+ yield vercel.DataChunk(+ id=data_id,+ type="data-artwork-card",+ data={+ "title": "The Starry Night",+ "year": 1889,+ "movement": "Post-Impressionism",+ },+ )++ yield vercel.TextStartChunk(id=followup_id)+ yield vercel.TextDeltaChunk(+ id=followup_id,+ delta=(+ "\n\nNext I'll try a translation tool that's expected to"+ " fail — handy for seeing how errors render."+ ),+ )+ yield vercel.TextEndChunk(id=followup_id)++ yield vercel.FinishStepChunk()++ # ── Step 3: a tool whose execution fails ──────────────────────+ yield vercel.StartStepChunk()++ yield vercel.ToolInputStartChunk(+ tool_call_id=translate_id, tool_name="translate"+ )+ yield vercel.ToolInputAvailableChunk(+ tool_call_id=translate_id,+ tool_name="translate",+ input={"text": "Sterrennacht", "from": "nl", "to": "klingon"},+ )+ yield vercel.ToolOutputErrorChunk(+ tool_call_id=translate_id,+ error_text="UnsupportedLanguage: 'klingon' is not a supported target.",+ )++ yield vercel.TextStartChunk(id=error_text_id)yield vercel.TextDeltaChunk(- id=text_id,- delta="\nThis masterpiece is now housed at the Museum of Modern Art in New York and remains one of the most recognizable paintings in the world.",+ id=error_text_id,+ delta="That call failed, as expected — moving on.",)- yield vercel.TextEndChunk(id=text_id)+ yield vercel.TextEndChunk(id=error_text_id)+yield vercel.FinishStepChunk()- yield vercel.FinishChunk()+ # ── Step 4: ask for approval, then stop ───────────────────────+ yield vercel.StartStepChunk()- custom_chat = mo.ui.chat(custom_model)+ yield vercel.TextStartChunk(id=ask_id)+ yield vercel.TextDeltaChunk(+ id=ask_id,+ delta=(+ "I'd like to delete the search cache file. "+ "Approve below to proceed, or deny to keep it."+ ),+ )+ yield vercel.TextEndChunk(id=ask_id)++ yield vercel.ToolInputStartChunk(+ tool_call_id=delete_id, tool_name="delete_file"+ )+ yield vercel.ToolInputAvailableChunk(+ tool_call_id=delete_id,+ tool_name="delete_file",+ input={"path": "/tmp/van-gogh-search.cache"},+ )+ yield vercel.ToolApprovalRequestChunk(+ approval_id=approval_id, tool_call_id=delete_id+ )++ yield vercel.FinishStepChunk()+ yield vercel.FinishChunk(finish_reason="tool-calls")+++ async def _resume_after_approval(pending: dict):+ tool_call_id = pending["toolCallId"]+ approval = pending.get("approval") or {}+ approved = bool(approval.get("approved"))+ path = (pending.get("input") or {}).get("path", "<unknown>")++ text_id = _new_id("text")++ yield vercel.MessageMetadataChunk(+ message_metadata={+ "demo": "vercel-ai-sdk-showcase",+ "turn": 2,+ "approval": approval,+ }+ )+ yield vercel.StartStepChunk()++ if approved:+ yield vercel.ToolOutputAvailableChunk(+ tool_call_id=tool_call_id,+ output={"deleted": True, "path": path},+ )+ yield vercel.TextStartChunk(id=text_id)+ yield vercel.TextDeltaChunk(+ id=text_id, delta=f"Done — `{path}` has been removed."+ )+ yield vercel.TextEndChunk(id=text_id)+ else:+ yield vercel.ToolOutputDeniedChunk(tool_call_id=tool_call_id)+ yield vercel.TextStartChunk(id=text_id)+ yield vercel.TextDeltaChunk(+ id=text_id,+ delta=(+ f"No problem — I'll leave `{path}` alone. "+ f"Reason: {approval.get('reason') or 'no reason given'}."+ ),+ )+ yield vercel.TextEndChunk(id=text_id)++ yield vercel.FinishStepChunk()+ yield vercel.FinishChunk(finish_reason="stop")+++ custom_chat = mo.ui.chat(+ custom_model,+ prompts=[+ "Run the full Vercel AI SDK part showcase",+ "Show me reasoning, citations, and an approval-gated tool",+ ],+ )custom_chatreturn (custom_chat,)diff --git a/frontend/src/components/chat/__tests__/chat-utils.test.ts b/frontend/src/components/chat/__tests__/chat-utils.test.tsnew file mode 100644index 0000000000..6b4ad17158--- /dev/null+++ b/frontend/src/components/chat/__tests__/chat-utils.test.ts@@ -0,0 +1,269 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { UIMessage } from "ai";+import { describe, expect, it } from "vitest";+import { hasPendingToolCalls } from "../chat-utils";++/**+ * `hasPendingToolCalls` powers `sendAutomaticallyWhen` in `mo.ui.chat`:+ * returns true only when the last assistant message *ends* with a tool+ * call in a ready-to-round-trip state. Any trailing non-tool part (text,+ * file, source-*, reasoning, data-*, new step-start) means the assistant+ * has already answered and we leave the next turn to the user. The+ * approval flow relies on this firing for `approval-responded`.+ */++const userMessage = (text: string): UIMessage => ({+ id: `user-${text}`,+ role: "user",+ parts: [{ type: "text", text }],+});++const assistantToolMessage = (+ parts: UIMessage["parts"],+ id = "assistant-1",+): UIMessage => ({+ id,+ role: "assistant",+ parts,+});++describe("hasPendingToolCalls", () => {+ it("returns false when there are no messages", () => {+ expect(hasPendingToolCalls([])).toBe(false);+ });++ it("returns false when the last message is a user message", () => {+ expect(hasPendingToolCalls([userMessage("hi")])).toBe(false);+ });++ it("returns false when the last assistant message has no tool parts", () => {+ expect(+ hasPendingToolCalls([+ userMessage("hi"),+ assistantToolMessage([{ type: "text", text: "hello!" }]),+ ]),+ ).toBe(false);+ });++ it("returns false while a tool is still streaming or awaiting approval", () => {+ expect(+ hasPendingToolCalls([+ userMessage("delete it"),+ assistantToolMessage([+ {+ type: "tool-delete_file",+ toolCallId: "call-1",+ state: "approval-requested",+ input: { path: "secrets.env" },+ approval: { id: "approval-1" },+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(false);+ });++ it("returns true when the user has responded to an approval request", () => {+ // The chat must auto-resume as soon as Approve/Deny is clicked.+ expect(+ hasPendingToolCalls([+ userMessage("delete it"),+ assistantToolMessage([+ {+ type: "tool-delete_file",+ toolCallId: "call-1",+ state: "approval-responded",+ input: { path: "secrets.env" },+ approval: { id: "approval-1", approved: true },+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(true);+ });++ it("returns true when a tool reached a terminal output state", () => {+ expect(+ hasPendingToolCalls([+ userMessage("run it"),+ assistantToolMessage([+ {+ type: "tool-run_query",+ toolCallId: "call-1",+ state: "output-available",+ input: { sql: "select 1" },+ output: 1,+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(true);+ });++ it("returns false when only some tool calls are ready", () => {+ expect(+ hasPendingToolCalls([+ userMessage("two things"),+ assistantToolMessage([+ {+ type: "tool-first",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: 1,+ } as unknown as UIMessage["parts"][number],+ {+ type: "tool-second",+ toolCallId: "call-2",+ state: "input-available",+ input: {},+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(false);+ });++ it("returns false once the assistant has appended text after the tool result", () => {+ expect(+ hasPendingToolCalls([+ userMessage("run it"),+ assistantToolMessage([+ {+ type: "tool-run_query",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: 1,+ } as unknown as UIMessage["parts"][number],+ { type: "text", text: "The query returned 1." },+ ]),+ ]),+ ).toBe(false);+ });++ it("returns false when a file part trails the completed tool call", () => {+ // Regression: tool → text → file used to loop because only trailing+ // text counted as "the assistant has answered".+ expect(+ hasPendingToolCalls([+ userMessage("show me Starry Night"),+ assistantToolMessage([+ { type: "step-start" },+ {+ type: "tool-search_artwork",+ toolCallId: "call-1",+ state: "output-available",+ input: { artist: "Van Gogh" },+ output: { title: "The Starry Night" },+ } as unknown as UIMessage["parts"][number],+ { type: "text", text: "Here is the painting:" },+ {+ type: "file",+ mediaType: "image/jpeg",+ url: "https://example.com/starry-night.jpg",+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(false);+ });++ it("returns false when a source-url part trails the completed tool call", () => {+ expect(+ hasPendingToolCalls([+ userMessage("cite your sources"),+ assistantToolMessage([+ {+ type: "tool-web_search",+ toolCallId: "call-1",+ state: "output-available",+ input: { q: "marimo notebook" },+ output: "found",+ } as unknown as UIMessage["parts"][number],+ { type: "text", text: "marimo is a reactive notebook." },+ {+ type: "source-url",+ sourceId: "src-1",+ url: "https://marimo.io",+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(false);+ });++ it("returns false when a reasoning part trails the completed tool call", () => {+ expect(+ hasPendingToolCalls([+ userMessage("explain"),+ assistantToolMessage([+ {+ type: "tool-lookup",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: 1,+ } as unknown as UIMessage["parts"][number],+ {+ type: "reasoning",+ text: "Now I'll summarize.",+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(false);+ });++ it("returns false when a new step-start follows the completed tool call", () => {+ expect(+ hasPendingToolCalls([+ userMessage("multi-step"),+ assistantToolMessage([+ { type: "step-start" },+ {+ type: "tool-run_query",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: 1,+ } as unknown as UIMessage["parts"][number],+ { type: "step-start" },+ ]),+ ]),+ ).toBe(false);+ });++ it("ignores providerExecuted tools", () => {+ // Provider-side tools are resolved by the model, not the runtime, so+ // they must not drive an auto-resume.+ expect(+ hasPendingToolCalls([+ userMessage("hi"),+ assistantToolMessage([+ {+ type: "tool-web_search",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: 1,+ providerExecuted: true,+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(false);+ });++ it("returns true for dynamic-tool parts in a terminal state", () => {+ // `dynamic-tool` parts must drive auto-resume alongside `tool-*`.+ expect(+ hasPendingToolCalls([+ userMessage("run it"),+ assistantToolMessage([+ {+ type: "dynamic-tool",+ toolName: "run_query",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: 1,+ } as unknown as UIMessage["parts"][number],+ ]),+ ]),+ ).toBe(true);+ });+});diff --git a/frontend/src/components/chat/chat-utils.ts b/frontend/src/components/chat/chat-utils.tsindex fbb3552f30..c09195345a 100644--- a/frontend/src/components/chat/chat-utils.ts+++ b/frontend/src/components/chat/chat-utils.ts@@ -5,7 +5,8 @@ import {type ChatAddToolOutputFunction,type FileUIPart,isToolUIPart,- type ToolUIPart,+ lastAssistantMessageIsCompleteWithApprovalResponses,+ lastAssistantMessageIsCompleteWithToolCalls,type UIMessage,} from "ai";import { useState } from "react";@@ -17,7 +18,6 @@ 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";@@ -169,69 +169,25 @@ 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 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.+ * Auto-send the next turn when the last assistant message ends with a+ * tool call ready to round-trip. Any non-tool trailing part (text, file,+ * source-*, reasoning, data-*, new step-start) means the assistant has+ * already answered, so we leave the next turn to the user. State checks+ * are delegated to the SDK to stay in sync with upstream.*/export function hasPendingToolCalls(messages: UIMessage[]): boolean {- if (messages.length === 0) {- return false;- }-- const lastMessage = messages[messages.length - 1];- const parts = lastMessage.parts;-- if (parts.length === 0) {- return false;- }-- // Only auto-send if the last message is an assistant message- // Because assistant messages are the ones that can have tool calls- if (lastMessage.role !== "assistant") {+ const lastMessage = messages.at(-1);+ if (!lastMessage || lastMessage.role !== "assistant") {return false;}-- const toolParts = parts.filter(isToolUIPart);-- if (toolParts.length === 0) {+ const lastPart = lastMessage.parts.at(-1);+ if (!lastPart || !isToolUIPart(lastPart)) {return false;}-- const allToolCallsReady = toolParts.every((part) =>- isToolCallReadyToSend(part.state),+ return (+ lastAssistantMessageIsCompleteWithToolCalls({ messages }) ||+ lastAssistantMessageIsCompleteWithApprovalResponses({ messages }));-- // Check if the last part has any text content- const lastPart = parts[parts.length - 1];- const hasTextContent =- lastPart.type === "text" && lastPart.text?.trim().length > 0;-- Logger.debug("All tool calls ready to send: %s", allToolCallsReady);-- return allToolCallsReady && !hasTextContent;}export function useFileState() {diff --git a/frontend/src/plugins/impl/chat/ChatPlugin.tsx b/frontend/src/plugins/impl/chat/ChatPlugin.tsxindex ea3c74b4d4..814a5c810b 100644--- a/frontend/src/plugins/impl/chat/ChatPlugin.tsx+++ b/frontend/src/plugins/impl/chat/ChatPlugin.tsx@@ -6,7 +6,7 @@ import { z } from "zod";import { createPlugin } from "@/plugins/core/builder";import { rpc } from "@/plugins/core/rpc";import { Arrays } from "@/utils/arrays";-import type { SendMessageRequest } from "./types";+import type { CancelPromptRequest, SendMessageRequest } from "./types";const LazyChatbot = React.lazy(() =>import("./chat-ui").then((m) => ({ default: m.Chatbot })),@@ -18,6 +18,7 @@ export type PluginFunctions = {delete_chat_history: (req: {}) => Promise<null>;delete_chat_message: (req: { index: number }) => Promise<null>;send_prompt: (req: SendMessageRequest) => Promise<unknown>;+ cancel_prompt: (req: CancelPromptRequest) => Promise<null>;};const messageSchema = z.array(@@ -65,11 +66,15 @@ export const ChatPlugin = createPlugin<{ messages: UIMessage[] }>(send_prompt: rpc.input(z.object({+ request_id: z.string(),messages: messageSchema,config: configSchema,}),).output(z.unknown()),+ cancel_prompt: rpc+ .input(z.object({ request_id: z.string() }))+ .output(z.null()),}).renderer((props) => (<Suspense>@@ -84,6 +89,7 @@ export const ChatPlugin = createPlugin<{ messages: UIMessage[] }>(delete_chat_history={props.functions.delete_chat_history}delete_chat_message={props.functions.delete_chat_message}send_prompt={props.functions.send_prompt}+ cancel_prompt={props.functions.cancel_prompt}value={props.value?.messages || Arrays.EMPTY}setValue={(messages) => props.setValue({ messages })}host={props.host}diff --git a/frontend/src/plugins/impl/chat/__tests__/chat-ui.test.ts b/frontend/src/plugins/impl/chat/__tests__/chat-ui.test.tsnew file mode 100644index 0000000000..e3fed0af8a--- /dev/null+++ b/frontend/src/plugins/impl/chat/__tests__/chat-ui.test.ts@@ -0,0 +1,278 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { UIMessageChunk } from "ai";+import { describe, expect, it, vi } from "vitest";+import { routeIncomingChatChunk } from "../chat-ui";++/**+ * The stale-chunk filter prevents chunks from an aborted run from being enqueued into a new run's stream.+ *+ * It triggers when:+ * 1. User sends a prompt (request_id = OLD), kernel starts emitting chunks+ * 2. User clicks Stop — frontend tears down its controller, fires cancel_prompt+ * 3. Kernel hasn't received the cancel yet and is still emitting chunks+ * 4. User sends a new prompt (request_id = NEW), new controller opens+ * 5. Late chunks tagged OLD arrive after NEW's controller is in place+ */++const makeChunk = (opts: {+ messageId: string;+ content: unknown;+ isFinal?: boolean;+}): Parameters<typeof routeIncomingChatChunk>[0] => ({+ type: "stream_chunk",+ message_id: opts.messageId,+ content: opts.content as UIMessageChunk | null,+ is_final: opts.isFinal ?? false,+});++const makeRefs = () => ({+ controllerRef: {+ current: null as ReadableStreamDefaultController<UIMessageChunk> | null,+ },+ activeRequestIdRef: { current: null as string | null },+});++const makeMockController = () => {+ return {+ enqueue: vi.fn(),+ close: vi.fn(),+ error: vi.fn(),+ desiredSize: 0,+ } as unknown as ReadableStreamDefaultController<UIMessageChunk> & {+ enqueue: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+ };+};++describe("routeIncomingChatChunk", () => {+ it("drops chunks when there is no active controller", () => {+ const refs = makeRefs();++ const result = routeIncomingChatChunk(+ makeChunk({+ messageId: "req-A",+ content: { type: "text-delta", id: "t1", delta: "hi" },+ }),+ refs,+ );++ expect(result).toBe("dropped-no-controller");+ });++ it("enqueues chunks that match the active request_id", () => {+ const refs = makeRefs();+ const controller = makeMockController();+ refs.controllerRef.current = controller;+ refs.activeRequestIdRef.current = "req-A";++ const chunk = { type: "text-delta", id: "t1", delta: "hi" } as const;+ const result = routeIncomingChatChunk(+ makeChunk({ messageId: "req-A", content: chunk }),+ refs,+ );++ expect(result).toBe("enqueued");+ expect(controller.enqueue).toHaveBeenCalledWith(chunk);+ expect(controller.close).not.toHaveBeenCalled();+ });++ it("closes the controller and clears refs on is_final", () => {+ const refs = makeRefs();+ const controller = makeMockController();+ refs.controllerRef.current = controller;+ refs.activeRequestIdRef.current = "req-A";++ const result = routeIncomingChatChunk(+ makeChunk({ messageId: "req-A", content: null, isFinal: true }),+ refs,+ );++ expect(result).toBe("closed");+ expect(controller.close).toHaveBeenCalledTimes(1);+ expect(refs.controllerRef.current).toBeNull();+ expect(refs.activeRequestIdRef.current).toBeNull();+ });++ it("drops chunks whose message_id does not match the active run", () => {+ // Simulates the bug: kernel hasn't received cancel for OLD yet but the+ // user has already started a NEW run. A reasoning-delta for OLD arrives+ // here; it must not be enqueued into NEW's stream.+ const refs = makeRefs();+ const controller = makeMockController();+ refs.controllerRef.current = controller;+ refs.activeRequestIdRef.current = "req-NEW";++ const staleChunk = {+ type: "reasoning-delta",+ id: "r-old",+ delta: "...",+ } as const;+ const result = routeIncomingChatChunk(+ makeChunk({ messageId: "req-OLD", content: staleChunk }),+ refs,+ );++ expect(result).toBe("dropped-stale");+ expect(controller.enqueue).not.toHaveBeenCalled();+ expect(controller.close).not.toHaveBeenCalled();+ expect(refs.activeRequestIdRef.current).toBe("req-NEW");+ });++ it("drops is_final from a stale run without closing the active stream", () => {+ // Belt-and-suspenders: an `is_final` for OLD that races in after NEW+ // started must not tear down NEW's controller.+ const refs = makeRefs();+ const controller = makeMockController();+ refs.controllerRef.current = controller;+ refs.activeRequestIdRef.current = "req-NEW";++ const result = routeIncomingChatChunk(+ makeChunk({ messageId: "req-OLD", content: null, isFinal: true }),+ refs,+ );++ expect(result).toBe("dropped-stale");+ expect(controller.close).not.toHaveBeenCalled();+ expect(refs.controllerRef.current).toBe(controller);+ expect(refs.activeRequestIdRef.current).toBe("req-NEW");+ });++ it("forwards reasoning-start/delta/end sequences when ids match", () => {+ // Walks the canonical happy path for a reasoning stream end-to-end.+ const refs = makeRefs();+ const controller = makeMockController();+ refs.controllerRef.current = controller;+ refs.activeRequestIdRef.current = "req-A";++ const sequence = [+ { type: "reasoning-start", id: "r1" },+ { type: "reasoning-delta", id: "r1", delta: "thinking" },+ { type: "reasoning-end", id: "r1" },+ ] as const;+ for (const chunk of sequence) {+ const result = routeIncomingChatChunk(+ makeChunk({ messageId: "req-A", content: chunk }),+ refs,+ );+ expect(result).toBe("enqueued");+ }++ expect(controller.enqueue).toHaveBeenCalledTimes(3);+ expect(controller.enqueue).toHaveBeenNthCalledWith(1, sequence[0]);+ expect(controller.enqueue).toHaveBeenNthCalledWith(2, sequence[1]);+ expect(controller.enqueue).toHaveBeenNthCalledWith(3, sequence[2]);+ });++ it(+ "drops stale reasoning-delta after Stop → new run sequence " ++ "(regression for missing reasoning part error)",+ () => {+ // Full scenario: A runs, A is stopped, B starts, A's late chunk arrives.+ const refs = makeRefs();++ // 1. Run A starts: controller A active.+ const controllerA = makeMockController();+ refs.controllerRef.current = controllerA;+ refs.activeRequestIdRef.current = "req-A";++ // First reasoning chunks for A flow through.+ routeIncomingChatChunk(+ makeChunk({+ messageId: "req-A",+ content: { type: "reasoning-start", id: "rA" },+ }),+ refs,+ );+ routeIncomingChatChunk(+ makeChunk({+ messageId: "req-A",+ content: {+ type: "reasoning-delta",+ id: "rA",+ delta: "thinking",+ },+ }),+ refs,+ );+ expect(controllerA.enqueue).toHaveBeenCalledTimes(2);++ // 2. User clicks Stop: abort handler clears refs (simulated).+ refs.controllerRef.current = null;+ refs.activeRequestIdRef.current = null;++ // A late chunk for A arrives in this window — must be a no-op.+ const between = routeIncomingChatChunk(+ makeChunk({+ messageId: "req-A",+ content: {+ type: "reasoning-delta",+ id: "rA",+ delta: "leftover",+ },+ }),+ refs,+ );+ expect(between).toBe("dropped-no-controller");++ // 3. User sends Run B: new controller, new active id.+ const controllerB = makeMockController();+ refs.controllerRef.current = controllerB;+ refs.activeRequestIdRef.current = "req-B";++ // 4. Another late chunk for A arrives AFTER B opened. This is the+ // case that previously threw `Received reasoning-delta for missing+ // reasoning part with ID "rA"` in the SDK parser.+ const stale = routeIncomingChatChunk(+ makeChunk({+ messageId: "req-A",+ content: {+ type: "reasoning-delta",+ id: "rA",+ delta: "still leaking",+ },+ }),+ refs,+ );+ expect(stale).toBe("dropped-stale");+ expect(controllerB.enqueue).not.toHaveBeenCalled();++ // 5. B's own chunks flow normally.+ routeIncomingChatChunk(+ makeChunk({+ messageId: "req-B",+ content: { type: "reasoning-start", id: "rB" },+ }),+ refs,+ );+ routeIncomingChatChunk(+ makeChunk({+ messageId: "req-B",+ content: { type: "reasoning-delta", id: "rB", delta: "fresh" },+ }),+ refs,+ );+ expect(controllerB.enqueue).toHaveBeenCalledTimes(2);+ },+ );++ it("enqueues content alongside is_final and then closes", () => {+ // Sanity: a single chunk that carries both `content` and `is_final` (rare+ // but legal — backend may bundle final content with the terminator)+ // should enqueue then close.+ const refs = makeRefs();+ const controller = makeMockController();+ refs.controllerRef.current = controller;+ refs.activeRequestIdRef.current = "req-A";++ const chunk = { type: "text-delta", id: "t1", delta: "bye" } as const;+ const result = routeIncomingChatChunk(+ makeChunk({ messageId: "req-A", content: chunk, isFinal: true }),+ refs,+ );++ expect(result).toBe("closed");+ expect(controller.enqueue).toHaveBeenCalledWith(chunk);+ expect(controller.close).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/plugins/impl/chat/chat-ui.tsx b/frontend/src/plugins/impl/chat/chat-ui.tsxindex 77e117cab6..f4fabb3b8d 100644--- a/frontend/src/plugins/impl/chat/chat-ui.tsx+++ b/frontend/src/plugins/impl/chat/chat-ui.tsx@@ -20,13 +20,17 @@ import {RotateCwIcon,SendHorizontalIcon,SettingsIcon,+ SquareIcon,Trash2Icon,X,} from "lucide-react";import React, { useEffect, useRef, useState } from "react";import { z } from "zod";import { renderUIMessage } from "@/components/chat/chat-display";-import { convertToFileUIPart } from "@/components/chat/chat-utils";+import {+ convertToFileUIPart,+ hasPendingToolCalls,+} from "@/components/chat/chat-utils";import {type AdditionalCompletions,PromptInput,@@ -60,6 +64,7 @@ import { cn } from "@/utils/cn";import { Logger } from "@/utils/Logger";import { Objects } from "@/utils/objects";import { Strings } from "@/utils/strings";+import { generateUUID } from "@/utils/uuid";import { ErrorBanner } from "../common/error-banner";import type { PluginFunctions } from "./ChatPlugin";import type { ChatConfig } from "./types";@@ -86,6 +91,48 @@ const ChatMessageIncomingSchema = z.object({is_final: z.boolean().optional(),});+type ChatMessageIncoming = z.infer<typeof ChatMessageIncomingSchema>;++export interface IncomingChatChunkRefs {+ controllerRef: {+ current: ReadableStreamDefaultController<UIMessageChunk> | null;+ };+ activeRequestIdRef: { current: string | null };+}++/**+ * Route a single incoming chunk to the active stream controller, dropping it+ * if it belongs to a stale (aborted-but-not-yet-cancelled) backend run.+ */+export function routeIncomingChatChunk(+ message: ChatMessageIncoming,+ refs: IncomingChatChunkRefs,+): "enqueued" | "closed" | "dropped-no-controller" | "dropped-stale" {+ const { controllerRef, activeRequestIdRef } = refs;+ const controller = controllerRef.current;+ if (controller === null) {+ return "dropped-no-controller";+ }+ const activeRequestId = activeRequestIdRef.current;+ if (activeRequestId !== null && message.message_id !== activeRequestId) {+ Logger.debug("Dropping stale chat chunk", {+ chunkRequestId: message.message_id,+ activeRequestId,+ });+ return "dropped-stale";+ }+ if (message.content) {+ controller.enqueue(message.content);+ }+ if (message.is_final) {+ controller.close();+ controllerRef.current = null;+ activeRequestIdRef.current = null;+ return "closed";+ }+ return "enqueued";+}+export const Chatbot: React.FC<Props> = (props) => {const [input, setInput] = useState("");const [config, setConfig] = useState<ChatConfig>(props.config);@@ -113,16 +160,15 @@ export const Chatbot: React.FC<Props> = (props) => {const configRef = useRef<ChatConfig>(config);configRef.current = config;- // Track streaming state - maps backend message_id to frontend message index- const streamingStateRef = useRef<{- backendMessageId: string | null;- frontendMessageIndex: number | null;- }>({ backendMessageId: null, frontendMessageIndex: null });-// For frontend-managed streaming, create a controller to enqueue chunks to.const frontendStreamControllerRef =useRef<ReadableStreamDefaultController<UIMessageChunk> | null>(null);+ // The request_id of the currently-active prompt run. Chunks arriving with a+ // different message_id are stale (from an aborted-but-not-yet-cancelled run+ // on the kernel) and must be dropped+ const activeRequestIdRef = useRef<string | null>(null);+const { data: backendMessages } = useAsyncData(async () => {const response = await props.get_chat_history({});return response.messages;@@ -143,7 +189,9 @@ export const Chatbot: React.FC<Props> = (props) => {error,regenerate,clearError,+ addToolApprovalResponse,} = useChat({+ sendAutomaticallyWhen: ({ messages }) => hasPendingToolCalls(messages),transport: new DefaultChatTransport({fetch: async (request: RequestInfo | URL,@@ -180,17 +228,33 @@ export const Chatbot: React.FC<Props> = (props) => {};});+ // Client-generated id used to (a) route chunks back to this stream+ // and (b) ask the kernel to cancel just this run on Stop.+ const requestId = generateUUID();+const stream = new ReadableStream<UIMessageChunk>({start(controller) {frontendStreamControllerRef.current = controller;+ activeRequestIdRef.current = requestId;const abortHandler = () => {+ // Close the local controller first so the chat status flips to+ // "ready" immediately and any racing chunks are dropped; then+ // fire-and-forget the backend cancel so the kernel stops the+ // model and we don't waste tokens / leak chunks to the next+ // run.try {controller.close();} catch (error) {Logger.debug("Controller may already be closed", { error });}frontendStreamControllerRef.current = null;+ activeRequestIdRef.current = null;+ void props+ .cancel_prompt({ request_id: requestId })+ .catch((error: Error) => {+ Logger.debug("cancel_prompt failed", { error });+ });};signal?.addEventListener("abort", abortHandler);@@ -200,28 +264,25 @@ export const Chatbot: React.FC<Props> = (props) => {},cancel() {frontendStreamControllerRef.current = null;+ activeRequestIdRef.current = null;},});// Start the prompt, chunks will be sent via eventsvoid props.send_prompt({+ request_id: requestId,messages: messages,config: chatConfig,}).catch((error: Error) => {frontendStreamControllerRef.current?.error(error);frontendStreamControllerRef.current = null;+ activeRequestIdRef.current = null;});return createUIMessageStreamResponse({ stream });} catch (error: unknown) {- // Clear streaming state on error- streamingStateRef.current = {- backendMessageId: null,- frontendMessageIndex: null,- };-// Handle abort gracefully without showing an errorif (error instanceof Error && error.name === "AbortError") {return new Response("Aborted", { status: 499 });@@ -244,21 +305,10 @@ export const Chatbot: React.FC<Props> = (props) => {}Logger.debug("Finished streaming message:", message);- // Clear streaming state- streamingStateRef.current = {- backendMessageId: null,- frontendMessageIndex: null,- };-props.setValue(message.messages);},onError: (error) => {Logger.error("An error occurred:", error);- // Clear streaming state on error- streamingStateRef.current = {- backendMessageId: null,- frontendMessageIndex: null,- };},});@@ -273,23 +323,10 @@ export const Chatbot: React.FC<Props> = (props) => {if (!parsedMessage.success) {return;}- const message = parsedMessage.data;-- // Push to the stream for useChat to process- const controller = frontendStreamControllerRef.current;- if (!controller) {- return;- }-- if (message.content) {- controller.enqueue(message.content);- }- if (message.is_final) {- controller.close();- frontendStreamControllerRef.current = null;- }-- return;+ routeIncomingChatChunk(parsedMessage.data, {+ controllerRef: frontendStreamControllerRef,+ activeRequestIdRef,+ });},);@@ -408,6 +445,9 @@ export const Chatbot: React.FC<Props> = (props) => {message,isStreamingReasoning: status === "streaming",isLast,+ addToolApprovalResponse: isLast+ ? addToolApprovalResponse+ : undefined,})}</div><div className="flex justify-end text-xs gap-2 invisible group-hover:visible">@@ -429,16 +469,8 @@ export const Chatbot: React.FC<Props> = (props) => {})}{isLoading && (- <div className="flex items-center justify-center space-x-2 mb-4">+ <div className="flex items-center justify-center mb-4"><Spinner size="small" />- <Button- variant="link"- size="sm"- onClick={() => stop()}- className="text-(--red-9) hover:text-(--red-11)"- >- Stop- </Button></div>)}@@ -569,15 +601,30 @@ export const Chatbot: React.FC<Props> = (props) => {/></>)}- <Button- type="submit"- disabled={isLoading || !input}- variant="outline"- size="xs"- className="text-(--slate-11)"- >- <SendHorizontalIcon className="h-4 w-4" />- </Button>+ {isLoading ? (+ <Tooltip content="Stop generating">+ <Button+ type="button"+ variant="link"+ size="xs"+ onClick={() => stop()}+ className="text-(--red-9) hover:text-(--red-11)"+ >+ <SquareIcon className="h-4 w-4 fill-current" />+ </Button>+ </Tooltip>+ ) : (+ <Button+ type="submit"+ disabled={!input}+ variant="outline"+ size="xs"+ className="text-(--slate-11)"+ aria-label="Send message"+ >+ <SendHorizontalIcon className="h-4 w-4" />+ </Button>+ )}</form></div>);diff --git a/frontend/src/plugins/impl/chat/types.ts b/frontend/src/plugins/impl/chat/types.tsindex 28392fd528..c2afebf92a 100644--- a/frontend/src/plugins/impl/chat/types.ts+++ b/frontend/src/plugins/impl/chat/types.ts@@ -22,6 +22,11 @@ export interface ChatConfig {}export interface SendMessageRequest {+ request_id: string;messages: ChatMessage[];config: ChatConfig;}++export interface CancelPromptRequest {+ request_id: string;+}diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.pyindex 3fe7b6507b..198195a62d 100644--- a/marimo/_ai/_convert.py+++ b/marimo/_ai/_convert.py@@ -164,8 +164,13 @@ def convert_to_openai_messages(# Reset parts since we've added the messagescurrent_parts = []- else:+ elif dataclasses.is_dataclass(part) and not isinstance(part, type):current_parts.append(dataclasses.asdict(part)) # type: ignore+ else:+ LOGGER.debug(+ "Dropping unsupported part %s during OpenAI conversion",+ type(part).__name__,+ )if current_parts:openai_messages.append(diff --git a/marimo/_ai/_pydantic_ai_utils.py b/marimo/_ai/_pydantic_ai_utils.pyindex c1653ad21d..2b37f7e0e2 100644--- a/marimo/_ai/_pydantic_ai_utils.py+++ b/marimo/_ai/_pydantic_ai_utils.py@@ -98,7 +98,7 @@ def convert_to_pydantic_messages(or generate_id("message"))role = message.get("role", "assistant")- parts = [_sanitize_part(part) for part in message.get("parts", [])]+ parts = [sanitize_part(part) for part in message.get("parts", [])]metadata = message.get("metadata")ui_message = UIMessage(@@ -147,7 +147,7 @@ def _tool_part_allowed_fields() -> dict[tuple[bool, str], frozenset[str]]:return result-def _sanitize_part(part: Any) -> Any:+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 }`, whichdiff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.pyindex a179e07b54..56fa50c560 100644--- a/marimo/_ai/_types.py+++ b/marimo/_ai/_types.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport abcimport mimetypes-from collections.abc import Iteratorfrom dataclasses import asdict, dataclass, is_dataclassfrom typing import TYPE_CHECKING, Any, Literal, TypedDict, cast@@ -11,7 +10,6 @@ import msgspecfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager-from marimo._utils.dicts import remove_none_valuesfrom marimo._utils.parse_dataclass import parse_rawLOGGER = _loggers.marimo_logger()@@ -169,6 +167,8 @@ class StepStartPart:if TYPE_CHECKING:from collections.abc import Iterator+ from pydantic_ai.ui.vercel_ai.request_types import UIMessagePart+ChatPart = (TextPart| ReasoningPart@@ -190,7 +190,7 @@ PART_TYPES = []-class ChatMessage(msgspec.Struct):+class ChatMessage(msgspec.Struct, dict=True):"""A message in a chat."""@@ -215,44 +215,89 @@ class ChatMessage(msgspec.Struct):metadata: Any | None = Nonedef __post_init__(self) -> None:- # Hack: msgspec only supports discriminated unions. This is a hack to just- # iterate through possible part variants and decode until one works.- if self.parts:- parts = []- for part in self.parts:- if converted := self._convert_part(part):- parts.append(converted)- self.parts = parts+ # Non-struct attribute (via `dict=True`) so it isn't serialized.+ # Snapshots raw dict inputs 1:1 with `self.parts` so SDK fields the+ # typed dataclasses don't model survive the round-trip.+ self._raw_parts: list[dict[str, Any] | None] | None = None+ if not self.parts:+ return+ snapshots: list[dict[str, Any] | None] = []+ typed: list[ChatPart] = []+ for part in self.parts:+ converted = self._convert_part(part)+ if converted is None:+ continue+ snapshots.append(+ cast(dict[str, Any], part) if isinstance(part, dict) else None+ )+ typed.append(converted)+ if any(s is not None for s in snapshots):+ self._raw_parts = snapshots+ self.parts = typeddef _convert_part(self, part: Any) -> ChatPart | None:- # If we receive a Vercel AI SDK part (through pydantic-ai), return it as is.if DependencyManager.pydantic_ai.imported():from pydantic_ai.ui.vercel_ai.request_types import UIMessagePartif isinstance(part, UIMessagePart):return cast(ChatPart, part)- PartType = None- for PartType in PART_TYPES:- try:- if is_dataclass(part):- return cast(ChatPart, part)- return parse_raw(part, cls=PartType, allow_unknown_keys=True)- except Exception:- continue+ if is_dataclass(part) and not isinstance(part, type):+ return cast(ChatPart, part)++ # Unknown dicts pass through verbatim so future SDK part types still+ # round-trip.+ if isinstance(part, dict):+ for PartType in PART_TYPES:+ try:+ return parse_raw(+ part, cls=PartType, allow_unknown_keys=True+ )+ except Exception:+ continue+ return cast(ChatPart, part)- LOGGER.debug(- f"Could not decode part {part}. Ignore if it's a Vercel UI message part."- )+ LOGGER.debug("Dropping unrecognized part %r", part)return None+ def raw_or_dumped_parts(self) -> list[dict[str, Any]]:+ """Return parts in dict form, preferring the original wire payload."""+ ui_message_part_cls: type[UIMessagePart] | None = None+ if DependencyManager.pydantic_ai.imported():+ from pydantic_ai.ui.vercel_ai.request_types import UIMessagePart++ # `UIMessagePart` is a union type alias; the runtime value works+ # with `isinstance` but doesn't match `type[...]` statically.+ ui_message_part_cls = UIMessagePart # type: ignore[assignment] # pyright: ignore[reportAssignmentType]++ def dump(part: Any) -> dict[str, Any] | None:+ if is_dataclass(part) and not isinstance(part, type):+ return asdict(part)+ if ui_message_part_cls is not None and isinstance(+ part, ui_message_part_cls+ ):+ return part.model_dump(by_alias=True, exclude_none=True) # type: ignore[no-any-return]+ if isinstance(part, dict):+ return cast(dict[str, Any], part)+ return None++ raws = self._raw_parts+ result: list[dict[str, Any]] = []+ for i, part in enumerate(self.parts):+ snap = raws[i] if raws is not None and i < len(raws) else None+ if snap is not None:+ result.append(snap)+ elif (d := dump(part)) is not None:+ result.append(d)+ return result+def __iter__(self) -> Iterator[tuple[str, Any]]:"""Allow dict(message) to build the serialized dict."""out: ChatMessageDict = {"role": self.role,"id": self.id,"content": self.content,- "parts": [cast(ChatPartDict, asdict(part)) for part in self.parts],+ "parts": cast(list[ChatPartDict], self.raw_or_dumped_parts()),"attachments": [cast(ChatAttachmentDict, asdict(a)) for a in self.attachments]@@ -278,12 +323,16 @@ class ChatMessage(msgspec.Struct):"""if part_validator_class:+ # Lazy import: `_pydantic_ai_utils` pulls in `marimo._server.*`,+ # which we don't want to load just to define the types module.+ from marimo._ai._pydantic_ai_utils import sanitize_part+validated_parts = []for part in parts:if isinstance(part, part_validator_class):validated_parts.append(part)elif isinstance(part, dict):- sanitized_part = remove_none_values(part)+ sanitized_part = sanitize_part(part)# Try pydantic validation for dict -> class conversiontry:from pydantic import TypeAdapterdiff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex c3980af68f..6d838c94cf 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -1,16 +1,14 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import dataclassesimport jsonimport osimport refrom typing import TYPE_CHECKING, Any, castfrom marimo import _loggers-from marimo._ai._pydantic_ai_utils import generate_id+from marimo._ai._pydantic_ai_utils import generate_id, sanitize_partfrom marimo._plugins.ui._impl.chat.chat import AI_SDK_VERSION, DONE_CHUNK-from marimo._utils.dicts import remove_none_valuesif TYPE_CHECKING:from collections.abc import AsyncGenerator, Callable, Generator@@ -747,18 +745,14 @@ class pydantic_ai(ChatModel):if not message.id:LOGGER.warning("Message %s has no id", message)+ # Prefer the raw wire payload when we have it so fields outside+ # marimo's lossy dataclasses (`approval`, `providerExecuted`,+ # `preliminary`, ...) survive the round-trip into pydantic-ai.parts: list[UIMessagePart] = []if message.parts:parts = cast(list[UIMessagePart],- [- self._remove_none_values(- dataclasses.asdict(part)- if dataclasses.is_dataclass(part)- else part- )- for part in message.parts- ],+ [sanitize_part(p) for p in message.raw_or_dumped_parts()],)if not parts:if message.content is not None:@@ -784,11 +778,6 @@ class pydantic_ai(ChatModel):)return ui_messages- def _remove_none_values(self, obj: dict[str, Any]) -> dict[str, Any]:- if isinstance(obj, dict) and hasattr(obj, "items"):- return remove_none_values(obj)- return obj-def _serialize_vercel_ai_chunk(self, chunk: BaseChunk) -> dict[str, Any] | None:@@ -849,7 +838,17 @@ class pydantic_ai(ChatModel):messages=ui_messages,)- adapter = VercelAIAdapter(agent=self.agent, run_input=run_input)+ try:+ adapter = VercelAIAdapter(+ agent=self.agent,+ run_input=run_input,+ sdk_version=AI_SDK_VERSION,+ )+ except TypeError:+ adapter = VercelAIAdapter(+ agent=self.agent,+ run_input=run_input,+ )event_stream = adapter.run_stream(model_settings=model_settings)async for event in event_stream:if serialized := self._serialize_vercel_ai_chunk(event):diff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.pyindex b79d3fbf6c..556e851cb5 100644--- a/marimo/_plugins/ui/_impl/chat/chat.py+++ b/marimo/_plugins/ui/_impl/chat/chat.py@@ -1,11 +1,13 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import asyncio+import contextlibimport inspectimport jsonimport uuid-from dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Final, Literal, cast+from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, castfrom marimo import _loggersfrom marimo._ai._types import (@@ -54,6 +56,7 @@ def require_vercel_ai_sdk_support() -> None:class SendMessageRequest:messages: list[ChatMessage]config: ChatModelConfig+ request_id: str | None = None@dataclass@@ -66,6 +69,11 @@ class DeleteChatMessageRequest:index: int+@dataclass+class CancelPromptRequest:+ request_id: str++@mddocclass chat(UIElement[dict[str, Any], list[ChatMessage]]):"""A chatbot UI element for interactive conversations.@@ -170,6 +178,19 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):```Refer to examples/ai/chat/pydantic-ai-chat.py for a complete example.+ Cancellation:+ When the user clicks Stop in the UI, marimo cancels the in-flight+ model invocation. Async model code receives+ `asyncio.CancelledError` at the next `await`. Sync generators are+ closed instead, which raises `GeneratorExit` inside the generator+ rather than `CancelledError`. If your model holds resources such as+ HTTP clients, file handles, or database cursors, release them in a+ `try/finally` block so they are cleaned up promptly on cancellation;+ do not rely on catching `CancelledError` in sync generators.+ Async generators that catch and swallow `CancelledError` will not+ actually stop and may continue to consume tokens from upstream+ providers.+Attributes:value (List[ChatMessage]): The current chat history, a list of ChatMessage objects.@@ -214,6 +235,9 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):) -> None:self._model = modelself._chat_history: list[ChatMessage] = []+ # Tracks in-flight _send_prompt tasks keyed by request_id, so that+ # _cancel_prompt can interrupt the model generation cleanly.+ self._in_flight: dict[str, asyncio.Task[None]] = {}if config is None:config = DEFAULT_CONFIG@@ -255,6 +279,11 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):arg_cls=SendMessageRequest,function=self._send_prompt,),+ Function(+ name="cancel_prompt",+ arg_cls=CancelPromptRequest,+ function=self._cancel_prompt,+ ),),)@@ -290,7 +319,12 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):buffers=None,)- async def _handle_streaming_response(self, response: Any) -> None:+ async def _handle_streaming_response(+ self,+ response: Any,+ *,+ message_id: str | None = None,+ ) -> None:"""Handle streaming from both sync and async generators, and lists.Generators should yield delta chunks (new content only), which this@@ -298,8 +332,13 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):This follows the standard streaming pattern used by OpenAI, Anthropic,and other AI providers. For frontend-managed streaming, the response is set on the frontend,so we don't need to return anything. If generators just yield strings, we update the chat history with the accumulated text.++ On cancellation, any open text/reasoning blocks are closed and a final+ chunk is emitted so the frontend stream tears down cleanly, then the+ CancelledError propagates."""- message_id = str(uuid.uuid4())+ if message_id is None:+ message_id = str(uuid.uuid4())def send_chunk(chunk: dict[str, Any]) -> None:self._send_chat_message(@@ -313,16 +352,42 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):response)- if inspect.isasyncgen(response):- async for delta in response:- if isinstance(delta, str):- accumulated_text += delta- serializer.handle_chunk(delta)- else:- for delta in response:- if isinstance(delta, str):- accumulated_text += delta- serializer.handle_chunk(delta)+ try:+ if inspect.isasyncgen(response):+ async for delta in response:+ if isinstance(delta, str):+ accumulated_text += delta+ serializer.handle_chunk(delta)+ else:+ for delta in response:+ if isinstance(delta, str):+ accumulated_text += delta+ serializer.handle_chunk(delta)+ # Yield to the event loop so cancellation can propagate+ # promptly into sync generators that don't await.+ await asyncio.sleep(0)+ except asyncio.CancelledError:+ # Close any open blocks on the wire so the frontend parser doesn't+ # see dangling text-delta / reasoning-delta chunks. Best-effort;+ # the frontend may have already torn down its controller.+ try:+ self._emit_cancellation_chunks(+ serializer=serializer, message_id=message_id+ )+ except Exception:+ LOGGER.debug(+ "Failed to emit cancellation chunks", exc_info=True+ )+ # Explicitly close the user-supplied generator so cleanup blocks+ # (HTTP sockets, file handles, try/finally in user code) run+ # promptly rather than waiting on GC finalizers.+ if inspect.isasyncgen(response):+ with contextlib.suppress(Exception):+ await response.aclose()+ elif inspect.isgenerator(response):+ with contextlib.suppress(Exception):+ response.close()+ raise# Generators that yield strings should update the 'content' field of the assistant messageif accumulated_text and is_generator:@@ -339,6 +404,51 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):is_final=True,)+ def _emit_cancellation_chunks(+ self,+ *,+ serializer: ChunkSerializer,+ message_id: str,+ ) -> None:+ """Close open serializer blocks and emit a final chunk on cancellation."""+ # If pydantic-ai is available, prefer the protocol's AbortChunk to+ # signal "stream cut off, anything open is incomplete".+ abort_payload: dict[str, Any] | None = None+ if DependencyManager.pydantic_ai.imported():+ try:+ require_vercel_ai_sdk_support()+ from pydantic_ai.ui.vercel_ai.response_types import (+ AbortChunk,+ )++ abort_payload = json.loads( # pyright: ignore[reportAny]+ AbortChunk(reason="user_cancelled").encode(+ sdk_version=AI_SDK_VERSION+ )+ )+ except Exception:+ LOGGER.debug(+ (+ "Could not build AbortChunk; will fall back to explicit "+ "end chunks for open blocks."+ ),+ exc_info=True,+ )++ if abort_payload is not None:+ serializer.close_open_blocks_when_cancelled()+ self._send_chat_message(+ message_id=message_id,+ content=abort_payload,+ is_final=False,+ )+ else:+ serializer.close_open_blocks_when_cancelled()++ self._send_chat_message(+ message_id=message_id, content=None, is_final=True+ )+def _update_chat_history(self, chat_history: list[ChatMessage]) -> None:self._chat_history = chat_history# The frontend doesn't manage state, so we have to manually enqueue@@ -365,6 +475,49 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):)async def _send_prompt(self, args: SendMessageRequest) -> None:+ request_id = args.request_id or str(uuid.uuid4())+ if args.request_id is None:+ LOGGER.debug(+ (+ "send_prompt received without a request_id; "+ "generated %s server-side."+ ),+ request_id,+ )++ task = asyncio.create_task(self._run_prompt(request_id, args))+ self._in_flight[request_id] = task+ try:+ await task+ except asyncio.CancelledError:+ # Note: if both `_cancel_prompt` and an outer kernel cancellation+ # fire near-simultaneously, we'll take the `pass` branch and the+ # outer cancel is effectively lost. That's acceptable in practice+ # because kernel shutdown tears the whole event loop down anyway.+ if task.done() and task.cancelled():+ # Inner task was cancelled (typically via _cancel_prompt).+ # The user-visible Stop happened; complete the RPC normally.+ pass+ else:+ # Outer task was cancelled (e.g., kernel shutdown). Make sure+ # the inner task is cleaned up, then propagate the cancel.+ if not task.done():+ task.cancel()+ with contextlib.suppress(BaseException):+ await task+ raise+ finally:+ self._in_flight.pop(request_id, None)++ async def _cancel_prompt(self, args: CancelPromptRequest) -> None:+ """Cancel an in-flight prompt by request_id. No-op if already done."""+ task = self._in_flight.get(args.request_id)+ if task is not None and not task.done():+ task.cancel()++ async def _run_prompt(+ self, request_id: str, args: SendMessageRequest+ ) -> None:messages = args.messagesself._chat_history = messages@@ -384,7 +537,9 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):if inspect.isasyncgen(response) or inspect.isgenerator(response):# We support functions that stream the response with generators# (both sync and async)- await self._handle_streaming_response(response)+ await self._handle_streaming_response(+ response, message_id=request_id+ )# For streaming, we don't have a final response string to add to history# The frontend will add the accumulated messagereturn@@ -398,7 +553,9 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):response if isinstance(response, str) else as_html(response).text)- await self._handle_streaming_response([response_str])+ await self._handle_streaming_response(+ [response_str], message_id=request_id+ )# Update the chat history to trigger UI updates and on_message callbackself._add_assistant_message_to_chat_history(response, response_str)@@ -468,7 +625,20 @@ class chat(UIElement[dict[str, Any], list[ChatMessage]]):@dataclassclass ChunkSerializer:on_send_chunk: Callable[[dict[str, Any]], None]+ # Id of the implicit text block synthesized for plain-string yields._text_id: str | None = None+ # Open block id -> kind, for blocks we've seen a `*-start` for but not+ # yet a `*-end`. Drained on end-of-stream and on cancellation.+ _open_blocks: dict[str, str] = field(default_factory=dict)++ # The AI SDK UI parser holds parts in `state: "streaming"` until a+ # matching `*-end` arrives — without one the part renders as still+ # in-progress. These are the only block kinds with that property in+ # [email protected]; others either use a different lifecycle (e.g. tool-input+ # pairs with tool-output-available/-error and keys on `toolCallId`)+ # or are single-chunk events (file, source-url, data-*). Don't extend+ # without checking the SDK parser.+ _BLOCK_KINDS: ClassVar[tuple[str, ...]] = ("text", "reasoning")def handle_chunk(self, chunk: Any) -> None:"""Handle a Vercel AI SDK chunk"""@@ -484,6 +654,7 @@ class ChunkSerializer:serialized = json.loads(chunk.encode(sdk_version=AI_SDK_VERSION))+ self._track_block_state(serialized)self.on_send_chunk(serialized)return@@ -493,15 +664,56 @@ class ChunkSerializer:chunk = str(chunk)if self._text_id is None:self._text_id = f"text_{uuid.uuid4().hex}"+ self._open_blocks[self._text_id] = "text"self.on_send_chunk({"type": "text-start", "id": self._text_id})self.on_send_chunk({"type": "text-delta", "id": self._text_id, "delta": chunk})return+ # Track block lifecycle for plain dict chunks before forwarding.+ if isinstance(chunk, dict):+ self._track_block_state(chunk)+# Otherwise, we return the chunk as isself.on_send_chunk(chunk)def on_end(self) -> None:- if self._text_id is not None:- self.on_send_chunk({"type": "text-end", "id": self._text_id})+ """Drain blocks still open at successful end-of-stream. Propagate exceptions."""+ self._drain_open_blocks(suppress_errors=False)++ def close_open_blocks_when_cancelled(self) -> None:+ self._drain_open_blocks(suppress_errors=True)++ def _drain_open_blocks(self, *, suppress_errors: bool) -> None:+ # Iterate over a copy since we mutate _open_blocks as we go.+ for block_id, kind in list(self._open_blocks.items()):+ end_chunk = {"type": f"{kind}-end", "id": block_id}+ if suppress_errors:+ try:+ self.on_send_chunk(end_chunk)+ except Exception:+ LOGGER.debug(+ "Failed to emit %s for open block id=%s during drain",+ end_chunk["type"],+ block_id,+ exc_info=True,+ )+ else:+ self.on_send_chunk(end_chunk)+ self._open_blocks.pop(block_id, None)+ self._text_id = None++ def _track_block_state(self, chunk: dict[str, Any]) -> None:+ """Update _open_blocks based on a passing dict chunk's type."""+ chunk_type = chunk.get("type")+ chunk_id = chunk.get("id")+ if not isinstance(chunk_type, str) or not isinstance(chunk_id, str):+ return+ for kind in self._BLOCK_KINDS:+ if chunk_type == f"{kind}-start":+ self._open_blocks[chunk_id] = kind+ return+ if chunk_type == f"{kind}-end":+ self._open_blocks.pop(chunk_id, None)+ returndiff --git a/tests/_ai/llm/test_impl.py b/tests/_ai/llm/test_impl.pyindex 6b23b74c55..9a84c7233d 100644--- a/tests/_ai/llm/test_impl.py+++ b/tests/_ai/llm/test_impl.py@@ -3,7 +3,7 @@from __future__ import annotationsimport os-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, castfrom unittest.mock import MagicMock, patchimport pytest@@ -20,8 +20,11 @@ from marimo._ai.llm._impl import (simple,)from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.ui._impl.chat.chat import AI_SDK_VERSIONif TYPE_CHECKING:+ from collections.abc import AsyncIterator+from pydantic_ai.settings import ModelSettings@@ -1410,6 +1413,9 @@ class TestPydanticAI:{"id": "2", "type": "text-delta", "delta": " World"},]+ _, kwargs = mock_adapter.call_args+ assert kwargs.get("sdk_version") == AI_SDK_VERSION+async def test_stream_text(self):"""Test _stream_text streams text from the model."""mock_agent = MagicMock()@@ -1597,6 +1603,137 @@ class TestPydanticAI:result = model._serialize_vercel_ai_chunk(cast(Any, error_chunk))assert result is None+ def test_build_ui_messages_preserves_tool_approval_field(self):+ """When the frontend posts back an `approval-responded` tool part,+ the `approval` payload must reach pydantic-ai intact. The lossy+ `ToolInvocationPart` dataclass doesn't model `approval`, so without+ the `_raw_parts` snapshot the field would be silently dropped and+ the agent would loop on the same tool call forever.++ Regression for the second half of the tool-approval fix: the first+ half (`sdk_version=AI_SDK_VERSION`) made the request chunk visible+ to the frontend; this half makes the user's response visible to the+ agent.+ """+ from pydantic_ai.ui.vercel_ai.request_types import (+ ToolApprovalResponded,+ ToolApprovalRespondedPart,+ )++ model = pydantic_ai(MagicMock())+ messages = [+ ChatMessage(+ role="user",+ content="Delete secrets.env",+ id="msg-user-1",+ parts=cast( # pyright: ignore[reportAny]+ Any,+ [{"type": "text", "text": "Delete secrets.env"}],+ ),+ ),+ ChatMessage(+ role="assistant",+ content=None,+ id="msg-assistant-1",+ parts=cast( # pyright: ignore[reportAny]+ Any,+ [+ {+ "type": "tool-delete_file",+ "toolCallId": "call-1",+ "state": "approval-responded",+ "input": {"path": "secrets.env"},+ "approval": {+ "id": "call-1",+ "approved": True,+ },+ }+ ],+ ),+ ),+ ]++ ui_messages = model._build_ui_messages(messages)+ assert len(ui_messages) == 2++ # The tool part must be reified as the *responded* variant — the+ # one that carries the approval — and the approval must survive.+ tool_part = ui_messages[1].parts[0]+ assert isinstance(tool_part, ToolApprovalRespondedPart), (+ f"Expected ToolApprovalRespondedPart, got {type(tool_part).__name__}: "+ f"{tool_part!r}"+ )+ approval = tool_part.approval+ assert isinstance(approval, ToolApprovalResponded), (+ f"Expected ToolApprovalResponded, got {approval!r}"+ )+ assert approval.id == "call-1"+ assert approval.approved is True++ async def test_stream_response_emits_tool_approval_request(self):+ """Tools with `requires_approval=True` should surface an+ approval-request chunk so the frontend can render an Approve/Deny+ card. This is the v6-only behavior unlocked by passing+ `sdk_version=AI_SDK_VERSION` to the adapter.+ """+ from pydantic_ai import Agent, DeferredToolRequests+ from pydantic_ai.models.function import (+ AgentInfo,+ DeltaToolCall,+ DeltaToolCalls,+ FunctionModel,+ )++ async def respond(+ messages: list[Any], _info: AgentInfo+ ) -> AsyncIterator[DeltaToolCalls]:+ del messages, _info+ yield {+ 0: DeltaToolCall(+ name="delete_file",+ json_args='{"path": "secrets.env"}',+ tool_call_id="call-1",+ )+ }++ agent = Agent(+ FunctionModel(stream_function=respond),+ output_type=[str, DeferredToolRequests],+ )++ @agent.tool_plain(requires_approval=True)+ def delete_file(path: str) -> str:+ return f"File {path!r} deleted"++ model = pydantic_ai(agent)+ messages = [+ ChatMessage(+ role="user",+ content="Delete secrets.env",+ id="msg-user-1",+ parts=[TextPart(type="text", text="Delete secrets.env")],+ ),+ ]+ config = ChatModelConfig(max_tokens=100)++ chunks = [+ chunk async for chunk in model._stream_response(messages, config)+ ]++ approval_chunks = [+ chunk+ for chunk in chunks+ if chunk.get("type") == "tool-approval-request"+ ]+ # Older pydantic-ai generates a UUID approvalId; newer versions reuse+ # toolCallId. Either is fine — assert the shape, not the exact value.+ assert len(approval_chunks) == 1+ chunk = approval_chunks[0]+ assert chunk["type"] == "tool-approval-request"+ assert chunk["toolCallId"] == "call-1"+ assert isinstance(chunk["approvalId"], str)+ assert chunk["approvalId"]+class MockBaseChunkWithError:"""Mock BaseChunk that raises on serialization."""diff --git a/tests/_ai/test_ai_types.py b/tests/_ai/test_ai_types.pyindex 2f262bd5b2..4724750610 100644--- a/tests/_ai/test_ai_types.py+++ b/tests/_ai/test_ai_types.py@@ -473,7 +473,11 @@ class TestChatMessagePostInit:assert message.parts[0] is text_partdef test_handles_invalid_parts_gracefully(self):- """Test that invalid parts are dropped gracefully."""+ """Unknown dict parts don't crash construction; they're preserved+ verbatim so future SDK part types still round-trip on serialization.+ See `test_raw_part_round_trips_verbatim` for the contract.+ """+ raw_unknown = {"type": "unknown_type", "data": "invalid"}message = ChatMessage(role="user",content="Hello",@@ -481,17 +485,19 @@ class TestChatMessagePostInit:Any,[{"type": "text", "text": "Valid"},- {"type": "unknown_type", "data": "invalid"},+ raw_unknown,],),)- # Valid part should be kept, invalid should be dropped- assert message == ChatMessage(- role="user",- content="Hello",- parts=[TextPart(type="text", text="Valid")],- )+ assert len(message.parts) == 2+ assert isinstance(message.parts[0], TextPart)+ assert message.parts[0].text == "Valid"+ assert message.parts[1] == raw_unknown+ assert message.raw_or_dumped_parts() == [+ {"type": "text", "text": "Valid"},+ raw_unknown,+ ]def test_with_none_parts(self):"""Test that None parts is handled."""@@ -546,3 +552,129 @@ class TestChatMessageDict:],"metadata": None,}+++class TestChatMessageRawPartsRoundTrip:+ """`ChatMessage` must snapshot raw wire payloads so we don't drop AI+ SDK fields the typed dataclasses don't model (e.g. `approval`,+ `callProviderMetadata`). Without this the pydantic-ai bridge would+ lose context on every deferred tool run.+ """++ def test_typed_input_does_not_snapshot(self):+ """Typed parts are themselves the source of truth — no snapshot."""+ message = ChatMessage(+ role="user",+ content="hi",+ id="msg",+ parts=[TextPart(type="text", text="hi")],+ )+ assert message._raw_parts is None+ assert dict[str, Any](message)["parts"] == [+ {"type": "text", "text": "hi"}+ ]++ def test_equality_ignores_raw_parts(self):+ """Equality compares value, not cache state."""+ from_dict = ChatMessage(+ role="user",+ content="hi",+ id="msg",+ parts=[cast(ChatPart, {"type": "text", "text": "hi"})],+ )+ from_typed = ChatMessage(+ role="user",+ content="hi",+ id="msg",+ parts=[TextPart(type="text", text="hi")],+ )+ assert from_dict._raw_parts is not None+ assert from_typed._raw_parts is None+ assert from_dict == from_typed++ @pytest.mark.parametrize(+ "raw",+ [+ # Tool part carrying fields marimo's dataclass doesn't model —+ # this is the case that motivated `_raw_parts` in the first place.+ {+ "type": "tool-delete_file",+ "toolCallId": "call-1",+ "state": "approval-responded",+ "input": {"path": "secrets.env"},+ "approval": {"id": "call-1", "approved": True},+ "callProviderMetadata": {"openai": {"foo": "bar"}},+ },+ # Alternate tool shape.+ {+ "type": "dynamic-tool",+ "toolName": "delete_file",+ "toolCallId": "call-1",+ "state": "input-streaming",+ },+ # Non-tool part with its own bag of optional fields.+ {+ "type": "file",+ "mediaType": "image/png",+ "url": "data:image/png;base64,abc",+ },+ # `data-*` parts are user-defined; the type string itself+ # carries information and must survive the round-trip.+ {+ "type": "data-reasoning-signature",+ "data": {"signature": "x"},+ },+ ],+ )+ def test_raw_part_round_trips_verbatim(self, raw: dict[str, Any]):+ """`dict(ChatMessage(parts=[raw]))["parts"]` must equal `[raw]`."""+ message = ChatMessage(+ role="assistant",+ content=None,+ id="msg",+ parts=[cast(ChatPart, raw)],+ )+ assert dict[str, Any](message)["parts"] == [raw]+ assert message._raw_parts == [raw]++ def test_mixed_dict_and_typed_parts_preserve_raw_dicts(self):+ """When `parts` mixes raw dicts and typed inputs, the raw dicts'+ unmodeled fields (e.g. `approval`) must survive — not just the+ all-dicts case.+ """+ raw = {+ "type": "tool-delete_file",+ "toolCallId": "call-1",+ "state": "approval-responded",+ "input": {"path": "secrets.env"},+ "approval": {"id": "call-1", "approved": True},+ }+ message = ChatMessage(+ role="assistant",+ content=None,+ id="msg",+ parts=[+ cast(ChatPart, raw),+ TextPart(type="text", text="ok"),+ ],+ )+ assert message.raw_or_dumped_parts() == [+ raw,+ {"type": "text", "text": "ok"},+ ]++ def test_dict_part_appended_after_init_is_preserved(self):+ message = ChatMessage(+ role="assistant",+ content=None,+ id="msg",+ parts=[TextPart(type="text", text="hi")],+ )+ assert message._raw_parts is None++ extra = {"type": "data-custom", "data": {"k": "v"}}+ message.parts.append(cast(ChatPart, extra))++ dumped = message.raw_or_dumped_parts()+ assert dumped == [{"type": "text", "text": "hi"}, extra]+ assert dict[str, Any](message)["parts"] == dumpeddiff --git a/tests/_ai/test_pydantic_utils.py b/tests/_ai/test_pydantic_utils.pyindex 91a36600f9..e3b7944161 100644--- a/tests/_ai/test_pydantic_utils.py+++ b/tests/_ai/test_pydantic_utils.py@@ -9,11 +9,11 @@ import pytestpytest.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,generate_id,+ sanitize_part,)from marimo._server.ai.tools.types import ToolDefinition@@ -521,7 +521,7 @@ class TestSanitizePart:"output": "Invalid arguments for tool request_user_blessing","errorText": "boom",}- clean = _sanitize_part(stale)+ clean = sanitize_part(stale)assert "output" not in cleanassert "errorText" not in cleanassert clean["approval"] == {"id": "call_abc", "approved": True}@@ -538,7 +538,7 @@ class TestSanitizePart:"output": {"ok": True},"preliminary": False,}- clean = _sanitize_part(part)+ clean = sanitize_part(part)assert clean["output"] == {"ok": True}assert clean["preliminary"] is False@@ -551,7 +551,7 @@ class TestSanitizePart:"rawInput": {"x": 1},"errorText": "boom",}- clean = _sanitize_part(part)+ clean = sanitize_part(part)assert clean["errorText"] == "boom"assert clean["rawInput"] == {"x": 1}@@ -565,7 +565,7 @@ class TestSanitizePart:"approval": {"id": "c1", "approved": True},"output": "stale",}- clean = _sanitize_part(stale)+ clean = sanitize_part(stale)assert "output" not in cleanassert clean["toolName"] == "my_tool"@@ -584,7 +584,7 @@ class TestSanitizePart:],)def test_non_tool_parts_pass_through_unchanged(self, part):- assert _sanitize_part(part) is part+ assert sanitize_part(part) is part@pytest.mark.parametrize("part",@@ -606,7 +606,7 @@ class TestSanitizePart:],)def test_malformed_parts_pass_through_unchanged(self, part):- assert _sanitize_part(part) == part+ assert sanitize_part(part) == partclass TestConvertToPydanticMessagesSanitizes:diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.pyindex 622c66f08b..fac6d2c535 100644--- a/tests/_plugins/ui/_impl/chat/test_chat.py+++ b/tests/_plugins/ui/_impl/chat/test_chat.py@@ -15,6 +15,7 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins import uifrom marimo._plugins.ui._impl.chat.chat import (DEFAULT_CONFIG,+ CancelPromptRequest,ChunkSerializer,DeleteChatMessageRequest,SendMessageRequest,@@ -1577,3 +1578,269 @@ async def test_chat_value_multiple_exchanges():assert len(chat.value) == 4assert chat.value[2].content == "Second"assert chat.value[3].content == "Echo: Second"+++async def test_send_prompt_uses_request_id_as_message_id():+ """Chunks for a given run should be tagged with the client's request_id+ so the frontend can filter stale chunks from orphaned runs."""++ async def mock_model(messages: list[ChatMessage], config: ChatModelConfig):+ del messages, config+ yield "hello"+ yield " "+ yield "world"++ chat = ui.chat(mock_model)+ sent_messages: list[dict] = []++ def capture(message: dict, buffers): # noqa: ARG001+ sent_messages.append(message)++ chat._send_message = capture++ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="hi")],+ config=ChatModelConfig(),+ request_id="req-abc",+ )+ await chat._send_prompt(request)++ assert sent_messages, "should have sent at least one chunk"+ # Every chunk for this run must carry the request_id as its message_id.+ assert all(m["message_id"] == "req-abc" for m in sent_messages)+ # And the run must always end with a final chunk so the frontend tears down.+ assert sent_messages[-1]["is_final"] is True+++async def test_send_prompt_generates_request_id_when_missing():+ """Backwards compat: older frontends may omit request_id entirely."""++ def mock_model(+ messages: list[ChatMessage], config: ChatModelConfig+ ) -> str:+ del messages, config+ return "ok"++ chat = ui.chat(mock_model)+ sent_messages: list[dict] = []++ def capture(message: dict, buffers): # noqa: ARG001+ sent_messages.append(message)++ chat._send_message = capture++ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="hi")],+ config=ChatModelConfig(),+ )+ await chat._send_prompt(request)++ assert sent_messages, "should have sent chunks"+ # A single shared id is used across all chunks for the run.+ message_id = sent_messages[0]["message_id"]+ assert message_id # non-empty+ assert all(m["message_id"] == message_id for m in sent_messages)+++async def test_cancel_prompt_interrupts_async_generator():+ """_cancel_prompt should stop an in-flight async generator promptly and+ emit a final chunk so the frontend stream tears down cleanly."""++ started = asyncio.Event()++ async def slow_model(messages: list[ChatMessage], config: ChatModelConfig):+ del messages, config+ yield "first"+ started.set()+ # Keep yielding indefinitely (slowly) until the test cancels us.+ for i in range(1_000):+ await asyncio.sleep(0.05)+ yield f"chunk-{i}"++ chat = ui.chat(slow_model)+ sent_messages: list[dict] = []++ def capture(message: dict, buffers): # noqa: ARG001+ sent_messages.append(message)++ chat._send_message = capture++ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="hi")],+ config=ChatModelConfig(),+ request_id="req-cancel-async",+ )+ send_task = asyncio.create_task(chat._send_prompt(request))++ # Wait until the model has yielded its first chunk so the cancel races+ # against an in-flight generator, not the setup path.+ await asyncio.wait_for(started.wait(), timeout=1.0)+ await chat._cancel_prompt(+ CancelPromptRequest(request_id="req-cancel-async")+ )++ # _send_prompt should complete cleanly (CancelledError is swallowed).+ await asyncio.wait_for(send_task, timeout=1.0)++ # The run is no longer tracked.+ assert "req-cancel-async" not in chat._in_flight++ # A final chunk was emitted so the frontend stream closes.+ finals = [m for m in sent_messages if m["is_final"]]+ assert len(finals) == 1+ assert finals[0]["content"] is None or isinstance(+ finals[0]["content"], dict+ )++ # And every chunk carries the cancelled run's id (no leakage to other ids).+ assert all(m["message_id"] == "req-cancel-async" for m in sent_messages)+++async def test_cancel_prompt_interrupts_sync_generator():+ """Sync generators that yield regularly should still be cancellable+ thanks to the await asyncio.sleep(0) checkpoint in the chunk loop."""++ yielded = 0+ closed = False++ def slow_sync_model(messages: list[ChatMessage], config: ChatModelConfig):+ del messages, config+ nonlocal yielded, closed+ try:+ for i in range(1_000):+ yielded = i + 1+ yield f"chunk-{i}"+ finally:+ closed = True++ chat = ui.chat(slow_sync_model)+ sent_messages: list[dict] = []++ def capture(message: dict, buffers): # noqa: ARG001+ sent_messages.append(message)++ chat._send_message = capture++ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="hi")],+ config=ChatModelConfig(),+ request_id="req-cancel-sync",+ )+ send_task = asyncio.create_task(chat._send_prompt(request))++ # Give the task a few event-loop turns so it can yield some chunks; each+ # chunk yields control via the sleep(0) checkpoint.+ for _ in range(5):+ await asyncio.sleep(0)+ await chat._cancel_prompt(+ CancelPromptRequest(request_id="req-cancel-sync")+ )+ await asyncio.wait_for(send_task, timeout=1.0)++ # We should have stopped well before exhausting the 1000-chunk generator.+ assert yielded < 1_000+ # The user generator's finally: must have run, i.e. the generator was+ # explicitly closed and any cleanup it owns has executed.+ assert closed+ # The frontend gets a clean termination signal.+ finals = [m for m in sent_messages if m["is_final"]]+ assert len(finals) == 1+++async def test_cancel_prompt_unknown_request_id_is_noop():+ """Cancelling a request_id that isn't in flight should not error."""++ def mock_model(+ messages: list[ChatMessage], config: ChatModelConfig+ ) -> str:+ del messages, config+ return "ok"++ chat = ui.chat(mock_model)++ # Should silently no-op rather than raise.+ await chat._cancel_prompt(CancelPromptRequest(request_id="never-existed"))+++async def test_cancel_prompt_emits_reasoning_end_for_open_block():+ """If the model is mid-reasoning when cancelled, the serializer should+ close any open reasoning block so the SDK parser stays well-formed."""++ started = asyncio.Event()++ async def reasoning_model(+ messages: list[ChatMessage], config: ChatModelConfig+ ):+ del messages, config+ yield {"type": "reasoning-start", "id": "r-1"}+ yield {"type": "reasoning-delta", "id": "r-1", "delta": "thinking"}+ started.set()+ # Sleep long enough that we can cancel mid-reasoning, before any+ # `reasoning-end` is emitted by the model.+ await asyncio.sleep(5)+ yield {"type": "reasoning-end", "id": "r-1"}++ chat = ui.chat(reasoning_model)+ sent_messages: list[dict] = []++ def capture(message: dict, buffers): # noqa: ARG001+ sent_messages.append(message)++ chat._send_message = capture++ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="think")],+ config=ChatModelConfig(),+ request_id="req-reason",+ )+ send_task = asyncio.create_task(chat._send_prompt(request))++ await asyncio.wait_for(started.wait(), timeout=1.0)+ await chat._cancel_prompt(CancelPromptRequest(request_id="req-reason"))+ await asyncio.wait_for(send_task, timeout=1.0)++ # We must have emitted a reasoning-end for the open block (either as a+ # plain end chunk or as part of the AbortChunk fallback path), and a final+ # chunk to close the stream.+ types_sent = [+ m["content"].get("type") if isinstance(m["content"], dict) else None+ for m in sent_messages+ ]+ assert "reasoning-end" in types_sent+ assert sent_messages[-1]["is_final"] is True+++def test_chunk_serializer_close_open_blocks_for_dict_chunks():+ """close_open_blocks should emit `*-end` for any still-open dict block."""+ sent: list[dict] = []++ def on_send(chunk: dict):+ sent.append(chunk)++ s = ChunkSerializer(on_send_chunk=on_send)+ s.handle_chunk({"type": "reasoning-start", "id": "r-1"})+ s.handle_chunk({"type": "reasoning-delta", "id": "r-1", "delta": "a"})+ # No reasoning-end — simulate cancellation mid-stream.+ s.close_open_blocks_when_cancelled()++ assert sent[-1] == {"type": "reasoning-end", "id": "r-1"}+ # Calling again should be a no-op (bookkeeping cleared).+ before = list(sent)+ s.close_open_blocks_when_cancelled()+ assert sent == before+++def test_chunk_serializer_close_open_blocks_for_text():+ """An open text block from plain-string streaming should also close."""+ sent: list[dict] = []++ def on_send(chunk: dict):+ sent.append(chunk)++ s = ChunkSerializer(on_send_chunk=on_send)+ s.handle_chunk("partial")+ # Cancelled before on_end() — close_open_blocks should still flush text-end.+ s.close_open_blocks_when_cancelled()++ end_chunks = [c for c in sent if c.get("type") == "text-end"]+ assert len(end_chunks) == 1