The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Assist project sources read PDFs (uploads and links); unreadable ones are refused
Claudee174e72e60eb
diff --git a/package.json b/package.jsonindex 85a263ef..9328d75b 100644--- a/package.json+++ b/package.json@@ -39,6 +39,7 @@"sonner": "^2.0.8","three": "0.183.2","tw-animate-css": "^1.4.0",+ "unpdf": "1.8.1","zod": "^4.6.7"},"devDependencies": {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a8a4dbb3..30bb21f9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -77,6 +77,9 @@ importers:tw-animate-css:specifier: ^1.4.0version: 1.4.0+ unpdf:+ specifier: 1.8.1+ version: 1.8.1zod:specifier: ^4.6.7version: 4.6.7@@ -4289,6 +4292,15 @@ packages:resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}+ resolution: {integrity: sha512-xkURhy2SoGpOIH0a1gLHNkASPIQYonadDJs2AQwPEfUakafeD9EA1WTWWsaR++gfTCXJpV27W7tU1nXuk82UKQ==}+ engines: {node: '>=22'}+ peerDependencies:+ '@napi-rs/canvas': ^0.1.69 || ^1.0.0+ peerDependenciesMeta:+ '@napi-rs/canvas':+ optional: true+resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}engines: {node: '>= 0.8'}@@ -9276,6 +9288,8 @@ snapshots:+ [email protected]: {}+diff --git a/src/app/api/assist/projects/[projectId]/sources/route.ts b/src/app/api/assist/projects/[projectId]/sources/route.tsindex 16d27045..1b3580b9 100644--- a/src/app/api/assist/projects/[projectId]/sources/route.ts+++ b/src/app/api/assist/projects/[projectId]/sources/route.ts@@ -1,9 +1,9 @@import { z } from "zod";import { addSource, ProjectError } from "@/server/assist/projects";-import { contentTypeFor, saveFile } from "@/server/storage";+import { contentTypeFor, deleteAsset, saveFile } from "@/server/storage";const MAX_BYTES = 25 * 1024 * 1024;-/** Documents Assist can read (text) or keep as a reference (PDF), plus media it can pass on as inputs. */+/** Documents Assist can read (text, Markdown, PDF), plus media it can pass on as inputs. */const ALLOWED = /^(text\/[\w.+-]+|application\/(json|pdf|xml|x-subrip|x-yaml|yaml)|image\/(png|jpeg|webp|gif)|video\/(mp4|webm|quicktime)|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;const TEXT_EXT: Record<string, string> = { md: "text/markdown", markdown: "text/markdown", txt: "text/plain", csv: "text/csv", srt: "application/x-subrip", vtt: "text/vtt", json: "application/json", yml: "application/x-yaml", yaml: "application/x-yaml", pdf: "application/pdf" };@@ -33,7 +33,13 @@ export async function POST(request: Request, ctx: RouteContext<"/api/assist/projlet name = file.name.replace(/[\\/]/g, "_").replace(/[^\w.\- ()]+/g, "_").slice(-120) || "file";if (!/\.[a-z0-9]{1,8}$/i.test(name)) name = `${name}.${Object.entries(TEXT_EXT).find(([, t]) => t === type)?.[0] ?? "bin"}`;const asset = saveFile({ data: Buffer.from(await file.arrayBuffer()), contentType: type, name, source: "upload" });- return Response.json(await addSource(projectId, { kind: "file", url: asset.url, name: file.name.slice(0, 160) }), { status: 201 });+ try {+ return Response.json(await addSource(projectId, { kind: "file", url: asset.url, name: file.name.slice(0, 160) }), { status: 201 });+ } catch (e) {+ // Refused (an unreadable PDF, the project is full): don't keep the upload.+ deleteAsset(asset.id);+ throw e;+ }}const parsed = Json.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Add a link, a file, an element or a note" }, { status: 400 });diff --git a/src/server/assist/pdf.ts b/src/server/assist/pdf.tsnew file mode 100644index 00000000..111d6d35--- /dev/null+++ b/src/server/assist/pdf.ts@@ -0,0 +1,52 @@+import "server-only";++/**+ * The text of a PDF (brand guides, briefs, scripts), page by page, for project sources. Runs+ * PDF.js through unpdf's serverless build (no worker, no canvas), stops once `maxChars` is read,+ * and reads at most `maxPages` pages so a huge document can't hold the request up.+ */++export class PdfError extends Error {}++export async function pdfText(data: Buffer, opts: { maxChars: number; maxPages?: number }): Promise<{ text: string; pages: number; title?: string }> {+ const { getDocumentProxy } = await import("unpdf");+ let pdf: Awaited<ReturnType<typeof getDocumentProxy>>;+ try {+ pdf = await getDocumentProxy(new Uint8Array(data), { isEvalSupported: false, stopAtErrors: false });+ } catch (e) {+ const name = (e as { name?: string }).name;+ if (name === "PasswordException") throw new PdfError("This PDF is password-protected — remove the password and add it again");+ throw new PdfError("This PDF is damaged or isn't a PDF");+ }+ try {+ const pages = Math.min(pdf.numPages, opts.maxPages ?? 300);+ const parts: string[] = [];+ let chars = 0;+ for (let n = 1; n <= pages && chars < opts.maxChars; n++) {+ const page = await pdf.getPage(n);+ const content = await page.getTextContent();+ let line = "";+ for (const item of content.items) {+ if (!("str" in item)) continue;+ line += item.str + (item.hasEOL ? "\n" : "");+ }+ page.cleanup();+ const clean = line+ .replace(/[ \t ]+/g, " ")+ .replace(/ *\n */g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+ if (clean) {+ parts.push(clean);+ chars += clean.length + 2;+ }+ }+ const text = parts.join("\n\n").slice(0, opts.maxChars);+ if (!text.trim()) throw new PdfError("This PDF has no text to read (it may be scanned images) — paste the text as a note instead");+ const meta = await pdf.getMetadata().catch(() => null);+ const title = typeof (meta?.info as { Title?: unknown } | undefined)?.Title === "string" ? ((meta!.info as { Title: string }).Title.trim() || undefined) : undefined;+ return { text, pages: pdf.numPages, ...(title && { title }) };+ } finally {+ await pdf.loadingTask.destroy().catch(() => {});+ }+}diff --git a/src/server/assist/projects.ts b/src/server/assist/projects.tsindex 4b964a4d..7b1cd29c 100644--- a/src/server/assist/projects.ts+++ b/src/server/assist/projects.ts@@ -3,6 +3,7 @@ import { nanoid } from "nanoid";import { MAX_PROJECT_SOURCES, PROJECT_COLORS, PROJECT_LIMITS, type AssistProject, type ProjectColor, type ProjectSource, type SourceKind } from "@/lib/assist";import { db } from "../db";import { getElement } from "../elements";+import { PdfError, pdfText } from "./pdf";import { fetchRemote } from "../remote-fetch";import { readRef } from "../storage";import { deleteProjectMemories } from "./memory";@@ -209,6 +210,10 @@ export type SourceInput =async function fetchLink(url: string): Promise<{ title: string; text: string }> {const res = await fetchRemote(url, { maxBytes: 4_000_000, timeoutMs: 20_000 });const type = res.contentType ?? "";+ if (/application\/pdf/.test(type) || res.data.subarray(0, 5).toString("latin1") === "%PDF-") {+ const pdf = await pdfText(res.data, { maxChars: PROJECT_LIMITS.sourceText });+ return { title: pdf.title ?? "", text: pdf.text };+ }const raw = res.data.toString("utf8");if (/html|xml/.test(type) || /^\s*</.test(raw)) return htmlToText(raw);if (TEXT_TYPE.test(type) || !type) return { title: "", text: raw };@@ -248,15 +253,14 @@ export async function addSource(projectId: string, input: SourceInput): Promise<if (TEXT_TYPE.test(contentType) || /\.(md|txt|csv|json|srt|vtt|ya?ml)$/i.test(title)) {return insertSource(projectId, { kind: "file", title, url: input.url, element_id: null, content: data.toString("utf8"), status: "ready", error: null });}- return insertSource(projectId, {- kind: "file",- title,- url: input.url,- element_id: null,- content: null,- status: "error",- error: `Assist can't read ${/\.([a-z0-9]{1,8})$/i.exec(title)?.[1]?.toUpperCase() ?? contentType.split(";")[0]} files yet — paste the text as a note, or add a .txt or .md version`,- });+ if (contentType.startsWith("application/pdf") || /\.pdf$/i.test(title)) {+ // A PDF that can't be read is refused (not saved), so it doesn't take one of the 20 places.+ const pdf = await pdfText(data, { maxChars: PROJECT_LIMITS.sourceText }).catch((e) => {+ throw new ProjectError(e instanceof PdfError ? e.message : "Couldn't read that PDF — paste the text as a note instead", 422);+ });+ return insertSource(projectId, { kind: "file", title, url: input.url, element_id: null, content: pdf.text, status: "ready", error: null });+ }+ throw new ProjectError(`Assist can't read ${/\.([a-z0-9]{1,8})$/i.exec(title)?.[1]?.toUpperCase() ?? contentType.split(";")[0]} files — paste the text as a note, or add a PDF, .txt or .md version`, 415);}case "element": {const el = getElement(input.elementId);diff --git a/tests/assist-skills.test.ts b/tests/assist-skills.test.tsindex 949ec5cf..a25eacae 100644--- a/tests/assist-skills.test.ts+++ b/tests/assist-skills.test.ts@@ -37,6 +37,31 @@ afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const md = (fm: string, body = "# Do it\n\n1. Step one.") => `---\n${fm}\n---\n\n${body}\n`;+/** A small valid PDF: one page per entry, each line drawn with Helvetica (empty lines: no text layer). */+function makePdf(pages: string[][], title?: string): Buffer {+ const objs: string[] = [];+ const kids = pages.map((_, i) => `${4 + i * 2} 0 R`).join(" ");+ objs.push("<< /Type /Catalog /Pages 2 0 R >>");+ objs.push(`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>`);+ objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");+ pages.forEach((lines, i) => {+ const ops = lines.map((l, k) => `BT /F1 12 Tf 72 ${720 - k * 18} Td (${l.replace(/[()\\]/g, "\\$&")}) Tj ET`).join("\n");+ objs.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${5 + i * 2} 0 R >>`);+ objs.push(`<< /Length ${Buffer.byteLength(ops)} >>\nstream\n${ops}\nendstream`);+ });+ if (title) objs.push(`<< /Title (${title}) >>`);+ let out = "%PDF-1.4\n";+ const offsets: number[] = [];+ objs.forEach((o, i) => {+ offsets.push(Buffer.byteLength(out));+ out += `${i + 1} 0 obj\n${o}\nendobj\n`;+ });+ const xref = Buffer.byteLength(out);+ out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n${offsets.map((o) => `${String(o).padStart(10, "0")} 00000 n \n`).join("")}`;+ out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R${title ? ` /Info ${objs.length} 0 R` : ""} >>\nstartxref\n${xref}\n%%EOF\n`;+ return Buffer.from(out, "latin1");+}+describe("SKILL.md parsing and validation", () => {it("reads the frontmatter: quoted values, block scalars, lists and the offline map", () => {const fm = parseFrontmatter(`name: product-photos@@ -344,6 +369,9 @@ describe("projects", () => {if (req.url === "/brand") {res.setHeader("content-type", "text/html; charset=utf-8");res.end(`<html><head><title>Oatly-ish & Co</title><meta name="description" content="Oat milk, playfully."><style>.x{}</style></head><body><nav>Menu</nav><h1>About us</h1><p>We make oat milk.</p><script>evil()</script><ul><li>Teal</li><li>Cream</li></ul></body></html>`);+ } else if (req.url === "/guide.pdf") {+ res.setHeader("content-type", "application/pdf");+ res.end(makePdf([["Brand guide", "Teal and cream, rounded type."]], "Oat Brand Guide"));} else if (req.url === "/image") {res.setHeader("content-type", "image/png");res.end(Buffer.from([0x89, 0x50]));@@ -411,6 +439,25 @@ describe("projects", () => {expect(canUseSkill("narration", p.id)).toBe(true);});+ it("reads PDFs (uploads and links) as text; an unreadable PDF is refused and takes no place", async () => {+ const p = projects.createProject({ name: "Guides" });+ const pdf = saveFile({ data: makePdf([["Brand guide", "Use teal (#1E9E8F) on cream."], ["Voice", "Playful, short sentences."]]), contentType: "application/pdf", name: "guide.pdf", source: "upload" });+ const s = await projects.addSource(p.id, { kind: "file", url: pdf.url, name: "guide.pdf" });+ expect(s).toMatchObject({ kind: "file", status: "ready", title: "guide.pdf" });+ const text = projects.sourceText(p.id, s.id)!.text!;+ expect(text).toContain("Use teal (#1E9E8F) on cream.");+ expect(text.indexOf("Brand guide")).toBeLessThan(text.indexOf("Playful, short sentences."));+ const link = await projects.addSource(p.id, { kind: "link", url: `${base}/guide.pdf` });+ expect(link).toMatchObject({ kind: "link", status: "ready", title: "Oat Brand Guide" });+ expect(link.excerpt).toContain("Teal and cream, rounded type.");+ // No text layer (a scan) and not a PDF at all: refused with a reason, nothing saved.+ const scan = saveFile({ data: makePdf([[]]), contentType: "application/pdf", name: "scan.pdf", source: "upload" });+ await expect(projects.addSource(p.id, { kind: "file", url: scan.url, name: "scan.pdf" })).rejects.toThrow(/no text to read/);+ const junk = saveFile({ data: Buffer.from("not a pdf"), contentType: "application/pdf", name: "junk.pdf", source: "upload" });+ await expect(projects.addSource(p.id, { kind: "file", url: junk.url, name: "junk.pdf" })).rejects.toMatchObject({ status: 422 });+ expect(projects.getProject(p.id)!.sources).toHaveLength(2);+ });+it("deleting a project keeps its chats as personal chats and drops its memory", () => {const p = projects.createProject({ name: "Doomed" });const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id });