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.

Studio: paste links, tables, lists and formatting into the composer as Markdown (#16298)

Michael Han63a3896459a9
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 025e62fb61a..759fb08b9cc 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -131,6 +131,8 @@ import {
pasteLongTextAsFile,
isPlainPasteChord,
plainPasteStillCounts,
+ insertAtCaret,
+ richPasteMarkdown,
currentDictationEntryMode,
isStudioDictationAvailable,
notifyStudioDictationUnavailable,
@@ -3033,6 +3035,7 @@ const Composer: FC<{
const pastedTextMinChars = useChatPreferencesStore(
(state) => state.pastedTextMinChars,
);
+ const richTextPaste = useChatPreferencesStore((s) => s.richTextPaste);
const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
const submitIntentRef = useRef<ComposerSubmitIntent>("default");
const submitOnKey = useCallback(
@@ -3147,6 +3150,21 @@ const Composer: FC<{
}),
);
if (event.defaultPrevented) return;
+ const markdown =
+ richTextPaste && !plainPaste ? richPasteMarkdown(event.clipboardData) : null;
+ if (markdown !== null) {
+ event.preventDefault();
+ if (pastedYoutubeUrl) setYoutubeLink(pastedYoutubeUrl);
+ // Before inserting: execCommand's input event is not a paste, so the guard would refuse a resend.
+ if (justSentRef.current?.draftKey === draftKeyRef.current) {
+ justSentRef.current = null;
+ }
+ insertAtCaret(input, markdown, (next, caret) => {
+ aui.composer().setText(next);
+ requestAnimationFrame(() => input.setSelectionRange(caret, caret));
+ });
+ return;
+ }
if (pastedYoutubeUrl) {
setYoutubeLink(pastedYoutubeUrl);
if (!pastedText.includes(pastedYoutubeUrl)) {
@@ -3179,7 +3197,7 @@ const Composer: FC<{
justSentRef.current = null;
}
},
- [aui, overlay, pastedTextMinChars],
+ [aui, overlay, pastedTextMinChars, richTextPaste],
);
const composerText = useAuiState(({ composer }) => composer.text);
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index fe4a0b15051..733ecd7621f 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -460,6 +460,7 @@ export {
pastedTextPreview,
shouldAttachPastedText,
} from "./utils/pasted-text";
+export { insertAtCaret, richPasteMarkdown } from "./utils/rich-paste";
export { useBookmarkedTurnsStore } from "./stores/bookmarked-turns-store";
export {
type DocumentAnnotation,
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index e633c4b5735..860e626b06e 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -93,6 +93,8 @@ import {
import { modelIdsMatch } from "@/features/hub/lib/model-identity";
import { CONVERSATION_MARKDOWN_LABEL } from "./utils/conversation-markdown";
import { pasteClipboardFiles } from "./utils/clipboard-files";
+import { insertAtCaret, richPasteMarkdown } from "./utils/rich-paste";
+import { isPlainPasteChord, plainPasteStillCounts } from "./utils/pasted-text";
import {
composerDraftKey,
latestDraft,
@@ -623,6 +625,7 @@ export function SharedComposer({
}): ReactElement {
const t = useT();
const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
+ const richTextPaste = useChatPreferencesStore((s) => s.richTextPaste);
const navigate = useNavigate();
const handleExitCompare = useCallback(() => {
if (onExitCompare) {
@@ -1337,8 +1340,12 @@ export function SharedComposer({
[trackAttaching, addFilesUntracked],
);
+ // Plain paste: a paste event carries no modifiers, so the chord is read from the keydown before it.
+ const plainPasteAtRef = useRef(0);
const handleFilePaste = useCallback(
(event: ClipboardEvent<HTMLTextAreaElement>) => {
+ const plainPaste = plainPasteStillCounts(plainPasteAtRef.current, performance.now());
+ plainPasteAtRef.current = 0;
pasteClipboardFiles(
event,
(pasted) =>
@@ -1357,8 +1364,17 @@ export function SharedComposer({
description: "Compare supports images and audio within the attachment size limits.",
}),
);
+ if (event.defaultPrevented || !richTextPaste || plainPaste) return;
+ const markdown = richPasteMarkdown(event.clipboardData);
+ if (markdown === null) return;
+ event.preventDefault();
+ const input = event.currentTarget;
+ insertAtCaret(input, markdown, (next, caret) => {
+ setCurrentText(next);
+ requestAnimationFrame(() => input.setSelectionRange(caret, caret));
+ });
},
- [trackAttaching, addFilesUntracked],
+ [trackAttaching, addFilesUntracked, richTextPaste, setCurrentText],
);
const removePendingImage = useCallback((id: string) => {
@@ -3074,8 +3090,15 @@ export function SharedComposer({
onKeyDown={(event) => {
if (!skillMentions.onKeyDown(event)) onKeyDown(event);
}}
+ onKeyDownCapture={(event) => {
+ plainPasteAtRef.current = isPlainPasteChord(event) ? performance.now() : 0;
+ }}
+ onKeyUpCapture={() => {
+ plainPasteAtRef.current = 0;
+ }}
onPaste={handleFilePaste}
onBlur={() => {
+ plainPasteAtRef.current = 0;
// Mac: switching input methods can fire compositionstart without a matching compositionend,
// leaving composingRef pinned. The OS always commits or cancels before focus is lost.
imeSessionOpenRef.current = false;
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index 57cffe5262b..ed83bf12f09 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -60,6 +60,8 @@ export interface ChatPreferencesState {
setNewChatComposerAtBottom: (value: boolean) => void;
showTurnNavigation: boolean;
setShowTurnNavigation: (value: boolean) => void;
+ richTextPaste: boolean;
+ setRichTextPaste: (value: boolean) => void;
}
// A stale stored value would leave the dropdown blank and unfixable.
@@ -123,6 +125,8 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
set({ newChatComposerAtBottom }),
showTurnNavigation: true,
setShowTurnNavigation: (showTurnNavigation) => set({ showTurnNavigation }),
+ richTextPaste: true,
+ setRichTextPaste: (richTextPaste) => set({ richTextPaste }),
}),
{
name: "unsloth_chat_preferences",
@@ -170,6 +174,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
notifyWhenReplyFinishes: saved?.notifyWhenReplyFinishes === true,
filesPanelCollapsed: saved?.filesPanelCollapsed === true,
showTurnNavigation: saved?.showTurnNavigation !== false,
+ richTextPaste: saved?.richTextPaste !== false,
newChatComposerAtBottom: saved?.newChatComposerAtBottom === true,
};
},
diff --git a/studio/frontend/src/features/chat/utils/rich-paste.ts b/studio/frontend/src/features/chat/utils/rich-paste.ts
new file mode 100644
index 00000000000..c7088e6f4be
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/rich-paste.ts
@@ -0,0 +1,283 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export interface PasteNode {
+ nodeType: number;
+ nodeName: string;
+ childNodes: ArrayLike<PasteNode>;
+ textContent: string | null;
+ getAttribute?: (name: string) => string | null;
+}
+
+type Ctx = { pre: boolean; bold: boolean; italic: boolean };
+
+// Everything convert() can turn into Markdown, styled spans included.
+const STRUCTURE =
+ /<a\s[^>]*\bhref|<(?:table|ul|ol|h[1-6]|blockquote|pre|strong|em|del|s|b|i)[\s>]|font-weight:\s*(?:bold|[6-9]00)|font-style:\s*italic/i;
+const SKIP = new Set([
+ "SCRIPT", "STYLE", "HEAD", "TITLE", "META", "LINK", "NOSCRIPT", "TEMPLATE",
+ "SVG", "BUTTON", "INPUT", "SELECT", "TEXTAREA", "IMG", "PICTURE", "VIDEO",
+ "AUDIO", "IFRAME", "OBJECT", "CANVAS",
+]);
+const BLOCK = new Set([
+ "P", "DIV", "SECTION", "ARTICLE", "HEADER", "FOOTER", "MAIN", "ASIDE",
+ "NAV", "FIGURE", "FIGCAPTION", "DL", "DT", "DD", "BODY", "HTML", "CAPTION",
+]);
+const INDENT = "\u0001";
+const FENCE_OPEN = "\u0002";
+const FENCE_CLOSE = "\u0003";
+
+function attr(node: PasteNode, name: string): string {
+ return node.getAttribute?.(name) ?? "";
+}
+
+function elements(node: PasteNode): PasteNode[] {
+ return Array.from(node.childNodes).filter((child) => child.nodeType === 1);
+}
+
+function children(node: PasteNode, ctx: Ctx): string {
+ return Array.from(node.childNodes)
+ .map((child) => convert(child, ctx))
+ .join("");
+}
+
+const FENCED = new RegExp(`${FENCE_OPEN}[\\s\\S]*?${FENCE_CLOSE}`, "g");
+
+function clean(text: string): string {
+ const fences: string[] = [];
+ return text
+ .replace(FENCED, (block) => `${FENCE_OPEN}${fences.push(block) - 1}${FENCE_CLOSE}`)
+ .replace(/[ \t]+\n/g, "\n")
+ .replace(/\n[ \t]+/g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim()
+ .replace(new RegExp(`${FENCE_OPEN}(\\d+)${FENCE_CLOSE}`, "g"), (_, i: string) => fences[Number(i)]);
+}
+
+function wrap(marker: string, inner: string): string {
+ const body = inner.trim();
+ if (!body) return inner;
+ const lead = inner.slice(0, inner.length - inner.trimStart().length);
+ const trail = inner.slice(inner.trimEnd().length);
+ return `${lead}${marker}${body}${marker}${trail}`;
+}
+
+function safeHref(raw: string): string | null {
+ const href = raw.trim();
+ if (!/^(?:https?:|mailto:)/i.test(href)) return null;
+ return href.replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29");
+}
+
+function codeSpan(text: string): string {
+ const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
+ const ticks = "`".repeat(longest + 1);
+ const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";
+ return `${ticks}${pad}${text}${pad}${ticks}`;
+}
+
+// textContent drops <br>, which some editors use for the line breaks in code.
+function preText(node: PasteNode): string {
+ if (node.nodeType === 3) return node.textContent ?? "";
+ if (node.nodeName.toUpperCase() === "BR") return "\n";
+ return Array.from(node.childNodes).map(preText).join("");
+}
+
+function preBlock(node: PasteNode): string {
+ const code = elements(node).find((child) => child.nodeName.toUpperCase() === "CODE");
+ const cls = `${attr(node, "class")} ${code ? attr(code, "class") : ""}`;
+ const lang = /(?:language|lang)-([\w+#-]+)/.exec(cls)?.[1] ?? "";
+ const text = preText(node).replace(/\n$/, "");
+ const fence = "`".repeat(Math.max(3, ...(text.match(/`{3,}/g) ?? []).map((run) => run.length + 1)));
+ return `\n\n${FENCE_OPEN}${fence}${lang}\n${text}\n${fence}${FENCE_CLOSE}\n\n`;
+}
+
+function list(node: PasteNode, ctx: Ctx, ordered: boolean): string {
+ let index = Number.parseInt(attr(node, "start"), 10) || 1;
+ const lines: string[] = [];
+ for (const item of elements(node)) {
+ const tag = item.nodeName.toUpperCase();
+ if (tag === "UL" || tag === "OL") {
+ for (const line of list(item, ctx, tag === "OL").split("\n"))
+ lines.push(`${INDENT.repeat(ordered ? 3 : 2)}${line}`);
+ continue;
+ }
+ const marker = ordered ? `${index++}.` : "-";
+ // Blank lines are kept only inside fenced code.
+ let fenced = false;
+ const body = clean(children(item, ctx))
+ .split("\n")
+ .filter((line) => {
+ const keep = fenced || line.trim() !== "";
+ if (line.includes(FENCE_OPEN)) fenced = true;
+ if (line.includes(FENCE_CLOSE)) fenced = false;
+ return keep;
+ });
+ const [first = "", ...rest] = body;
+ lines.push(`${marker} ${first}`);
+ for (const line of rest) lines.push(line ? `${INDENT.repeat(marker.length + 1)}${line}` : "");
+ }
+ return lines.join("\n");
+}
+
+function tableRows(node: PasteNode): PasteNode[] {
+ const rows: PasteNode[] = [];
+ for (const child of elements(node)) {
+ const tag = child.nodeName.toUpperCase();
+ if (tag === "TR") rows.push(child);
+ else if (tag === "THEAD" || tag === "TBODY" || tag === "TFOOT") rows.push(...tableRows(child));
+ }
+ return rows;
+}
+
+function span(cell: PasteNode, name: string, max: number): number {
+ const value = Number.parseInt(attr(cell, name), 10);
+ return Number.isFinite(value) && value > 0 ? Math.min(value, max) : 1;
+}
+
+function table(node: PasteNode, ctx: Ctx): string {
+ const physical = tableRows(node);
+ // Lay merged cells onto the grid so every value stays under its own header.
+ const rows: string[][] = physical.map(() => []);
+ physical.forEach((row, r) => {
+ let c = 0;
+ for (const cell of elements(row).filter((child) => /^T[DH]$/i.test(child.nodeName))) {
+ while (rows[r][c] !== undefined) c++;
+ const text = clean(children(cell, ctx))
+ .replace(new RegExp(`[${INDENT}${FENCE_OPEN}${FENCE_CLOSE}]`, "g"), "")
+ .replace(/\s*\n\s*/g, " ")
+ .replace(/\|/g, "\\|");
+ const cols = span(cell, "colspan", 1000);
+ const down = span(cell, "rowspan", physical.length - r);
+ for (let dr = 0; dr < down; dr++)
+ for (let dc = 0; dc < cols; dc++) rows[r + dr][c + dc] = dr === 0 && dc === 0 ? text : "";
+ c += cols;
+ }
+ });
+ const width = Math.max(0, ...rows.map((row) => row.length));
+ if (rows.length === 0 || width === 0) return children(node, ctx);
+ const line = (cells: string[]) =>
+ `| ${Array.from({ length: width }, (_, i) => cells[i] ?? "").join(" | ")} |`;
+ const [head, ...body] = rows;
+ const caption = elements(node).find((child) => child.nodeName.toUpperCase() === "CAPTION");
+ const title = caption ? clean(children(caption, ctx)).replace(/\s*\n\s*/g, " ") : "";
+ return [...(title ? [title, ""] : []), line(head), `| ${Array(width).fill("---").join(" | ")} |`, ...body.map(line)].join("\n");
+}
+
+function convert(node: PasteNode, ctx: Ctx): string {
+ if (node.nodeType === 3) {
+ const text = node.textContent ?? "";
+ return ctx.pre ? text : text.replace(/\s+/g, " ");
+ }
+ if (node.nodeType !== 1) return "";
+ const tag = node.nodeName.toUpperCase();
+ if (SKIP.has(tag)) return "";
+ const style = attr(node, "style").toLowerCase();
+ switch (tag) {
+ case "BR":
+ return "\n";
+ case "HR":
+ return "\n\n---\n\n";
+ case "A": {
+ const raw = attr(node, "href").trim();
+ const href = safeHref(raw);
+ const inner = children(node, ctx);
+ if (!href) return inner;
+ const text = inner.trim();
+ const lead = inner.slice(0, inner.length - inner.trimStart().length);
+ const trail = inner.slice(inner.trimEnd().length);
+ if (!text || text === raw || text === href || `mailto:${text}` === raw) return `${lead}${href}${trail}`;
+ return `${lead}[${text.replace(/([[\]])/g, "\\$1")}](${href})${trail}`;
+ }
+ case "STRONG":
+ case "B":
+ // Google Docs wraps every copy in <b style="font-weight:normal">.
+ if (ctx.bold || /font-weight:\s*(?:normal|[1-4]00)/.test(style)) return children(node, ctx);
+ return wrap("**", children(node, { ...ctx, bold: true }));
+ case "EM":
+ case "I":
+ if (ctx.italic) return children(node, ctx);
+ return wrap("*", children(node, { ...ctx, italic: true }));
+ case "DEL":
+ case "S":
+ case "STRIKE":
+ return wrap("~~", children(node, ctx));
+ case "CODE":
+ return ctx.pre ? children(node, ctx) : codeSpan(node.textContent ?? "");
+ case "PRE":
+ return preBlock(node);
+ case "H1":
+ case "H2":
+ case "H3":
+ case "H4":
+ case "H5":
+ case "H6":
+ return `\n\n${"#".repeat(Number(tag[1]))} ${clean(children(node, { ...ctx, bold: true })).replace(/\n+/g, " ")}\n\n`;
+ case "BLOCKQUOTE":
+ return `\n\n${clean(children(node, ctx))
+ .split("\n")
+ .map((line) => (line ? `> ${line}` : ">"))
+ .join("\n")}\n\n`;
+ case "UL":
+ case "OL":
+ return `\n\n${list(node, ctx, tag === "OL")}\n\n`;
+ case "TABLE":
+ return `\n\n${table(node, ctx)}\n\n`;
+ case "SPAN": {
+ let inner = children(node, {
+ ...ctx,
+ bold: ctx.bold || /font-weight:\s*(?:bold|[6-9]00)/.test(style),
+ italic: ctx.italic || /font-style:\s*italic/.test(style),
+ });
+ if (!ctx.italic && /font-style:\s*italic/.test(style)) inner = wrap("*", inner);
+ if (!ctx.bold && /font-weight:\s*(?:bold|[6-9]00)/.test(style)) inner = wrap("**", inner);
+ return inner;
+ }
+ default:
+ return BLOCK.has(tag) ? `\n\n${children(node, ctx)}\n\n` : children(node, ctx);
+ }
+}
+
+export function htmlNodeToMarkdown(root: PasteNode): string {
+ return clean(convert(root, { pre: false, bold: false, italic: false })).replace(
+ new RegExp(`[${INDENT}${FENCE_OPEN}${FENCE_CLOSE}]`, "g"),
+ (mark) => (mark === INDENT ? " " : ""),
+ );
+}
+
+const squash = (text: string) => text.replace(/\s+/g, " ").trim();
+
+export function richPasteMarkdown(
+ data: Pick<DataTransfer, "getData" | "types"> | null | undefined,
+ parse: (html: string) => PasteNode | null = parseHtml,
+): string | null {
+ if (!data) return null;
+ // Skip VS Code and other editors' syntax-colored HTML.
+ if (Array.from(data.types ?? []).includes("vscode-editor-data")) return null;
+ const html = data.getData("text/html");
+ if (!html || !STRUCTURE.test(html)) return null;
+ const root = parse(html);
+ if (!root) return null;
+ const markdown = htmlNodeToMarkdown(root);
+ const plain = data.getData("text/plain");
+ if (!markdown || squash(markdown) === squash(plain)) return null;
+ // Restore the copied text's edge whitespace, which conversion trims.
+ return `${/^\s*/.exec(plain)?.[0] ?? ""}${markdown}${/\s*$/.exec(plain)?.[0] ?? ""}`;
+}
+
+function parseHtml(html: string): PasteNode | null {
+ if (typeof DOMParser === "undefined") return null;
+ // Inert document: nothing in it runs or loads.
+ return new DOMParser().parseFromString(html, "text/html").body as unknown as PasteNode;
+}
+
+export function insertAtCaret(
+ input: HTMLTextAreaElement,
+ text: string,
+ fallback: (next: string, caret: number) => void,
+): void {
+ input.focus();
+ // execCommand is the only insertion that joins the native undo stack.
+ if (document.execCommand?.("insertText", false, text)) return;
+ const { selectionStart, selectionEnd, value } = input;
+ fallback(value.slice(0, selectionStart) + text + value.slice(selectionEnd), selectionStart + text.length);
+}
diff --git a/studio/frontend/src/features/settings/components/composer-settings.tsx b/studio/frontend/src/features/settings/components/composer-settings.tsx
index 6847ffe80f8..d62e6599122 100644
--- a/studio/frontend/src/features/settings/components/composer-settings.tsx
+++ b/studio/frontend/src/features/settings/components/composer-settings.tsx
@@ -3,6 +3,7 @@
import { useEffect, useId, useRef } from "react";
import { SegmentedPill } from "@/components/segmented-control";
+import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
@@ -143,6 +144,19 @@ export function ComposerSettings({ embedded = false }: { embedded?: boolean }) {
onCheckedChange={prefs.setPlainTextComposer}
/>
</SettingsRow>
+ <SettingsRow
+ label={t("composerSettings.richPaste")}
+ badge={<Badge variant="secondary" className="h-4 px-1.5 text-[10px] text-muted-foreground">{t("shell.beta")}</Badge>}
+ description={t("composerSettings.richPasteDescription", {
+ shortcut: isMacPlatform() ? "\u21e7\u2318V" : "Ctrl+Shift+V",
+ })}
+ >
+ <Switch
+ aria-label={t("composerSettings.richPaste")}
+ checked={prefs.richTextPaste}
+ onCheckedChange={prefs.setRichTextPaste}
+ />
+ </SettingsRow>
<SettingsRow label={t("composerSettings.showContext")}>
<Switch
aria-label={t("composerSettings.showContext")}
diff --git a/studio/frontend/src/features/settings/components/settings-row.tsx b/studio/frontend/src/features/settings/components/settings-row.tsx
index 760cc30d7df..3409d172050 100644
--- a/studio/frontend/src/features/settings/components/settings-row.tsx
+++ b/studio/frontend/src/features/settings/components/settings-row.tsx
@@ -15,6 +15,7 @@ export function SettingsRow({
label,
description,
hint,
+ badge,
icon,
iconAlign = "center",
children,
@@ -27,6 +28,7 @@ export function SettingsRow({
description?: ReactNode;
/** Shown on hover; plain text because it doubles as the trigger's aria-label. */
hint?: string;
+ badge?: ReactNode;
icon?: ReactNode;
iconAlign?: "center" | "top";
children?: ReactNode;
@@ -56,6 +58,7 @@ export function SettingsRow({
<div className="flex min-w-0 w-full max-w-[calc(32rem*var(--ui-space-scale,1))] flex-col gap-0.5">
<span className="text-sm font-medium text-foreground">
{label}
+ {badge ? <span className="ml-1.5 inline-flex align-middle">{badge}</span> : null}
{hint ? (
<Tooltip>
<TooltipTrigger asChild={true}>
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index e3b522dbe14..f3311430c54 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -136,6 +136,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"composerSettings.sendShortcut",
"composerSettings.followUp",
"composerSettings.plainText",
+ "composerSettings.richPaste",
"composerSettings.showContext",
"settings.chat.pastedTextThreshold",
"settings.chat.turnNavigation",
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 1fd6a894e97..91bc11a690b 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -652,6 +652,8 @@ export const ar = {
title: "كتابة الرسائل",
plainText: "محرر نص عادي",
plainTextDescription: "إبقاء التعليمات البرمجية وMarkdown والروابط كنص حرفي. عطّل هذا الخيار لعرض معاينة منسقة.",
+ richPaste: "لصق النص المنسّق",
+ richPasteDescription: "يلصق الروابط والجداول والتنسيق بصيغة Markdown. {shortcut} يلصق نصًا عاديًا. محرر نص منسق كامل قريبًا.",
showContext: "إظهار استخدام نافذة السياق",
sendShortcut: "اختصار الإرسال",
sendMultiline: "{mod} + Enter للرسائل متعددة الأسطر",
diff --git a/studio/frontend/src/i18n/locales/cs.ts b/studio/frontend/src/i18n/locales/cs.ts
index 14cde0fe964..603a917f948 100644
--- a/studio/frontend/src/i18n/locales/cs.ts
+++ b/studio/frontend/src/i18n/locales/cs.ts
@@ -737,6 +737,8 @@ export const cs = {
plainText: "Pole zprávy s prostým textem",
plainTextDescription:
"Ponechá kód, Markdown a odkazy jako doslovný text. Po vypnutí se zobrazí formátovaný náhled.",
+ richPaste: "Vkládání formátovaného textu",
+ richPasteDescription: "Vkládá odkazy, tabulky a formátování jako Markdown. {shortcut} vloží prostý text. Plný editor formátovaného textu brzy.",
showContext: "Využití kontextového okna",
sendShortcut: "Zkratka pro odeslání",
sendMultiline: "{mod} + Enter pro víceřádkové prompty",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index f6b49f4dcf2..a2ed9d1bac9 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -652,6 +652,8 @@ export const de = {
title: "Nachrichteneingabe",
plainText: "Eingabe als Klartext",
plainTextDescription: "Code, Markdown und Links als wörtlichen Text anzeigen. Ausschalten, um eine formatierte Vorschau zu sehen.",
+ richPaste: "Formatiert einfügen",
+ richPasteDescription: "Fügt Links, Tabellen und Formatierung als Markdown ein. {shortcut} fügt reinen Text ein. Vollständiger Rich-Text-Editor folgt bald.",
showContext: "Auslastung des Kontextfensters anzeigen",
sendShortcut: "Tastenkürzel zum Senden",
sendMultiline: "{mod} + Enter bei mehrzeiligen Nachrichten",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 3add17f0b39..85be3835507 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -649,6 +649,8 @@ export const en = {
title: "Composer",
plainText: "Plain text composer",
plainTextDescription: "Keep code, Markdown, and links as literal text. Turn off to show a formatted preview.",
+ richPaste: "Rich text paste",
+ richPasteDescription: "Pastes links, tables and formatting as Markdown. {shortcut} pastes plain text. Full rich text composer coming soon.",
showContext: "Context window usage",
sendShortcut: "Send shortcut",
sendMultiline: "{mod} + Enter for multiline prompts",
diff --git a/studio/frontend/src/i18n/locales/es-419.ts b/studio/frontend/src/i18n/locales/es-419.ts
index 80658fa7143..24d98326bdc 100644
--- a/studio/frontend/src/i18n/locales/es-419.ts
+++ b/studio/frontend/src/i18n/locales/es-419.ts
@@ -740,6 +740,8 @@ export const es419 = {
plainText: "Redactor de texto sin formato",
plainTextDescription:
"Mantiene el código, Markdown y los enlaces como texto literal. Desactívalo para mostrar una vista previa con formato.",
+ richPaste: "Pegar texto con formato",
+ richPasteDescription: "Pega enlaces, tablas y formato como Markdown. {shortcut} pega texto sin formato. Pronto, un editor de texto enriquecido completo.",
showContext: "Uso de la ventana de contexto",
sendShortcut: "Atajo para enviar",
sendMultiline: "{mod} + Enter en mensajes de varias líneas",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index afd7dd2995e..3d1b9db7f01 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -652,6 +652,8 @@ export const es = {
title: "Redacción de mensajes",
plainText: "Redactor de texto sin formato",
plainTextDescription: "Mantener el código, Markdown y los enlaces como texto literal. Desactívalo para mostrar una vista previa con formato.",
+ richPaste: "Pegar texto con formato",
+ richPasteDescription: "Pega enlaces, tablas y formato como Markdown. {shortcut} pega texto sin formato. Pronto, un editor de texto enriquecido completo.",
showContext: "Mostrar uso de la ventana de contexto",
sendShortcut: "Atajo para enviar",
sendMultiline: "{mod} + Enter en mensajes de varias líneas",
diff --git a/studio/frontend/src/i18n/locales/fa.ts b/studio/frontend/src/i18n/locales/fa.ts
index ee027757466..b294e584b68 100644
--- a/studio/frontend/src/i18n/locales/fa.ts
+++ b/studio/frontend/src/i18n/locales/fa.ts
@@ -733,6 +733,8 @@ export const fa = {
plainText: "کادر نوشتن متن ساده",
plainTextDescription:
"کد، Markdown و پیوندها به‌صورت متن خام نگه داشته شوند. برای نمایش پیش‌نمایش قالب‌بندی‌شده، خاموش کنید.",
+ richPaste: "چسباندن متن قالب‌دار",
+ richPasteDescription: "پیوندها، جدول‌ها و قالب‌بندی را به‌صورت Markdown می‌چسباند. {shortcut} متن ساده می‌چسباند. ویرایشگر کامل متن غنی به‌زودی.",
showContext: "میزان استفاده از پنجرهٔ زمینه",
sendShortcut: "میان‌بر ارسال",
sendMultiline: "{mod} + Enter برای پرامپت‌های چندخطی",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 9254d516786..56ef9865bb5 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -652,6 +652,8 @@ export const fr = {
title: "Saisie des messages",
plainText: "Saisie en texte brut",
plainTextDescription: "Conserver le code, le Markdown et les liens en texte brut. Désactivez pour afficher un aperçu mis en forme.",
+ richPaste: "Coller le texte enrichi",
+ richPasteDescription: "Colle liens, tableaux et mise en forme en Markdown. {shortcut} colle du texte brut. Éditeur de texte enrichi complet bientôt disponible.",
showContext: "Afficher l’utilisation de la fenêtre de contexte",
sendShortcut: "Raccourci d’envoi",
sendMultiline: "{mod} + Enter pour les messages sur plusieurs lignes",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index e1edfdcb1e7..1b58aa81f24 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -686,6 +686,8 @@ export const he = {
plainText: "עורך טקסט פשוט",
plainTextDescription:
"שמור קוד, Markdown וקישורים כטקסט מילולי. כבה כדי להציג תצוגה מקדימה מעוצבת.",
+ richPaste: "הדבקת טקסט מעוצב",
+ richPasteDescription: "מדביק קישורים, טבלאות ועיצוב כ-Markdown. {shortcut} מדביק טקסט פשוט. עורך טקסט עשיר מלא בקרוב.",
showContext: "שימוש בחלון ההקשר",
sendShortcut: "קיצור שליחה",
sendMultiline: "{mod} + Enter להנחיות מרובות שורות",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 86cad297575..9b94d96c820 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -652,6 +652,8 @@ export const hi = {
title: "संदेश लिखना",
plainText: "सादा टेक्स्ट इनपुट",
plainTextDescription: "कोड, Markdown और लिंक को मूल टेक्स्ट के रूप में रखें। फ़ॉर्मैट किया हुआ पूर्वावलोकन दिखाने के लिए इसे बंद करें।",
+ richPaste: "रिच टेक्स्ट पेस्ट",
+ richPasteDescription: "लिंक, टेबल और फ़ॉर्मैटिंग को Markdown के रूप में पेस्ट करता है। {shortcut} सादा टेक्स्ट पेस्ट करता है। पूरा रिच टेक्स्ट कंपोज़र जल्द आ रहा है।",
showContext: "कॉन्टेक्स्ट विंडो का उपयोग दिखाएँ",
sendShortcut: "भेजने का शॉर्टकट",
sendMultiline: "कई पंक्तियों वाले संदेशों के लिए {mod} + Enter",
diff --git a/studio/frontend/src/i18n/locales/id.ts b/studio/frontend/src/i18n/locales/id.ts
index df20235adfe..006a4d52f96 100644
--- a/studio/frontend/src/i18n/locales/id.ts
+++ b/studio/frontend/src/i18n/locales/id.ts
@@ -734,6 +734,8 @@ export const id = {
plainText: "Kolom pesan teks biasa",
plainTextDescription:
"Pertahankan kode, Markdown, dan tautan sebagai teks literal. Nonaktifkan untuk menampilkan pratinjau berformat.",
+ richPaste: "Tempel teks berformat",
+ richPasteDescription: "Menempel tautan, tabel, dan format sebagai Markdown. {shortcut} menempel teks biasa. Composer teks kaya lengkap segera hadir.",
showContext: "Penggunaan jendela konteks",
sendShortcut: "Pintasan kirim",
sendMultiline: "{mod} + Enter untuk prompt multibaris",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 24d97361b47..1c918c0f7d3 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -649,6 +649,8 @@ export const it = {
title: "Composizione dei messaggi",
plainText: "Composizione in testo semplice",
plainTextDescription: "Mantieni codice, Markdown e link come testo letterale. Disattiva per mostrare un’anteprima formattata.",
+ richPaste: "Incolla testo formattato",
+ richPasteDescription: "Incolla link, tabelle e formattazione come Markdown. {shortcut} incolla testo semplice. Editor di testo formattato completo in arrivo.",
showContext: "Mostra l’utilizzo della finestra di contesto",
sendShortcut: "Scorciatoia di invio",
sendMultiline: "{mod} + Enter per i messaggi su più righe",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index c1405e40044..4657f7746aa 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -653,6 +653,8 @@ export const ja = {
title: "入力欄",
plainText: "プレーンテキスト入力",
plainTextDescription: "コード、Markdown、リンクをそのままのテキストで表示します。オフにすると書式付きプレビューを表示します。",
+ richPaste: "書式付きテキストの貼り付け",
+ richPasteDescription: "リンク、表、書式を Markdown として貼り付けます。{shortcut} でプレーンテキスト。完全なリッチテキスト入力欄は近日公開。",
showContext: "コンテキストウィンドウの使用量を表示",
sendShortcut: "送信ショートカット",
sendMultiline: "複数行のメッセージは {mod} + Enter",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 5da416570b7..b735af9830b 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -652,6 +652,8 @@ export const ko = {
title: "메시지 입력",
plainText: "일반 텍스트 입력",
plainTextDescription: "코드, Markdown, 링크를 원문 그대로 표시합니다. 끄면 서식 미리보기를 표시합니다.",
+ richPaste: "서식 있는 텍스트 붙여넣기",
+ richPasteDescription: "링크, 표, 서식을 Markdown으로 붙여넣습니다. {shortcut}는 일반 텍스트로 붙여넣습니다. 완전한 서식 입력창은 곧 제공됩니다.",
showContext: "컨텍스트 창 사용량 표시",
sendShortcut: "전송 단축키",
sendMultiline: "여러 줄 메시지는 {mod} + Enter",
diff --git a/studio/frontend/src/i18n/locales/nl.ts b/studio/frontend/src/i18n/locales/nl.ts
index 237af5748c0..4cceffffe51 100644
--- a/studio/frontend/src/i18n/locales/nl.ts
+++ b/studio/frontend/src/i18n/locales/nl.ts
@@ -741,6 +741,8 @@ export const nl = {
plainText: "Invoerveld met platte tekst",
plainTextDescription:
"Behoud code, Markdown en links als letterlijke tekst. Schakel uit om een opgemaakt voorbeeld te tonen.",
+ richPaste: "Opgemaakte tekst plakken",
+ richPasteDescription: "Plakt links, tabellen en opmaak als Markdown. {shortcut} plakt platte tekst. Volledige rich-text-editor volgt binnenkort.",
showContext: "Gebruik van contextvenster",
sendShortcut: "Sneltoets voor versturen",
sendMultiline: "{mod} + Enter voor prompts met meerdere regels",
diff --git a/studio/frontend/src/i18n/locales/pl.ts b/studio/frontend/src/i18n/locales/pl.ts
index f9beace1c89..692cb93ee46 100644
--- a/studio/frontend/src/i18n/locales/pl.ts
+++ b/studio/frontend/src/i18n/locales/pl.ts
@@ -741,6 +741,8 @@ export const pl = {
plainText: "Pole wiadomości z czystym tekstem",
plainTextDescription:
"Zachowuj kod, Markdown i linki jako zwykły tekst. Wyłącz, aby pokazywać sformatowany podgląd.",
+ richPaste: "Wklejanie sformatowanego tekstu",
+ richPasteDescription: "Wkleja linki, tabele i formatowanie jako Markdown. {shortcut} wkleja zwykły tekst. Pełny edytor tekstu sformatowanego wkrótce.",
showContext: "Użycie okna kontekstu",
sendShortcut: "Skrót wysyłania",
sendMultiline: "{mod} + Enter dla promptów wielowierszowych",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 5d0e40da0b9..e9977ac65dc 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -652,6 +652,8 @@ export const ptBR = {
title: "Composição de mensagens",
plainText: "Composição em texto simples",
plainTextDescription: "Manter código, Markdown e links como texto literal. Desative para mostrar uma prévia formatada.",
+ richPaste: "Colar texto formatado",
+ richPasteDescription: "Cola links, tabelas e formatação como Markdown. {shortcut} cola texto simples. Editor de texto formatado completo em breve.",
showContext: "Mostrar uso da janela de contexto",
sendShortcut: "Atalho de envio",
sendMultiline: "{mod} + Enter para mensagens de várias linhas",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 764f7863c6f..465c4335ca7 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -652,6 +652,8 @@ export const ru = {
title: "Ввод сообщений",
plainText: "Обычный текст",
plainTextDescription: "Показывать код, Markdown и ссылки как обычный текст. Отключите для предпросмотра форматирования.",
+ richPaste: "Вставка форматированного текста",
+ richPasteDescription: "Вставляет ссылки, таблицы и форматирование как Markdown. {shortcut} вставляет обычный текст. Полноценный редактор форматированного текста скоро.",
showContext: "Показывать использование контекстного окна",
sendShortcut: "Клавиши отправки",
sendMultiline: "{mod} + Enter для многострочных сообщений",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 8c585013291..b5f2045a379 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -695,6 +695,8 @@ export const sv = {
plainText: "Skrivfält med oformaterad text",
plainTextDescription:
"Behåll kod, Markdown och länkar som ren text. Stäng av för att visa en formaterad förhandsvisning.",
+ richPaste: "Klistra in formaterad text",
+ richPasteDescription: "Klistrar in länkar, tabeller och formatering som Markdown. {shortcut} klistrar in oformaterad text. Fullständig redigerare för formaterad text kommer snart.",
showContext: "Användning av kontextfönstret",
sendShortcut: "Kortkommando för att skicka",
sendMultiline: "{mod} + Enter för uppmaningar med flera rader",
diff --git a/studio/frontend/src/i18n/locales/th.ts b/studio/frontend/src/i18n/locales/th.ts
index 1f8e8f60af6..20ff9846369 100644
--- a/studio/frontend/src/i18n/locales/th.ts
+++ b/studio/frontend/src/i18n/locales/th.ts
@@ -700,6 +700,8 @@ export const th = {
plainText: "ช่องเขียนข้อความแบบข้อความธรรมดา",
plainTextDescription:
"เก็บโค้ด Markdown และลิงก์ไว้เป็นข้อความตามตัวอักษร ปิดเพื่อแสดงตัวอย่างแบบจัดรูปแบบ",
+ richPaste: "วางข้อความแบบมีรูปแบบ",
+ richPasteDescription: "วางลิงก์ ตาราง และการจัดรูปแบบเป็น Markdown {shortcut} วางเป็นข้อความธรรมดา ตัวเขียนข้อความแบบมีรูปแบบเต็มรูปแบบเร็ว ๆ นี้",
showContext: "การใช้หน้าต่างบริบท",
sendShortcut: "ทางลัดการส่ง",
sendMultiline: "{mod} + Enter สำหรับพรอมต์หลายบรรทัด",
diff --git a/studio/frontend/src/i18n/locales/tr.ts b/studio/frontend/src/i18n/locales/tr.ts
index 1888a8bdebe..fb4967ca800 100644
--- a/studio/frontend/src/i18n/locales/tr.ts
+++ b/studio/frontend/src/i18n/locales/tr.ts
@@ -735,6 +735,8 @@ export const tr = {
plainText: "Düz metin yazma alanı",
plainTextDescription:
"Kod, Markdown ve bağlantılar olduğu gibi metin olarak kalır. Biçimlendirilmiş önizleme göstermek için kapatın.",
+ richPaste: "Biçimli metin yapıştırma",
+ richPasteDescription: "Bağlantıları, tabloları ve biçimlendirmeyi Markdown olarak yapıştırır. {shortcut} düz metin yapıştırır. Tam zengin metin düzenleyicisi yakında.",
showContext: "Bağlam penceresi kullanımı",
sendShortcut: "Gönderme kısayolu",
sendMultiline: "Çok satırlı istemlerde {mod} + Enter",
diff --git a/studio/frontend/src/i18n/locales/uk.ts b/studio/frontend/src/i18n/locales/uk.ts
index cfd1d6a9976..60872f324fd 100644
--- a/studio/frontend/src/i18n/locales/uk.ts
+++ b/studio/frontend/src/i18n/locales/uk.ts
@@ -742,6 +742,8 @@ export const uk = {
plainText: "Поле введення простого тексту",
plainTextDescription:
"Залишати код, Markdown і посилання звичайним текстом. Вимкніть, щоб показувати відформатований попередній перегляд.",
+ richPaste: "Вставлення форматованого тексту",
+ richPasteDescription: "Вставляє посилання, таблиці й форматування як Markdown. {shortcut} вставляє звичайний текст. Повноцінний редактор форматованого тексту незабаром.",
showContext: "Використання контекстного вікна",
sendShortcut: "Сполучення клавіш для надсилання",
sendMultiline: "{mod} + Enter для багаторядкових запитів",
diff --git a/studio/frontend/src/i18n/locales/vi.ts b/studio/frontend/src/i18n/locales/vi.ts
index 16e650949c7..4c444b46bc8 100644
--- a/studio/frontend/src/i18n/locales/vi.ts
+++ b/studio/frontend/src/i18n/locales/vi.ts
@@ -737,6 +737,8 @@ export const vi = {
plainText: "Khung soạn thảo văn bản thuần",
plainTextDescription:
"Giữ mã, Markdown và liên kết dưới dạng văn bản nguyên bản. Tắt để hiển thị bản xem trước có định dạng.",
+ richPaste: "Dán văn bản có định dạng",
+ richPasteDescription: "Dán liên kết, bảng và định dạng dưới dạng Markdown. {shortcut} dán văn bản thuần. Trình soạn văn bản định dạng đầy đủ sắp ra mắt.",
showContext: "Mức sử dụng cửa sổ ngữ cảnh",
sendShortcut: "Phím tắt gửi",
sendMultiline: "{mod} + Enter cho lời nhắc nhiều dòng",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 099f481676c..b2dae71bd94 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -652,6 +652,8 @@ export const zhCN = {
title: "消息输入",
plainText: "纯文本输入",
plainTextDescription: "将代码、Markdown 和链接保留为原始文本。关闭后显示格式化预览。",
+ richPaste: "粘贴富文本",
+ richPasteDescription: "将链接、表格和格式粘贴为 Markdown。{shortcut} 粘贴纯文本。完整的富文本输入框即将推出。",
showContext: "显示上下文窗口使用量",
sendShortcut: "发送快捷键",
sendMultiline: "多行消息使用 {mod} + Enter",
diff --git a/studio/frontend/src/i18n/locales/zh-TW.ts b/studio/frontend/src/i18n/locales/zh-TW.ts
index 37d3bd07ef8..acedf74a63f 100644
--- a/studio/frontend/src/i18n/locales/zh-TW.ts
+++ b/studio/frontend/src/i18n/locales/zh-TW.ts
@@ -696,6 +696,8 @@ export const zhTW = {
plainText: "純文字輸入框",
plainTextDescription:
"將程式碼、Markdown 和連結保留為原始文字。關閉後會顯示格式化預覽。",
+ richPaste: "貼上豐富文字",
+ richPasteDescription: "將連結、表格和格式貼上為 Markdown。{shortcut} 貼上純文字。完整的富文字輸入框即將推出。",
showContext: "上下文視窗用量",
sendShortcut: "傳送快速鍵",
sendMultiline: "多行提示詞使用 {mod} + Enter",
diff --git a/studio/frontend/tests/rich-paste.test.ts b/studio/frontend/tests/rich-paste.test.ts
new file mode 100644
index 00000000000..4e8fadf841e
--- /dev/null
+++ b/studio/frontend/tests/rich-paste.test.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ htmlNodeToMarkdown,
+ type PasteNode,
+ richPasteMarkdown,
+} from "../src/features/chat/utils/rich-paste.ts";
+
+type Child = PasteNode | string;
+function el(tag: string, attrs: Record<string, string> | Child = {}, ...kids: Child[]): PasteNode {
+ const attributes = typeof attrs === "object" && !("nodeType" in attrs) ? attrs : {};
+ const all = typeof attrs === "object" && !("nodeType" in attrs) ? kids : [attrs as Child, ...kids];
+ const childNodes = all.map((kid) =>
+ typeof kid === "string"
+ ? { nodeType: 3, nodeName: "#text", childNodes: [], textContent: kid }
+ : kid,
+ );
+ const text = (node: PasteNode): string =>
+ node.nodeType === 3 ? (node.textContent ?? "") : Array.from(node.childNodes).map(text).join("");
+ const node: PasteNode = {
+ nodeType: 1,
+ nodeName: tag.toUpperCase(),
+ childNodes,
+ textContent: "",
+ getAttribute: (name) => attributes[name] ?? null,
+ };
+ node.textContent = text(node);
+ return node;
+}
+
+function clipboard(html: string, plain: string, types: string[] = ["text/html", "text/plain"]) {
+ return {
+ types,
+ getData: (type: string) => (type === "text/html" ? html : type === "text/plain" ? plain : ""),
+ };
+}
+
+test("links keep their target, and bare URLs stay bare", () => {
+ const body = el("body", el("p", "See ", el("a", { href: "https://unsloth.ai/docs" }, "the docs"), " or ", el("a", { href: "https://x.com/a b" }, "https://x.com/a b"), "."));
+ assert.equal(htmlNodeToMarkdown(body), "See [the docs](https://unsloth.ai/docs) or https://x.com/a%20b.");
+});
+
+test("spaces inside a link's tag still separate it from its neighbours", () => {
+ const body = el("body", el("p", "Read", el("a", { href: "https://unsloth.ai/docs" }, " the docs "), "now"));
+ assert.equal(htmlNodeToMarkdown(body), "Read [the docs](https://unsloth.ai/docs) now");
+});
+
+test("unsafe or relative links paste as their text only", () => {
+ const body = el("body", el("a", { href: "javascript:alert(1)" }, "click"), " ", el("a", { href: "/relative" }, "here"));
+ assert.equal(htmlNodeToMarkdown(body), "click here");
+});
+
+test("tables become GFM tables with escaped pipes and ragged rows padded", () => {
+ const body = el(
+ "body",
+ el(
+ "table",
+ el("thead", el("tr", el("th", "Model"), el("th", "VRAM"))),
+ el("tbody", el("tr", el("td", "Qwen | 7B"), el("td", el("b", "8 GB"))), el("tr", el("td", "Llama"))),
+ ),
+ );
+ assert.equal(
+ htmlNodeToMarkdown(body),
+ ["| Model | VRAM |", "| --- | --- |", "| Qwen \\| 7B | **8 GB** |", "| Llama | |"].join("\n"),
+ );
+});
+
+test("merged cells keep the other values under their own headers", () => {
+ const body = el(
+ "body",
+ el(
+ "table",
+ el("tr", el("th", "Group"), el("th", "Value"), el("th", "Note")),
+ el("tr", el("td", { rowspan: "2" }, "A"), el("td", "10"), el("td", "x")),
+ el("tr", el("td", { colspan: "2" }, "20")),
+ ),
+ );
+ assert.equal(
+ htmlNodeToMarkdown(body),
+ ["| Group | Value | Note |", "| --- | --- | --- |", "| A | 10 | x |", "| | 20 | |"].join("\n"),
+ );
+});
+
+test("lists, nesting, headings, quotes and emphasis", () => {
+ const body = el(
+ "body",
+ el("h2", "Setup"),
+ el("ol", el("li", "Install ", el("code", "uv")), el("li", "Run", el("ul", el("li", el("em", "fast")), el("li", "safe")))),
+ el("blockquote", el("p", "Quoted ", el("strong", "text"))),
+ );
+ assert.equal(
+ htmlNodeToMarkdown(body),
+ ["## Setup", "", "1. Install `uv`", "2. Run", " - *fast*", " - safe", "", "> Quoted **text**"].join("\n"),
+ );
+});
+
+test("code blocks keep their indentation and language", () => {
+ const body = el("body", el("pre", el("code", { class: "language-python" }, "def f():\n return 1\n")));
+ assert.equal(htmlNodeToMarkdown(body), "```python\ndef f():\n return 1\n```");
+});
+
+test("code inside a list item keeps its blank lines", () => {
+ const body = el("body", el("ul", el("li", "Example", el("pre", el("code", 'message = """first\n\nthird"""')))));
+ assert.equal(htmlNodeToMarkdown(body), '- Example\n ```\n message = """first\n\n third"""\n ```');
+});
+
+test("Google Docs: the normal-weight wrapper adds nothing, styled spans become emphasis", () => {
+ const body = el(
+ "body",
+ el("b", { style: "font-weight:normal;" }, el("span", { style: "font-weight:700" }, "Bold"), " and ", el("span", { style: "font-style:italic" }, "italic")),
+ );
+ assert.equal(htmlNodeToMarkdown(body), "**Bold** and *italic*");
+});
+
+test("rich paste falls back to the plain text when it would add nothing", () => {
+ const parse = () => el("body", el("b", { style: "font-weight:normal" }, "just words"));
+ assert.equal(richPasteMarkdown(clipboard('<b style="font-weight:normal">just words</b>', "just words"), parse), null);
+ assert.equal(richPasteMarkdown(clipboard("<div><span>x</span></div>", "x"), () => el("body", "x")), null);
+ assert.equal(richPasteMarkdown(clipboard("", "plain only")), null);
+});
+
+test("code copied from VS Code is never converted", () => {
+ const data = clipboard("<div><a href='https://a.b'>x</a></div>", "x", ["text/plain", "text/html", "vscode-editor-data"]);
+ assert.equal(richPasteMarkdown(data, () => el("body", el("a", { href: "https://a.b" }, "x"))), null);
+});
+
+test("the copied text's edge spaces survive conversion", () => {
+ const parse = () => el("body", el("strong", "Hello "));
+ assert.equal(richPasteMarkdown(clipboard("<strong>Hello </strong>", "Hello "), parse), "**Hello** ");
+});
+
+test("a structural paste returns the Markdown", () => {
+ const html = '<p>Read <a href="https://unsloth.ai">Unsloth</a></p>';
+ const parse = () => el("body", el("p", "Read ", el("a", { href: "https://unsloth.ai" }, "Unsloth")));
+ assert.equal(richPasteMarkdown(clipboard(html, "Read Unsloth"), parse), "Read [Unsloth](https://unsloth.ai)");
+});
+
+test("a copy holding only a code block or styled spans still converts", () => {
+ const code = () => el("body", el("pre", el("code", { class: "language-python" }, "def f():\n return 1\n")));
+ const fenced = richPasteMarkdown(
+ clipboard('<pre><code class="language-python">def f():\n return 1\n</code></pre>', "def f():\n return 1\n"),
+ code,
+ );
+ assert.match(fenced ?? "", /^```python\ndef f\(\):\n {4}return 1\n```/);
+ const styled = () => el("body", el("span", { style: "font-weight:700" }, "Bold"), " text");
+ assert.equal(
+ richPasteMarkdown(clipboard('<span style="font-weight:700">Bold</span> text', "Bold text"), styled),
+ "**Bold** text",
+ );
+});
+
+test("a table caption and line breaks inside code survive", () => {
+ assert.equal(
+ htmlNodeToMarkdown(el("table", el("caption", "Use these limits"), el("tr", el("th", "A")), el("tr", el("td", "1")))),
+ "Use these limits\n\n| A |\n| --- |\n| 1 |",
+ );
+ assert.equal(
+ htmlNodeToMarkdown(el("pre", "def f():", el("br"), " return 1")),
+ "```\ndef f():\n return 1\n```",
+ );
+});