Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Feature: implement editable assistant messages (#6397)

CelesteHeartsong9666e5de94be
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index c9dfb348d92..a65a157707b 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -162,6 +162,7 @@ import {
useState,
} from "react";
import { create } from "zustand";
+import { extractTaggedText, updateThreadMessage } from "@/features/chat/utils/update-thread-message";
// True while a file is dragged anywhere over the chat page, so the composer
// can show its "Drop files here" affordance.
@@ -3195,41 +3196,138 @@ const DiffusionCanvas: FC = () => {
);
};
+/**
+ * AssistantMessage handles the display and inline-editing of AI responses.
+ *
+ * It utilizes a "Tagged Text" system (<THINK> and <TOOL> tags) to allow users
+ * to edit structured reasoning and tool outputs within a plain-text textarea
+ * while preserving the underlying data schema and tool-call metadata.
+ */
const AssistantMessage: FC = () => {
+ const aui = useAui();
+ const messageId = useAuiState(({ message }) => message.id);
+ const messageContent = useAuiState(({ message }) => message.content);
+ const incognito = useChatRuntimeStore((s) => s.incognito);
+
+ // Use global store for editing state to ensure a single source of truth
+ const editingId = useChatRuntimeStore((s) => s.editingMessageId);
+ const setEditingId = useChatRuntimeStore((s) => s.setEditingMessageId);
+ const isEditing = editingId === messageId;
+
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ // Auto-grow textarea height based on content
+ const adjustHeight = () => {
+ const el = textareaRef.current;
+ if (el) {
+ el.style.height = "auto";
+ el.style.height = `${el.scrollHeight}px`;
+ }
+ };
+
+ useEffect(() => {
+ if (isEditing) setTimeout(adjustHeight, 0);
+ }, [isEditing]);
+
+ const handleSave = async () => {
+ const finalText = textareaRef.current?.value || "";
+
+ // Prioritize the specific thread item ID, then fallback to the global active thread ID
+ const remoteId = aui.threadListItem().getState().remoteId
+ || useChatRuntimeStore.getState().activeThreadId;
+
+ if (!remoteId || remoteId === "" || remoteId === "/") {
+ toast.error("Save failed: No thread ID found.");
+ setEditingId(null);
+ return;
+ }
+
+ try {
+ await updateThreadMessage({
+ thread: {
+ export: () => aui.thread().export(),
+ import: (data) => aui.thread().import(data)
+ },
+ messageId,
+ remoteId,
+ newText: finalText,
+ isIncognito: incognito,
+ });
+ } catch (error) {
+ console.error("UI: Error during save:", error);
+ toast.error("Failed to save message edits.");
+ } finally {
+ setEditingId(null);
+ }
+ };
+
return (
<MessagePrimitive.Root
className="aui-assistant-message-root relative mx-auto min-w-0 w-full max-w-(--thread-content-max-width) pt-0.5 pb-4 text-[15.5px] [font-weight:410] tracking-[0.01em] dark:tracking-[0.02em]"
data-role="assistant"
>
<div className="aui-assistant-message-content wrap-break-word min-w-0 text-[#0d0d0d] dark:text-foreground leading-relaxed">
- <GeneratingIndicator />
- <CancelledIndicator />
- <DiffusionCanvas />
- <MessagePrimitive.Parts
- components={{
- Text: MarkdownText,
- Reasoning: Reasoning,
- ReasoningGroup: ReasoningGroup,
- Source: Sources,
- ToolGroup: ToolGroup,
- tools: {
- by_name: {
- web_search: WebSearchToolUIConfirmable,
- search_knowledge_base: KnowledgeBaseToolUIConfirmable,
- python: PythonToolUIConfirmable,
- terminal: TerminalToolUIConfirmable,
- code_execution: CodeExecutionToolUIConfirmable,
- image_generation: ImageGenerationToolUIConfirmable,
- render_html: RenderHtmlToolUIConfirmable,
- },
- Fallback: ToolFallbackConfirmable,
- },
- }}
- />
- <SourcesGroup />
- <RagSourcesGroup />
- <MessageHtmlArtifacts />
- <MessageError />
+ {isEditing ? (
+ <div className="flex flex-col gap-2 w-full">
+ <textarea
+ ref={textareaRef}
+ defaultValue={extractTaggedText(messageContent)}
+ className="w-full p-3 rounded-xl bg-muted border border-border text-foreground focus:ring-2 focus:ring-primary outline-none overflow-y-auto resize-none font-mono text-sm max-h-[70vh]"
+ autoFocus
+ onInput={adjustHeight}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
+ handleSave();
+ }
+ if (e.key === 'Escape') {
+ setEditingId(null); // UX: Close editor on Escape
+ }
+ }}
+ />
+ <div className="flex justify-end gap-2">
+ <Button size="sm" variant="ghost" onClick={() => setEditingId(null)} className="h-8 text-xs">Cancel</Button>
+ <Button size="sm" onClick={handleSave} className="h-8 text-xs">Save</Button>
+ </div>
+ </div>
+ ) : (
+ <>
+ <GeneratingIndicator />
+ <CancelledIndicator />
+ <DiffusionCanvas />
+
+ {/*
+ We use the standard MessagePrimitive.Parts. This ensures that
+ edited messages maintain the same professional styling,
+ Markdown rendering, and tool-call components as original responses.
+ */}
+ <MessagePrimitive.Parts
+ components={{
+ Text: MarkdownText,
+ Reasoning: Reasoning,
+ ReasoningGroup: ReasoningGroup,
+ Source: Sources,
+ ToolGroup: ToolGroup,
+ tools: {
+ by_name: {
+ web_search: WebSearchToolUIConfirmable,
+ search_knowledge_base: KnowledgeBaseToolUIConfirmable,
+ python: PythonToolUIConfirmable,
+ terminal: TerminalToolUIConfirmable,
+ code_execution: CodeExecutionToolUIConfirmable,
+ image_generation: ImageGenerationToolUIConfirmable,
+ render_html: RenderHtmlToolUIConfirmable,
+ },
+ Fallback: ToolFallbackConfirmable,
+ },
+ }}
+ />
+ <SourcesGroup />
+ <RagSourcesGroup />
+ <MessageHtmlArtifacts />
+ <MessageError />
+ </>
+ )}
</div>
<div className="aui-assistant-message-footer mt-1.5 -ml-[var(--icon-btn-inset)] flex min-h-8">
@@ -3416,6 +3514,26 @@ const CopyButton: FC = () => {
);
};
+const EditAssistantMessageButton: FC = () => {
+ const messageId = useAuiState(({ message }) => message.id);
+ const isRunning = useAuiState(({ thread }) => thread.isRunning);
+ const setEditingId = useChatRuntimeStore((s) => s.setEditingMessageId);
+
+ return (
+ <TooltipIconButton
+ tooltip="Edit response"
+ disabled={isRunning}
+ onClick={() => setEditingId(messageId)}
+ >
+ <HugeiconsIcon
+ icon={Edit03Icon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
+ </TooltipIconButton>
+ );
+};
+
const AssistantActionBar: FC = () => {
const { forkMessage, forkDisabled } = useForkMessageAction();
@@ -3425,6 +3543,7 @@ const AssistantActionBar: FC = () => {
className="aui-assistant-action-bar-root col-start-3 row-start-2 flex items-center gap-1 text-chat-icon-fg [&_button:not([data-slot=message-timing-trigger])]:size-8 [&_button]:!rounded-full [&_button:hover]:bg-chat-icon-bg-hover [&_button:hover]:text-chat-icon-fg-hover"
>
<CopyButton />
+ <EditAssistantMessageButton />
<ActionBarPrimitive.Reload asChild={true}>
<TooltipIconButton tooltip="Refresh">
<RefreshCwIcon strokeWidth={1.75} className="size-icon" />
@@ -3457,7 +3576,11 @@ const AssistantActionBar: FC = () => {
</ActionBarMorePrimitive.Item>
<ActionBarPrimitive.ExportMarkdown asChild={true}>
<ActionBarMorePrimitive.Item className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-[12px] px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground">
- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />
+ <HugeiconsIcon
+ icon={Download01Icon}
+ strokeWidth={1.75}
+ className="size-icon"
+ />
Export as Markdown
</ActionBarMorePrimitive.Item>
</ActionBarPrimitive.ExportMarkdown>
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 68b8d1d523e..f5db82366c2 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -606,6 +606,7 @@ type ChatRuntimeStore = {
*/
incognito: boolean;
settingsPanelOpen: boolean;
+ editingMessageId: string | null;
pendingAudioBase64: string | null;
pendingAudioName: string | null;
pendingImageEditReference: PendingImageEditReference | null;
@@ -639,6 +640,7 @@ type ChatRuntimeStore = {
setActiveProjectId: (projectId: string | null) => void;
setIncognito: (incognito: boolean) => void;
setSettingsPanelOpen: (open: boolean) => void;
+ setEditingMessageId: (id: string | null) => void;
clearCheckpoint: () => void;
setReasoningEnabled: (
enabled: boolean,
@@ -1012,6 +1014,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
activeProjectId: null,
incognito: false,
settingsPanelOpen: false,
+ editingMessageId: null,
pendingAudioBase64: null,
pendingAudioName: null,
pendingImageEditReference: null,
@@ -1186,6 +1189,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
setActiveProjectId: (activeProjectId) => set({ activeProjectId }),
setIncognito: (incognito) => set({ incognito }),
setSettingsPanelOpen: (settingsPanelOpen) => set({ settingsPanelOpen }),
+ setEditingMessageId: (id) => set({ editingMessageId: id }),
clearCheckpoint: () => {
// Mirror setCheckpoint's persistence: dropping the checkpoint must also
// clear any stored external selection so the next refresh doesn't snap
diff --git a/studio/frontend/src/features/chat/utils/update-thread-message.ts b/studio/frontend/src/features/chat/utils/update-thread-message.ts
new file mode 100644
index 00000000000..5029b059561
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/update-thread-message.ts
@@ -0,0 +1,155 @@
+import type { ExportedMessageRepository, ThreadMessage } from "@assistant-ui/react";
+import { saveChatMessage } from "../api/chat-api";
+
+type ThreadImportExport = {
+ export: () => ExportedMessageRepository;
+ import: (data: ExportedMessageRepository) => void;
+};
+
+type ContentPart = { type: "text" | "reasoning" | "tool"; text: string };
+
+/**
+ * Extracts only the editable text and reasoning from a message,
+ * ignoring structured parts like tool calls that cannot be edited as plain text.
+ */
+export function extractTaggedText(content: any): string {
+ if (typeof content === 'string') return content;
+ if (!Array.isArray(content)) return "";
+
+ const open = "\u003C"; // <
+ const close = "\u003E"; // >
+
+ return content
+ .map((part: any) => {
+ if (typeof part === 'string') return part;
+ if (!part) return "";
+
+ // Only extract text from 'text' or 'reasoning' parts.
+ // Tool calls/responses are ignored here so they aren't accidentally
+ // deleted or corrupted by the user in the textarea.
+ const text = part.text || part.content || "";
+ if (!text) return "";
+
+ switch (part.type) {
+ case 'reasoning':
+ // Trim the text first so we don't accumulate newlines
+ // around the tags on every save.
+ return `${open}THINK${close}\n${text.trim()}\n${open}/THINK${close}`;
+ case 'text':
+ default:
+ return text;
+ }
+ })
+ .filter(Boolean)
+ .join('\n\n');
+}
+
+function parseTaggedTextToContent(text: string): ContentPart[] {
+ const parts: ContentPart[] = [];
+ const tagRegex = /(<\/?(THINK|TOOL)>)/g;
+ let lastIndex = 0;
+ let match;
+ let currentType: ContentPart["type"] = "text";
+
+ while ((match = tagRegex.exec(text)) !== null) {
+ const fullTag = match[0];
+ const tagName = match[2];
+ const index = match.index;
+
+ if (index > lastIndex) {
+ // Trim the extracted content to remove any leading/trailing
+ // newlines created by the tag wrapping process.
+ const content = text.substring(lastIndex, index).trim();
+ if (content) parts.push({ type: currentType, text: content });
+ }
+
+ currentType = fullTag.startsWith("</") ? "text" : (tagName === "THINK" ? "reasoning" : "tool");
+ lastIndex = index + fullTag.length;
+ }
+
+ if (lastIndex < text.length) {
+ const remainingText = text.substring(lastIndex).trim();
+ if (remainingText) parts.push({ type: currentType, text: remainingText });
+ }
+
+ return parts;
+}
+
+export async function updateThreadMessage(args: {
+ thread: ThreadImportExport;
+ messageId: string;
+ remoteId: string | undefined;
+ newText: string;
+ isIncognito: boolean; // <--- ADD THIS
+}) {
+ const { thread, messageId, remoteId, newText, isIncognito } = args;
+ const parsedEditableContent = parseTaggedTextToContent(newText);
+ const currentExport = thread.export();
+
+ const targetMessageEntry = currentExport.messages.find(m => m.message.id === messageId);
+ if (!targetMessageEntry) {
+ throw new Error(`Message with ID ${messageId} not found in thread.`);
+ }
+
+ const { parentId: originalParentId } = targetMessageEntry;
+ const { createdAt: originalCreatedAt } = targetMessageEntry.message;
+
+ const updatedMessages = currentExport.messages.map((m) => {
+ if (m.message.id !== messageId) return m;
+
+ const originalContent = m.message.content;
+ let finalContent: any[] = [];
+
+ if (Array.isArray(originalContent)) {
+ const firstEditableIndex = originalContent.findIndex((part: any) =>
+ part.type === 'text' || part.type === 'reasoning'
+ );
+
+ if (firstEditableIndex === -1) {
+ const nonEditableParts = originalContent.filter((part: any) =>
+ part.type !== 'text' && part.type !== 'reasoning'
+ );
+ finalContent = [...parsedEditableContent, ...nonEditableParts];
+ } else {
+ const before = originalContent.slice(0, firstEditableIndex);
+ const after = originalContent.slice(firstEditableIndex + 1).filter((part: any) =>
+ part.type !== 'text' && part.type !== 'reasoning'
+ );
+ finalContent = [...before, ...parsedEditableContent, ...after];
+ }
+ } else {
+ finalContent = parsedEditableContent;
+ }
+
+ return {
+ ...m,
+ message: {
+ ...m.message,
+ content: finalContent,
+ },
+ };
+ }) as typeof currentExport.messages;
+
+ const originalExport = currentExport;
+ thread.import({ ...currentExport, messages: updatedMessages });
+
+ // If it's NOT incognito, we attempt to save to the DB regardless of the ID.
+ if (remoteId && !isIncognito) {
+ try {
+ await saveChatMessage({
+ id: messageId,
+ threadId: remoteId,
+ parentId: originalParentId,
+ role: "assistant",
+ content: (updatedMessages.find(m => m.message.id === messageId)?.message.content) || [],
+ createdAt: originalCreatedAt ? Number(originalCreatedAt) : Date.now(),
+ });
+ } catch (e) {
+ thread.import(originalExport);
+ console.error("Backend sync failed for message update. Rolling back UI.", e);
+ throw e;
+ }
+ }
+
+ return (updatedMessages.find(m => m.message.id === messageId)?.message.content) || [];
+}
\ No newline at end of file