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
Studio: say when an attached PDF has no readable text (#12237)
Nilay5ec226e393a9
diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 205ad85a9d1..f8598886b1a 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -942,6 +942,16 @@ export async function getDocxAttachmentError(return null;}+export function getPdfAttachmentTextError(+ fileName: string,+ text: string,+ pythonToolOpensFile: boolean,+): string | null {+ return text || pythonToolOpensFile+ ? null+ : `PDF has no readable text: ${fileName}. Scanned pages can't be read.`;+}+export async function extractPdfAttachmentText(file: File): Promise<string> {assertDocumentAttachmentSize(file, "PDF");const [{ extractText, getDocumentProxy }, buffer] = await Promise.all([diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 9a8cdfc3ce2..7bda7d3a40f 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -69,6 +69,7 @@ import {extractPdfAttachmentText,getDocumentAttachmentSizeError,getDocxAttachmentError,+ getPdfAttachmentTextError,} from "./attachment-content";import {type ChatAttachmentOriginal,@@ -434,39 +435,74 @@ class VisionImageAdapter implements AttachmentAdapter {class PDFAttachmentAdapter implements AttachmentAdapter {accept = "application/pdf";+ private readonly texts = new Map<string, Promise<string | null>>();// Refused here, not at send: the composer empties itself before it awaits send(), so a ceiling that// only fires there discards the typed message too. The throw is invisible (nothing subscribes to// attachmentAddError and the picker never awaits addAttachment), so the toast is the only reason given.- add({ file }: { file: File }): Promise<PendingAttachment> {+ async *add({+ file,+ }: {+ file: File;+ }): AsyncGenerator<PendingAttachment, void> {const sizeError = getDocumentAttachmentSizeError(file, "PDF");if (sizeError) {toast.error(sizeError);throw new Error(sizeError);}- return Promise.resolve({+ const attachment = {id: crypto.randomUUID(),type: "document",name: file.name,contentType: file.type,file,+ status: { type: "running", reason: "uploading", progress: 0 },+ } satisfies PendingAttachment;+ // A running chip parks Send while the PDF is read; without one, Send goes out without the PDF.+ yield attachment;+ const text = extractPdfAttachmentText(file).catch(() => null);+ this.texts.set(attachment.id, text);+ const error = pdfAttachmentError(file.name, await text);+ // Removed or sent while reading: yielding again would put the chip back.+ if (this.texts.get(attachment.id) !== text) return;+ if (error) {+ toast.error(error);+ yield { ...attachment, status: { type: "incomplete", reason: "error" } };+ return;+ }+ yield {+ ...attachment,status: { type: "requires-action", reason: "composer-send" },- });+ };}async send(attachment: PendingAttachment): Promise<CompleteAttachment> {- const text = await extractPdfAttachmentText(attachment.file);+ const pending = this.texts.get(attachment.id);+ this.texts.delete(attachment.id);+ const text = await (pending ??+ extractPdfAttachmentText(attachment.file).catch(() => null));+ // Rechecked: Code or a temporary chat can change after the attach check passed.+ const textError = pdfAttachmentError(attachment.name, text);+ if (textError && attachment.status.type !== "incomplete") {+ toast.error(textError);+ }return {id: attachment.id,type: "document",name: attachment.name,contentType: attachment.contentType,- content: [{ type: "text", text: `[PDF: ${attachment.name}]\n${text}` }],+ content: [+ {+ type: "text",+ text: `[PDF: ${attachment.name}]\n${textError ?? text}`,+ },+ ],status: { type: "complete" },};}- remove(): Promise<void> {+ remove(attachment: Attachment): Promise<void> {+ this.texts.delete(attachment.id);return Promise.resolve();}}@@ -877,6 +913,16 @@ function pythonToolRunsInStudio(): boolean {}).local.includes("python");}+function pythonToolOpensAttachments(): boolean {+ return pythonToolRunsInStudio() && !useChatRuntimeStore.getState().incognito;+}++function pdfAttachmentError(name: string, text: string | null): string | null {+ return text === null+ ? `PDF file could not be read: ${name}`+ : getPdfAttachmentTextError(name, text, pythonToolOpensAttachments());+}+class ToolOnlyAttachmentAdapter implements AttachmentAdapter {accept = TOOL_ONLY_ATTACHMENT_EXTENSIONS;private readonly uploads = new Map<diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsindex 668e6f3c539..8c332e576fc 100644--- a/studio/frontend/tests/attachment-preview-text.test.ts+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -24,6 +24,7 @@ const {extractHtmlAttachmentText,extractPdfAttachmentText,getDocxAttachmentError,+ getPdfAttachmentTextError,isAudioAttachment,isTextAttachment,parseAttachmentText,@@ -463,6 +464,73 @@ test("extractPdfAttachmentText destroys the PDF proxy after success and failure"}});+function singlePagePdf(content: string, resources: string, extra: string[]) {+ const objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources ${resources} /Contents 4 0 R >>`,+ `<< /Length ${content.length} >>\nstream\n${content}\nendstream`,+ ...extra,+ ];+ let body = "%PDF-1.4\n";+ const offsets = objects.map((object, index) => {+ const offset = body.length;+ body += `${index + 1} 0 obj\n${object}\nendobj\n`;+ return offset;+ });+ const xref = body.length;+ body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ body += offsets+ .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)+ .join("");+ body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;+ return Uint8Array.from(body, (char) => char.charCodeAt(0));+}++test("a scanned pdf is refused unless the python tool can open it", async () => {+ const pixels = "\x80".repeat(4);+ const scan = new File(+ [+ singlePagePdf(+ "q 200 0 0 200 0 0 cm /Im1 Do Q",+ "<< /XObject << /Im1 5 0 R >> >>",+ [+ `<< /Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length ${pixels.length} >>\nstream\n${pixels}\nendstream`,+ ],+ ),+ ],+ "scan.pdf",+ { type: "application/pdf" },+ );+ const typed = new File(+ [+ singlePagePdf(+ "BT /F1 12 Tf 20 100 Td (quokka invoice) Tj ET",+ "<< /Font << /F1 5 0 R >> >>",+ ["<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"],+ ),+ ],+ "typed.pdf",+ { type: "application/pdf" },+ );++ const scanText = await extractPdfAttachmentText(scan);+ const typedText = await extractPdfAttachmentText(typed);+ assert.equal(scanText, "");+ assert.equal(typedText, "quokka invoice");+ assert.equal(+ (await readAttachmentText(scan, scan.name, scan.type)).text,+ "",+ );++ assert.match(+ getPdfAttachmentTextError(scan.name, scanText, false) ?? "",+ /^PDF has no readable text: scan\.pdf\./,+ );+ assert.equal(getPdfAttachmentTextError(scan.name, scanText, true), null);+ assert.equal(getPdfAttachmentTextError(typed.name, typedText, false), null);+});+// The bytes are requested synchronously, so the extractor is reached without// waiting on unpdf, which the preview test does not exercise.test("readAttachmentText reads a pdf under the ceiling", () => {