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
improvement: perf improvements to AI sidebar (#3760)
Myles Scolnickc57766aa541b
diff --git a/frontend/package.json b/frontend/package.jsonindex ab15882986..0b429cc95b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -87,7 +87,7 @@"@xterm/xterm": "^5.5.0","ag-grid-community": "^32.3.3","ag-grid-react": "^32.3.3",- "ai": "^3.4.33",+ "ai": "^4.1.34","ansi_up": "^6.0.2","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -110,6 +110,7 @@"lodash-es": "^4.17.21","lucide-react": "^0.474.0","lz-string": "^1.5.0",+ "marked": "^15.0.7","mermaid": "^11.4.1","partysocket": "1.0.3","path-to-regexp": "^8.2.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 2f34d0b6f4..bff2bdeaec 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -238,8 +238,8 @@ importers:specifier: ^32.3.3ai:- specifier: ^3.4.33+ specifier: ^4.1.34+ version: 4.1.34([email protected])([email protected])ansi_up:specifier: ^6.0.2version: 6.0.2@@ -306,6 +306,9 @@ importers:lz-string:specifier: ^1.5.0version: 1.5.0+ marked:+ specifier: ^15.0.7+ version: 15.0.7mermaid:specifier: ^11.4.1version: 11.4.1@@ -602,8 +605,8 @@ packages:'@adobe/[email protected]':resolution: {integrity: sha512-Ff9+ksdQQB3rMncgqDK78uLznstjyfIf2Arnh22pW8kBpLs6rpKDwgnZT46hin5Hl1WzazzK64DOrhSwYpS7bQ==}- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-YHK2rpj++wnLVc9vPGzGFP3Pjeld2MwhKinetA0zKXOoHAT/Jit5O8kZsxcSlJPu9wvcGT1UGZEjZrtO7PfFOQ==}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-Pfyaj0QZS22qyVn5Iz7IXcJ8nKIKlu2MeSAdKJzTwkAks7zdLaKVB+396Rqcp1bfQnxl7vaduQVMQiXUrgK8Gw==}engines: {node: '>=18'}peerDependencies:zod: ^3.0.0@@ -611,12 +614,12 @@ packages:zod:optional: true- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-dQkfBDs2lTYpKM8389oopPdQgIU007GQyCbuPPrV+K6MtSII3HBfE0stUIMXUb44L+LK1t6GXPP7wjSzjO6uKg==}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-q1PJEZ0qD9rVR+8JFEd01/QM++csMT5UVwYXSN2u54BrVw/D8TZLTeg2FEfKK00DgAx0UtWd8XOhhwITP9BT5g==}engines: {node: '>=18'}- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-GnwbtjW4/4z7MleLiW+TOZC2M29eCg1tOUpuEiYFMmFNZK8mkrqM0PFZMo6UsYeUYMWqEOOcPOU9OQVJMJh7IQ==}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-vfjZ7w2M+Me83HTMMrnnrmXotz39UDCMd27YQSrvt2f1YCLPloVpLhP+Y9TLZeFE/QiiRCrPYLDQm6aQJYJ9PQ==}engines: {node: '>=18'}peerDependencies:react: ^18 || ^19 || ^19.0.0-rc@@ -627,26 +630,8 @@ packages:zod:optional: true- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-96KWTVK+opdFeRubqrgaJXoNiDP89gNxFRWUp0PJOotZW816AbhUf4EnDjBjXTLjXL1n0h8tGSE9sZsRkj9wQQ==}- engines: {node: '>=18'}- peerDependencies:- solid-js: '*'- peerDependenciesMeta:- solid-js:- optional: true-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-SyF9ItIR9ALP9yDNAD+2/5Vl1IT6kchgyDH8xkmhysfJI6WrvJbtO1wdQ0nylvPLcsPoYu+cAlz1krU4lFHcYw==}- engines: {node: '>=18'}- peerDependencies:- svelte: '*'- peerDependenciesMeta:- svelte:- optional: true-- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-Z5QYJVW+5XpSaJ4jYCCAVG7zIAuKOOdikhgpksneNmKvx61ACFaf98pmOd+xnjahl0pIlc/QIe6O4yVaJ1sEaw==}+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-1SC9W4VZLcJtxHRv4Y0aX20EFeaEP6gUvVqoKLBBtMLOgtcZrv/F/HQRjGavGugiwlS3dsVza4X+E78fiwtlTA==}engines: {node: '>=18'}peerDependencies:zod: ^3.0.0@@ -654,15 +639,6 @@ packages:zod:optional: true- '@ai-sdk/[email protected]':- resolution: {integrity: sha512-+ofYlnqdc8c4F6tM0IKF0+7NagZRAiqBJpGDJ+6EYhDW8FHLUP/JFBgu32SjxSxC6IKFZxEnl68ZoP/Z38EMlw==}- engines: {node: '>=18'}- peerDependencies:- vue: '*'- peerDependenciesMeta:- vue:- optional: true-'@alloc/[email protected]':resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}@@ -4010,24 +3986,15 @@ packages:resolution: {integrity: sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==}engines: {node: '>= 14'}- resolution: {integrity: sha512-plBlrVZKwPoRTmM8+D1sJac9Bq8eaa2jiZlHLZIWekKWI1yMWYZvCCEezY9ASPwRhULYDJB2VhKOBUUeg3S5JQ==}+ resolution: {integrity: sha512-9IB5duz6VbXvjibqNrvKz6++PwE8Ui5UfbOC9/CtcQN5Z9sudUQErss+maj7ptoPysD2NPjj99e0Hp183Cz5LQ==}engines: {node: '>=18'}peerDependencies:- openai: ^4.42.0react: ^18 || ^19 || ^19.0.0-rc- sswr: ^2.1.0- svelte: '*'zod: ^3.0.0peerDependenciesMeta:- openai:- optional: truereact:optional: true- sswr:- optional: true- svelte:- optional: truezod:optional: true@@ -5409,9 +5376,9 @@ packages:resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}- resolution: {integrity: sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA==}- engines: {node: '>=14.18'}+ resolution: {integrity: sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==}+ engines: {node: '>=18.0.0'}resolution: {integrity: sha512-bFi65yM+xZgk+u/KRIpekdSYkTB5W1pEf0Lt8Q8Msh7b+eQ7LXVtIB1Bkm4fvclDEL1b2CZkMhv2mOeF8tMdkA==}@@ -6528,8 +6495,8 @@ packages:engines: {node: '>= 18'}hasBin: true- resolution: {integrity: sha512-Y07CUOE+HQXbVDCGl3LXggqJDbXDP2pArc2C1N1RRMN0ONiShoSsIInMd5Gsxupe7fKLpgimTV+HOJ9r7bA+pg==}+ resolution: {integrity: sha512-dgLIeKGLx5FwziAnsk4ONoGwHwGPJzselimvlVskE9XLN4Orv9u2VA3GWw/lYUqjfA0rUT/6fqKwfZJapP9BEg==}engines: {node: '>= 18'}hasBin: true@@ -7986,9 +7953,6 @@ packages:engines: {node: '>=0.10.0'}hasBin: true- resolution: {integrity: sha512-Cqc355SYlTAaUt8iDPaC/4DPPXK925PePLMxyBKuWd5kKc5mwsG3nT9+Mq2tyguL5s7b4Jg+IRMpTRsNTAfpSQ==}-resolution: {integrity: sha512-vjUc6sfgtgY0dxCdnc40mK6Oftjo9+2K8H/NG81TMhgL392FtiPA9tn9RLyTxXmTLPJPjF3VyzFp6bsWFLisMQ==}@@ -8215,12 +8179,6 @@ packages:peerDependencies:react: ^16.11.0 || ^17.0.0 || ^18.0.0- resolution: {integrity: sha512-LqVcOHSB4cPGgitD1riJ1Hh4vdmITOp+BkmfmXRh4hSF/t7EnS4iD+SOTmq7w5pPm/SiPeto4ADbKS6dHUDWFA==}-- resolution: {integrity: sha512-zjEkcP8Ywmj+xOJW3lIT65ciY/4AL4e/Or7Gj0MzU3zBJNMdJiT8geVZhINavnlHRMMCcJLHhraLTAiDOTmQ9g==}-resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}@@ -9178,62 +9136,37 @@ snapshots:'@adobe/[email protected]': {}- '@ai-sdk/[email protected]([email protected])':+ '@ai-sdk/[email protected]([email protected])':dependencies:- '@ai-sdk/provider': 0.0.26- eventsource-parser: 1.1.2+ '@ai-sdk/provider': 1.0.7+ eventsource-parser: 3.0.0nanoid: 3.3.8secure-json-parse: 2.7.0optionalDependencies:zod: 3.24.1- '@ai-sdk/[email protected]':+ '@ai-sdk/[email protected]':dependencies:json-schema: 0.4.0dependencies:- '@ai-sdk/provider-utils': 1.0.22([email protected])- '@ai-sdk/ui-utils': 0.0.50([email protected])+ '@ai-sdk/provider-utils': 2.1.6([email protected])+ '@ai-sdk/ui-utils': 1.1.11([email protected])swr: 2.2.5([email protected])throttleit: 2.1.0optionalDependencies:react: 18.3.1zod: 3.24.1- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider-utils': 1.0.22([email protected])- '@ai-sdk/ui-utils': 0.0.50([email protected])- transitivePeerDependencies:- - zod-- '@ai-sdk/[email protected]([email protected])':+ '@ai-sdk/[email protected]([email protected])':dependencies:- '@ai-sdk/provider-utils': 1.0.22([email protected])- '@ai-sdk/ui-utils': 0.0.50([email protected])- sswr: 2.1.0- transitivePeerDependencies:- - zod-- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider': 0.0.26- '@ai-sdk/provider-utils': 1.0.22([email protected])- json-schema: 0.4.0- secure-json-parse: 2.7.0+ '@ai-sdk/provider': 1.0.7+ '@ai-sdk/provider-utils': 2.1.6([email protected])zod-to-json-schema: 3.24.1([email protected])optionalDependencies:zod: 3.24.1- '@ai-sdk/[email protected]([email protected])':- dependencies:- '@ai-sdk/provider-utils': 1.0.22([email protected])- '@ai-sdk/ui-utils': 0.0.50([email protected])- swrv: 1.0.4- transitivePeerDependencies:- - zod-'@alloc/[email protected]': {}'@ampproject/[email protected]':@@ -13459,28 +13392,17 @@ snapshots:transitivePeerDependencies:- supports-colordependencies:- '@ai-sdk/provider': 0.0.26- '@ai-sdk/provider-utils': 1.0.22([email protected])- '@ai-sdk/react': 0.0.70([email protected])([email protected])- '@ai-sdk/solid': 0.0.54([email protected])- '@ai-sdk/svelte': 0.0.57([email protected])- '@ai-sdk/ui-utils': 0.0.50([email protected])- '@ai-sdk/vue': 0.0.59([email protected])+ '@ai-sdk/provider': 1.0.7+ '@ai-sdk/provider-utils': 2.1.6([email protected])+ '@ai-sdk/react': 1.1.11([email protected])([email protected])+ '@ai-sdk/ui-utils': 1.1.11([email protected])'@opentelemetry/api': 1.9.0- eventsource-parser: 1.1.2- json-schema: 0.4.0jsondiffpatch: 0.6.0- secure-json-parse: 2.7.0- zod-to-json-schema: 3.24.1([email protected])optionalDependencies:react: 18.3.1- sswr: 2.1.0zod: 3.24.1- transitivePeerDependencies:- - solid-js- - vueoptionalDependencies:@@ -13953,7 +13875,7 @@ snapshots:'@codemirror/state': 6.5.2'@codemirror/view': 6.36.2'@open-rpc/client-js': 1.8.1- marked: 15.0.6+ marked: 15.0.7vscode-languageserver-protocol: 3.17.5transitivePeerDependencies:- bufferutil@@ -15176,7 +15098,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -16393,7 +16315,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -18267,10 +18189,6 @@ snapshots:safer-buffer: 2.1.2tweetnacl: 0.14.5- dependencies:- swrev: 4.0.0-@@ -18583,10 +18501,6 @@ snapshots:react: 18.3.1use-sync-external-store: 1.4.0([email protected])- [email protected]: {}-- [email protected]: {}-diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex e1e624d677..ae11a290a5 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -8,10 +8,22 @@ import {PopoverTrigger,} from "@/components/ui/popover";import { ClockIcon, Loader2, PlusIcon } from "lucide-react";-import { chatStateAtom, activeChatAtom, type Chat } from "@/core/ai/state";-import { useState, useRef, useEffect } from "react";+import {+ chatStateAtom,+ activeChatAtom,+ type Chat,+ type ChatState,+} from "@/core/ai/state";+import {+ useState,+ useRef,+ useEffect,+ type SetStateAction,+ type Dispatch,+ memo,+} from "react";import { generateUUID } from "@/utils/uuid";-import { useChat } from "ai/react";+import { type Message, useChat } from "ai/react";import { PromptInput } from "../editor/ai/add-cell-with-ai";import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";import { Tooltip } from "../ui/tooltip";@@ -24,12 +36,156 @@ import { getCodes } from "@/core/codemirror/copilot/getCodes";import { getAICompletionBody } from "../editor/ai/completion-utils";import { addMessageToChat } from "@/core/ai/chat-utils";import { ErrorBanner } from "@/plugins/impl/common/error-banner";-import { useTheme } from "@/theme/useTheme";+import { type ResolvedTheme, useTheme } from "@/theme/useTheme";++interface ChatHeaderProps {+ onNewChat: () => void;+ activeChatId: string | undefined;+ setActiveChat: (id: string | null) => void;+ chats: Chat[];+ setMessages: (messages: Message[]) => void;+}++const ChatHeader: React.FC<ChatHeaderProps> = ({+ onNewChat,+ activeChatId,+ setActiveChat,+ chats,+ setMessages,+}) => (+ <div className="flex border-b px-2 py-1 justify-between flex-shrink-0">+ <Tooltip content="New chat">+ <Button variant="text" size="icon" onClick={onNewChat}>+ <PlusIcon className="h-4 w-4" />+ </Button>+ </Tooltip>+ <Popover>+ <Tooltip content="Previous chats">+ <PopoverTrigger asChild={true}>+ <Button variant="text" size="icon">+ <ClockIcon className="h-4 w-4" />+ </Button>+ </PopoverTrigger>+ </Tooltip>+ <PopoverContent className="w-[520px] p-0" align="start" side="right">+ <ScrollArea className="h-[500px] p-4">+ <div className="space-y-4">+ {chats.map((chat) => (+ <div+ key={chat.id}+ className={cn(+ "p-3 rounded-md cursor-pointer hover:bg-accent",+ chat.id === activeChatId && "bg-accent",+ )}+ onClick={() => {+ setActiveChat(chat.id);+ setMessages(+ chat.messages.map(({ role, content, timestamp }) => ({+ role,+ content,+ id: timestamp.toString(),+ })),+ );+ }}+ >+ <div className="font-medium">{chat.title}</div>+ <div className="text-sm text-muted-foreground">+ {new Date(chat.updatedAt).toLocaleString()}+ </div>+ </div>+ ))}+ </div>+ </ScrollArea>+ </PopoverContent>+ </Popover>+ </div>+);++interface ChatMessageProps {+ message: Message;+ index: number;+ theme: ResolvedTheme;+ onEdit: (index: number, newValue: string) => void;+ setChatState: Dispatch<SetStateAction<ChatState>>;+ chatState: ChatState;+}+const ChatMessage: React.FC<ChatMessageProps> = memo(+ ({ message, index, theme, onEdit, setChatState, chatState }) => (+ <div+ className={cn(+ "flex",+ message.role === "user" ? "justify-end" : "justify-start",+ )}+ >+ {message.role === "user" ? (+ <div className="w-[95%] bg-background border p-1 rounded-sm">+ <PromptInput+ key={message.id}+ value={message.content}+ theme={theme}+ placeholder="Type your message..."+ onChange={() => {+ // noop+ }}+ onSubmit={(e, newValue) => {+ if (!newValue.trim()) {+ return;+ }+ onEdit(index, newValue);+ if (chatState.activeChatId) {+ setChatState((prev: ChatState) =>+ addMessageToChat(+ prev,+ chatState.activeChatId,+ "user",+ newValue,+ ),+ );+ }+ }}+ onClose={() => {+ // noop+ }}+ />+ </div>+ ) : (+ <div className="w-[95%]">+ <MarkdownRenderer content={message.content} />+ </div>+ )}+ </div>+ ),+);+ChatMessage.displayName = "ChatMessage";++interface ChatInputProps {+ input: string;+ setInput: (value: string) => void;+ onSubmit: (e: KeyboardEvent | undefined, value: string) => void;+ theme: ResolvedTheme;+ inputRef: React.RefObject<ReactCodeMirrorRef>;+}++const ChatInput: React.FC<ChatInputProps> = memo(+ ({ input, setInput, onSubmit, theme, inputRef }) => (+ <div className="px-2 py-3 border-t relative flex-shrink-0 min-h-[80px]">+ <PromptInput+ value={input}+ onChange={setInput}+ onSubmit={onSubmit}+ onClose={() => inputRef.current?.editor?.blur()}+ theme={theme}+ placeholder="Type your message..."+ />+ </div>+ ),+);++ChatInput.displayName = "ChatInput";export const ChatPanel = () => {const [chatState, setChatState] = useAtom(chatStateAtom);const [activeChat, setActiveChat] = useAtom(activeChatAtom);- const [completionBody, setCompletionBody] = useState<object>({});const [newThreadInput, setNewThreadInput] = useState("");const newThreadInputRef = useRef<ReactCodeMirrorRef>(null);const newMessageInputRef = useRef<ReactCodeMirrorRef>(null);@@ -39,7 +195,7 @@ export const ChatPanel = () => {const {messages,input,- setInput: setInputInternal,+ setInput,setMessages,append,handleSubmit,@@ -48,11 +204,18 @@ export const ChatPanel = () => {reload,} = useChat({keepLastMessageOnError: true,+ // Throttle the messages and data updates to 100ms+ experimental_throttle: 100,api: asURL("api/ai/chat").toString(),headers: API.headers(),- body: {- ...completionBody,- includeOtherCode: getCodes(""),+ experimental_prepareRequestBody: (options) => {+ return {+ ...options,+ ...getAICompletionBody(+ options.messages.map((m) => m.content).join("\n"),+ ),+ includeOtherCode: getCodes(""),+ };},streamProtocol: "text",onFinish: (message) => {@@ -71,17 +234,22 @@ export const ChatPanel = () => {Logger.debug("Received HTTP response from server:", response);},});-- const setInput = (newValue: string) => {- setInputInternal(newValue);- const messagesConcat = messages.map((m) => m.content).join("\n");- setCompletionBody(getAICompletionBody(`${messagesConcat}\n\n${newValue}`));- };-const lastMessageText = messages.at(-1)?.content;useEffect(() => {if (isLoading) {- messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });+ const BUFFER = 150;+ const container = messagesEndRef.current?.parentElement;+ if (!container) {+ return;+ }++ const isNearBottom =+ container.scrollHeight - container.scrollTop - container.clientHeight <+ BUFFER;++ if (isNearBottom) {+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });+ }}}, [messages, isLoading, lastMessageText]);@@ -105,82 +273,63 @@ export const ChatPanel = () => {activeChatId: newChat.id,}));- const nextCompletionBody = getAICompletionBody(initialMessage);- setCompletionBody(nextCompletionBody);+ setMessages([]);+ setInput("");+ append({+ role: "user",+ content: initialMessage,+ });+ };+ const handleNewChat = () => {+ setActiveChat(null);setMessages([]);setInput("");- append(- {- role: "user",- content: initialMessage,- },- {- body: {- ...nextCompletionBody,- includeOtherCode: getCodes(""),- },- },- );+ setNewThreadInput("");+ };++ const handleMessageEdit = (index: number, newValue: string) => {+ setMessages((messages) => messages.slice(0, index));+ append({+ role: "user",+ content: newValue,+ });+ };++ const handleChatInputSubmit = (+ e: KeyboardEvent | undefined,+ newValue: string,+ ): void => {+ if (!newValue.trim()) {+ return;+ }+ handleSubmit(e);+ if (chatState.activeChatId) {+ setChatState((prev) =>+ addMessageToChat(prev, chatState.activeChatId, "user", newValue),+ );+ }+ };++ const handleReload = () => {+ reload();+ };++ const handleNewThreadSubmit = () => {+ newThreadInput.trim() && createNewThread(newThreadInput.trim());};+ const handleOnCloseThread = () => newThreadInputRef.current?.editor?.blur();+return (<div className="flex flex-col h-[calc(100%-53px)]">- <div className="flex border-b px-2 py-1 justify-between flex-shrink-0">- <Tooltip content="New chat">- <Button- variant="text"- size="icon"- onClick={() => {- setActiveChat(null);- setMessages([]);- setInput("");- setNewThreadInput("");- }}- >- <PlusIcon className="h-4 w-4" />- </Button>- </Tooltip>- <Popover>- <Tooltip content="Previous chats">- <PopoverTrigger asChild={true}>- <Button variant="text" size="icon">- <ClockIcon className="h-4 w-4" />- </Button>- </PopoverTrigger>- </Tooltip>- <PopoverContent className="w-[520px] p-0" align="start" side="right">- <ScrollArea className="h-[500px] p-4">- <div className="space-y-4">- {chatState.chats.map((chat) => (- <div- key={chat.id}- className={cn(- "p-3 rounded-md cursor-pointer hover:bg-accent",- chat.id === activeChat?.id && "bg-accent",- )}- onClick={() => {- setActiveChat(chat.id);- setMessages(- chat.messages.map(({ role, content, timestamp }) => ({- role,- content,- id: timestamp.toString(),- })),- );- }}- >- <div className="font-medium">{chat.title}</div>- <div className="text-sm text-muted-foreground">- {new Date(chat.updatedAt).toLocaleString()}- </div>- </div>- ))}- </div>- </ScrollArea>- </PopoverContent>- </Popover>- </div>+ <ChatHeader+ onNewChat={handleNewChat}+ activeChatId={activeChat?.id}+ setActiveChat={setActiveChat}+ chats={chatState.chats}+ setMessages={setMessages}+ /><div className="flex-1 px-3 bg-[var(--slate-1)] gap-4 py-3 flex flex-col overflow-y-auto">{(!messages || messages.length === 0) && (@@ -190,66 +339,23 @@ export const ChatPanel = () => {value={newThreadInput}placeholder="Ask anything, @ to include context"theme={theme}- onClose={() => newThreadInputRef.current?.editor?.blur()}+ onClose={handleOnCloseThread}onChange={setNewThreadInput}- onSubmit={() =>- newThreadInput.trim() && createNewThread(newThreadInput.trim())- }+ onSubmit={handleNewThreadSubmit}/></div>)}{messages.map((message, idx) => (- <div+ <ChatMessagekey={idx}- className={cn(- "flex",- message.role === "user" ? "justify-end" : "justify-start",- )}- >- {message.role === "user" ? (- <div className="w-[95%] bg-background border p-1 rounded-sm">- <PromptInput- key={message.id}- value={message.content}- theme={theme}- placeholder="Type your message..."- onChange={() => {- // noop- }}- onSubmit={(e, newValue) => {- if (!newValue.trim()) {- return;- }- // Remove all messages from here to the end- setMessages((messages) => messages.slice(0, idx));- setCompletionBody(getAICompletionBody(newValue));- append({- role: "user",- content: newValue,- });- if (chatState.activeChatId) {- setChatState((prev) =>- addMessageToChat(- prev,- chatState.activeChatId,- "user",- newValue,- ),- );- }- }}- onClose={() => {- // noop- }}- />- </div>- ) : (- <div className="w-[95%]">- <MarkdownRenderer content={message.content} />- </div>- )}- </div>+ message={message}+ index={idx}+ theme={theme}+ onEdit={handleMessageEdit}+ setChatState={setChatState}+ chatState={chatState}+ />))}{isLoading && (@@ -261,7 +367,7 @@ export const ChatPanel = () => {{error && (<div className="flex items-center justify-center space-x-2 mb-4"><ErrorBanner error={error} />- <Button variant="outline" size="sm" onClick={() => reload()}>+ <Button variant="outline" size="sm" onClick={handleReload}>Retry</Button></div>@@ -271,44 +377,13 @@ export const ChatPanel = () => {</div>{messages && messages.length > 0 && (- <div className="px-2 py-3 border-t relative flex-shrink-0 min-h-[80px]">- {isLoading && (- <div className="flex justify-center mb-2 absolute -top-10 left-0 right-0">- <Button- variant="secondary"- size="xs"- onClick={() => stop()}- className="text-muted-foreground hover:text-foreground"- >- Cancel- </Button>- </div>- )}-- <PromptInput- value={input}- onChange={setInput}- onSubmit={(e, newValue) => {- if (!newValue.trim()) {- return;- }- handleSubmit(e);- if (chatState.activeChatId) {- setChatState((prev) =>- addMessageToChat(- prev,- chatState.activeChatId,- "user",- newValue,- ),- );- }- }}- onClose={() => newMessageInputRef.current?.editor?.blur()}- theme={theme}- placeholder="Type your message..."- />- </div>+ <ChatInput+ input={input}+ setInput={setInput}+ onSubmit={handleChatInputSubmit}+ theme={theme}+ inputRef={newMessageInputRef}+ />)}</div>);diff --git a/frontend/src/components/chat/markdown-renderer.tsx b/frontend/src/components/chat/markdown-renderer.tsxindex 1c0310dd88..1c07f04d82 100644--- a/frontend/src/components/chat/markdown-renderer.tsx+++ b/frontend/src/components/chat/markdown-renderer.tsx@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";import { BetweenHorizontalStartIcon } from "lucide-react";import { EditorView } from "@codemirror/view";import Markdown, { type Components } from "react-markdown";-import { useEffect, useState } from "react";+import { useEffect, useState, memo, useMemo } from "react";import { useLastFocusedCellId } from "@/core/cells/focus";import { copyToClipboard } from "@/utils/copy";import { SQLLanguageAdapter } from "@/core/codemirror/language/sql";@@ -14,6 +14,7 @@ import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { useAtomValue } from "jotai";import { autoInstantiateAtom } from "@/core/config/config";import { MarkdownLanguageAdapter } from "@/core/codemirror/language/markdown";+import { marked } from "marked";const extensions = [EditorView.lineWrapping];@@ -147,13 +148,39 @@ const COMPONENTS: Components = {},};-export const MarkdownRenderer = ({ content }: { content: string }) => {+function parseMarkdownIntoBlocks(markdown: string): string[] {+ const tokens = marked.lexer(markdown);+ return tokens.map((token) => token.raw);+}++const MemoizedMarkdownBlock = memo(+ ({ content }: { content: string }) => {+ return (+ <Markdown+ components={COMPONENTS}+ className="prose dark:prose-invert max-w-none prose-pre:pl-0"+ >+ {content}+ </Markdown>+ );+ },+ (prevProps, nextProps) => prevProps.content === nextProps.content,+);++MemoizedMarkdownBlock.displayName = "MemoizedMarkdownBlock";++export const MarkdownRenderer = memo(({ content }: { content: string }) => {+ const blocks = useMemo(() => parseMarkdownIntoBlocks(content), [content]);+return (- <Markdown- components={COMPONENTS}- className="prose dark:prose-invert max-w-none prose-pre:pl-0"- >- {content}- </Markdown>+ <>+ {blocks.map((block, index) => (+ <MemoizedMarkdownBlock+ content={block}+ key={`markdown-block-${index}`}+ />+ ))}+ </>);-};+});+MarkdownRenderer.displayName = "MarkdownRenderer";diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsxindex 5128d392d0..7ea6d4b057 100644--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx@@ -66,7 +66,9 @@ export const AddCellWithAI: React.FC<{} = useCompletion({api: asURL("api/ai/completion").toString(),headers: API.headers(),- streamMode: "text",+ streamProtocol: "text",+ // Throttle the messages and data updates to 100ms+ experimental_throttle: 100,body: {...completionBody,language: language,diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsxindex 128c2ba3ea..9157aca5b2 100644--- a/frontend/src/components/editor/ai/ai-completion-editor.tsx+++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx@@ -80,7 +80,9 @@ export const AiCompletionEditor: React.FC<Props> = ({api: asURL("api/ai/completion").toString(),headers: API.headers(),initialInput: initialPrompt,- streamMode: "text",+ streamProtocol: "text",+ // Throttle the messages and data updates to 100ms+ experimental_throttle: 100,body: {...completionBody,includeOtherCode: includeOtherCells ? getCodes(currentCode) : "",diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.tsindex 4352904661..6c51e0231f 100644--- a/frontend/src/core/ai/state.ts+++ b/frontend/src/core/ai/state.ts@@ -9,7 +9,7 @@ export const aiCompletionCellAtom = atom<{export const includeOtherCellsAtom = atom<boolean>(false);export interface Message {- role: "user" | "assistant" | "function" | "data" | "system" | "tool";+ role: "user" | "assistant" | "data" | "system";content: string;timestamp: number;}diff --git a/frontend/src/css/app/reset.css b/frontend/src/css/app/reset.cssindex 6c01d43e53..aee725bdce 100644--- a/frontend/src/css/app/reset.css+++ b/frontend/src/css/app/reset.css@@ -6,6 +6,7 @@ body,}#root {+ isolation: isolate;width: 100%;display: flex;flex-direction: column;diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex d28f4e327b..a6ea2dfba7 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -140,6 +140,10 @@ class AppKernelRunnerRegistry:# isolated across run sessions.self._runners: dict[int, dict[App, AppKernelRunner]] = {}+ @property+ def size(self) -> int:+ return len(self._runners)+def get_runner(self, app: App) -> AppKernelRunner:app_runners = self._runners.setdefault(threading.get_ident(), {})runner = app_runners.get(app, None)diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.pyindex e840ccff75..0e05d89d9d 100644--- a/marimo/_runtime/app/kernel_runner.py+++ b/marimo/_runtime/app/kernel_runner.py@@ -92,9 +92,10 @@ class AppKernelRunner:parent=ctx,)ctx.add_child(self._runtime_context)- weakref.finalize(+ finalizer = weakref.finalize(self, ctx.remove_child, self._runtime_context- ).atexit = False+ )+ finalizer.atexit = False# Register cells through the kernel runner, so that compilation only# occurs once.diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex e7278eb19e..7bfea9eba2 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -163,9 +163,9 @@ def get_model(config: MarimoConfig) -> str:def get_content(- response: RawMessageStreamEvent- | ChatCompletionChunk- | GenerateContentResponse,+ response: (+ RawMessageStreamEvent | ChatCompletionChunk | GenerateContentResponse+ ),) -> str | None:if hasattr(response, "choices") and response.choices:return response.choices[0].delta.content # type: ignore@@ -186,9 +186,11 @@ def get_content(def make_stream_response(- response: OpenAiStream[ChatCompletionChunk]- | AnthropicStream[RawMessageStreamEvent]- | GenerateContentResponse,+ response: (+ OpenAiStream[ChatCompletionChunk]+ | AnthropicStream[RawMessageStreamEvent]+ | GenerateContentResponse+ ),) -> Generator[str, None, None]:original_content = ""buffer = ""@@ -242,9 +244,11 @@ def make_stream_response(def as_stream_response(- response: OpenAiStream[ChatCompletionChunk]- | AnthropicStream[RawMessageStreamEvent]- | GenerateContentResponse,+ response: (+ OpenAiStream[ChatCompletionChunk]+ | AnthropicStream[RawMessageStreamEvent]+ | GenerateContentResponse+ ),) -> Generator[str, None, None]:original_content = ""buffer = ""@@ -330,7 +334,9 @@ async def ai_completion(app_state = AppState(request)app_state.require_current_session()config = app_state.config_manager.get_config(hide_secrets=False)- body = await parse_request(request, cls=AiCompletionRequest)+ body = await parse_request(+ request, cls=AiCompletionRequest, allow_unknown_keys=True+ )custom_rules = config.get("ai", {}).get("rules", None)prompter = Prompter(code=body.code)@@ -414,7 +420,9 @@ async def ai_chat(app_state = AppState(request)app_state.require_current_session()config = app_state.config_manager.get_config(hide_secrets=False)- body = await parse_request(request, cls=ChatRequest)+ body = await parse_request(+ request, cls=ChatRequest, allow_unknown_keys=True+ )# Get the model from request or fallback to configmodel = body.model or get_model(config)diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex bf5add3c72..38d1c47bb8 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -8,7 +8,12 @@ from typing import Any, TYPE_CHECKINGimport pytest-from marimo._ast.app import App, AppKernelRunnerRegistry, _AppConfig, InternalApp+from marimo._ast.app import (+ App,+ AppKernelRunnerRegistry,+ _AppConfig,+ InternalApp,+)from marimo._ast.errors import (CycleError,DeleteNonlocalError,@@ -17,6 +22,7 @@ from marimo._ast.errors import ()from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.stateless.flex import vstack+from marimo._runtime.context.types import get_contextfrom marimo._runtime.requests import SetUIElementValueRequestfrom tests.conftest import ExecReqProvider@@ -699,6 +705,9 @@ class TestAppComposition:async def test_app_comp_multiple_ui_elements(self, k: Kernel, exec_req: ExecReqProvider) -> None:+ ctx = get_context()++ assert ctx.app_kernel_runner_registry.size == 0await k.run([exec_req.get(@@ -714,19 +723,27 @@ class TestAppComposition:])assert not k.errors+ assert ctx.app_kernel_runner_registry.size == 1result = k.globals["result"]+ app = k.globals["app"]+ app_kernel_runner = app._get_kernel_runner()# two number inputs: x and yx = result.defs["x"]y = result.defs["y"]assert x.value == 1assert y.value == 1+ assert app_kernel_runner == app._get_kernel_runner()+ assert ctx.app_kernel_runner_registry.size == 1# testing that only descendants of the updated UI elements run,# and that the other UI element is not resetawait k.set_ui_element_value(SetUIElementValueRequest.from_ids_and_values([(x._id, 2)]))++ assert app_kernel_runner == app._get_kernel_runner()+ assert ctx.app_kernel_runner_registry.size == 1assert x.value == 2assert y.value == 1diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 230f043319..70802e3d6d 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -584,6 +584,7 @@ class TestStreamResponse(unittest.TestCase):"model": "gpt-4-turbo","variables": [],"include_other_code": "",+ "id": "123",},)assert response.status_code == 200, response.text@@ -624,6 +625,7 @@ class TestStreamResponse(unittest.TestCase):"model": "gpt-4-turbo","variables": [],"include_other_code": "import pandas as pd",+ "id": "123",},)assert response.status_code == 200, response.text