Skip to content

Attach long pastes as a text file in Chat - #8472

Merged
shimmyshimmer merged 23 commits into
mainfrom
studio-paste-long-text-attachment
Aug 13, 2026
Merged

shimmyshimmer merged 23 commits into
mainfrom
studio-paste-long-text-attachment

Conversation

@shimmyshimmer

@shimmyshimmer shimmyshimmer commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Pasting a big block of text into the chat composer dumped every line into the input, which buried whatever you were actually asking and made the composer unusable until you cleared it. There was no way to hand over a wall of text as a file.

Long pastes now attach instead of paste.

Behaviour

  • A paste of 2000+ characters or 40+ lines becomes a .txt attachment. Anything shorter pastes inline exactly as before.
  • The file is named after the opening of the paste, so a pasted release note shows up as Introducing Unsloth Studio.txt rather than a timestamp. Path separators and control characters are stripped, the cut prefers a word boundary, and an opening with nothing usable in it falls back to Pasted text.txt.
  • The chip shows the name and size, with the usual remove button. It is borderless in both themes, and in dark mode it sits a shade under the composer surface.
  • Hovering the chip swaps the size for "Show in text field". Clicking it puts the text back into the composer (appended after whatever is already there) and drops the attachment, so nothing is trapped in the chip.
  • After sending, the chip stays on the message. Clicking it there opens a read only preview of what was pasted.
  • The model still gets the full text: the file goes through the existing TextAttachmentAdapter, so no content is lost.
  • Pastes carrying images or real files still take the existing file paste path, including the native payloads Tauri advertises through types alone. A real .txt you attach yourself keeps the normal file tile, since a pasted file is matched by identity rather than by name.

Changes

  • studio/frontend/src/features/chat/utils/pasted-text.ts (new): thresholds, naming, file creation and recognition, the paste interception, and the wrapper stripping used by the preview.
  • studio/frontend/src/components/assistant-ui/thread.tsx: the composer paste handler tries the text path first, then falls through to the file paste path.
  • studio/frontend/src/components/assistant-ui/attachment.tsx: the chip, the "Show in text field" action, and the preview dialog.
  • studio/frontend/tests/pasted-text-attachment.test.ts (new): 11 tests covering the thresholds, naming, recognition, interception, and fall through for short pastes, file pastes, native payloads and a missing clipboard.

The compare composer is untouched: it only supports image and audio attachments, so a long paste there still goes inline.

One known limit: the chip on an already sent message is matched by attachment id, which is in memory only. Reload the page and an old pasted attachment renders as a normal file tile with the same name. The text itself is unaffected.

Testing

  • npm run typecheck clean.
  • npm test: 1964 pass, 0 fail (includes the 11 new tests).
  • npm run build succeeds and serves the new bundle.

The paste path, naming and thresholds are covered by the unit tests. The chip hover and click behaviour has not been clicked through in the browser yet, so a quick manual pass on that would be welcome before merge. Happy to tune the 2000 char / 40 line threshold if it feels too eager.

Pasting a large block of text dumped every line into the composer.
Pastes of 2000+ chars or 40+ lines now become a Pasted_Text_*.txt
attachment; clicking the chip shows the text back in the input.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

- Attach oversized pastes instead of letting them fall back inline
- Match a live File by identity so a user's Pasted_Text_*.txt is untouched
- Skip the text path when the clipboard advertises native images or files
- Drop the inline action if the attachment left the composer while reading
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed 7ba8281 with all four of these addressed. Summary:

  • Oversized pastes: the 20 MiB cap is gone. It made the largest pastes fall back to an inline paste, which is the case this PR is meant to prevent.
  • Lookalike filenames: a live File is matched by identity only, so a .txt you attach yourself keeps the normal tile. The filename fallback is now limited to sent messages, where no File remains.
  • Inline race: the read continuation checks that the component is still mounted and that the attachment is still in the composer before writing, and a failed read no longer leaves an unhandled rejection.
  • Native clipboard payloads: the text path now defers on the same types signals pasteClipboardFiles uses, so native images and copied files are not swallowed as text.

Tests are up to 9 for this file (1962 total, all passing), typecheck and build clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

- Name the file from the first line of the paste instead of a timestamp
- Chip is borderless, and sits a shade under the composer in dark mode
- Track the attachment id so the chip survives the send without the name
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed af2cd93 with the design and naming feedback.

  • The chip has no border in either theme now. Light mode keeps the --muted fill, dark mode drops to --background (#181818), which is a shade under the composer surface (--card, #212121), with hover going to --muted.
  • The file is named after the first non-empty line of the paste instead of Pasted_Text_<epoch>.txt, cut at 32 characters on a word boundary. Path separators and control characters are stripped, and an opening with nothing usable falls back to Pasted text.txt.

Since the name no longer marks a paste, the chip on a sent message is matched by attachment id, which the send path preserves. That is in memory, so after a page reload an old pasted attachment falls back to the normal file tile. The text is unaffected either way.

1964 tests pass, typecheck and build clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

- Mark a sent paste with its own wrapper tag so the chip survives a reload
- Cap the preview and say how much of the paste it is holding back
- Read the name through a window instead of splitting the whole paste
- Attach whitespace-only pastes rather than letting them through inline
- Report an attachment that throws synchronously, instead of losing it
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed f545a97. Five of the six were real, one was already fixed.

  • Unbounded preview: capped at 100,000 characters, with a line saying how many more went with the message. The attachment keeps everything.
  • Reload persistence: a pasted file is now sent as <pasted_text name=...> rather than <attachment name=...>. That content is persisted and restored with the message, so the chip and preview survive a reload. The in-memory id registry is gone.
  • split("\n") for the name: replaced with an indexOf walk that copies at most 256 characters of the first non-blank line. A 20 MiB single-line paste names itself in about 3 ms.
  • Whitespace bypass: only an empty string is rejected now, so a huge whitespace-only paste attaches instead of landing inline.
  • Synchronous throw: the file is built before preventDefault, and the addFile call is wrapped, so a synchronous failure shows the toast instead of silently eating the clipboard.
  • The filename fallback comment was against the previous commit. That fallback no longer exists.

13 tests in this file, 1966 total, all passing. Typecheck and build clean.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

- Carry the byte count in the wrapper header and read it in constant time
- Preview sent content by slicing it, instead of unwrapping the whole body
- Drop unwrapAttachmentText, which existed only to copy megabytes
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed 181da79 for the one new comment, which was right.

Sizing a sent paste ran during render: mounting a chip unwrapped the whole attachment with a regex and built a Blob from it, so a large paste could stall the thread before paint even if the preview was never opened. Capping the preview in the previous commit had not touched that path.

  • The byte count now travels in the header as <pasted_text name=... bytes=N>, taken from file.size when the message is sent, and the chip reads it with a regex bounded to the first 1024 characters.
  • The preview slices the body out of the wrapped string by index rather than unwrapping it, so nothing materialises beyond the 100,000 characters on screen.
  • unwrapAttachmentText is deleted; copying the body was the only thing it did.

On a 60 MB sent paste the whole render-path cost is now about 0.002 ms. 14 tests here, 1967 total, all passing, typecheck and build clean.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

A paste-only message sends no inline text, so the thread stayed
"New Chat" and the title model got nothing to work from. Titles and
project snippets now fall back to a bounded opening of the attachment.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Pushed 3df8170. The one new comment was right, and it was a regression from this PR rather than a pre-existing gap.

Sending a paste with an empty composer produces content: [], so extractTextParts returned nothing and the thread kept the name "New Chat". With automatic titles on, the title model got "New Chat" as the user text. Before this PR the same paste was inline and named the thread.

  • Titles now fall back to a bounded 512 character opening of the first attachment that carries text, which the existing first-line cut then trims.
  • The fallback is not paste-specific, so an attached .txt, PDF or DOCX names its thread too. That was already broken before this PR.
  • The project chat list drew its snippet from the same empty content, so those rows would have been blank as well. They read from the attachment now.

16 tests here, 1969 total, all passing. Typecheck and build clean.

@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3df81701f5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The deep import into `@/features/hub/lib/format` trips the repo's
`no-restricted-imports` eslint rule, which allows `@/features/[name]` only.
`formatBytes` is already re-exported from `features/hub/index.ts`, and the
built bundle is byte-identical either way.
`pasted-text.ts` carried its own copy of the clipboard inspection already in
`clipboard-files.ts`. The two paths run back to back on the same event, so any
drift between them means a paste is handled twice or not at all.

Both now import `clipboard-payload.ts`, which owns `browserClipboardFiles`,
`clipboardHasFileEntries`, `clipboardAdvertisesFiles` and `clipboardHasPlainText`,
plus the private type and file-URI helpers. `pasteClipboardFiles` collapses its
separate `advertisesImage` and `advertisesFile` checks into the one call, since
both uses were the disjunction.

The surviving `clipboardHasLocalFileUri` catches per type rather than abandoning
the scan on the first `getData` that throws, so a readable `text/uri-list` is no
longer hidden by an unreadable sibling type.

Relative imports carry the `.ts` extension: `npm test` runs
`node --experimental-strip-types`, whose ESM resolver does not add it.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed 1cb339c, two commits from a review pass over the branch.

Restricted import (f687017)

attachment.tsx reached into @/features/hub/lib/format for formatBytes. That trips the repo's no-restricted-imports eslint rule, which allows @/features/[name] only, and formatBytes is already re-exported from features/hub/index.ts. Now imported from the feature index. The built bundle is byte-identical either way, same chunk hash, so the barrel costs nothing here.

Duplicated clipboard inspection (1cb339c)

pasted-text.ts carried its own copy of the clipboard detection that clipboard-files.ts already had: clipboardHasLocalFileUri, the type sniffing for native payloads, and a near-twin of browserClipboardFiles. Both run back to back on the same paste event, so any drift between the two copies means a paste gets handled twice or falls through both.

New studio/frontend/src/features/chat/utils/clipboard-payload.ts owns it: browserClipboardFiles, clipboardHasFileEntries, clipboardAdvertisesFiles, clipboardHasPlainText, plus the private type and file-URI helpers. Both callers import from it and neither keeps a local copy.

Two things fell out of merging them:

  • pasteClipboardFiles used advertisesImage and advertisesFile separately, but both uses were the disjunction, so it collapses to one clipboardAdvertisesFiles call.
  • The surviving clipboardHasLocalFileUri is the pasted-text.ts version, which catches per type instead of abandoning the scan on the first getData that throws. A readable text/uri-list is no longer hidden by an unreadable sibling type. Both paths read that as "this is a file", so the change only ever routes a paste to the file path, never away from it.

One trap worth flagging

The relative imports carry the .ts extension. npm test runs node --experimental-strip-types, whose ESM resolver will not add it, so an extensionless ./clipboard-payload typechecks fine and passes under tsx but fails the entire pasted-text-attachment.test.ts file with ERR_MODULE_NOT_FOUND. Matches the existing convention in conversation-markdown-export.ts:9 and sse-json-events.ts:4.

Verification

npm run typecheck clean. npm test 1969/1969. npm run build clean. npx eslint over the four touched files is down to the one pre-existing set-state-in-effect error at attachment.tsx:59, which is on main too.

Left alone deliberately: EditComposer has no onPaste, so a long paste while editing a message still goes inline. Its attachments are not editable, so there is nothing for the paste to become.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1cb339c653

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Chat Search builds its text from `message.content` only, so moving a long paste
into an attachment made everything past its first line unfindable. Searching for
a phrase from the middle of a pasted log returned nothing.

`extractText` in `use-chat-search-index.ts` now prepends `attachmentsPastedText`,
which unwraps `<pasted_text ...>` bodies via the new `pastedTextContentBody`.
Only pastes are read: PDF, DOCX and attached text files were never indexed, and
picking them up here would change search behaviour beyond the regression and add
their bodies to an index that already holds 200 threads in memory.

The body goes in whole rather than sampled. That is what the index held before
the paste moved out of `content`, so memory is back where it was.
`canQueueCurrentPrompt` rejects any composer holding an attachment, so a paste
that used to queue as inline text started failing with "Only text prompts can be
queued". Pasting a log while a response streams is exactly when queueing earns
its keep, and the user was left waiting for the run or pouring the paste back
into the composer by hand.

The queue carries strings, and a pasted attachment is a string the composer
parked in a chip, so `queuePastedTextPrompt` reads those files and folds them
into the queued prompt after whatever was typed. Composers holding a real
attachment still take the existing refusal.

`canQueueCurrentPrompt` keeps its exact conditions; the shared ones move into
`composerAcceptsQueueing` so the pasted-text path cannot drift from them. The
started callback clears only when the text and the attachment ids are still the
ones that were queued, matching the text-only guard it sits beside.

Manual check: start a response, paste 3000 characters, press enter. The chip
clears and the prompt queues with the pasted text; it sends when the run ends.
Repeat with an image attached and the refusal toast still appears.
Composer drafts are plain strings in localStorage, and a pasted attachment is a
File held in memory, so refreshing before sending threw the whole paste away.
Inline text survived that reload before this PR moved it into an attachment.

Pastes get their own slot, `chat-draft-pastes:<thread>`, rather than joining the
text draft. Two reasons: the text slot is rewritten 300ms after every keystroke
and a paste can run to megabytes, and a paste large enough to blow the storage
quota now fails on its own key instead of taking the typed draft with it. The
save effect is keyed on the attachment ids, so typing beside a paste does not
touch it.

`createPastedTextFile` keeps the text in a `WeakMap` beside the existing
identity `WeakSet`, which is what lets the save path run without awaiting
`File.text()`. Restore recreates the attachment through the same constructor, so
the chip and its name come back unchanged; names are not stored because a pasted
file is named from its own text.

Restore skips a composer that already holds a paste. The composer outlives a
thread switch, so appending there would stack one thread's paste onto another's;
the stored draft keeps until the composer is clear.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed bd0b69f. Three commits for the three P2s, all of which reproduced.

Chat Search stopped finding pastes (d8e8162)

extractText in use-chat-search-index.ts builds its text from message.content alone, so a paste became findable only by whatever the title happened to catch. It now prepends attachmentsPastedText, which unwraps <pasted_text ...> bodies through the new pastedTextContentBody.

The whole body goes in, not a sample, because that is what the index held before the paste left content, so memory lands back where it was. Scoped to pastes: PDF, DOCX and attached text files were never indexed, and pulling them in here would change search beyond this regression and grow an index that already holds 200 threads.

Long pastes could not be queued (16d1b72)

canQueueCurrentPrompt rejects any composer holding an attachment, so a paste that used to queue as inline text hit "Only text prompts can be queued". Pasting a log while a response streams is exactly when queueing earns its keep.

queuePastedTextPrompt reads those files and folds them into the queued prompt after whatever was typed. A composer holding a real attachment still gets the existing refusal. canQueueCurrentPrompt keeps its exact conditions; the shared ones moved into composerAcceptsQueueing so the two paths cannot drift. The started callback clears only when the text and the attachment ids are still the ones that were queued, matching the text-only guard beside it.

An unsent paste died on reload (bd0b69f)

Drafts are plain strings in localStorage and a pasted attachment is a File in memory, so a refresh before sending lost the paste outright. Inline text survived that before this PR.

Pastes now persist under their own key, chat-draft-pastes:<thread>, and restore as the same chip. Keeping them out of the text slot is deliberate: that slot is rewritten 300ms after every keystroke and a paste can run to megabytes, and a paste large enough to blow the quota now fails on its own key instead of taking the typed draft with it. The save effect is keyed on attachment ids, so typing beside a paste never rewrites it. createPastedTextFile keeps the text in a WeakMap beside the identity WeakSet, which is what lets the save path run without awaiting File.text().

Restore skips a composer that already holds a paste. The composer outlives a thread switch, so appending there would stack one thread's paste onto another's; the stored draft keeps until the composer is clear.

Older items

Reacted and replied to the three still-open inline comments from earlier rounds. All three were already fixed on the branch and had only been answered in prose: the inlining continuation guard (7ba8281), the preview cap (f545a97) and title generation from attachments (181da79, 3df8170).

Verification

npm run typecheck clean. npm test 1975 tests, new: 4 in tests/composer-paste-draft.test.ts covering the round trip, key separation, quota failure isolation and corrupt slots, plus 2 in tests/pasted-text-attachment.test.ts for the search bodies and the text cache. npm run build clean. npx eslint over every touched file holds at the same 47 pre-existing errors it had before these commits, none in the new files.

Unrelated flake worth knowing about: tests/credential-persistence.test.ts:416 and :469 ("HF hydration does not overwrite an in-flight user edit", "cross-tab refresh replays after an active HF hydration") fail roughly one run in five, on this branch and on the untouched head before any of these commits.

Manual checks for the parts that are UI:

  • Start a response, paste 3000 characters, press enter. The chip clears and the prompt queues with the pasted text, then sends when the run ends. With an image attached instead, the refusal toast still appears.
  • Paste 3000 characters, reload before sending. The chip comes back with the same name, and clicking it still shows the text.
  • Open Chat Search and search for a phrase from the middle of a sent paste.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b5dc502523

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

description: "Paste it again, or paste it in smaller pieces.",
}),
);
if (attachedPastedText) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve pasted text when editing a sent prompt

After this path turns a long paste into an attachment, the sent message's regular content contains only separately typed text. The user-message Edit action seeds EditComposer from that regular content, and the editor at thread.tsx:6323-6381 neither renders nor unwraps attachments, so editing a paste-only turn opens a blank input and editing a mixed turn cannot modify the pasted portion; before this interception, the same text was editable inline. Populate the edit composer with the pasted attachment body or provide attachment editing there.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one: the paste is not lost on edit.

DefaultEditComposerRuntimeCore seeds _previousAttachments from message.attachments and calls setAttachments in its constructor, and handleSend re-sends them with the edited content (@assistant-ui/core/dist/runtime/base/default-edit-composer-runtime-core.js). Editing a paste-only turn and sending keeps the attachment; if neither the text nor the attachments changed, handleSend does not append at all.

What is true is that an attachment is not editable there and EditComposer renders no attachment UI. That is how every attachment type has always behaved in that composer, including PDFs and .txt files, and it predates this PR. Seeding the edit composer with the pasted body instead would put megabytes back into an input, which is the thing this PR exists to stop.

`messageToPlainText` shares one `collect` between `msg.content` and attachment
content, so b5dc502 ran `unwrapPastedTextContent` over message bodies too. A
message that legitimately opens with `<pasted_text name=...>`, a code sample
about this feature being the obvious case, had its first and last lines stripped
out of fine-tuning exports.

`collect` now takes the source, and only attachment blocks are unwrapped, which
is what `messageToText` and `messageToMarkdown` already did.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed 4011c4a. One held up, one did not.

Fixed: unwrapping reached message bodies (4011c4a)

Correct, and the comment I wrote in b5dc502 claiming it was a no-op was simply wrong. messageToPlainText shares one collect between msg.content and attachment content, so a message that legitimately opens with <pasted_text name=...>, a code sample about this feature being the obvious case, had its first and last lines stripped out of fine-tuning exports. collect now takes the source and unwraps only attachment blocks, matching what messageToText and messageToMarkdown already did.

Not taking: editing a sent prompt

The paste is not lost on edit. DefaultEditComposerRuntimeCore seeds _previousAttachments from message.attachments and calls setAttachments in its constructor, and handleSend re-sends them with the edited content, in @assistant-ui/core/dist/runtime/base/default-edit-composer-runtime-core.js. Edit a paste-only turn, type, send, and the attachment goes with it. Change nothing and handleSend does not append at all.

What is true is that the attachment is not editable there and EditComposer renders no attachment UI. That is how every attachment type behaves in that composer, PDFs and .txt files included, and it predates this PR. Seeding the edit composer with the pasted body would put megabytes back into an input, which is the thing this PR exists to stop.

Verification

npm run typecheck clean. npm test 1976 pass. npm run build clean. eslint on prompt-storage-dialog.tsx unchanged at its existing 17.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4011c4ad96

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2110 to +2112
const attachedPastedText = pasteLongTextAsFile(
event,
(file) => aui.composer().addAttachment(file),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Intercept long pastes in the Compare composer

When the user is in Compare mode, this new interception is never reached because SharedComposer owns a separate textarea whose onPaste handler at shared-composer.tsx:944-963 only calls pasteClipboardFiles. A 2,000-character or 40-line paste there therefore still follows the browser's inline path and can flood or freeze the controlled Compare input; wire the long-text handling into that composer as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. Compare behaves exactly as it did before this PR, so nothing regressed there.

SharedComposer's addFiles only accepts audio and images (shared-composer.tsx:909-947); a text/plain File is dropped on the floor, and its handleFilePaste already rejects anything else with "Compare supports images and audio within the attachment size limits." Wiring pasteLongTextAsFile in would need text attachments in Compare, which do not exist, and the chip, preview, draft and send paths that go with them.

Worth doing as its own change. The PR description calls the omission out rather than leaving it implied.

`create_research_run` rejects a user message whose `content` has no text, and
`_research_question_context` builds the question from `content` alone. A long
paste now lives in an attachment, so a paste-only prompt was refused with
"Deep research requires a user message with non-empty text" and a mixed prompt
quietly researched only the short typed part.

`message_text_with_pastes` in `core/inference/message_content.py` reads a
message's text plus any pasted attachment bodies, with `pasted_text_body`
stripping the `<pasted_text ...>` wrapper the composer adds. Both research paths
use it.

Other attachment types stay out. A PDF or an attached `.txt` was never part of a
message's text, and pulling those into the research question would change what
runs for prompts that have nothing to do with pasting.
b5dc502 stripped the paste wrapper from `messageToText`, `messageToMarkdown` and
`messageToPlainText` but left `messageToOpenAI`, so Raw JSONL and bulk
`jsonl-raw` exports still carried `<pasted_text name=... bytes=...>` and its
closing tag.

It now unwraps text parts that came from attachments, leaving message content
untouched for the same reason as 4011c4a: a body may quote that syntax.
The generated-image edit overlay submits `composerText`, and its branch in
`handleSubmit` returns early when that is empty. A long edit instruction became
an attachment instead, which left the Send control enabled through
`hasSendableContent` and then did nothing when pressed.

Long pastes are no longer intercepted while the overlay is open, so an edit
instruction stays where the only code path that reads it can find it.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed 359145d. Three of the four held up.

Deep Research refused a pasted question (cdbbdd5)

The sharpest of the four, and a hard failure rather than a degradation: create_research_run validates content_to_text(user_message["content"]) and a paste-only prompt came back 400 "Deep research requires a user message with non-empty text". A mixed prompt researched only the typed part, since _research_question_context read content alone.

New message_text_with_pastes in core/inference/message_content.py reads a message's text plus any pasted attachment bodies, with pasted_text_body stripping the wrapper. Both research paths use it. Other attachment types stay out: a PDF or an attached .txt was never part of a message's text, and pulling those in would change what runs for prompts unrelated to pasting. Four cases added to studio/backend/tests/test_message_content.py.

Raw JSONL still carried the wrapper (03212ad)

b5dc502 covered messageToText, messageToMarkdown and messageToPlainText and missed messageToOpenAI. It now unwraps attachment-sourced text parts, message content left verbatim for the same reason as 4011c4a.

Image-edit Send was a dead control (359145d)

Confirmed: the overlay branch returns on empty composerText while hasSendableContent counts the attachment, so the button stayed enabled and did nothing. Long pastes are no longer intercepted while the overlay is open, so the instruction stays where the only code path that reads it looks. Unwrapping into the edit prompt instead would mean handing an image-edit call a multi-megabyte instruction.

Not taking: the Compare composer

Compare behaves exactly as it did before this PR, so nothing regressed. SharedComposer's addFiles accepts only audio and images (shared-composer.tsx:909-947), a text/plain File is dropped, and its handleFilePaste already answers anything else with "Compare supports images and audio within the attachment size limits." Wiring the interception in would need text attachments in Compare, which do not exist, plus the chip, preview, draft and send paths that go with them. Worth its own change; the PR description names the omission rather than leaving it implied.

Verification

npm run typecheck clean, npm test 1976 pass, npm run build clean, eslint unchanged per file. ruff check clean on the four Python files and scripts/run_ruff_format.py leaves them alone. pytest studio/backend/tests/test_message_content.py 15 pass.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 359145d2ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +3092 to +3096
const queuedPrompt = [textAtQueue, ...texts]
.filter((part) => part.trim().length > 0)
.join("\n\n");
if (queuedPrompt.length === 0) return;
startHydratedPromptQueue([queuedPrompt], waitForCurrentRun, () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep queued pastes out of inline prompt text

When a response is running and the paste is large, this expands the uncapped file back into a single queued string. PromptQueueStack then renders the entire value in both the row and its aria-label, and dispatch later places it in a normal inline message via appendTextToThread; a multi-megabyte paste can therefore freeze the queue UI and conversation despite the attachment path being introduced to prevent exactly that. Preserve pasted attachments or use bounded queue display metadata rather than converting the body to inline prompt content.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. Folding the paste into the queued string is the first of the two options the earlier queueing item offered, and it restores exactly what happened before this PR: the same text pasted inline, queued as one prompt, rendered by the same PromptQueueStack row and aria-label and dispatched through the same appendTextToThread. Nothing about that path changed here.

The queue rendering an unbounded prompt is worth bounding, but it is true of any long typed or pasted prompt and predates this change; capping item.prompt in the row and the label is a queue-UI change on its own terms. Carrying attachments through the queue is the other option, and that is a queue schema change: startPromptQueue takes string[], and the entries are persisted and rehydrated as strings.

Comment on lines +69 to +72
const end = text.indexOf("\n", start);
const stop = Math.min(
end === -1 ? text.length : end,
start + PASTED_TEXT_NAME_SCAN_CHARS,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the newline search to the filename scan window

For an uncapped single-line paste, or one whose next newline lies beyond the 64 KiB naming window, indexOf("\n", start) still scans the entire remaining payload before stop applies either bound. A hundreds-of-megabytes paste therefore incurs an additional full synchronous pass inside the paste event before file construction. Fresh evidence after the earlier allocation fix is that the replacement avoids copying the whole line but does not bound the newline search itself; inspect only the configured scan window.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. createPastedTextFile runs new File([text], ...) on the same string in the same handler, which encodes every byte of it. That pass is strictly larger than the indexOf scan being described, so removing the scan changes nothing measurable about the paste.

Bounding the search also costs correctness: end === -1 currently distinguishes "no newline anywhere" from "line continues past the window", and a window-limited search cannot tell those apart, so a blank opening window would have to guess between falling back and skipping to the next line. The total walk is already bounded at 64 KB by 3592e7a, which was the case that actually scaled with input.

Pasting over selected text normally replaces it. `pasteLongTextAsFile` calls
`preventDefault` and only adds an attachment, so selecting an obsolete prompt
and pasting its replacement left the old text in the composer and sent both.

The paste handler now drops the selected range once the attachment is accepted.

Paste restore also waits on every attachment rather than pasted ones alone. A
composer still holding the previous thread's image passed the old check, so the
destination's paste was restored into a composer that was not yet clear, and
removing that image did not re-run the effect because the signature ignored it.
`composerAttachmentSignature` covers all attachment ids, and the guard is now
"any attachment at all".
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed a7b2180. Two of the four held up.

Fixed: a swallowed paste left the selection behind

The common editing move: select an obsolete prompt, paste its replacement, and both went out. pasteLongTextAsFile calls preventDefault and only adds an attachment, so the replacement the browser would have made never happened. The handler now drops the selected range once the attachment is accepted.

Fixed: paste restore waited on the wrong thing

The guard checked pasted attachments alone, so a composer still holding the previous thread's image passed it and the destination's paste was restored into a composer that was not clear. Removing that image did not re-run the effect either, since the signature ignored it. composerAttachmentSignature now covers every attachment id and the guard is "any attachment at all", so the restore defers until the composer is empty and retries when it becomes so.

Not taking: queued pastes as inline prompt text

This is the first of the two options the earlier queueing item offered, and it restores exactly what happened before this PR: the same text pasted inline, queued as one prompt, rendered by the same PromptQueueStack row and aria-label, dispatched through the same appendTextToThread. That path is unchanged here.

The queue rendering an unbounded prompt is worth bounding, but it holds for any long typed or pasted prompt and predates this change. The other option, carrying attachments through the queue, is a schema change: startPromptQueue takes string[] and the entries are persisted and rehydrated as strings.

Not taking: bounding the newline search

createPastedTextFile runs new File([text], ...) on the same string in the same handler, encoding every byte. That pass is strictly larger than the indexOf scan, so removing the scan changes nothing measurable. Bounding it also costs correctness: end === -1 distinguishes "no newline anywhere" from "line continues past the window", and a window-limited search cannot tell those apart. The total walk was already bounded at 64 KB in 3592e7a, which was the part that scaled with input.

Verification

npm run typecheck clean, npm test 1976 pass on a clean run, npm run build clean, eslint on thread.tsx unchanged at 46.

The credential-persistence.test.ts flake noted earlier is still around: "HF hydration does not overwrite an in-flight user edit" and "cross-tab refresh replays after an active HF hydration" fail on roughly two runs in three here, on this branch and on heads that predate any of these commits.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

async send(attachment: PendingAttachment): Promise<CompleteAttachment> {
const text = await attachment.file.text();

P2 Badge Reuse the cached paste body when sending

For a large or uncapped paste, createPastedTextFile already retains the original string in pastedTextByFile while the File holds an encoded copy, but this call decodes the entire file into another full-size string before constructing the completed attachment. A tens- or hundreds-of-megabytes paste therefore has substantially higher peak memory than the previous inline path and can fail during send despite attaching successfully; use pastedTextOf(attachment.file) for pasted files and fall back to file.text() only for ordinary text attachments.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

An attachment is serialised after all inline text, so pasting into the middle of
a prompt reordered it: `before|after` with a paste at the caret sent
`beforeafter` and then the pasted body, turning one sentence into two halves
joined with nothing between them.

Only a paste already heading to the end of the composer becomes an attachment
now. Anything mid-text pastes inline, where the order survives. Recording an
insertion offset and splicing it back at serialisation would put a
paste-specific case into the shared attachment path for every message.

Titles pick up the paste as well. `titleTextOf` returned inline text whenever
there was any, so "summarise this" plus a long paste titled the thread from the
instruction alone, where the same text inline used to reach the title model.
Both are now joined, with the attachment side bounded to 512 characters.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed b2470c2. Both held up.

Mixed prompts came out in the wrong order

An attachment is serialised after all inline text, so before|after with a paste at the caret sent beforeafter and then the body: one sentence's two halves joined with nothing between them, and the data after both.

Only a paste already heading to the end of the composer becomes an attachment now, selectionEnd === value.length. Anything mid-text pastes inline, where the order survives. That still covers the two shapes this feature exists for, an empty composer and an instruction typed before the paste.

Not an insertion offset: splicing it back at serialisation would put a paste-specific case into the shared attachment path that every message goes through.

Titles lost the pasted subject

titleTextOf returned inline text whenever there was any, so "summarise this" plus a long paste titled the thread from the instruction alone, where the same text inline used to reach the title model. Both are joined now, the attachment side bounded to 512 characters.

One correction to the item: the disabled-autotitle half is not a regression. fallbackTitleFromUserText takes the first line, so that path named the thread "summarise this" before this PR too, with the paste on the lines after it. The model path is where the subject was actually going missing.

Verification

npm run typecheck clean, npm test 1976 pass on a clean run, npm run build clean, eslint unchanged per file (thread.tsx 46, runtime-provider.tsx 3).

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b2470c2bcc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2115 to +2116
const pasteGoesLast = input.selectionEnd === input.value.length;
const attachedPastedText = !overlay && pasteGoesLast && pasteLongTextAsFile(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve order when text is entered after the paste

The fresh case not covered by this end-caret guard is typing after the attachment is created: pasting a long body at the end and then adding a trailing instruction leaves that instruction in message.content, while collectTextParts in chat-adapter.ts:709-721 appends every attachment after all inline text. Thus BODY followed by Only analyze errors is sent as Only analyze errors followed by BODY, whereas the same below-threshold paste preserves the entered order; retain the paste position across subsequent composer edits or interleave it during serialization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. Typing after any attachment puts the typed text first, because collectTextParts appends every attachment after all inline content. Attach a PDF, a DOCX or a .txt and then type, and you get the same order; nothing about that is specific to pastes.

The mid-text case fixed in b2470c2 was different in kind: it produced beforeafter, splicing one sentence's two halves together with nothing between them. That is corrupted text. "Only analyze errors" followed by the body is an ordinary instruction-then-data prompt, unambiguous and arguably the shape a model reads best.

Making pastes uniquely position-aware means threading an insertion offset through the shared serializer that every attachment type goes through, for an ordering preference rather than a correctness problem. Same reason I declined it for the mid-text case; there I could fix it by not attaching, which is not available once the user types later.

a7b2180 deleted the selected range as soon as `pasteLongTextAsFile` returned,
but that returns synchronously while `addAttachment` is still running. An
attachment that then failed left the user with neither their clipboard nor the
text they had selected to replace.

The deletion moved into the add callback, after the attachment resolves, and it
checks that the composer still holds the text that was pasted into before
splicing.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Pushed 6e34f69. One held up, one did not.

Fixed: a failed paste ate the selected text

Mine, from a7b2180. pasteLongTextAsFile returns synchronously while addAttachment is still running, so the selection was deleted before the attachment was known to have landed. A failure left the user with neither the clipboard nor the text they had selected to replace.

The deletion moved into the add callback, after the attachment resolves, and it checks the composer still holds the text that was pasted into before splicing.

Not taking: typing after the paste

Typing after any attachment puts the typed text first, because collectTextParts appends every attachment after all inline content. Attach a PDF, a DOCX or a .txt and then type, and the order is the same. Nothing here is specific to pastes.

The mid-text case fixed in b2470c2 was different in kind: it produced beforeafter, splicing one sentence's two halves together with nothing between them. That is corrupted text. "Only analyze errors" followed by the body is an ordinary instruction-then-data prompt.

Making pastes uniquely position-aware means threading an insertion offset through the shared serializer every attachment type goes through, for an ordering preference rather than a correctness problem. Same reason as last round; the difference is that there I could fix it by not attaching, which is not available once the user types later.

Verification

npm run typecheck clean, npm test 1976 pass on a clean run, npm run build clean, eslint on thread.tsx unchanged at 46.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 6e34f69493

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@shimmyshimmer
shimmyshimmer merged commit faf3343 into main Aug 13, 2026
56 of 58 checks passed
@shimmyshimmer
shimmyshimmer deleted the studio-paste-long-text-attachment branch August 13, 2026 12:48
danielhanchen added a commit that referenced this pull request Aug 13, 2026
All three assert against source text, so a refactor that keeps the behaviour can
still turn them red. That is what happened here, and the result is that every PR
branching off main inherits a red Repo tests (CPU) job it did not cause.

The clipboard contract reads clipboard-files.ts, but #8472 moved the DataTransfer
half into clipboard-payload.ts when long pastes became attachments. The strings
it looks for are all still there, just in the sibling file, so it now reads both
as the one contract they always were.

The title contract pins the exact line that reads the first user message. #8472
replaced extractTextParts with titleTextOf, which wraps it and appends an
attachment sample for a user turn. The first user message still titles the
thread, so the assertion follows the rename, plus one on titleTextOf itself so
the indirection cannot quietly drop the text.

The font-scale contract is the one real finding: attachment.tsx used a raw
text-[11px], which ignores the UI font size preference, so that label stayed
fixed while the rest of the UI scaled. Swapped for the text-ui-11 token, which
is the same 11px at scale 1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants