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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Support text attachments in per-chat prompt queues (#12964)
Lee Jackson6be99644bfe8
diff --git a/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsx b/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsxindex 32d3ea0f178..31f5565cf56 100644--- a/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsx+++ b/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsx@@ -143,7 +143,7 @@ export function PromptQueueList({const id = editingId;setEditingId(null);setDraft("");- // The editor replaces its row controls. Restore focus once they return.+ // restore focus after the editor's row controls return.requestAnimationFrame(() => {const row = Array.from(listRef.current?.querySelectorAll<HTMLElement>(@@ -155,7 +155,7 @@ export function PromptQueueList({}function saveEditing() {- if (!editingItem || !draft.trim()) return;+ if (!editingItem || (!draft.trim() && !editingItem.attachmentNames?.length)) return;if (onEdit(editingItem.id, draft)) {setAnnouncement(t("promptQueue.announceUpdated"));finishEditing();@@ -165,8 +165,7 @@ export function PromptQueueList({}return (- // Browsers paint the scrollbar outside the scroller's own radius, so the- // rounding and the clip live on this frame instead.+ // browsers paint scrollbars outside scroller radii, so this frame owns rounding and clipping.<divdata-queue-frame=""className="relative z-0 mx-3 mb-[calc(-8px*var(--ui-space-scale,1))] overflow-hidden rounded-t-[20px] border border-border/60 bg-background sm:mx-5 dark:bg-[color-mix(in_srgb,var(--card)_50%,var(--background))]"@@ -205,7 +204,7 @@ export function PromptQueueList({aria-label={t("promptQueue.itemLabel", {position,total: items.length,- prompt: item.prompt,+ prompt: [item.prompt, ...(item.attachmentNames ?? [])].filter(Boolean).join(" · "),})}className={cn("group relative rounded-lg transition-colors",@@ -306,7 +305,7 @@ export function PromptQueueList({type="button"size="sm"className="focus-visible:bg-primary/80"- disabled={!draft.trim()}+ disabled={!draft.trim() && !item.attachmentNames?.length}onClick={saveEditing}>{t("promptQueue.save")}@@ -355,6 +354,12 @@ export function PromptQueueList({/><span className="min-w-0 flex-1 truncate px-1.5 text-sm text-foreground/80">{item.prompt}+ {item.attachmentNames?.length ? (+ <span title={item.attachmentNames.join(", ")}>+ {item.prompt ? " · " : ""}+ {item.attachmentNames.join(", ")}+ </span>+ ) : null}</span>{index === 0 && entry.paused && (<span className="hidden shrink-0 px-1 text-xs text-muted-foreground sm:inline">diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 6de24c67f5d..0db6690a522 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -1,6 +1,17 @@// 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 {+ canQueueTextAttachment,+ normalizeQueuedPrompt,+ prepareQueuedPromptFiles,+ queuedPromptHasContent,+ queuedPromptMessage,+ snapshotQueuedTextPrompt,+ type QueuedPrompt,+} from "@/features/chat/utils/queued-text-attachments";+import { getAuthSessionEpoch } from "@/features/auth";+import {ComposerAttachments,UserMessageAttachments,@@ -93,6 +104,8 @@ import {useInComparePane,refreshSkillsCatalog,stopRecoveredRun,+ pythonToolRunsInStudio,+ withAttachmentOriginal,} from "@/features/chat";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import {@@ -251,6 +264,7 @@ import {useChatProjectScope,shouldAbortPendingQueueForModelBoundary,shouldAbortPendingQueueForSettingsChange,+ resolveDeferredQueuedModelSettings,snapshotQueuedChatRunSettings,composerDraftKey,composerPasteDraftKey,@@ -438,19 +452,16 @@ function followUpShortcutBehavior(event: {return id ? FOLLOW_UP_SHORTCUTS[id] : null;}-// Prompt queues live at module level so they survive Composer remounts,-// including the first queued message that creates a new thread. Each chat gets-// its own queue run; completion detection subscribes to runningByThreadId-// instead of aui.thread() so queues can keep advancing in the background.+// module scope and runningByThreadId let queues survive Composer remounts and advance off-screen.type PromptQueueTarget = {getDocumentThreadId: () => string | null;- /** The project this queue was started in, for a chat with no row to read. */+ /** project captured when a new chat has no persisted row to read. */getQueueProjectId: () => string | null;- /** A knowledge base replaces every other scope, project sources included. */+ /** a knowledge base replaces every other scope, project sources included. */usesKnowledgeBase: boolean;getRunningThreadIds: () => string[];isRunning: () => boolean;- append: (prompt: string) => void | Promise<void>;+ append: (prompt: QueuedPrompt) => void | Promise<void>;complete: () => void;cancel: () => void;cancelActiveRun: () => void;@@ -458,15 +469,14 @@ type PromptQueueTarget = {usesThreadDocuments: boolean;usesLocalModel: boolean;usesDeepResearch: boolean;- /** Whether a research run now holds this queue's thread. */+ /** whether a research run now holds this queue's thread. */researchStarted: () => boolean;temporary: boolean;consumeDeepResearch: () => void;};-type PromptQueueItem = {+type PromptQueueItem = QueuedPrompt & {id: string;- prompt: string;target: PromptQueueTarget;dispatched: boolean;dispatchRetries: number;@@ -630,7 +640,7 @@ function appendQueuedPrompt(run: PromptQueueRun, item: PromptQueueItem) {promptQueueActiveRunIds.add(run.id);syncPromptQueueUI();try {- const result = item.target.append(item.prompt);+ const result = item.target.append(item);if (result && typeof result.catch === "function") {void result.then(() => consumePromptQueueDeepResearch(run, item))@@ -855,7 +865,7 @@ async function dispatchQueuedPrompt(if (!isActivePromptQueueItem(run, item, generation)) {return;}- // Recheck loading after the document probe.+ // recheck loading after the document probe.if (hasIndexingDocuments ||(item.target.usesLocalModel && useChatRuntimeStore.getState().modelLoading)@@ -870,24 +880,16 @@ async function dispatchQueuedPrompt(appendQueuedPrompt(run, item);}-function createQueuedPrompt(prompt: string, target: PromptQueueTarget) {+function createQueuedPrompt(prompt: QueuedPrompt, target: PromptQueueTarget) {return {id: createPromptQueueItemId(),- prompt,+ ...prompt,target,dispatched: false,dispatchRetries: 0,};}-function appendTextToThread(prompt: string) {- return {- role: "user",- content: [{ type: "text", text: prompt }],- createdAt: new Date(),- } as never;-}-function getPromptQueueTargetIds(target: PromptQueueTarget) {return compactIds([...target.getRunningThreadIds(),@@ -1009,6 +1011,7 @@ function getPromptQueueUIItemsForRun(run: PromptQueueRun) {id: item.id,runId: run.id,prompt: item.prompt,+ attachmentNames: item.attachments?.map((attachment) => attachment.name),position: index + 1,total,status: getPromptQueueItemStatus(run, index, activeItemIndex),@@ -1073,15 +1076,12 @@ function syncPromptQueueUI() {function editPromptQueueItem(itemId: string, prompt: string) {const nextPrompt = prompt.trim();- if (!nextPrompt) {- return false;- }const match = findPromptQueueRunByItemId(itemId);if (!match) {return false;}const { item } = match;- if (!canEditPromptQueueItem(item)) {+ if (!canEditPromptQueueItem(item) || !queuedPromptHasContent({ ...item, prompt: nextPrompt })) {return false;}item.prompt = nextPrompt;@@ -1372,7 +1372,7 @@ function steerPromptQueueItem(itemId: string) {});return false;}- // Move the existing item so its captured settings and identity stay intact.+ // move the item so its captured settings and identity stay intact.run.items.splice(itemIndex, 1);run.items.splice(steeringInsertionIndex(run.items, run.index), 0, item);steerPromptQueueTarget(item.target);@@ -1380,12 +1380,12 @@ function steerPromptQueueItem(itemId: string) {}function startPromptQueue(- items: string[],+ items: Array<string | QueuedPrompt>,target: PromptQueueTarget,waitForCurrentRun = false,behavior: ComposerFollowUpBehavior = "queue",) {- const filtered = items.map((item) => item.trim()).filter(Boolean);+ const filtered = items.map(normalizeQueuedPrompt).filter(queuedPromptHasContent);if (filtered.length === 0) {return;}@@ -2985,7 +2985,6 @@ const Composer: FC<{},[],);- // Only once the draft outgrows the compact box: a hard break, or past row 3.const showWritingToggle = composerText.includes("\n") || editorRows > 3;const hasAttachments = useAuiState(({ composer }) => composer.attachments.length > 0,@@ -2995,16 +2994,15 @@ const Composer: FC<{(attachment) => attachment.status.type === "running",),);- const attachmentsAreAllPastedText = useAuiState(+ const attachmentsAreQueueableText = useAuiState(({ composer }) =>composer.attachments.length > 0 &&composer.attachments.every((attachment) =>+ canQueueTextAttachment(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.+ // track every attachment id so removing any file releases paste restore without hashing bodiesconst composerAttachmentSignature = useAuiState(({ composer }) =>composer.attachments.map((attachment) => attachment.id).join(","),);@@ -3710,30 +3708,22 @@ const Composer: FC<{!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;- // The queue carries text only, so other attachments park in the composer and- // send once the run and the queue are idle.+ // validated text uploads and long pastes can join the per-chat queue+ const canQueueTextAttachmentsPrompt =+ attachmentsAreQueueableText && composerAcceptsQueueing;+ // attachments without prepared text stay parked until the run and queue are idleconst canQueueAttachmentPrompt =- hasAttachments && !attachmentsAreAllPastedText && composerAcceptsQueueing;+ hasAttachments && !attachmentsAreQueueableText && composerAcceptsQueueing;- // Per-thread draft autosave: restore on mount, then mirror composer text- // into localStorage (debounced) so a half-typed message survives a- // navigation or reload. Cleared once empty (i.e. after a send). Setting the- // text even when no draft exists keeps a thread from inheriting the- // previous thread's composer contents.+ // mirror each thread's draft to localStorage and restore it on mountconst 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.+ // unsent pasted File objects need a separate slot because they exist only in memoryconst 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.+ // save only after this key's paste restore finishes to avoid premature clearingconst restoredPasteKeyRef = useRef<string | null>(null);const draftSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);useEffect(() => {@@ -4015,19 +4005,17 @@ const Composer: FC<{const usesKnowledgeBaseAtQueueStart =chatStateAtQueueStart.ragEnabled &&chatStateAtQueueStart.ragSource.type === "kb";+ const deferModelResolution =+ chatStateAtQueueStart.modelLoading &&+ parseExternalModelId(+ chatStateAtQueueStart.loadingModelPick &&+ !chatStateAtQueueStart.loadingModelPick.selectionSuperseded+ ? chatStateAtQueueStart.loadingModelPick.id+ : chatStateAtQueueStart.params.checkpoint,+ ) === null;const runSettingsAtQueueStart = snapshotQueuedChatRunSettings(chatStateAtQueueStart,- {- // Resolve the incoming model at dispatch; retain the prompt's settings.- deferModelResolution:- chatStateAtQueueStart.modelLoading &&- parseExternalModelId(- chatStateAtQueueStart.loadingModelPick &&- !chatStateAtQueueStart.loadingModelPick.selectionSuperseded- ? chatStateAtQueueStart.loadingModelPick.id- : chatStateAtQueueStart.params.checkpoint,- ) === null,- },+ { deferModelResolution },);const getThreadListItemState = () => {const runtime =@@ -4207,17 +4195,44 @@ const Composer: FC<{return;}}- // Initialization can replace a fresh thread's local id with a remote- // id. Refresh queue aliases before the run begins so stop dialogs- // deduplicate the two identities.+ // refresh aliases after initialization replaces a local id so stop dialogs deduplicate itsyncPromptQueueUI();+ const resolvedRunSettings = deferModelResolution+ ? resolveDeferredQueuedModelSettings(+ runSettingsAtQueueStart,+ useChatRuntimeStore.getState(),+ )+ : runSettingsAtQueueStart;+ const keepQueuedFilesForPython = pythonToolRunsInStudio(+ resolvedRunSettings,+ );+ const authSessionEpoch = getAuthSessionEpoch();+ const readyPrompt = await prepareQueuedPromptFiles(+ prompt,+ (file, attachment) =>+ withAttachmentOriginal(+ { file },+ attachment,+ incognitoAtQueueStart,+ authSessionEpoch,+ keepQueuedFilesForPython,+ ),+ );+ prompt.attachments = readyPrompt.attachments;+ prompt.attachmentFiles = readyPrompt.attachmentFiles;+ if (+ removeFreshThreadPersistedAfterAbort() ||+ cancelled ||+ epoch !== appendEpoch ||+ !pendingSettingsIds.has(settingsId)+ ) {+ return;+ }const appendResult = thread.append(- appendTextToThread(prompt),+ queuedPromptMessage(readyPrompt),) as unknown;freshThreadAppendAccepted = true;- // Calling append synchronously accepts the user turn; its promise- // follows the whole provider run. Do not turn a later paid/streaming- // failure into an automatic duplicate dispatch.+ // thread.append accepts synchronously; later provider failures must not dispatch a duplicateif (appendResult &&typeof (appendResult as Promise<void>).catch === "function"@@ -4225,8 +4240,7 @@ const Composer: FC<{void (appendResult as Promise<void>).catch(() => undefined);}} catch (error) {- // A setup failure is retryable. Keep the initialized record unless a- // concurrent stop or Clear all explicitly invalidated this queue.+ // retry setup failures unless stop or Clear all invalidated this queueremoveFreshThreadPersistedAfterAbort();pendingSettingsIds.delete(settingsId);discardQueuedChatRunSettings(settingsId);@@ -4302,12 +4316,11 @@ const Composer: FC<{const startHydratedPromptQueue = useCallback((- items: string[],+ items: Array<string | QueuedPrompt>,waitForCurrentRun = false,onStarted?: () => void,onAborted?: () => void,- // Captured before an awaited step that precedes this call, so a boundary- // or setting changed during that step still invalidates the queue.+ // capture before awaiting so intervening boundary or setting changes invalidate the queuecapturedAt?: {localModelBoundaryGeneration: number;queuedSettingsEpoch: number;@@ -4316,8 +4329,7 @@ const Composer: FC<{behavior: ComposerFollowUpBehavior = "queue",) => {const reservationKey = JSON.stringify([referenceThreadId, items]);- // A reservation that is still going to start owns this prompt. One that- // is already invalid is replaced, so the retry is the one that queues.+ // replace only invalid reservations so one attempt owns each promptconst existing = promptQueueStartPendingRef.current.get(reservationKey);if (existing && !pendingQueueStartIsStale(existing)) {// A new shortcut updates the pending draft instead of sending it twice.@@ -4407,15 +4419,47 @@ const Composer: FC<{],);- // 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(+ // preserve pure pastes as editable text while snapshotting uploaded text files+ const queueTextAttachmentsPrompt = useCallback((waitForCurrentRun: boolean,behavior: ComposerFollowUpBehavior = "queue",): boolean => {const composer = aui.composer();const attachments = composer.getState().attachments;+ // keep validated decoded file payloads separate from the editable prompt+ if (!attachments.every((attachment) => isPastedTextFile(attachment.file))) {+ const text = composer.getState().text;+ const prepared = snapshotQueuedTextPrompt(text, attachments);+ if (!prepared) return false;+ const ids = attachments.map((attachment) => attachment.id);+ startHydratedPromptQueue(+ [prepared],+ waitForCurrentRun,+ () => {+ const state = composer.getState();+ if (+ state.text !== text ||+ state.attachments.length !== ids.length ||+ !state.attachments.every((attachment, index) => attachment.id === ids[index])+ ) {+ return;+ }+ void composer.clearAttachments();+ flushResourcesSync(() => composer.setText(""));+ clearStoredDraft();+ armJustSent(text);+ },+ () => {+ toast.info("Text attachments were not queued", {+ description: "The chat or settings changed. Send them again.",+ });+ },+ undefined,+ behavior,+ );+ return true;+ }const files: File[] = [];for (const attachment of attachments) {const file = (attachment as { file?: File }).file;@@ -4809,15 +4853,14 @@ const Composer: FC<{);const livePreStreamRunActive =hasPreStreamRunReservation(preStreamThreadIds);- // pendingSendRef too: a cancel earlier in this same commit has already- // dropped the send, while `pendingSend` still reads true from this render.+ // pendingSendRef is authoritative because pendingSend still reflects the pre-cancel render.if (!pendingSend ||!pendingSendRef.current ||indexingActive ||threadScopedSettingsPending ||(hasAttachments &&- !attachmentsAreAllPastedText &&+ !attachmentsAreQueueableText &&(liveThreadIsRunning ||livePromptQueueActive ||livePreStreamRunActive)) ||@@ -4856,28 +4899,24 @@ const Composer: FC<{findPromptQueueEntry(usePromptQueueUI.getState(), preStreamThreadIds),);if (waitForCurrentRun || queueAlreadyActive) {- // Queueing on the project new-chat composer binds the follow-up to a- // thread that does not exist yet.+ // queueing here would bind the follow-up to a nonexistent project new-chat thread.if (disableQueue) {toast.error("Wait for the current response to finish");return;}- // queueComposerText clears the draft from its onStarted callback, so a- // queue that never starts leaves the text recoverable.+ // queueComposerText preserves the draft until the queue starts.if (canQueueCurrentPrompt) {queueComposerText(waitForCurrentRun, behavior);return;}- // A long paste lives in an attachment, so queueing the text alone- // queues nothing when that is all there is.+ // a long paste has no separate prompt text to queue.if (- canQueuePastedTextPrompt &&- queuePastedTextPrompt(waitForCurrentRun, behavior)+ canQueueTextAttachmentsPrompt &&+ queueTextAttachmentsPrompt(waitForCurrentRun, behavior)) {return;}- // Nothing queueable while a run is live: keep it and say why. Sending- // would push the attachment into the running thread.+ // sending here would add the attachment to the active thread.if (overlay || hasAttachments || hasPendingAudio) {toast.error("Wait for the current response to finish", {description:@@ -4887,8 +4926,7 @@ const Composer: FC<{return;}clearStoredDraft();- // Stays synchronous: deferring lets the run state above go stale, and the- // send is then refused after the wait toast is already gone.+ // keep this synchronous so stale run state cannot drop the send after dismissing the toast.// eslint-disable-next-line react-hooks/set-state-in-effect -- see abovesendReservedComposer();}@@ -4900,17 +4938,17 @@ const Composer: FC<{threadIsRunning,promptQueueActive,promptQueueThreadIds,- attachmentsAreAllPastedText,+ attachmentsAreQueueableText,hasMaterializingImageAttachments,hasMaterializingAudioAttachments,hasMaterializingVideoAttachments,aui,canQueueCurrentPrompt,- canQueuePastedTextPrompt,+ canQueueTextAttachmentsPrompt,clearStoredDraft,dismissWaitToast,queueComposerText,- queuePastedTextPrompt,+ queueTextAttachmentsPrompt,sendReservedComposer,preStreamThreadIds,disableQueue,@@ -4920,7 +4958,6 @@ const Composer: FC<{hasPendingAudio,]);- // Drop any queued send + toast on unmount (e.g. thread switch).useEffect(() => () => {pendingSendRef.current = false;@@ -5205,15 +5242,15 @@ const Composer: FC<{livePreStreamRunActive) {event.preventDefault();- // Project new-chat composer: never queue, just ask the user to wait.+ // the project new-chat composer has no thread to bind a queue to.if (disableQueue) {toast.error("Wait for the current response to finish");return;}if (!canQueueCurrentPrompt) {if (- canQueuePastedTextPrompt &&- queuePastedTextPrompt(+ canQueueTextAttachmentsPrompt &&+ queueTextAttachmentsPrompt(liveThreadIsRunning || livePreStreamRunActive,behavior,)@@ -5310,9 +5347,9 @@ const Composer: FC<{aui,canQueueAttachmentPrompt,canQueueCurrentPrompt,- canQueuePastedTextPrompt,+ canQueueTextAttachmentsPrompt,queueComposerText,- queuePastedTextPrompt,+ queueTextAttachmentsPrompt,clearStoredDraft,closeOverlay,composerText,@@ -5348,15 +5385,14 @@ const Composer: FC<{const startQueue = useCallback((- items: string[],+ items: Array<string | QueuedPrompt>,waitForCurrentRun =threadIsRunning || aui.thread().getState().isRunning,onAborted?: () => void,) => {- // Saved-prompt Run-list calls this directly, so honour disableQueue here- // too: queuing from the project new-chat composer misbinds the thread.+ // saved-prompt calls bypass the button, so project new-chat must still refuse queues.if (disableQueue) return false;- // false here only means an identical start is already pending and will run: not a refusal.+ // false means an identical start is pending, not refused.startHydratedPromptQueue(items, waitForCurrentRun, undefined, onAborted);return true;},@@ -5511,19 +5547,17 @@ const Composer: FC<{hasPendingAttachments}dictationDisabled={dictationEntryDisabled}- // disableQueue (project new-chat composer) also blocks the queue- // button, so a running thread shows Stop instead of Queue.+ // disableQueue makes running threads show Stop instead of Queue.queueDisabled={disableQueue ||!(canQueueCurrentPrompt ||- canQueuePastedTextPrompt ||+ canQueueTextAttachmentsPrompt ||canQueueAttachmentPrompt)}onQueueClick={() => formRef.current?.requestSubmit()}- // ComposerPrimitive.Send handles clicks itself rather than- // submitting the form, so run the complete queue/capacity path.+ // ComposerPrimitive.Send skips form submit, so run the full queue and capacity path.onSendClick={handleSubmit}onStopClick={stopQueue}onResumeClick={resumeQueue}diff --git a/studio/frontend/src/features/chat/attachment-originals.ts b/studio/frontend/src/features/chat/attachment-originals.tsindex 28ebbd9bda2..b2e921308cd 100644--- a/studio/frontend/src/features/chat/attachment-originals.ts+++ b/studio/frontend/src/features/chat/attachment-originals.ts@@ -33,7 +33,7 @@ export function attachmentOriginal(attachment: unknown): ChatAttachmentOriginal}export async function withAttachmentOriginal(- pending: PendingAttachment,+ pending: Pick<PendingAttachment, "file">,complete: CompleteAttachment,temporary: boolean,epoch: number,diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 063eaf7a15e..8eb582e75c7 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -65,7 +65,12 @@ export {refreshModelDisclaimerPreference,saveModelDisclaimerPreference,} from "./sync-model-disclaimer-preference";-export { useChatActive, useInComparePane } from "./runtime-provider";+export {+ pythonToolRunsInStudio,+ useChatActive,+ useInComparePane,+} from "./runtime-provider";+export { withAttachmentOriginal } from "./attachment-originals";export {CHAT_RAG_CAPTION_KEY,CHAT_RAG_OCR_KEY,@@ -272,6 +277,7 @@ export {discardQueuedChatRunSettings,discardQueuedChatRunSettingsForThread,registerQueuedChatRunSettings,+ resolveDeferredQueuedModelSettings,snapshotQueuedChatRunSettings,type QueuedChatRunSettings,} from "./utils/queued-chat-run-settings";diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 978cbfbfb2a..25d60a1383d 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -222,14 +222,10 @@ import {import { syncExportedRepositoryToBackend } from "./utils/delete-thread-message";import { getImageInputUnavailableReason } from "./utils/image-input-support";import {- attachmentContentText,attachmentsSample,- isPastedTextFile,} from "./utils/pasted-text";-import {- annotationsContentText,- annotationsOfFile,-} from "./utils/document-annotations";+import { annotationsOfFile } from "./utils/document-annotations";+import { completeTextAttachment } from "./utils/queued-text-attachments";import {adoptPreStreamRunReservation,claimPreStreamRunReservation,@@ -680,28 +676,7 @@ class TextAttachmentAdapter implements AttachmentAdapter {async send(attachment: PendingAttachment): Promise<CompleteAttachment> {const annotations = annotationsOfFile(attachment.file);const text = annotations ? "" : await readTextAttachmentOnce(attachment.file);- return {- id: attachment.id,- type: "document",- name: attachment.name,- contentType: attachment.contentType,- content: [- {- type: "text",- // A pasted file gets its own tag and size, the markers that outlive the File once the message is stored.- // Annotations carry their own tag, which the chip reads back once the File is gone.- text: annotations- ? annotationsContentText(annotations)- : attachmentContentText(- attachment.name,- text,- isPastedTextFile(attachment.file),- attachment.file.size,- ),- },- ],- status: { type: "complete" },- };+ return completeTextAttachment(attachment, text);}remove(): Promise<void> {@@ -989,8 +964,9 @@ class OpenDocumentAttachmentAdapter implements AttachmentAdapter {const MAX_TOOL_ONLY_ATTACHMENT_BYTES = 200 * 1024 * 1024;/** Whether this turn's python tool runs in Studio's sandbox; chat-adapter.ts decides it the same way. */-function pythonToolRunsInStudio(): boolean {- const state = useChatRuntimeStore.getState();+export function pythonToolRunsInStudio(+ state: Parameters<typeof codeToolsOn>[0] = useChatRuntimeStore.getState(),+): boolean {// The effective Code state, as the send path computes it: Full access turns it on locally.const codeToolsEnabled = codeToolsOn(state);const external = parseExternalModelId(state.params.checkpoint);diff --git a/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.ts b/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.tsindex a0e4ddb2524..b0676761fdc 100644--- a/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.ts+++ b/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.ts@@ -24,6 +24,7 @@ export type PromptQueueUIItem = {id: string;runId: string;prompt: string;+ attachmentNames?: string[];position: number;total: number;status: PromptQueueUIItemStatus;diff --git a/studio/frontend/src/features/chat/text-attachment-accept.ts b/studio/frontend/src/features/chat/text-attachment-accept.tsindex e6160f747ec..a152909b1cf 100644--- a/studio/frontend/src/features/chat/text-attachment-accept.ts+++ b/studio/frontend/src/features/chat/text-attachment-accept.ts@@ -1319,17 +1319,21 @@ export async function isBinaryOfficeTemplate(file: File): Promise<boolean> {);}-/** Decode editor text, including the BOM emitted by Windows Registry Editor. */+/** decodes editor text, including the BOM from Windows Registry Editor. */export async function readTextAttachment(file: File): Promise<string> {const bytes = new Uint8Array(await file.arrayBuffer());return decodeTextAttachmentBytes(bytes, file.name);}-// Dropped with the File itself, so a removed attachment retains nothing.+// the cache entry is collected with its File, so removed attachments retain no data.const decodedOnce = new WeakMap<File, string>();-/** Decode once per file. The composer decodes while attaching, to report a bad- * encoding there, and sending the same file must not read all of it again. */+/** returns adapter-decoded text without starting another read. */+export function cachedTextAttachment(file: File): string | undefined {+ return decodedOnce.get(file);+}++/** caches text decoded during attachment validation so sending does not reread the file. */export async function readTextAttachmentOnce(file: File): Promise<string> {const cached = decodedOnce.get(file);if (cached !== undefined) {@@ -1340,7 +1344,7 @@ export async function readTextAttachmentOnce(file: File): Promise<string> {return text;}-// MIME is unreliable for source files, so match by extension too.+// source file MIME types are unreliable, so extensions must also match.export const TEXT_ATTACHMENT_ACCEPT = ["text/plain,text/markdown,text/csv,text/tab-separated-values,text/xml,text/json,text/css","text/vtt,application/x-subrip,text/x-log,text/calendar,text/vcard,message/rfc822",diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.tsindex 0a26c30ca47..e1721e8b7e9 100644--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts@@ -83,6 +83,20 @@ export function snapshotQueuedChatRunSettings(return snapshot;}+export function resolveDeferredQueuedModelSettings(+ settings: QueuedChatRunSettings,+ resolved: Pick<ChatRuntimeState, "params" | "supportsTools">,+): QueuedChatRunSettings {+ return {+ ...settings,+ params: {+ ...settings.params,+ checkpoint: resolved.params.checkpoint,+ },+ supportsTools: resolved.supportsTools,+ };+}+/** A queued send may only fill in the model of a row that was written without one. */export function shouldPersistResolvedQueuedModel(storedThread: { modelId?: string | null } | null | undefined,diff --git a/studio/frontend/src/features/chat/utils/queued-text-attachments.ts b/studio/frontend/src/features/chat/utils/queued-text-attachments.tsnew file mode 100644index 00000000000..c34da5ad1e5--- /dev/null+++ b/studio/frontend/src/features/chat/utils/queued-text-attachments.ts@@ -0,0 +1,139 @@+// 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 type {+ Attachment,+ CompleteAttachment,+ PendingAttachment,+} from "@assistant-ui/react";+import { cachedTextAttachment } from "../text-attachment-accept.ts";+import { attachmentContentText, isPastedTextFile } from "./pasted-text.ts";++import { annotationsContentText, annotationsOfFile } from "./document-annotations.ts";++export type QueuedPrompt = {+ prompt: string;+ attachments?: CompleteAttachment[];+ attachmentFiles?: File[];+};++export async function prepareQueuedPromptFiles(+ item: QueuedPrompt,+ prepare: (+ file: File,+ attachment: CompleteAttachment,+ ) => Promise<CompleteAttachment>,+): Promise<QueuedPrompt> {+ const { attachments, attachmentFiles } = item;+ if (attachmentFiles === undefined || attachmentFiles.length === 0) {+ return item;+ }+ if (!attachments || attachments.length !== attachmentFiles.length) {+ throw new Error("Queued attachment snapshot is inconsistent");+ }+ return {+ ...item,+ attachments: await Promise.all(+ attachments.map((attachment, index) => {+ const file = attachmentFiles[index];+ if (!file) {+ throw new Error("Queued attachment snapshot is inconsistent");+ }+ return prepare(file, attachment);+ }),+ ),+ attachmentFiles: undefined,+ };+}++/** keeps normal sends and queues aligned on filenames, encoding, and paste markers. */+export function completeTextAttachment(+ attachment: PendingAttachment,+ text: string,+): CompleteAttachment {+ const annotations = annotationsOfFile(attachment.file);+ return {+ id: attachment.id,+ type: "document",+ name: attachment.name,+ contentType: attachment.contentType,+ content: [+ {+ type: "text",+ text: annotations ? annotationsContentText(annotations) : attachmentContentText(+ attachment.name,+ text,+ isPastedTextFile(attachment.file),+ attachment.file.size,+ ),+ },+ ],+ status: { type: "complete" },+ };+}++/** requires a validated decode because extensions can also match pending, failed, or binary files. */+export function canQueueTextAttachment(attachment: Attachment): boolean {+ return (+ attachment.type === "document" &&+ attachment.status.type === "requires-action" &&+ attachment.status.reason === "composer-send" &&+ attachment.file !== undefined &&+ cachedTextAttachment(attachment.file) !== undefined+ );+}++/** snapshots decoded content without File objects or reads that later submits could overtake. */+export function snapshotQueuedTextAttachments(+ attachments: readonly Attachment[],+): CompleteAttachment[] | null {+ if (!attachments.length || !attachments.every(canQueueTextAttachment))+ return null;+ return attachments.map((attachment) =>+ completeTextAttachment(+ attachment as PendingAttachment,+ cachedTextAttachment(attachment.file!)!,+ ),+ );+}++export function snapshotQueuedTextPrompt(+ prompt: string,+ attachments: readonly Attachment[],+): QueuedPrompt | null {+ const completed = snapshotQueuedTextAttachments(attachments);+ if (!completed) {+ return null;+ }+ return {+ prompt,+ attachments: completed,+ attachmentFiles: attachments.map((attachment) => {+ if (!attachment.file) {+ throw new Error("Queued attachment snapshot is inconsistent");+ }+ return attachment.file;+ }),+ };+}++export function normalizeQueuedPrompt(+ item: string | QueuedPrompt,+): QueuedPrompt {+ return typeof item === "string"+ ? { prompt: item.trim() }+ : { ...item, prompt: item.prompt.trim() };+}++export function queuedPromptHasContent(item: QueuedPrompt): boolean {+ return item.prompt.trim().length > 0 || Boolean(item.attachments?.length);+}++export function queuedPromptMessage(item: QueuedPrompt) {+ return {+ role: "user" as const,+ content: item.prompt ? [{ type: "text" as const, text: item.prompt }] : [],+ attachments: item.attachments ?? [],+ createdAt: new Date(),+ };+}diff --git a/studio/frontend/tests/composer-steering.test.ts b/studio/frontend/tests/composer-steering.test.tsindex c36de12048c..6300f6895d7 100644--- a/studio/frontend/tests/composer-steering.test.ts+++ b/studio/frontend/tests/composer-steering.test.ts@@ -7,7 +7,14 @@ import {shouldAbortPendingQueueForModelBoundary,shouldAbortPendingQueueForSettingsChange,} from "../src/features/chat/utils/prompt-queue-model-boundary.ts";-import { snapshotQueuedChatRunSettings } from "../src/features/chat/utils/queued-chat-run-settings.ts";+import {+ normalizeQueuedPrompt,+ queuedPromptHasContent,+} from "../src/features/chat/utils/queued-text-attachments.ts";+import {+ resolveDeferredQueuedModelSettings,+ snapshotQueuedChatRunSettings,+} from "../src/features/chat/utils/queued-chat-run-settings.ts";import { reorderPromptQueueItems } from "../src/features/chat/utils/prompt-queue-reorder.ts";import { steeringInsertionIndex } from "../src/features/chat/utils/composer-preferences.ts";import { chatModelLifecycleGate } from "../src/features/chat/utils/model-lifecycle-gate.ts";@@ -17,7 +24,7 @@ import {userStopTargetCancelMode,} from "../src/features/chat/utils/prompt-queue-user-stop.ts";-// Run the production queue engine with controlled stores and transport.+// runs the production queue engine with controlled stores and transport.const source = ts.createSourceFile("thread.tsx",readSrc("components/assistant-ui/thread.tsx"),@@ -111,6 +118,8 @@ function world() {let indexing: () => Promise<boolean> = async () => false;const noop = () => undefined;const deps = {+ normalizeQueuedPrompt,+ queuedPromptHasContent,promptQueueRuns: runs,promptQueueRunOrder: [],promptQueueActiveRunIds: new Set(),@@ -441,6 +450,13 @@ function composerCallbackJs(name: string) {const factoryJs = composerCallbackJs("startHydratedPromptQueue");const targetFactoryJs = composerCallbackJs("createPromptQueueTarget");+test("queued files use resolved model capabilities before append", () => {+ assert.match(+ targetFactoryJs,+ /const resolvedRunSettings = deferModelResolution[\s\S]*?resolveDeferredQueuedModelSettings\([\s\S]*?useChatRuntimeStore\.getState\(\)[\s\S]*?pythonToolRunsInStudio\([\s\S]*?prepareQueuedPromptFiles\([\s\S]*?withAttachmentOriginal\([\s\S]*?keepQueuedFilesForPython[\s\S]*?queuedPromptMessage\(readyPrompt\)/,+ );+});+async function targetForSelection(checkpoint: string,modelLoading: boolean,@@ -475,12 +491,20 @@ async function targetForSelection(return settings;},parseExternalModelId,+ pythonToolRunsInStudio: () => false,+ prepareQueuedPromptFiles: async (prompt: unknown) => prompt,+ resolveDeferredQueuedModelSettings,+ withAttachmentOriginal: async (_pending: unknown, complete: unknown) => complete,+ getAuthSessionEpoch: () => 0,hasPreStreamRunReservation: () => false,};const create = new Function(...Object.keys(deps), targetFactoryJs)(...Object.values(deps),) as () => Promise<Target>;- return { target: Object.assign(makeTarget("chat", false), await create()), settings };+ return {+ target: Object.assign(makeTarget("chat", false), await create()),+ settings,+ };}function hydratedFactory(@@ -1005,6 +1029,32 @@ test("loading defers model resolution while retaining queued sampling and permisassert.equal(ready.activeGgufVariant, "old-Q4.gguf");});+test("deferred model settings take only the resolved model capability", () => {+ const captured = snapshotQueuedChatRunSettings(+ {+ params: { checkpoint: "outgoing-model", temperature: 0.4 },+ supportsTools: false,+ codeToolsEnabled: true,+ permissionMode: "ask",+ } as unknown as Parameters<typeof snapshotQueuedChatRunSettings>[0],+ { deferModelResolution: true },+ );+ const supported = resolveDeferredQueuedModelSettings(captured, {+ params: { ...captured.params, checkpoint: "incoming-tools-model" },+ supportsTools: true,+ });+ const unsupported = resolveDeferredQueuedModelSettings(captured, {+ params: { ...captured.params, checkpoint: "incoming-plain-model" },+ supportsTools: false,+ });+ assert.equal(supported.params.checkpoint, "incoming-tools-model");+ assert.equal(supported.supportsTools, true);+ assert.equal(unsupported.params.checkpoint, "incoming-plain-model");+ assert.equal(unsupported.supportsTools, false);+ assert.equal(supported.codeToolsEnabled, true);+ assert.equal(captured.params.checkpoint, "");+});+for (const behavior of ["queue", "steer"] as const) {for (const failed of [false, true]) {test(`external-to-local switch waits for the incoming model: ${behavior}, failed=${failed}`, async () => {@@ -1080,7 +1130,11 @@ test("external queues retain their provider across unrelated local loading and ffor (const checkpoint of ["outgoing-local", ""]) {test(`local loading still defers model resolution: checkpoint=${checkpoint || "empty"}`, async () => {for (const pick of ["incoming-local", null]) {- const { target, settings } = await targetForSelection(checkpoint, true, pick);+ const { target, settings } = await targetForSelection(+ checkpoint,+ true,+ pick,+ );assert.equal(target.usesLocalModel, true);assert.equal(settings.params.checkpoint, "");assert.equal(settings.activeGgufVariant, null);diff --git a/studio/frontend/tests/composer-submit-path.test.ts b/studio/frontend/tests/composer-submit-path.test.tsindex 4bd150c7638..2b4ed0ba5d1 100644--- a/studio/frontend/tests/composer-submit-path.test.ts+++ b/studio/frontend/tests/composer-submit-path.test.ts@@ -182,7 +182,7 @@ for (const active of ["runtime", "pre-stream", "queue", "idle"]) {threadScopedSettingsPending: false,threadIsRunning: false,promptQueueThreadIds: ["own-chat"],- attachmentsAreAllPastedText: false,+ attachmentsAreQueueableText: false,hasMaterializingImageAttachments: false,hasMaterializingAudioAttachments: false,hasMaterializingVideoAttachments: false,@@ -205,7 +205,7 @@ for (const active of ["runtime", "pre-stream", "queue", "idle"]) {canQueueCurrentPrompt: true,queueComposerText: (wait: boolean, behavior: string) =>calls.push([wait, behavior]),- canQueuePastedTextPrompt: false,+ canQueueTextAttachmentsPrompt: false,overlay: false,hasAttachments: false,hasPendingAudio: false,@@ -214,7 +214,7 @@ for (const active of ["runtime", "pre-stream", "queue", "idle"]) {};const release = createCallback(releaseCallback, deps);release();- release(); // An old render cannot release a cancelled/consumed send twice.+ release(); // stale renders cannot release a consumed or cancelled send twice.assert.deepEqual(calls,active === "idle" ? ["clear", "send"] : [[active !== "queue", "steer"]],@@ -236,7 +236,7 @@ for (const active of ["runtime", "pre-stream", "queue"]) {threadScopedSettingsPending: false,threadIsRunning: false,promptQueueThreadIds: ["own-chat"],- attachmentsAreAllPastedText: false,+ attachmentsAreQueueableText: false,hasMaterializingImageAttachments: false,hasMaterializingAudioAttachments: false,hasMaterializingVideoAttachments: false,@@ -260,8 +260,8 @@ for (const active of ["runtime", "pre-stream", "queue"]) {disableQueue: false,canQueueCurrentPrompt: false,queueComposerText: () => calls.push("queue-text"),- canQueuePastedTextPrompt: false,- queuePastedTextPrompt: () => calls.push("queue-paste"),+ canQueueTextAttachmentsPrompt: false,+ queueTextAttachmentsPrompt: () => calls.push("queue-paste"),overlay: false,hasAttachments: true,hasPendingAudio: false,diff --git a/studio/frontend/tests/composer-writing-expansion.test.ts b/studio/frontend/tests/composer-writing-expansion.test.tsindex 274d9d98b7e..6cb6a3b9b6a 100644--- a/studio/frontend/tests/composer-writing-expansion.test.ts+++ b/studio/frontend/tests/composer-writing-expansion.test.ts@@ -12,7 +12,7 @@ import { readSrcAsync } from "./helpers/kit.ts";test("expansion is reset wherever the composer is emptied, not only on send", async () => {const thread = await readSrcAsync("components/assistant-ui/thread.tsx");- // handleSubmit returns before send() on three queueing paths that also clear.+ // handleSubmit returns before send() on three queue paths that also clear.const at = thread.indexOf("const armJustSent = useCallback(");assert.notEqual(at, -1, "armJustSent should still be the shared clear hook");const body = thread.slice(at, thread.indexOf("\n }, [", at));@@ -27,7 +27,7 @@ test("expansion is reset wherever the composer is emptied, not only on send", asfor (const clearer of ["const queueComposerText = useCallback(",- "const queuePastedTextPrompt = useCallback(",+ "const queueTextAttachmentsPrompt = useCallback(",]) {const start = thread.indexOf(clearer);assert.notEqual(start, -1, `${clearer} should still exist`);diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex 88ff8e20004..68c67ba456b 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -110,7 +110,7 @@ const OPEN_DOCUMENT_EXTENSION_RE = /\.ods/;const RTF_ADAPTER_RE =/class RtfAttachmentAdapter[^{]*\{\s*accept = RTF_ATTACHMENT_ACCEPT;[\s\S]*?readRtfAttachmentContent\(file, file\.name\)[\s\S]*?new CompositeAttachmentAdapter\(\[[\s\S]*?new RtfAttachmentAdapter\(\),/;const TOOL_ONLY_ADAPTER_RE =- /function pythonToolRunsInStudio\(\)[\s\S]*?const codeToolsEnabled = codeToolsOn\(state\);[\s\S]*?if \(!external\) return state\.supportsTools && codeToolsEnabled;[\s\S]*?\}\)\.local\.includes\("python"\);[\s\S]*?class ToolOnlyAttachmentAdapter[^{]*\{\s*accept = TOOL_ONLY_ATTACHMENT_EXTENSIONS;[\s\S]*?!pythonToolRunsInStudio\(\)[\s\S]*?\?\?\s*\(await this\.upload\(attachment\.file\)\);[\s\S]*?return original \? \(\{ \.\.\.complete, original \}[\s\S]*?new RtfAttachmentAdapter\(\),\s*new ToolOnlyAttachmentAdapter\(\),\s*\]\)/;+ /function pythonToolRunsInStudio\([\s\S]*?\): boolean \{[\s\S]*?const codeToolsEnabled = codeToolsOn\(state\);[\s\S]*?if \(!external\) return state\.supportsTools && codeToolsEnabled;[\s\S]*?\}\)\.local\.includes\("python"\);[\s\S]*?class ToolOnlyAttachmentAdapter[^{]*\{\s*accept = TOOL_ONLY_ATTACHMENT_EXTENSIONS;[\s\S]*?!pythonToolRunsInStudio\(\)[\s\S]*?\?\?\s*\(await this\.upload\(attachment\.file\)\);[\s\S]*?return original \? \(\{ \.\.\.complete, original \}[\s\S]*?new RtfAttachmentAdapter\(\),\s*new ToolOnlyAttachmentAdapter\(\),\s*\]\)/;const OPEN_DOCUMENT_ADAPTER_ACCEPT_RE =/class OpenDocumentAttachmentAdapter[^{]*\{[\s\S]*?accept = OPEN_DOCUMENT_ATTACHMENT_ACCEPT;/;const OPEN_DOCUMENT_DROP_TO_COMPOSER_RE =diff --git a/studio/frontend/tests/queued-text-attachments.test.ts b/studio/frontend/tests/queued-text-attachments.test.tsnew file mode 100644index 00000000000..4efdbd412f7--- /dev/null+++ b/studio/frontend/tests/queued-text-attachments.test.ts@@ -0,0 +1,178 @@+// 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 type { PendingAttachment } from "@assistant-ui/react";+import { readTextAttachmentOnce } from "../src/features/chat/text-attachment-accept.ts";+import { createPastedTextFile } from "../src/features/chat/utils/pasted-text.ts";+import {+ canQueueTextAttachment,+ completeTextAttachment,+ prepareQueuedPromptFiles,+ snapshotQueuedTextAttachments,+ snapshotQueuedTextPrompt,+ normalizeQueuedPrompt,+ queuedPromptHasContent,+ queuedPromptMessage,+} from "../src/features/chat/utils/queued-text-attachments.ts";+import { reorderPromptQueueItems } from "../src/features/chat/utils/prompt-queue-reorder.ts";++function pending(file: File): PendingAttachment {+ return {+ id: crypto.randomUUID(),+ type: "document",+ name: file.name,+ file,+ contentType: file.type,+ status: { type: "requires-action", reason: "composer-send" },+ };+}++async function ready(+ file = new File(["file contents"], "notes.txt", { type: "text/plain" }),+) {+ await readTextAttachmentOnce(file);+ return pending(file);+}++test("uploaded text reaches dispatch with the same filename and content as a normal send", async () => {+ const attachment = await ready();+ const snapshot = snapshotQueuedTextAttachments([attachment])!;+ const message = queuedPromptMessage(+ normalizeQueuedPrompt({ prompt: " summarize ", attachments: snapshot }),+ );+ assert.deepEqual(message.content, [{ type: "text", text: "summarize" }]);+ assert.deepEqual(message.attachments, [+ completeTextAttachment(attachment, "file contents"),+ ]);+ assert.equal(message.attachments[0].name, "notes.txt");+ assert.deepEqual(message.attachments[0].content, [+ {+ type: "text",+ text: "<attachment name=notes.txt>\nfile contents\n</attachment>",+ },+ ]);+ assert.equal("file" in message.attachments[0], false);+});++test("queueing uses decoded bytes without another asynchronous file read", async () => {+ const file = new File(+ [new Uint8Array([0xff, 0xfe, 0x48, 0, 0x69, 0])],+ "windows.txt",+ );+ const attachment = await ready(file);+ file.arrayBuffer = () => {+ throw new Error("must not reread");+ };+ file.text = () => {+ throw new Error("must not decode with File.text");+ };+ const snapshot = snapshotQueuedTextAttachments([attachment])!;+ assert.deepEqual(snapshot[0].content, [+ { type: "text", text: "<attachment name=windows.txt>\nHi\n</attachment>" },+ ]);+});++test("queued files survive until dispatch preparation without leaking into the message", async () => {+ const file = new File(["a,b"], "data.csv", { type: "text/csv" });+ const item = snapshotQueuedTextPrompt("analyze", [await ready(file)])!;+ assert.equal(item.attachmentFiles?.[0], file);+ const prepared = await prepareQueuedPromptFiles(+ item,+ async (_source, attachment) => ({+ ...attachment,+ original: { sha256: "ab".repeat(32), sizeBytes: file.size },+ }) as never,+ );+ assert.equal(prepared.attachmentFiles, undefined);+ assert.deepEqual(+ (prepared.attachments?.[0] as { original?: unknown }).original,+ { sha256: "ab".repeat(32), sizeBytes: file.size },+ );+ assert.equal("attachmentFiles" in queuedPromptMessage(prepared), false);+ await assert.rejects(+ prepareQueuedPromptFiles(+ { prompt: "analyze", attachmentFiles: [file] },+ async (_source, attachment) => attachment,+ ),+ /Queued attachment snapshot is inconsistent/,+ );+});++test("attachment-only messages, including an empty file, survive queue filtering", async () => {+ const attachments = snapshotQueuedTextAttachments([+ await ready(new File([""], "empty.txt")),+ ])!;+ const items = [" ", { prompt: " ", attachments }, "next"]+ .map(normalizeQueuedPrompt)+ .filter(queuedPromptHasContent);+ assert.equal(items.length, 2);+ assert.deepEqual(queuedPromptMessage(items[0]).content, []);+ assert.equal(queuedPromptMessage(items[0]).attachments[0].name, "empty.txt");+});++test("undecoded, running, failed and unsupported attachments cannot slip into a queue", async () => {+ const text = await ready();+ assert.equal(+ canQueueTextAttachment(pending(new File(["text"], "new.txt"))),+ false,+ );+ assert.equal(snapshotQueuedTextAttachments([]), null);+ const unsupported = pending(+ new File(["PDF bytes"], "report.pdf", { type: "application/pdf" }),+ );+ assert.equal(snapshotQueuedTextAttachments([text, unsupported]), null);+ assert.equal(canQueueTextAttachment({ ...text, type: "image" }), false);+ assert.equal(+ canQueueTextAttachment({+ ...text,+ status: { type: "running", reason: "uploading", progress: 0 },+ }),+ false,+ );+ assert.equal(+ canQueueTextAttachment({+ ...text,+ status: { type: "incomplete", reason: "error" },+ }),+ false,+ );+});++test("mixed uploads and pastes preserve file order and paste metadata", async () => {+ const paste = createPastedTextFile("pasted body");+ const attachments = snapshotQueuedTextAttachments([+ await ready(),+ await ready(paste),+ ])!;+ assert.deepEqual(+ attachments.map((a) => a.name),+ ["notes.txt", paste.name],+ );+ assert.match(+ (attachments[1].content[0] as { text: string }).text,+ /^<pasted_text name=.*bytes=11>\npasted body\n<\/pasted_text>$/,+ );+});++test("editing, reordering and removing prompts keeps each file with its own message", async () => {+ const source = await ready();+ const attachments = snapshotQueuedTextAttachments([source])!;+ // later composer attachment changes must not alter the queued snapshot.+ source.name = "changed.txt";+ source.content = [{ type: "text", text: "changed" }];+ const first = { id: "first", prompt: "original", attachments };+ const second = { id: "second", prompt: "next" };+ first.prompt = "edited";+ const moved = reorderPromptQueueItems([first, second], 0, 1, 0)!;+ assert.equal(moved[1], first);+ assert.equal(queuedPromptMessage(moved[1]).attachments[0].name, "notes.txt");+ assert.deepEqual(queuedPromptMessage(moved[1]).content, [+ { type: "text", text: "edited" },+ ]);+ assert.equal(queuedPromptHasContent({ ...first, prompt: "" }), true);+ assert.equal(queuedPromptHasContent({ prompt: "" }), false);+ moved.splice(1, 1);+ assert.equal(queuedPromptMessage(moved[0]).attachments.length, 0);+});diff --git a/studio/frontend/tests/sandbox-attachments.test.ts b/studio/frontend/tests/sandbox-attachments.test.tsindex d35deb4cdf8..0eaff0cea2e 100644--- a/studio/frontend/tests/sandbox-attachments.test.ts+++ b/studio/frontend/tests/sandbox-attachments.test.ts@@ -6,6 +6,11 @@ import { readFileSync } from "node:fs";import test from "node:test";import { loadWithStubs } from "./helpers/module-stubs.ts";+import {+ prepareQueuedPromptFiles,+ snapshotQueuedTextPrompt,+} from "../src/features/chat/utils/queued-text-attachments.ts";+import { readTextAttachmentOnce } from "../src/features/chat/text-attachment-accept.ts";const accept = await import("../src/features/chat/open-document-accept.ts");const { TOOL_ONLY_ATTACHMENT_EXTENSIONS } = accept;@@ -124,6 +129,31 @@ test("a document outside the kept types is uploaded only for the python tool", aassert.deepEqual(uploads, ["data.csv"]);});+test("a queued text file is uploaded before the python sandbox request", async () => {+ const file = new File(["a,b"], "data.csv", { type: "text/csv" });+ await readTextAttachmentOnce(file);+ const pending = {+ id: "queued",+ type: "document",+ name: file.name,+ contentType: file.type,+ file,+ status: { type: "requires-action", reason: "composer-send" },+ } as never;+ const queued = snapshotQueuedTextPrompt("analyze", [pending])!;+ const prepared = await prepareQueuedPromptFiles(+ queued,+ (source, complete) =>+ withAttachmentOriginal({ file: source }, complete, false, 0, true),+ );+ const { sandboxAttachments } = withSandboxAttachmentPaths([+ { attachments: prepared.attachments },+ ]);+ assert.deepEqual(sandboxAttachments, [+ { sha256: SHA, name: "data.csv" },+ ]);+});+test("only a python turn asks for copies, and every tool-only file has a reader", () => {const read = (path: string) =>readFileSync(new URL(`../src/features/chat/${path}`, import.meta.url), "utf8");