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.

Attach long pastes as a text file in Chat (#8472)

Michael Hanfaf334358203
diff --git a/studio/backend/core/inference/message_content.py b/studio/backend/core/inference/message_content.py
index b7c499a0877..942569dc229 100644
--- a/studio/backend/core/inference/message_content.py
+++ b/studio/backend/core/inference/message_content.py
@@ -12,6 +12,11 @@ from __future__ import annotations
from typing import Any
+# The composer sends a long paste as a text attachment wrapped in this tag, so
+# a paste-only turn carries no `content` text at all.
+_PASTED_TEXT_OPEN = "<pasted_text name="
+_PASTED_TEXT_CLOSE = "</pasted_text>"
+
def content_to_text(content: Any) -> str:
"""Plain text of a `content`: str unchanged, list/tuple text parts newline-joined
@@ -36,3 +41,38 @@ def content_to_text(content: Any) -> str:
parts.append(text)
return "\n".join(parts)
return str(content)
+
+
+def pasted_text_body(text: str) -> str:
+ """Body of a wrapped paste, or "" for anything else."""
+ if not text.startswith(_PASTED_TEXT_OPEN):
+ return ""
+ body_start = text.find("\n")
+ if body_start == -1:
+ return ""
+ body_end = len(text)
+ closing = "\n" + _PASTED_TEXT_CLOSE
+ if text.endswith(closing):
+ body_end = max(len(text) - len(closing), body_start + 1)
+ return text[body_start + 1 : body_end]
+
+
+def message_text_with_pastes(message: Any) -> str:
+ """Text of a message including any pasted attachment bodies.
+
+ A paste above the composer's threshold is sent as an attachment rather than
+ inline, so `content_to_text` alone reads a paste-only turn as empty. Other
+ attachment types are left out: they were never part of a message's text.
+ """
+ if not isinstance(message, dict):
+ return ""
+ parts = [content_to_text(message.get("content"))]
+ attachments = message.get("attachments")
+ if isinstance(attachments, (list, tuple)):
+ for attachment in attachments:
+ if not isinstance(attachment, dict):
+ continue
+ body = pasted_text_body(content_to_text(attachment.get("content")))
+ if body:
+ parts.append(body)
+ return "\n\n".join(part for part in parts if part)
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 409c6230836..c5ae4901989 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -19,7 +19,7 @@ from typing import Any, AsyncIterator, Callable
import httpx
from auth import storage as auth_storage
-from core.inference.message_content import content_to_text
+from core.inference.message_content import message_text_with_pastes
from core.inference.tool_loop_controller import is_tool_error, strip_result_for_model
from core.inference.tools import EMPTY_SEARCH_RESULTS, RAG_SOURCES_SENTINEL, execute_tool
from core.inference.web_access_policy import check_url_access, website_policy_prompt
@@ -201,7 +201,7 @@ def _safe_error(exc: BaseException) -> str:
def _extract_text(message: dict) -> str:
- return content_to_text(message.get("content")).strip()
+ return message_text_with_pastes(message).strip()
def _research_question_context(thread_id: str, user_message_id: str) -> tuple[str, str]:
diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.py
index c8b3626acaf..53e9aec06fa 100644
--- a/studio/backend/routes/research_runs.py
+++ b/studio/backend/routes/research_runs.py
@@ -18,7 +18,7 @@ from fastapi.responses import StreamingResponse
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
from auth.authentication import get_current_subject
-from core.inference.message_content import content_to_text
+from core.inference.message_content import message_text_with_pastes
from core.inference.web_access_policy import normalize_website_policy
from storage import research_runs_db as db
from storage import providers_db
@@ -340,7 +340,7 @@ def create_research_run(
raise HTTPException(
status_code = 400, detail = "userMessageId must identify a user message in the thread"
)
- if not content_to_text(user_message.get("content")).strip():
+ if not message_text_with_pastes(user_message).strip():
raise HTTPException(
status_code = 400,
detail = "Deep research requires a user message with non-empty text",
diff --git a/studio/backend/tests/test_message_content.py b/studio/backend/tests/test_message_content.py
index 6da36821413..3d3cb1ce917 100644
--- a/studio/backend/tests/test_message_content.py
+++ b/studio/backend/tests/test_message_content.py
@@ -98,3 +98,52 @@ def test_result_supports_string_ops():
out = mc.content_to_text([{"type": "text", "text": " padded "}])
assert out.strip() == "padded"
assert isinstance(out, str)
+
+
+def _pasted(name, body, size):
+ return f"<pasted_text name={name} bytes={size}>\n{body}\n</pasted_text>"
+
+
+def test_paste_only_turn_is_not_empty_text():
+ mc = _load_message_content()
+ body = "Fix the retry backoff\ndetail"
+ message = {
+ "content": [],
+ "attachments": [{"content": [{"type": "text", "text": _pasted("Fix.txt", body, 28)}]}],
+ }
+ # Deep research rejects a message whose text is empty, and a long paste
+ # carries all of its text in the attachment.
+ assert mc.message_text_with_pastes(message) == body
+
+
+def test_typed_text_keeps_the_paste_after_it():
+ mc = _load_message_content()
+ message = {
+ "content": [{"type": "text", "text": "summarise this"}],
+ "attachments": [{"content": [{"type": "text", "text": _pasted("Log.txt", "line", 4)}]}],
+ }
+ assert mc.message_text_with_pastes(message) == "summarise this\n\nline"
+
+
+def test_other_attachments_are_left_out():
+ mc = _load_message_content()
+ message = {
+ "content": [{"type": "text", "text": "read this"}],
+ "attachments": [
+ {"content": [{"type": "text", "text": "[PDF: paper.pdf]\nAbstract"}]},
+ {"content": [{"type": "text", "text": "<attachment name=n.txt>\nx\n</attachment>"}]},
+ ],
+ }
+ assert mc.message_text_with_pastes(message) == "read this"
+ assert mc.message_text_with_pastes({}) == ""
+ assert mc.message_text_with_pastes(None) == ""
+
+
+def test_pasted_body_unwraps_only_the_wrapper():
+ mc = _load_message_content()
+ assert mc.pasted_text_body(_pasted("a.txt", "body", 4)) == "body"
+ # Without the size, and with a body that itself ends in a tag-like line.
+ assert mc.pasted_text_body("<pasted_text name=a.txt>\nbody") == "body"
+ assert mc.pasted_text_body("plain text") == ""
+ assert mc.pasted_text_body("<attachment name=a.txt>\nbody\n</attachment>") == ""
+ assert mc.pasted_text_body("") == ""
diff --git a/studio/frontend/src/components/assistant-ui/attachment.tsx b/studio/frontend/src/components/assistant-ui/attachment.tsx
index 5cfe0d8f24e..2c8ca6abdff 100644
--- a/studio/frontend/src/components/assistant-ui/attachment.tsx
+++ b/studio/frontend/src/components/assistant-ui/attachment.tsx
@@ -17,6 +17,15 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import {
+ PASTED_TEXT_PREVIEW_MAX_CHARS,
+ isPastedTextContent,
+ isPastedTextFile,
+ pastedTextContentBytes,
+ pastedTextContentPreview,
+ pastedTextPreview,
+} from "@/features/chat";
+import { formatBytes } from "@/features/hub";
import { cn } from "@/lib/utils";
import {
AttachmentPrimitive,
@@ -25,10 +34,21 @@ import {
useAui,
useAuiState,
} from "@assistant-ui/react";
-import { AudioWave01Icon, File02Icon } from "@hugeicons/core-free-icons";
+import {
+ AudioWave01Icon,
+ File02Icon,
+ TextAlignLeft01Icon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { PlusIcon, XIcon } from "lucide-react";
-import { type FC, type PropsWithChildren, useEffect, useState } from "react";
+import { ChevronRightIcon, PlusIcon, XIcon } from "lucide-react";
+import {
+ type FC,
+ type PropsWithChildren,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
import { useShallow } from "zustand/shallow";
const useFileSrc = (file: File | undefined): string | undefined => {
@@ -163,9 +183,194 @@ const AttachmentThumb: FC = () => {
);
};
+type PastedTextAttachment = {
+ readonly file?: File;
+ readonly sentText?: string;
+ readonly sentBytes?: number;
+};
+
+// Long pastes arrive as a synthetic .txt and render as a chip, not a tile.
+// The selector only passes references along: the text can be megabytes, so
+// nothing here may copy or scan it.
+const usePastedTextAttachment = (): PastedTextAttachment | null => {
+ return useAuiState(
+ useShallow(({ attachment }): PastedTextAttachment | null => {
+ if (attachment.type !== "document") return null;
+ const file = (attachment as { file?: File }).file;
+ const sentText = attachment.content?.flatMap((part) =>
+ part.type === "text" ? [part.text] : [],
+ )[0];
+ const pasted = file
+ ? isPastedTextFile(file)
+ : isPastedTextContent(sentText);
+ if (!pasted) return null;
+ return { file, sentText, sentBytes: pastedTextContentBytes(sentText) };
+ }),
+ );
+};
+
+/** Only the composer inlines, and there the File is always still around. */
+const readPastedText = async ({ file }: PastedTextAttachment): Promise<string> =>
+ file ? await file.text() : "";
+
+const readPastedTextPreview = async (
+ attachment: PastedTextAttachment,
+): Promise<{ text: string; remaining: number }> => {
+ if (attachment.sentText !== undefined) {
+ return pastedTextContentPreview(attachment.sentText);
+ }
+ return pastedTextPreview(await readPastedText(attachment));
+};
+
+const PastedTextPreviewDialog: FC<
+ PropsWithChildren<{ name: string; attachment: PastedTextAttachment }>
+> = ({ attachment, children, name }) => {
+ const [open, setOpen] = useState(false);
+ const [preview, setPreview] = useState<{
+ text: string;
+ remaining: number;
+ } | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ // Laying out megabytes in one text node locks the page, so show an
+ // opening. The attachment itself still holds everything.
+ readPastedTextPreview(attachment)
+ .then((value) => {
+ if (!cancelled) setPreview(value);
+ })
+ .catch(() => {
+ if (!cancelled) setPreview({ text: "", remaining: 0 });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, attachment]);
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild={true}>{children}</DialogTrigger>
+ <DialogContent className="aui-pasted-text-dialog flex max-h-[80dvh] w-[min(46rem,92vw)] max-w-none flex-col gap-3 overflow-hidden">
+ <DialogTitle className="truncate pr-8 text-sm">{name}</DialogTitle>
+ <pre className="aui-pasted-text-dialog-body max-h-[64dvh] overflow-auto whitespace-pre-wrap break-words rounded-lg border bg-muted/40 p-3 text-left font-mono text-xs leading-relaxed">
+ {preview?.text ?? "Loading…"}
+ </pre>
+ {preview && preview.remaining > 0 ? (
+ <p className="text-muted-foreground text-xs">
+ {`First ${PASTED_TEXT_PREVIEW_MAX_CHARS.toLocaleString()} characters shown. ${preview.remaining.toLocaleString()} more were sent with the message.`}
+ </p>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+const PastedTextAttachmentUI: FC<{
+ attachment: PastedTextAttachment;
+ isComposer: boolean;
+ name: string;
+}> = ({ attachment, isComposer, name }) => {
+ const aui = useAui();
+ const attachmentId = useAuiState(({ attachment: state }) => state.id);
+ const [inlining, setInlining] = useState(false);
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+ // Read off the header, never measured: the paste can be megabytes and this
+ // runs while the thread is trying to paint.
+ const bytes = attachment.file?.size ?? attachment.sentBytes;
+
+ // Clicking the chip pours the text back into the composer.
+ const showInTextField = useCallback(() => {
+ if (inlining) return;
+ setInlining(true);
+ void readPastedText(attachment)
+ .then((text) => {
+ // Reading a big file is slow enough to outlive the send that cleared
+ // the composer, which would leave the text behind as a stray draft.
+ if (!mountedRef.current || text.length === 0) return;
+ const composer = aui.composer();
+ if (
+ !composer
+ .getState()
+ .attachments.some((item) => item.id === attachmentId)
+ ) {
+ return;
+ }
+ const current = composer.getState().text;
+ composer.setText(current.length > 0 ? `${current}\n\n${text}` : text);
+ aui.attachment().remove();
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ if (mountedRef.current) setInlining(false);
+ });
+ }, [attachment, attachmentId, aui, inlining]);
+
+ const chip = (
+ <button
+ className={cn(
+ // Borderless, and in dark mode a shade under the composer surface.
+ "aui-pasted-text-chip group flex h-14 max-w-[15rem] min-w-0 cursor-pointer items-center gap-2.5 rounded-[14px] bg-muted px-3 text-left transition-colors hover:bg-muted-foreground/15 dark:bg-background dark:hover:bg-muted",
+ // Keep the label clear of the remove button in the corner.
+ isComposer && "aui-pasted-text-chip-composer pr-6",
+ )}
+ type="button"
+ aria-label={
+ isComposer
+ ? `Pasted text: ${name}. Show in text field`
+ : `Pasted text: ${name}. Show contents`
+ }
+ onClick={isComposer ? showInTextField : undefined}
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-foreground/10">
+ <HugeiconsIcon
+ icon={TextAlignLeft01Icon}
+ strokeWidth={2}
+ className="size-4 text-muted-foreground"
+ />
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate font-medium text-xs">{name}</span>
+ <span className="truncate text-[11px] text-muted-foreground">
+ {/* Hover swaps the size for the action. */}
+ <span className={isComposer ? "group-hover:hidden" : undefined}>
+ {bytes === undefined ? "Pasted text" : formatBytes(bytes)}
+ </span>
+ {isComposer ? (
+ <span className="hidden items-center gap-0.5 underline underline-offset-2 group-hover:inline-flex">
+ Show in text field
+ <ChevronRightIcon className="size-3" />
+ </span>
+ ) : null}
+ </span>
+ </span>
+ </button>
+ );
+
+ return (
+ <AttachmentPrimitive.Root className="aui-attachment-root relative">
+ {isComposer ? (
+ chip
+ ) : (
+ <PastedTextPreviewDialog attachment={attachment} name={name}>
+ {chip}
+ </PastedTextPreviewDialog>
+ )}
+ {isComposer && <AttachmentRemove />}
+ </AttachmentPrimitive.Root>
+ );
+};
+
const AttachmentUI: FC = () => {
const aui = useAui();
const isComposer = aui.attachment.source === "composer";
+ const pastedText = usePastedTextAttachment();
const isImage = useAuiState(({ attachment }) => attachment.type === "image");
const name = useAuiState(({ attachment }) => attachment.name);
@@ -193,6 +398,16 @@ const AttachmentUI: FC = () => {
? `${typeLabel} attachment: ${name}`
: `${typeLabel} attachment`;
+ if (pastedText) {
+ return (
+ <PastedTextAttachmentUI
+ attachment={pastedText}
+ isComposer={isComposer}
+ name={name ?? "Pasted text"}
+ />
+ );
+ }
+
return (
<Tooltip>
<AttachmentPrimitive.Root
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 076ae6fd71e..21745a054bc 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -36,7 +36,10 @@ import { TerminalToolUI } from "@/components/assistant-ui/tool-ui-terminal";
import { WebSearchToolUI } from "@/components/assistant-ui/tool-ui-web-search";
import { ChatDictationBar } from "@/components/assistant-ui/chat-dictation-bar";
import {
+ attachmentsPastedText,
+ isPastedTextFile,
pasteClipboardFiles,
+ pasteLongTextAsFile,
isStudioDictationAvailable,
notifyStudioDictationUnavailable,
} from "@/features/chat";
@@ -139,6 +142,11 @@ import {
shouldAbortPendingQueueForSettingsChange,
snapshotQueuedChatRunSettings,
composerDraftKey,
+ composerPasteDraftKey,
+ createPastedTextFile,
+ pastedTextOf,
+ readPasteDraft,
+ writePasteDraft,
markThreadIncognito,
markChatThreadDeleted,
type PromptQueueRunFailedEventDetail,
@@ -2103,6 +2111,35 @@ const Composer: FC<{
useImeComposerInputHandlers({ submitOnEnter: true });
const handleFilePaste = useCallback(
(event: ClipboardEvent<HTMLTextAreaElement>) => {
+ // Bulk text pastes attach as a file instead of filling the input, except
+ // in image-edit mode, whose submit path takes an inline instruction only.
+ const input = event.currentTarget;
+ // An attachment is serialised after all inline text, so only a paste that
+ // was already heading to the end can become one. Mid-text pastes stay
+ // inline, where the order the user typed them in survives.
+ const pasteGoesLast = input.selectionEnd === input.value.length;
+ const { selectionStart, selectionEnd, value } = input;
+ // Swallowing the paste also swallowed the replacement the browser would
+ // have made. Only once the attachment is in, and only if the composer is
+ // still the one that was pasted into, or a failed paste eats the text.
+ const dropReplacedSelection = () => {
+ if (selectionStart === selectionEnd) return;
+ const composer = aui.composer();
+ if (composer.getState().text !== value) return;
+ composer.setText(value.slice(0, selectionStart) + value.slice(selectionEnd));
+ };
+ const attachedPastedText = !overlay && pasteGoesLast && pasteLongTextAsFile(
+ event,
+ async (file) => {
+ await aui.composer().addAttachment(file);
+ dropReplacedSelection();
+ },
+ () =>
+ toast.error("Could not attach the pasted text.", {
+ description: "Paste it again, or paste it in smaller pieces.",
+ }),
+ );
+ if (attachedPastedText) return;
pasteClipboardFiles(
event,
async (files) => {
@@ -2116,7 +2153,7 @@ const Composer: FC<{
}),
);
},
- [aui],
+ [aui, overlay],
);
const composerText = useAuiState(({ composer }) => composer.text);
@@ -2159,6 +2196,19 @@ const Composer: FC<{
(attachment) => attachment.status.type === "running",
),
);
+ const attachmentsAreAllPastedText = useAuiState(
+ ({ composer }) =>
+ composer.attachments.length > 0 &&
+ composer.attachments.every((attachment) =>
+ isPastedTextFile((attachment as { file?: File }).file),
+ ),
+ );
+ // Identities only: paste autosave keys off this, and the bodies behind it can
+ // be megabytes. Every attachment counts, not just pasted ones, so removing an
+ // ordinary file also releases the paste restore waiting on it.
+ const composerAttachmentSignature = useAuiState(({ composer }) =>
+ composer.attachments.map((attachment) => attachment.id).join(","),
+ );
const hasPendingAudio = useChatRuntimeStore((s) =>
Boolean(s.pendingAudioName),
);
@@ -2504,9 +2554,7 @@ const Composer: FC<{
);
const hasSendableContent =
composerText.trim().length > 0 || hasAttachments || hasPendingAudio;
- const canQueueCurrentPrompt =
- composerText.trim().length > 0 &&
- !hasAttachments &&
+ const composerAcceptsQueueing =
!hasPendingAudio &&
!isComposing &&
!hasPendingAttachments &&
@@ -2514,6 +2562,12 @@ const Composer: FC<{
!hasMaterializingAudioAttachments &&
!disabled &&
!overlay;
+ const canQueueCurrentPrompt =
+ composerText.trim().length > 0 && !hasAttachments && composerAcceptsQueueing;
+ // A long paste is text the composer parked in a chip, so it queues like the
+ // same text did before it attached, rather than being refused as a file.
+ const canQueuePastedTextPrompt =
+ attachmentsAreAllPastedText && composerAcceptsQueueing;
// Per-thread draft autosave: restore on mount, then mirror composer text
// into localStorage (debounced) so a half-typed message survives a
@@ -2522,7 +2576,15 @@ const Composer: FC<{
// previous thread's composer contents.
const draftThreadId = referenceThreadId;
const draftKey = draftThreadId ? composerDraftKey(draftThreadId) : null;
+ // A pasted attachment is a File held in memory only, so without its own slot
+ // an unsent paste is the one draft a reload throws away.
+ const pasteDraftKey = draftThreadId
+ ? composerPasteDraftKey(draftThreadId)
+ : null;
const lastDraftKeyRef = useRef(draftKey);
+ // Which key the paste restore has finished for. The save effect writes only
+ // for that key, so a draft is never cleared before it has been put back.
+ const restoredPasteKeyRef = useRef<string | null>(null);
const draftSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
const draft = draftKey ? (readComposerDraft(draftKey) ?? "") : "";
@@ -2531,6 +2593,43 @@ const Composer: FC<{
composer.setText(draft);
}
}, [draftKey, aui]);
+ // Separate from the text restore above, which must stay keyed on the draft
+ // alone: this one retries on attachment changes, and rewriting the composer
+ // text on those would drop whatever had been typed since the last autosave.
+ useEffect(() => {
+ const composer = aui.composer();
+ if (!composer.getState().isEditing) return;
+ if (restoredPasteKeyRef.current === pasteDraftKey) return;
+ // The composer outlives a thread switch, so restore only into an empty one
+ // rather than mixing this thread's draft with whatever the last one left.
+ // Changing attachments re-runs this effect, which is how the retry happens.
+ if (composer.getState().attachments.length > 0) return;
+ const stored = pasteDraftKey ? readPasteDraft(pasteDraftKey) : [];
+ if (stored.length === 0) {
+ restoredPasteKeyRef.current = pasteDraftKey;
+ return;
+ }
+ // Claim the key only once the attachments are in, so the save effect
+ // cannot write an empty composer over the draft still being restored.
+ void Promise.all(
+ stored.map((text) => composer.addAttachment(createPastedTextFile(text))),
+ ).finally(() => {
+ restoredPasteKeyRef.current = pasteDraftKey;
+ });
+ }, [pasteDraftKey, composerAttachmentSignature, aui]);
+ // Keyed on the paste identities, never their bodies, so typing beside a
+ // megabyte paste does not rewrite it to localStorage every 300ms.
+ useEffect(() => {
+ if (!pasteDraftKey || restoredPasteKeyRef.current !== pasteDraftKey) return;
+ const pastes = aui
+ .composer()
+ .getState()
+ .attachments.flatMap((attachment) => {
+ const text = pastedTextOf((attachment as { file?: File }).file);
+ return text === undefined ? [] : [text];
+ });
+ writePasteDraft(pasteDraftKey, pastes);
+ }, [composerAttachmentSignature, pasteDraftKey, aui]);
useEffect(() => {
// After a thread switch composerText can still hold the previous
// thread's text; skip that cycle so it isn't saved under the new key.
@@ -2548,9 +2647,11 @@ const Composer: FC<{
// Without this the restore effect above puts the sent text back when the
// runtime rebinds on the first message.
const draftKeyRef = useRef(draftKey);
+ const pasteDraftKeyRef = useRef(pasteDraftKey);
useEffect(() => {
draftKeyRef.current = draftKey;
- }, [draftKey]);
+ pasteDraftKeyRef.current = pasteDraftKey;
+ }, [draftKey, pasteDraftKey]);
const clearStoredDraft = useCallback(() => {
if (draftSaveTimerRef.current !== null) {
clearTimeout(draftSaveTimerRef.current);
@@ -2560,6 +2661,10 @@ const Composer: FC<{
if (key) {
writeComposerDraft(key, "");
}
+ const pasteKey = pasteDraftKeyRef.current;
+ if (pasteKey) {
+ writePasteDraft(pasteKey, []);
+ }
}, []);
// react-textarea-autosize re-measures only on value change or window resize,
// not on the width swap from expanding, so it keeps the taller height and
@@ -2977,6 +3082,57 @@ const Composer: FC<{
[createPromptQueueTarget, referenceThreadId],
);
+ // The queue carries text, and a long paste is text the composer parked in a
+ // chip, so fold it back in rather than refusing to queue it as a file.
+ const queuePastedTextPrompt = useCallback(
+ (waitForCurrentRun: boolean): boolean => {
+ const composer = aui.composer();
+ const attachments = composer.getState().attachments;
+ const files: File[] = [];
+ for (const attachment of attachments) {
+ const file = (attachment as { file?: File }).file;
+ if (file === undefined || !isPastedTextFile(file)) return false;
+ files.push(file);
+ }
+ if (files.length === 0) return false;
+
+ const attachmentIds = attachments.map((attachment) => attachment.id);
+ const textAtQueue = composer.getState().text.trim();
+ void Promise.all(files.map((file) => file.text()))
+ .then((texts) => {
+ const queuedPrompt = [textAtQueue, ...texts]
+ .filter((part) => part.trim().length > 0)
+ .join("\n\n");
+ if (queuedPrompt.length === 0) return;
+ startHydratedPromptQueue([queuedPrompt], waitForCurrentRun, () => {
+ const state = composer.getState();
+ // Only clear the composer this prompt was queued from.
+ if (
+ state.text.trim() !== textAtQueue ||
+ state.attachments.length !== attachmentIds.length ||
+ !state.attachments.every(
+ (attachment, index) => attachment.id === attachmentIds[index],
+ )
+ ) {
+ return;
+ }
+ void composer.clearAttachments();
+ flushResourcesSync(() => {
+ composer.setText("");
+ });
+ clearStoredDraft();
+ });
+ })
+ .catch(() => {
+ toast.error("Could not queue the pasted text.", {
+ description: "Show it in the text field, then send it again.",
+ });
+ });
+ return true;
+ },
+ [aui, clearStoredDraft, startHydratedPromptQueue],
+ );
+
const dismissWaitToast = useCallback(() => {
if (waitToastRef.current !== null) {
toast.dismiss(waitToastRef.current);
@@ -3320,6 +3476,12 @@ const Composer: FC<{
return;
}
if (!canQueueCurrentPrompt) {
+ if (
+ canQueuePastedTextPrompt &&
+ queuePastedTextPrompt(liveThreadIsRunning || livePreStreamRunActive)
+ ) {
+ return;
+ }
if (overlay || hasAttachments || hasPendingAudio) {
toast.error(
liveThreadIsRunning
@@ -3411,6 +3573,8 @@ const Composer: FC<{
[
aui,
canQueueCurrentPrompt,
+ canQueuePastedTextPrompt,
+ queuePastedTextPrompt,
clearStoredDraft,
closeOverlay,
composerText,
@@ -3555,9 +3719,20 @@ const Composer: FC<{
}
// disableQueue (project new-chat composer) also blocks the queue
// button, so a running thread shows Stop instead of Queue.
- queueDisabled={disableQueue || !canQueueCurrentPrompt}
+ queueDisabled={
+ disableQueue ||
+ !(canQueueCurrentPrompt || canQueuePastedTextPrompt)
+ }
onQueueClick={() => {
if (disableQueue) return;
+ // Same pasted-text path the Enter key takes, or the button
+ // would refuse what submitting the form accepts.
+ if (
+ canQueuePastedTextPrompt &&
+ queuePastedTextPrompt(true)
+ ) {
+ return;
+ }
const queuedPrompt = composerText.trim();
if (queuedPrompt.length === 0) {
return;
@@ -5924,7 +6099,11 @@ const CopyButton: FC = () => {
const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleCopy = async () => {
- const text = aui.message().getCopyText();
+ // getCopyText reads content only, and a long paste sits in an attachment.
+ const pasted = attachmentsPastedText(aui.message().getState().attachments);
+ const text = [aui.message().getCopyText(), pasted]
+ .filter((part) => part.length > 0)
+ .join("\n\n");
if (await copyToClipboard(text)) {
setCopied(true);
if (resetTimeoutRef.current) {
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index d14785fd2b1..d5f3c5c65d3 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -206,6 +206,7 @@ import {
listStoredChatMessages,
listStoredChatThreads,
} from "./utils/chat-history-storage";
+import { attachmentsSample } from "./utils/pasted-text";
import { requestTemporaryPromptQueueStop } from "./utils/prompt-queue-boundary";
import { isAssistantLocalThreadId } from "./utils/thread-ids";
import {
@@ -1352,8 +1353,11 @@ function ProjectLanding({
return [
item.id,
{
+ // A paste-only message carries its text in the attachment, so
+ // the row would otherwise be blank.
snippet: firstUserMessage
- ? extractMessageText(firstUserMessage.content)
+ ? extractMessageText(firstUserMessage.content) ||
+ attachmentsSample(firstUserMessage.attachments)
: "",
date: formatProjectChatDate(item.createdAt),
},
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts b/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts
index 9badd43bc34..a6fc0ab1c6c 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts
@@ -8,6 +8,7 @@ import {
listStoredChatMessages,
listStoredChatThreads,
} from "../utils/chat-history-storage";
+import { attachmentsPastedText } from "../utils/pasted-text.ts";
export interface ChatSearchItem {
type: "single" | "compare";
@@ -83,11 +84,13 @@ function searchableText(value: unknown, depth = 0): string {
}
// Pull searchable text from a message: plain text, reasoning/thinking, tool
-// calls (name + args + result) and cited sources (title + url).
+// calls (name + args + result), cited sources (title + url) and pasted bodies.
function extractText(message: MessageRecord): string {
const content = message.content;
- if (!Array.isArray(content)) return "";
+ const pasted = attachmentsPastedText(message.attachments);
+ if (!Array.isArray(content)) return pasted;
const parts: string[] = [];
+ if (pasted) parts.push(pasted);
for (const part of content) {
if (!part || typeof part !== "object") continue;
const p = part as Record<string, unknown>;
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 476100bdada..1a62a61e316 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -144,6 +144,20 @@ export type { ProjectRecord } from "./types";
export { clearAllChats, countAllChats } from "./utils/clear-all-chats";
export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";
export { pasteClipboardFiles } from "./utils/clipboard-files";
+export {
+ PASTED_TEXT_PREVIEW_MAX_CHARS,
+ attachmentContentText,
+ attachmentsPastedText,
+ createPastedTextFile,
+ isPastedTextContent,
+ isPastedTextFile,
+ pasteLongTextAsFile,
+ pastedTextContentBytes,
+ pastedTextContentPreview,
+ pastedTextOf,
+ pastedTextPreview,
+ shouldAttachPastedText,
+} from "./utils/pasted-text";
export {
deleteStoredChatThreads,
ensureStoredChatThread,
@@ -180,8 +194,11 @@ export {
export {
clearNewChatDraft,
composerDraftKey,
+ composerPasteDraftKey,
readComposerDraft,
+ readPasteDraft,
writeComposerDraft,
+ writePasteDraft,
} from "./utils/composer-draft";
export {
CONVERSATION_MARKDOWN_FORMAT,
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index 0fbd3702da2..f2c3017f91b 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -60,6 +60,7 @@ import { toolResultModelText } from "../api/chat-adapter";
import { usePlusMenuPrefsStore } from "../stores/plus-menu-prefs-store";
import type { ThreadRecord, MessageRecord } from "../types";
import { createConversationMarkdownExporter } from "../utils/conversation-markdown-export";
+import { unwrapPastedTextContent } from "../utils/pasted-text.ts";
import {
contentBlocksToMarkdownBlocks,
renderConversationBlocks,
@@ -254,7 +255,11 @@ function messageToText(msg: { content: unknown; attachments?: unknown }): string
if (Array.isArray(msg.attachments)) {
for (const attachment of msg.attachments as Array<{ content?: unknown }>) {
if (!attachment?.content) continue;
- const attText = contentBlocksToText(attachment.content);
+ // A paste carries a wrapper the same text never had when it fitted
+ // inline, so strip it rather than exporting the marker.
+ const attText = unwrapPastedTextContent(
+ contentBlocksToText(attachment.content),
+ );
if (attText) parts.push(attText);
}
}
@@ -273,6 +278,10 @@ function messageToMarkdown(msg: { content: unknown; attachments?: unknown }): st
...contentBlocksToMarkdownBlocks(
attachment.content,
normalizeToolResult,
+ ).map((block) =>
+ block.kind === "text"
+ ? { ...block, text: unwrapPastedTextContent(block.text) }
+ : block,
),
);
}
@@ -308,9 +317,14 @@ function messageToOpenAI(msg: { role: unknown; content: unknown; attachments?: u
...blocks.map((b) => b as Record<string, unknown>),
...attachments.flatMap((a) => {
const att = a as { content?: unknown };
- return Array.isArray(att.content)
- ? (att.content as Record<string, unknown>[])
- : [];
+ if (!Array.isArray(att.content)) return [];
+ // Attachment text only: a message body is verbatim, and the paste
+ // wrapper is not something the user wrote.
+ return (att.content as Record<string, unknown>[]).map((part) =>
+ part?.type === "text" && typeof part.text === "string"
+ ? { ...part, text: unwrapPastedTextContent(part.text) }
+ : part,
+ );
}),
];
@@ -610,10 +624,15 @@ function messageToPlainText(msg: {
attachments?: unknown;
}): string {
const parts: string[] = [];
- const collect = (blocks: unknown) => {
+ // Only attachment text is unwrapped: a message body is verbatim, and may
+ // legitimately quote the wrapper syntax in a code sample.
+ const collect = (blocks: unknown, fromAttachment = false) => {
+ const normalize = fromAttachment
+ ? unwrapPastedTextContent
+ : (text: string) => text;
// Legacy and imported histories can store content as a plain string.
if (typeof blocks === "string") {
- if (blocks.trim()) parts.push(blocks);
+ if (blocks.trim()) parts.push(normalize(blocks));
return;
}
if (!Array.isArray(blocks)) return;
@@ -623,14 +642,14 @@ function messageToPlainText(msg: {
}
const block = b as Record<string, unknown>;
if (block.type === "text" && typeof block.text === "string" && block.text) {
- parts.push(block.text);
+ parts.push(normalize(block.text));
}
}
};
collect(msg.content);
if (Array.isArray(msg.attachments)) {
for (const attachment of msg.attachments as Array<{ content?: unknown }>) {
- collect(attachment?.content);
+ collect(attachment?.content, true);
}
}
return parts.join("\n\n").trim();
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index a07caa4f66a..acbd40f8b2c 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -81,6 +81,11 @@ import {
chatContentPartAttachmentSignature,
onChatAttachmentDeleted,
} from "./utils/chat-attachment-events";
+import {
+ attachmentContentText,
+ attachmentsSample,
+ isPastedTextFile,
+} from "./utils/pasted-text";
import {
refreshContextUsage,
setActiveBranchReader,
@@ -328,7 +333,14 @@ class TextAttachmentAdapter implements AttachmentAdapter {
content: [
{
type: "text",
- text: `<attachment name=${attachment.name}>\n${text}\n</attachment>`,
+ // A pasted file gets its own tag and size, the markers that outlive
+ // the File once the message is stored.
+ text: attachmentContentText(
+ attachment.name,
+ text,
+ isPastedTextFile(attachment.file),
+ attachment.file.size,
+ ),
},
],
status: { type: "complete" },
@@ -520,6 +532,17 @@ function extractTextParts(m: ThreadMessage | undefined): string {
.trim();
}
+// A paste leaves the message's text in an attachment, so a title built from
+// inline text alone is "New Chat" for a paste-only turn and the bare
+// instruction for "summarise this" plus a paste. The sample is bounded.
+function titleTextOf(m: ThreadMessage | undefined): string {
+ const text = extractTextParts(m);
+ if (m?.role !== "user") return text;
+ const sample = attachmentsSample(m.attachments);
+ if (sample.length === 0) return text;
+ return text.length > 0 ? `${text}\n\n${sample}` : sample;
+}
+
async function generateTitleWithModel(payload: {
userText: string;
assistantText?: string;
@@ -871,7 +894,7 @@ function createStudioDbAdapter(
firstUserIndex === -1
? undefined
: messages.find((m, i) => m.role === "assistant" && i > firstUserIndex);
- const userText = extractTextParts(firstUser) || defaultTitle;
+ const userText = titleTextOf(firstUser) || defaultTitle;
const assistantText = extractTextParts(firstAssistant);
if (!autoTitle) {
diff --git a/studio/frontend/src/features/chat/utils/clipboard-files.ts b/studio/frontend/src/features/chat/utils/clipboard-files.ts
index b2920d1497c..663205e2c95 100644
--- a/studio/frontend/src/features/chat/utils/clipboard-files.ts
+++ b/studio/frontend/src/features/chat/utils/clipboard-files.ts
@@ -3,6 +3,11 @@
import { isTauri } from "@/lib/api-base";
import { MAX_AUDIO_SIZE } from "@/lib/audio-utils";
+import {
+ browserClipboardFiles,
+ clipboardAdvertisesFiles,
+ clipboardHasPlainText,
+} from "./clipboard-payload.ts";
const MAX_NATIVE_IMAGE_DIMENSION = 8192;
const MAX_NATIVE_IMAGE_RGBA_BYTES = 64 * 1024 * 1024;
@@ -22,52 +27,6 @@ type NativeClipboardFile = {
readonly base64: string;
};
-function browserClipboardFiles(clipboardData: DataTransfer): File[] {
- const files = Array.from(clipboardData.files).filter((file) => file.size > 0);
- if (files.length > 0) return files;
-
- return Array.from(clipboardData.items)
- .filter((item) => item.kind === "file")
- .map((item) => item.getAsFile())
- .filter((file): file is File => file !== null && file.size > 0);
-}
-
-function clipboardTypes(clipboardData: DataTransfer): string[] {
- return Array.from(clipboardData.types, (type) => type.toLowerCase());
-}
-
-function clipboardHasLocalFileUri(
- clipboardData: DataTransfer,
- types: readonly string[],
-): boolean {
- const uriTypes = types.filter(
- (type) => type.includes("uri-list") || type.includes("urilist"),
- );
- for (const type of uriTypes) {
- try {
- if (
- clipboardData
- .getData(type)
- .split(/\r?\n/)
- .some((line) => line.trim().toLowerCase().startsWith("file:"))
- ) {
- return true;
- }
- } catch {
- return false;
- }
- }
- return false;
-}
-
-function clipboardHasPlainText(clipboardData: DataTransfer): boolean {
- try {
- return clipboardData.getData("text/plain").length > 0;
- } catch {
- return true;
- }
-}
-
function validDimension(value: number): boolean {
return (
Number.isSafeInteger(value) &&
@@ -244,16 +203,9 @@ export function pasteClipboardFiles(
return;
}
- const types = clipboardTypes(clipboardData);
- const advertisesImage = types.some((type) => type.startsWith("image/"));
- const advertisesFile =
- types.includes("files") ||
- types.some((type) => type.includes("copied-files")) ||
- clipboardHasLocalFileUri(clipboardData, types);
- if (!advertisesImage && !advertisesFile && clipboardHasPlainText(clipboardData)) {
- return;
- }
+ const advertisesFiles = clipboardAdvertisesFiles(clipboardData);
+ if (!advertisesFiles && clipboardHasPlainText(clipboardData)) return;
- if (advertisesImage || advertisesFile) event.preventDefault();
+ if (advertisesFiles) event.preventDefault();
addNativeClipboardFiles(addFiles, onError);
}
diff --git a/studio/frontend/src/features/chat/utils/clipboard-payload.ts b/studio/frontend/src/features/chat/utils/clipboard-payload.ts
new file mode 100644
index 00000000000..3a839e3b338
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/clipboard-payload.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Shared clipboard inspection. The file paste path and the long text paste path
+// must agree on what counts as a file, or a paste falls through both or neither.
+
+function clipboardTypes(clipboardData: DataTransfer): string[] {
+ return Array.from(clipboardData.types, (type) => type.toLowerCase());
+}
+
+function clipboardHasLocalFileUri(
+ clipboardData: DataTransfer,
+ types: readonly string[],
+): boolean {
+ return types
+ .filter((type) => type.includes("uri-list") || type.includes("urilist"))
+ .some((type) => {
+ try {
+ return clipboardData
+ .getData(type)
+ .split(/\r?\n/)
+ .some((line) => line.trim().toLowerCase().startsWith("file:"));
+ } catch {
+ return false;
+ }
+ });
+}
+
+/** Files the browser decoded for us, ready to attach. */
+export function browserClipboardFiles(clipboardData: DataTransfer): File[] {
+ const files = Array.from(clipboardData.files).filter((file) => file.size > 0);
+ if (files.length > 0) return files;
+
+ return Array.from(clipboardData.items)
+ .filter((item) => item.kind === "file")
+ .map((item) => item.getAsFile())
+ .filter((file): file is File => file !== null && file.size > 0);
+}
+
+/** A file entry the browser may still refuse to decode, so the text path defers. */
+export function clipboardHasFileEntries(clipboardData: DataTransfer): boolean {
+ if (Array.from(clipboardData.files).some((file) => file.size > 0)) return true;
+ return Array.from(clipboardData.items).some((item) => item.kind === "file");
+}
+
+// Native (Tauri) images and copied files are advertised by type only, with no
+// entry in files or items, and only pasteClipboardFiles can read them.
+export function clipboardAdvertisesFiles(clipboardData: DataTransfer): boolean {
+ const types = clipboardTypes(clipboardData);
+ return (
+ types.some((type) => type.startsWith("image/")) ||
+ types.includes("files") ||
+ types.some((type) => type.includes("copied-files")) ||
+ clipboardHasLocalFileUri(clipboardData, types)
+ );
+}
+
+export function clipboardHasPlainText(clipboardData: DataTransfer): boolean {
+ try {
+ return clipboardData.getData("text/plain").length > 0;
+ } catch {
+ return true;
+ }
+}
diff --git a/studio/frontend/src/features/chat/utils/composer-draft.ts b/studio/frontend/src/features/chat/utils/composer-draft.ts
index 10f3b9e8af5..01f65af198d 100644
--- a/studio/frontend/src/features/chat/utils/composer-draft.ts
+++ b/studio/frontend/src/features/chat/utils/composer-draft.ts
@@ -5,12 +5,54 @@
// share the NEW_CHAT_DRAFT_ID slot; callers clear it when a fresh chat starts
// so one new chat's draft never bleeds into the next.
const DRAFT_PREFIX = "chat-draft:";
+const PASTE_DRAFT_PREFIX = "chat-draft-pastes:";
const NEW_CHAT_DRAFT_ID = "__new__";
export function composerDraftKey(threadId: string | null | undefined): string {
return `${DRAFT_PREFIX}${threadId ?? NEW_CHAT_DRAFT_ID}`;
}
+// Pasted attachments live in their own slot rather than inside the text draft,
+// so typing never rewrites a paste that can run to megabytes.
+export function composerPasteDraftKey(
+ threadId: string | null | undefined,
+): string {
+ return `${PASTE_DRAFT_PREFIX}${threadId ?? NEW_CHAT_DRAFT_ID}`;
+}
+
+// The names are not stored: a pasted file is named from its own text, so
+// recreating it reproduces the name it had.
+export function readPasteDraft(key: string): string[] {
+ let raw: string | null = null;
+ try {
+ raw = window.localStorage.getItem(key);
+ } catch {
+ return [];
+ }
+ if (!raw) return [];
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((entry): entry is string => typeof entry === "string");
+ } catch {
+ return [];
+ }
+}
+
+// A paste large enough to blow the storage quota throws here, leaving the text
+// draft untouched, which is why the two slots are written separately.
+export function writePasteDraft(key: string, pastes: readonly string[]): void {
+ try {
+ if (pastes.length > 0) {
+ window.localStorage.setItem(key, JSON.stringify(pastes));
+ } else {
+ window.localStorage.removeItem(key);
+ }
+ } catch {
+ // ignore write failures
+ }
+}
+
// All storage access is best-effort: localStorage throws when unavailable
// (private mode, blocked storage) or full (quota), so swallow failures.
export function readComposerDraft(key: string): string | null {
@@ -33,6 +75,7 @@ export function writeComposerDraft(key: string, text: string): void {
export function clearComposerDraft(threadId: string | null | undefined): void {
try {
window.localStorage.removeItem(composerDraftKey(threadId));
+ window.localStorage.removeItem(composerPasteDraftKey(threadId));
} catch {
// ignore
}
diff --git a/studio/frontend/src/features/chat/utils/pasted-text.ts b/studio/frontend/src/features/chat/utils/pasted-text.ts
new file mode 100644
index 00000000000..d07f4aa8409
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/pasted-text.ts
@@ -0,0 +1,311 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Long pastes become a .txt attachment instead of flooding the composer.
+// TextAttachmentAdapter still sends the full text to the model.
+
+import {
+ clipboardAdvertisesFiles,
+ clipboardHasFileEntries,
+} from "./clipboard-payload.ts";
+
+const PASTED_TEXT_MIME = "text/plain";
+export const PASTED_TEXT_MIN_CHARS = 2000;
+export const PASTED_TEXT_MIN_LINES = 40;
+const PASTED_TEXT_NAME_MAX_CHARS = 32;
+// Enough for the name after whitespace collapses, without copying a line.
+const PASTED_TEXT_NAME_SCAN_CHARS = 256;
+// Blank lines are stepped over one at a time, so the walk needs its own bound.
+const PASTED_TEXT_NAME_TOTAL_SCAN_CHARS = 64 * 1024;
+const PASTED_TEXT_FALLBACK_NAME = "Pasted text";
+const PASTED_TEXT_TAG = "pasted_text";
+// A preview is for reading, so render an opening rather than megabytes.
+export const PASTED_TEXT_PREVIEW_MAX_CHARS = 100_000;
+// A title only ever uses the first line of this.
+const ATTACHMENT_SAMPLE_CHARS = 512;
+// Illegal in filenames on at least one platform, plus control characters.
+const UNSAFE_NAME_CHARS = /[\\/:*?"<>|\p{Cc}]/gu;
+
+type ClipboardTextPasteEvent = {
+ readonly clipboardData: DataTransfer | null;
+ readonly defaultPrevented: boolean;
+ preventDefault: () => void;
+};
+
+// Identity separates a pasted blob from a .txt the user attached. A sent
+// message keeps no File, so the wrapper below carries it over instead.
+const pastedTextFiles = new WeakSet<File>();
+// The text as pasted, so draft autosave never re-reads the File on a keystroke.
+const pastedTextByFile = new WeakMap<File, string>();
+
+function countLines(text: string): number {
+ let lines = 1;
+ for (let index = 0; index < text.length; index += 1) {
+ if (text[index] === "\n") lines += 1;
+ }
+ return lines;
+}
+
+// No upper bound, and whitespace is not exempt: the bigger the paste, the
+// worse it is inline.
+export function shouldAttachPastedText(text: string): boolean {
+ if (text.length === 0) return false;
+ return (
+ text.length >= PASTED_TEXT_MIN_CHARS ||
+ countLines(text) >= PASTED_TEXT_MIN_LINES
+ );
+}
+
+// Splitting a multi-megabyte paste to read one line allocates every other
+// line for nothing, so walk to the first non-blank line instead, and never
+// copy more of it than a name can hold.
+function firstTextLine(text: string): string {
+ // Bounded twice over: each slice, so one line cannot be copied whole, and
+ // the walk itself, so a paste of nothing but blank lines cannot be stepped
+ // through a line at a time.
+ const limit = Math.min(text.length, PASTED_TEXT_NAME_TOTAL_SCAN_CHARS);
+ let start = 0;
+ while (start < limit) {
+ const end = text.indexOf("\n", start);
+ const stop = Math.min(
+ end === -1 ? text.length : end,
+ start + PASTED_TEXT_NAME_SCAN_CHARS,
+ );
+ const line = text.slice(start, stop);
+ if (line.trim().length > 0) return line;
+ if (end === -1) return "";
+ start = end + 1;
+ }
+ return "";
+}
+
+/** Names the file after the opening of the paste, so the chip is readable. */
+export function pastedTextFileName(text: string): string {
+ const cleaned = firstTextLine(text)
+ .replace(UNSAFE_NAME_CHARS, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ let snippet = cleaned.slice(0, PASTED_TEXT_NAME_MAX_CHARS);
+ if (cleaned.length > PASTED_TEXT_NAME_MAX_CHARS) {
+ // Prefer a word boundary, but not one that leaves a stub.
+ const lastSpace = snippet.lastIndexOf(" ");
+ if (lastSpace >= PASTED_TEXT_NAME_MAX_CHARS / 2) {
+ snippet = snippet.slice(0, lastSpace);
+ }
+ }
+ snippet = snippet.replace(/[\s.]+$/, "");
+ return `${snippet.length > 0 ? snippet : PASTED_TEXT_FALLBACK_NAME}.txt`;
+}
+
+export function createPastedTextFile(text: string): File {
+ const file = new File([text], pastedTextFileName(text), {
+ type: PASTED_TEXT_MIME,
+ lastModified: Date.now(),
+ });
+ pastedTextFiles.add(file);
+ pastedTextByFile.set(file, text);
+ return file;
+}
+
+/** A live File must match by identity: the name no longer marks a paste. */
+export function isPastedTextFile(file: File | undefined): boolean {
+ return file !== undefined && pastedTextFiles.has(file);
+}
+
+/** What was pasted, without a `File.text()` round trip. */
+export function pastedTextOf(file: File | undefined): string | undefined {
+ return file === undefined ? undefined : pastedTextByFile.get(file);
+}
+
+/**
+ * Wraps an attachment for the model. A paste gets its own tag and its size,
+ * the only markers that survive a reload, since the File does not.
+ */
+export function attachmentContentText(
+ name: string,
+ text: string,
+ pasted: boolean,
+ bytes?: number,
+): string {
+ if (!pasted) return `<attachment name=${name}>\n${text}\n</attachment>`;
+ const size = bytes === undefined ? "" : ` bytes=${bytes}`;
+ return `<${PASTED_TEXT_TAG} name=${name}${size}>\n${text}\n</${PASTED_TEXT_TAG}>`;
+}
+
+export function isPastedTextContent(text: string | undefined): boolean {
+ return text?.startsWith(`<${PASTED_TEXT_TAG} name=`) === true;
+}
+
+// Header only. Sizing a sent paste any other way means walking every byte of
+// it during render, which is what the chip must never do.
+const PASTED_TEXT_BYTES_RE = /^<pasted_text name=[^\n>]* bytes=(\d+)>/;
+const PASTED_TEXT_HEADER_SCAN_CHARS = 1024;
+
+export function pastedTextContentBytes(
+ content: string | undefined,
+): number | undefined {
+ if (content === undefined) return undefined;
+ const bytes = PASTED_TEXT_BYTES_RE.exec(
+ content.slice(0, PASTED_TEXT_HEADER_SCAN_CHARS),
+ )?.[1];
+ return bytes === undefined ? undefined : Number(bytes);
+}
+
+// Where the body sits inside the wrapper, so callers can slice out the piece
+// they need instead of unwrapping megabytes. Unwrapped content is all body.
+function attachmentBodyRange(content: string): { start: number; end: number } {
+ const tag = content.startsWith("<attachment name=")
+ ? "attachment"
+ : isPastedTextContent(content)
+ ? PASTED_TEXT_TAG
+ : undefined;
+ const headerEnd = tag === undefined ? -1 : content.indexOf("\n");
+ if (headerEnd === -1) return { start: 0, end: content.length };
+
+ const closing = `\n</${tag}>`;
+ return {
+ start: headerEnd + 1,
+ end: content.endsWith(closing)
+ ? Math.max(content.length - closing.length, headerEnd + 1)
+ : content.length,
+ };
+}
+
+/**
+ * Previews wrapped content without unwrapping it: the body can be megabytes,
+ * and only the opening is ever rendered.
+ */
+export function pastedTextContentPreview(content: string): {
+ text: string;
+ remaining: number;
+} {
+ const { start, end } = attachmentBodyRange(content);
+ const length = end - start;
+ const taken = Math.min(length, PASTED_TEXT_PREVIEW_MAX_CHARS);
+ return {
+ text: content.slice(start, start + taken),
+ remaining: length - taken,
+ };
+}
+
+/**
+ * The opening of an attachment's body, for naming a thread. A paste-only
+ * message has no inline text, so this is all the title has to work from.
+ */
+export function attachmentContentSample(
+ content: string,
+ max: number = ATTACHMENT_SAMPLE_CHARS,
+): string {
+ const { start, end } = attachmentBodyRange(content);
+ return content.slice(start, Math.min(end, start + max)).trim();
+}
+
+type AttachmentLike = {
+ readonly content?: readonly {
+ readonly type: string;
+ readonly text?: string;
+ }[];
+};
+
+/** The same opening, taken from the first attachment that carries text. */
+export function attachmentsSample(
+ attachments: readonly AttachmentLike[] | undefined,
+): string {
+ for (const attachment of attachments ?? []) {
+ for (const part of attachment.content ?? []) {
+ if (part.type !== "text" || part.text === undefined) continue;
+ const sample = attachmentContentSample(part.text);
+ if (sample.length > 0) return sample;
+ }
+ }
+ return "";
+}
+
+/**
+ * A pasted body without its wrapper, for anything that shows the text as the
+ * user pasted it: copy, exports, fine-tuning rows. Other content is untouched.
+ */
+export function unwrapPastedTextContent(content: string): string {
+ if (!isPastedTextContent(content)) return content;
+ const { start, end } = attachmentBodyRange(content);
+ return content.slice(start, end);
+}
+
+/** The whole body of a sent paste, unwrapped. Empty for any other content. */
+export function pastedTextContentBody(content: string): string {
+ return isPastedTextContent(content) ? unwrapPastedTextContent(content) : "";
+}
+
+/**
+ * Every pasted body on a message, for the paths that read `content` alone and
+ * would otherwise lose the paste: Chat Search and copying a message. Other
+ * attachment types are not included, since neither path ever had them.
+ */
+export function attachmentsPastedText(
+ attachments: readonly AttachmentLike[] | undefined,
+): string {
+ const bodies: string[] = [];
+ for (const attachment of attachments ?? []) {
+ for (const part of attachment.content ?? []) {
+ if (part.type !== "text" || part.text === undefined) continue;
+ const body = pastedTextContentBody(part.text);
+ if (body.length > 0) bodies.push(body);
+ }
+ }
+ return bodies.join("\n\n");
+}
+
+function clipboardText(clipboardData: DataTransfer): string {
+ try {
+ return clipboardData.getData("text/plain");
+ } catch {
+ return "";
+ }
+}
+
+/** Attaches an oversized text paste. True means the caller must not paste. */
+export function pasteLongTextAsFile(
+ event: ClipboardTextPasteEvent,
+ addFile: (file: File) => void | Promise<void>,
+ onError?: () => void,
+): boolean {
+ if (event.defaultPrevented) return false;
+ const { clipboardData } = event;
+ if (!clipboardData) return false;
+ // Images and files keep the existing paste path.
+ if (clipboardHasFileEntries(clipboardData)) return false;
+ if (clipboardAdvertisesFiles(clipboardData)) return false;
+
+ const text = clipboardText(clipboardData);
+ if (!shouldAttachPastedText(text)) return false;
+
+ // Build the file first: if that throws, the browser can still paste.
+ let file: File;
+ try {
+ file = createPastedTextFile(text);
+ } catch {
+ return false;
+ }
+
+ event.preventDefault();
+ try {
+ void Promise.resolve(addFile(file)).catch(() => onError?.());
+ } catch {
+ // addFile can throw before it ever returns a promise to catch on.
+ onError?.();
+ }
+ return true;
+}
+
+/** Renders an opening rather than the whole paste, which can be megabytes. */
+export function pastedTextPreview(text: string): {
+ text: string;
+ remaining: number;
+} {
+ const remaining = Math.max(text.length - PASTED_TEXT_PREVIEW_MAX_CHARS, 0);
+ return {
+ text: remaining > 0 ? text.slice(0, PASTED_TEXT_PREVIEW_MAX_CHARS) : text,
+ remaining,
+ };
+}
diff --git a/studio/frontend/tests/composer-paste-draft.test.ts b/studio/frontend/tests/composer-paste-draft.test.ts
new file mode 100644
index 00000000000..3b55ed3b423
--- /dev/null
+++ b/studio/frontend/tests/composer-paste-draft.test.ts
@@ -0,0 +1,84 @@
+// 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";
+
+const store = new Map<string, string>();
+let failWrites = false;
+
+// The draft helpers read window at call time, so a stub is enough here.
+(globalThis as { window?: unknown }).window = {
+ localStorage: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ if (failWrites) throw new Error("QuotaExceededError");
+ store.set(key, value);
+ },
+ removeItem: (key: string) => {
+ store.delete(key);
+ },
+ },
+};
+
+const {
+ clearComposerDraft,
+ composerDraftKey,
+ composerPasteDraftKey,
+ readComposerDraft,
+ readPasteDraft,
+ writeComposerDraft,
+ writePasteDraft,
+} = await import("../src/features/chat/utils/composer-draft.ts");
+
+test.beforeEach(() => {
+ store.clear();
+ failWrites = false;
+});
+
+test("an unsent paste survives a reload", () => {
+ const key = composerPasteDraftKey("t1");
+ const paste = `Deploy log\n${"line\n".repeat(500)}`;
+
+ writePasteDraft(key, [paste]);
+ assert.deepEqual(readPasteDraft(key), [paste]);
+
+ // Several pastes keep their order, and clearing removes the slot.
+ writePasteDraft(key, [paste, "second"]);
+ assert.deepEqual(readPasteDraft(key), [paste, "second"]);
+ writePasteDraft(key, []);
+ assert.deepEqual(readPasteDraft(key), []);
+});
+
+test("the paste slot is separate from the text draft", () => {
+ // Typing must never rewrite a paste that can run to megabytes, so the two
+ // live under different keys.
+ assert.notEqual(composerDraftKey("t1"), composerPasteDraftKey("t1"));
+ assert.notEqual(composerPasteDraftKey("t1"), composerPasteDraftKey("t2"));
+
+ writeComposerDraft(composerDraftKey("t1"), "typed");
+ writePasteDraft(composerPasteDraftKey("t1"), ["pasted"]);
+ clearComposerDraft("t1");
+ assert.equal(readComposerDraft(composerDraftKey("t1")), null);
+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("t1")), []);
+});
+
+test("a paste too big for the quota does not cost the typed draft", () => {
+ writeComposerDraft(composerDraftKey("t1"), "typed");
+ failWrites = true;
+
+ writePasteDraft(composerPasteDraftKey("t1"), ["x".repeat(64)]);
+ assert.equal(readComposerDraft(composerDraftKey("t1")), "typed");
+ assert.deepEqual(readPasteDraft(composerPasteDraftKey("t1")), []);
+});
+
+test("a corrupt paste slot reads as empty rather than throwing", () => {
+ const key = composerPasteDraftKey("t1");
+ for (const raw of ["not json", '{"text":"a"}', "[1,2]", ""]) {
+ store.set(key, raw);
+ assert.deepEqual(readPasteDraft(key), []);
+ }
+ // Non-string entries are dropped, the rest survive.
+ store.set(key, JSON.stringify(["keep", 5, null, "also"]));
+ assert.deepEqual(readPasteDraft(key), ["keep", "also"]);
+});
diff --git a/studio/frontend/tests/pasted-text-attachment.test.ts b/studio/frontend/tests/pasted-text-attachment.test.ts
new file mode 100644
index 00000000000..0d52f3efd49
--- /dev/null
+++ b/studio/frontend/tests/pasted-text-attachment.test.ts
@@ -0,0 +1,457 @@
+// 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 { fallbackTitleFromUserText } from "../src/features/chat/utils/chat-title.ts";
+import {
+ PASTED_TEXT_MIN_CHARS,
+ PASTED_TEXT_MIN_LINES,
+ PASTED_TEXT_PREVIEW_MAX_CHARS,
+ attachmentContentSample,
+ attachmentContentText,
+ attachmentsPastedText,
+ attachmentsSample,
+ createPastedTextFile,
+ isPastedTextContent,
+ isPastedTextFile,
+ pasteLongTextAsFile,
+ pastedTextContentBody,
+ pastedTextContentBytes,
+ pastedTextContentPreview,
+ pastedTextFileName,
+ pastedTextOf,
+ pastedTextPreview,
+ shouldAttachPastedText,
+ unwrapPastedTextContent,
+} from "../src/features/chat/utils/pasted-text.ts";
+
+type ClipboardStub = {
+ readonly files: readonly File[];
+ readonly items: readonly { kind: string }[];
+ readonly types: readonly string[];
+ getData: (type: string) => string;
+};
+
+function clipboard(
+ text: string,
+ files: readonly File[] = [],
+ extra: { types?: readonly string[]; data?: Record<string, string> } = {},
+): ClipboardStub {
+ return {
+ files,
+ items: files.map(() => ({ kind: "file" })),
+ types: extra.types ?? ["text/plain"],
+ getData: (type) =>
+ type === "text/plain" ? text : (extra.data?.[type] ?? ""),
+ };
+}
+
+function pasteEvent(clipboardData: ClipboardStub | null) {
+ let defaultPrevented = false;
+ return {
+ clipboardData: clipboardData as unknown as DataTransfer | null,
+ get defaultPrevented() {
+ return defaultPrevented;
+ },
+ preventDefault: () => {
+ defaultPrevented = true;
+ },
+ };
+}
+
+test("short pastes stay inline", () => {
+ assert.equal(shouldAttachPastedText(""), false);
+ assert.equal(shouldAttachPastedText(" \n "), false);
+ assert.equal(shouldAttachPastedText("what does this function do?"), false);
+ assert.equal(
+ shouldAttachPastedText("a".repeat(PASTED_TEXT_MIN_CHARS - 1)),
+ false,
+ );
+ assert.equal(
+ shouldAttachPastedText("line\n".repeat(PASTED_TEXT_MIN_LINES - 2)),
+ false,
+ );
+});
+
+test("bulk pastes become attachments by length or by line count", () => {
+ assert.equal(shouldAttachPastedText("a".repeat(PASTED_TEXT_MIN_CHARS)), true);
+ // Many short lines (a log tail, a stack trace) are just as unusable inline.
+ assert.equal(
+ shouldAttachPastedText("x\n".repeat(PASTED_TEXT_MIN_LINES)),
+ true,
+ );
+});
+
+test("the file is named after the opening of the paste", () => {
+ assert.equal(
+ pastedTextFileName("Introducing Unsloth"),
+ "Introducing Unsloth.txt",
+ );
+ // Leading blank lines are skipped.
+ assert.equal(
+ pastedTextFileName("\n\n Release notes \nbody"),
+ "Release notes.txt",
+ );
+ // Long openings cut on a word boundary, short ones are not padded.
+ assert.equal(
+ pastedTextFileName(
+ "Introducing Unsloth Studio, the fastest way to finetune",
+ ),
+ "Introducing Unsloth Studio, the.txt",
+ );
+ assert.equal(
+ pastedTextFileName(`${"z".repeat(60)} tail`),
+ `${"z".repeat(32)}.txt`,
+ );
+ // Path separators and control characters cannot reach the filename.
+ assert.equal(
+ pastedTextFileName("src/lib\\util:\tmain"),
+ "src lib util main.txt",
+ );
+ assert.equal(pastedTextFileName("\n \n"), "Pasted text.txt");
+ assert.equal(pastedTextFileName("///"), "Pasted text.txt");
+ // A single line of megabytes is read through a window, not copied whole.
+ assert.equal(
+ pastedTextFileName("b".repeat(4 * 1024 * 1024)),
+ `${"b".repeat(32)}.txt`,
+ );
+ assert.equal(
+ pastedTextFileName(`${" ".repeat(300)}${"b".repeat(1000)}`),
+ "Pasted text.txt",
+ );
+ // Blank lines are stepped over one at a time, so the walk is bounded too:
+ // naming must not depend on how many of them there are.
+ const started = process.hrtime.bigint();
+ assert.equal(
+ pastedTextFileName(`${"\n".repeat(4 * 1024 * 1024)}Deploy log`),
+ "Pasted text.txt",
+ );
+ assert.ok(Number(process.hrtime.bigint() - started) / 1e6 < 250);
+});
+
+test("pasted text files are recognised by identity", () => {
+ const file = createPastedTextFile(
+ "Deploy log\n".repeat(PASTED_TEXT_MIN_LINES),
+ );
+ assert.equal(file.name, "Deploy log.txt");
+ assert.equal(file.type, "text/plain");
+ assert.equal(isPastedTextFile(file), true);
+ // A .txt the user actually attached keeps the normal file tile.
+ assert.equal(
+ isPastedTextFile(
+ new File(["hi"], "Deploy log.txt", { type: "text/plain" }),
+ ),
+ false,
+ );
+ assert.equal(isPastedTextFile(undefined), false);
+});
+
+test("the pasted text is kept beside the file, not re-read from it", () => {
+ // Draft autosave runs on a keystroke, so it cannot await File.text().
+ const text = `Deploy log\n${"line\n".repeat(200)}`;
+ assert.equal(pastedTextOf(createPastedTextFile(text)), text);
+ assert.equal(
+ pastedTextOf(new File(["hi"], "notes.txt", { type: "text/plain" })),
+ undefined,
+ );
+ assert.equal(pastedTextOf(undefined), undefined);
+});
+
+test("the sent wrapper is what marks a paste after the File is gone", () => {
+ const pasted = attachmentContentText("Deploy log.txt", "body", true, 4);
+ const attached = attachmentContentText("notes.txt", "body", false, 4);
+
+ assert.equal(
+ pasted,
+ "<pasted_text name=Deploy log.txt bytes=4>\nbody\n</pasted_text>",
+ );
+ // Only the paste is tagged and sized; a real attachment keeps its wrapper.
+ assert.equal(attached, "<attachment name=notes.txt>\nbody\n</attachment>");
+ assert.equal(isPastedTextContent(pasted), true);
+ assert.equal(isPastedTextContent(attached), false);
+ assert.equal(isPastedTextContent(undefined), false);
+ assert.equal(isPastedTextContent("pasted_text elsewhere in the body"), false);
+});
+
+test("the chip size is read off the header, never measured", () => {
+ const pasted = attachmentContentText("Deploy log.txt", "body", true, 12_483);
+ assert.equal(pastedTextContentBytes(pasted), 12_483);
+ // A name that itself looks like the size must not win over the real one.
+ assert.equal(
+ pastedTextContentBytes(
+ attachmentContentText("x bytes=5.txt", "body", true, 99),
+ ),
+ 99,
+ );
+ assert.equal(pastedTextContentBytes(undefined), undefined);
+ assert.equal(
+ pastedTextContentBytes(attachmentContentText("a.txt", "body", true)),
+ undefined,
+ );
+ assert.equal(
+ pastedTextContentBytes(attachmentContentText("a.txt", "body", false, 4)),
+ undefined,
+ );
+});
+
+test("previewing sent content never materialises the body", () => {
+ const body = "line one\nline two";
+ const pasted = attachmentContentText("a.txt", body, true, 17);
+ assert.deepEqual(pastedTextContentPreview(pasted), {
+ text: body,
+ remaining: 0,
+ });
+ assert.deepEqual(
+ pastedTextContentPreview(attachmentContentText("a.txt", body, false)),
+ { text: body, remaining: 0 },
+ );
+
+ const huge = "z".repeat(PASTED_TEXT_PREVIEW_MAX_CHARS + 40);
+ const cut = pastedTextContentPreview(
+ attachmentContentText("a.txt", huge, true, huge.length),
+ );
+ assert.equal(cut.text.length, PASTED_TEXT_PREVIEW_MAX_CHARS);
+ assert.equal(cut.remaining, 40);
+
+ // Unwrapped or truncated content still previews rather than throwing.
+ assert.deepEqual(pastedTextContentPreview("bare text"), {
+ text: "bare text",
+ remaining: 0,
+ });
+ assert.deepEqual(pastedTextContentPreview("<pasted_text name=a.txt>\nbody"), {
+ text: "body",
+ remaining: 0,
+ });
+});
+
+test("a paste-only message still has something to name the thread with", () => {
+ const paste = `Fix the retry backoff\n${"detail\n".repeat(500)}`;
+ const sent = attachmentContentText(
+ pastedTextFileName(paste),
+ paste,
+ true,
+ paste.length,
+ );
+
+ // The composer sends no text at all in this case, so the title comes from
+ // the attachment or the thread stays "New Chat".
+ assert.equal(
+ fallbackTitleFromUserText(attachmentsSample([{ content: [] }])),
+ "New Chat",
+ );
+ assert.equal(
+ fallbackTitleFromUserText(
+ attachmentsSample([{ content: [{ type: "text", text: sent }] }]),
+ ),
+ "Fix the retry backoff",
+ );
+ // Only a bounded opening is read, never the whole body.
+ assert.ok(
+ attachmentsSample([{ content: [{ type: "text", text: sent }] }]).length <=
+ 512,
+ );
+ // Non-text parts are skipped, and the first text part wins.
+ assert.equal(
+ attachmentsSample([
+ { content: [{ type: "image" }] },
+ { content: [{ type: "text", text: sent }] },
+ ]),
+ attachmentContentSample(sent),
+ );
+ assert.equal(attachmentsSample(undefined), "");
+});
+
+test("chat search still finds what the paste moved out of the message", () => {
+ const body = `Fix the retry backoff\n${"detail\n".repeat(500)}closing line`;
+ const sent = attachmentContentText("Fix.txt", body, true, body.length);
+
+ // The whole body, not the opening: a term late in a paste has to stay
+ // findable or the paste is searchable only by its first line.
+ assert.equal(pastedTextContentBody(sent), body);
+ assert.equal(
+ attachmentsPastedText([{ content: [{ type: "text", text: sent }] }]),
+ body,
+ );
+
+ // Attachments that were never indexed stay that way.
+ assert.equal(pastedTextContentBody("[PDF: paper.pdf]\nAbstract"), "");
+ assert.equal(
+ pastedTextContentBody(attachmentContentText("notes.txt", body, false)),
+ "",
+ );
+ assert.equal(
+ attachmentsPastedText([
+ { content: [{ type: "text", text: "[PDF: paper.pdf]\nAbstract" }] },
+ { content: [{ type: "image" }] },
+ ]),
+ "",
+ );
+ assert.equal(attachmentsPastedText(undefined), "");
+
+ // Several pastes on one message all reach the index.
+ const second = attachmentContentText("Log.txt", "second body", true, 11);
+ assert.equal(
+ attachmentsPastedText([
+ { content: [{ type: "text", text: sent }] },
+ { content: [{ type: "text", text: second }] },
+ ]),
+ `${body}\n\nsecond body`,
+ );
+});
+
+test("copies and exports carry the paste, not its wrapper", () => {
+ const body = "Deploy log\nline two";
+ const sent = attachmentContentText("Deploy log.txt", body, true, 19);
+
+ // The marker is an implementation detail; the same text pasted below the
+ // threshold never had one.
+ assert.equal(unwrapPastedTextContent(sent), body);
+ assert.ok(!unwrapPastedTextContent(sent).includes("pasted_text"));
+
+ // Everything else is handed back untouched, including the wrapper a real
+ // attachment has always exported with.
+ const attached = attachmentContentText("notes.txt", body, false);
+ assert.equal(unwrapPastedTextContent(attached), attached);
+ assert.equal(unwrapPastedTextContent("bare text"), "bare text");
+ assert.equal(unwrapPastedTextContent(""), "");
+});
+
+test("a sample of unwrapped content is left as it is", () => {
+ // PDF and DOCX adapters write their own prefix with no wrapper.
+ assert.equal(
+ attachmentContentSample("[PDF: paper.pdf]\nAbstract"),
+ "[PDF: paper.pdf]\nAbstract",
+ );
+ assert.equal(attachmentContentSample("plain", 3), "pla");
+});
+
+test("the preview is capped, and says how much it is holding back", () => {
+ const short = pastedTextPreview("all of it");
+ assert.equal(short.text, "all of it");
+ assert.equal(short.remaining, 0);
+
+ const long = pastedTextPreview(
+ "a".repeat(PASTED_TEXT_PREVIEW_MAX_CHARS + 25),
+ );
+ assert.equal(long.text.length, PASTED_TEXT_PREVIEW_MAX_CHARS);
+ assert.equal(long.remaining, 25);
+});
+
+test("a long text paste is swallowed and handed over as a file", async () => {
+ const text = "a".repeat(PASTED_TEXT_MIN_CHARS);
+ const added: File[] = [];
+ const event = pasteEvent(clipboard(text));
+
+ assert.equal(
+ pasteLongTextAsFile(event, (file) => {
+ added.push(file);
+ }),
+ true,
+ );
+ assert.equal(event.defaultPrevented, true);
+ assert.equal(added.length, 1);
+ assert.equal(await added[0]?.text(), text);
+});
+
+test("normal pastes and file pastes fall through untouched", () => {
+ const shortPaste = pasteEvent(clipboard("hello"));
+ assert.equal(
+ pasteLongTextAsFile(shortPaste, () => {}),
+ false,
+ );
+ assert.equal(shortPaste.defaultPrevented, false);
+
+ // An image on the clipboard belongs to the file-paste path, even when the
+ // app also offers a long text/plain rendering of it.
+ const withFile = pasteEvent(
+ clipboard("a".repeat(PASTED_TEXT_MIN_CHARS), [
+ new File([new Uint8Array([1, 2, 3])], "shot.png", { type: "image/png" }),
+ ]),
+ );
+ assert.equal(
+ pasteLongTextAsFile(withFile, () => {}),
+ false,
+ );
+ assert.equal(withFile.defaultPrevented, false);
+
+ assert.equal(
+ pasteLongTextAsFile(pasteEvent(null), () => {}),
+ false,
+ );
+});
+
+test("a paste too big to hold inline still attaches", () => {
+ // Anything the old cap rejected fell back to pasting inline, which is the
+ // one case the input cannot survive.
+ const huge = "a".repeat(20 * 1024 * 1024 + 1);
+ assert.equal(shouldAttachPastedText(huge), true);
+ // Whitespace is no exemption either: it used to skip both thresholds.
+ assert.equal(shouldAttachPastedText(" ".repeat(PASTED_TEXT_MIN_CHARS)), true);
+ assert.equal(
+ shouldAttachPastedText("\n".repeat(PASTED_TEXT_MIN_LINES)),
+ true,
+ );
+ assert.equal(shouldAttachPastedText(" "), false);
+});
+
+test("an attachment that throws on the spot reports instead of vanishing", () => {
+ let errors = 0;
+ const event = pasteEvent(clipboard("a".repeat(PASTED_TEXT_MIN_CHARS)));
+
+ const handled = pasteLongTextAsFile(
+ event,
+ () => {
+ throw new Error("no room for another attachment");
+ },
+ () => {
+ errors += 1;
+ },
+ );
+
+ // The paste is already swallowed at this point, so the toast is the only
+ // thing standing between the user and silently losing the clipboard.
+ assert.equal(handled, true);
+ assert.equal(event.defaultPrevented, true);
+ assert.equal(errors, 1);
+});
+
+test("a .txt named like a pasted one keeps the normal tile", () => {
+ const pasted = createPastedTextFile("Release notes\nbody");
+ const lookalike = new File(["hi"], pasted.name, { type: "text/plain" });
+ assert.equal(isPastedTextFile(lookalike), false);
+});
+
+test("native image and file payloads stay on the file paste path", () => {
+ const text = "a".repeat(PASTED_TEXT_MIN_CHARS);
+ // Tauri advertises native payloads by type only, with nothing in files.
+ const svg = pasteEvent(
+ clipboard(text, [], { types: ["text/plain", "image/svg+xml"] }),
+ );
+ assert.equal(
+ pasteLongTextAsFile(svg, () => {}),
+ false,
+ );
+ assert.equal(svg.defaultPrevented, false);
+
+ const copiedFiles = pasteEvent(
+ clipboard(text, [], {
+ types: ["text/plain", "text/uri-list"],
+ data: { "text/uri-list": "file:///tmp/notes.txt" },
+ }),
+ );
+ assert.equal(
+ pasteLongTextAsFile(copiedFiles, () => {}),
+ false,
+ );
+
+ // A plain text/html copy is still text, not a file payload.
+ const richText = pasteEvent(
+ clipboard(text, [], { types: ["text/plain", "text/html"] }),
+ );
+ assert.equal(
+ pasteLongTextAsFile(richText, () => {}),
+ true,
+ );
+});