Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(native): real @ files, image paste and drop in the composer

justrachf83130e2f3aa
diff --git a/apps/native/app/api/attach/route.ts b/apps/native/app/api/attach/route.ts
new file mode 100644
index 00000000..175c54ff
--- /dev/null
+++ b/apps/native/app/api/attach/route.ts
@@ -0,0 +1,83 @@
+import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+/** Pasted and dropped pixels arrive as bytes, but the harness stages a vision
+ * block from a *path* (`@[shot.png]` → `stageGuiImageAttachment`). So the
+ * bytes have to land on disk before a prompt can mention them. They go to a
+ * temp directory rather than the workspace: an attachment belongs to one
+ * message, not to the project the user happens to be sitting in. */
+const DIR = path.join(os.tmpdir(), "graff-native-attachments");
+
+/** Generous on purpose. The harness downscales an oversized image to fit its
+ * own budget, so a tight limit here would refuse work it could actually do;
+ * this only stops something pathological. */
+const MAX_BYTES = 25 * 1024 * 1024;
+
+/** Attachments are per-message scratch. Sweep anything from a previous day so
+ * the directory cannot grow without bound. */
+const MAX_AGE_MS = 24 * 60 * 60 * 1000;
+
+function sweep(now: number) {
+ let entries: string[];
+ try {
+ entries = readdirSync(DIR);
+ } catch {
+ return;
+ }
+ for (const name of entries) {
+ const full = path.join(DIR, name);
+ try {
+ if (now - statSync(full).mtimeMs > MAX_AGE_MS) rmSync(full, { force: true });
+ } catch {
+ // raced with another sweep, or not ours to remove
+ }
+ }
+}
+
+/** Keep the name recognisable in the chip, but never let it steer where the
+ * write lands. The extension carries meaning: `isImagePath` reads it to
+ * decide whether these bytes become a vision block. */
+function safeName(raw: string, type: string): string {
+ const base = path
+ .basename(raw || "")
+ .replace(/[^\w.-]+/g, "-")
+ .replace(/^[-.]+/, "");
+ if (base) return base.slice(0, 80);
+ const sub = type.startsWith("image/") ? type.slice(6).split("+")[0] : "";
+ return sub ? `pasted.${sub === "jpeg" ? "jpg" : sub}` : "pasted";
+}
+
+export async function POST(req: NextRequest) {
+ let form: FormData;
+ try {
+ form = await req.formData();
+ } catch {
+ return Response.json({ error: "expected multipart/form-data" }, { status: 400 });
+ }
+ const file = form.get("file");
+ if (!(file instanceof File)) return Response.json({ error: "no file field" }, { status: 400 });
+ if (file.size === 0) return Response.json({ error: "file is empty" }, { status: 400 });
+ if (file.size > MAX_BYTES) {
+ return Response.json({ error: `larger than the ${MAX_BYTES / (1024 * 1024)}MB attachment limit` }, { status: 413 });
+ }
+
+ const now = Date.now();
+ mkdirSync(DIR, { recursive: true });
+ sweep(now);
+
+ const name = safeName(file.name, file.type);
+ // Collisions are otherwise certain: every pasted screenshot has the same name.
+ const stamped = `${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}-${name}`;
+ const target = path.join(DIR, stamped);
+ try {
+ writeFileSync(target, new Uint8Array(await file.arrayBuffer()));
+ } catch (err) {
+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });
+ }
+ return Response.json({ ok: true, path: target, name, type: file.type, size: file.size });
+}
diff --git a/apps/native/app/api/fs/route.ts b/apps/native/app/api/fs/route.ts
index c50e03af..0bde0a28 100644
--- a/apps/native/app/api/fs/route.ts
+++ b/apps/native/app/api/fs/route.ts
@@ -31,11 +31,74 @@ function resolveInRoot(root: string, rel: string): string | null {
return target;
}
+/** Bounds for the `@` picker's walk. A workspace can be someone's whole home
+ * directory, so the walk is capped rather than exhaustive: it stops long
+ * before it could stall the composer, and says so with `partial`. */
+const SEARCH_SCAN_LIMIT = 20_000;
+const SEARCH_RESULT_LIMIT = 40;
+const SEARCH_MAX_DEPTH = 8;
+
+/** Rank a candidate for the query, or -1 to drop it. A file-name match beats
+ * one buried in a parent directory, because a name is what someone typing
+ * into the picker means; shorter paths break ties, so `src/x.ts` sorts above
+ * a deeply vendored namesake. */
+function score(rel: string, query: string): number {
+ const name = rel.slice(rel.lastIndexOf(path.sep) + 1).toLowerCase();
+ if (name.startsWith(query)) return 0;
+ if (name.includes(query)) return 1;
+ if (rel.toLowerCase().includes(query)) return 2;
+ return -1;
+}
+
+/** Files under `root` matching `query`, best first. Directories never match:
+ * the picker mentions files, and `@[some/dir]` means nothing to the agent. */
+function searchFiles(root: string, query: string): { matches: string[]; partial: boolean } {
+ const hits: { rel: string; rank: number }[] = [];
+ const queue: { dir: string; depth: number }[] = [{ dir: root, depth: 0 }];
+ let scanned = 0;
+ let partial = false;
+ while (queue.length > 0) {
+ const { dir, depth } = queue.shift()!;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue; // unreadable directory: skip it rather than fail the whole search
+ }
+ for (const entry of entries) {
+ if (HIDDEN.has(entry.name) || entry.name.startsWith(".")) continue;
+ if (++scanned > SEARCH_SCAN_LIMIT) {
+ partial = true;
+ queue.length = 0;
+ break;
+ }
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (depth < SEARCH_MAX_DEPTH) queue.push({ dir: full, depth: depth + 1 });
+ continue;
+ }
+ const rel = path.relative(root, full);
+ const rank = score(rel, query);
+ if (rank >= 0) hits.push({ rel, rank });
+ }
+ }
+ hits.sort((a, b) => (a.rank === b.rank ? a.rel.length - b.rel.length : a.rank - b.rank));
+ if (hits.length > SEARCH_RESULT_LIMIT) partial = true;
+ return { matches: hits.slice(0, SEARCH_RESULT_LIMIT).map((h) => h.rel), partial };
+}
+
export async function GET(req: NextRequest) {
// `?root=` picks the workspace (a tab's own cwd); paths stay inside it.
const resolved = resolveRoot(req.nextUrl.searchParams.get("root"));
if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
const root = resolved.root;
+ // `?q=` is the composer's @ picker, not the files pane: search, don't list.
+ const q = req.nextUrl.searchParams.get("q");
+ if (q !== null) {
+ const query = q.trim().toLowerCase();
+ const found = query ? searchFiles(root, query) : { matches: [], partial: false };
+ return Response.json({ ok: true, root, query, ...found });
+ }
const rel = req.nextUrl.searchParams.get("path") ?? "";
const target = resolveInRoot(root, rel);
if (!target) return Response.json({ error: "path escapes the workspace" }, { status: 400 });
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index 880e26a8..984080ad 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -3,6 +3,13 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createShader, playSweep, accentChain, ACCENTS } from "glimm";
import type { AcpCommand } from "@/lib/acp";
+import {
+ filesFrom,
+ releaseAttachments,
+ uploadAttachment,
+ withAttachmentMarkers,
+ type Attachment,
+} from "@/lib/attachments";
import { entryAt, historyKeyIntent, stepHistory } from "@/lib/prompt-history";
/* The built-in "prism" palette is only cyan→indigo→magenta, so a sweep
@@ -38,6 +45,7 @@ const GLYPHS: Record<string, React.ReactNode> = {
chart: <path d="M4 20V10M10 20V4M16 20v-7M22 20H2" />,
layers: <g><path d="M12 2 2 7l10 5 10-5-10-5z" /><path d="M2 17l10 5 10-5M2 12l10 5 10-5" /></g>,
globe: <g><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></g>,
+ file: <g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></g>,
};
/* real product marks, inline so the file stays self-contained */
@@ -138,13 +146,16 @@ const AUTO_STEPS: {
{ draft: "", hold: 900 },
];
-/* the last @word or /word being typed, if any */
+/* The last @word or /word being typed, if any. An @ query may carry path
+ * separators and dots, because narrowing by directory is how anyone finds a
+ * file in a large tree; a slash command never contains either. */
function parseToken(draft: string): { kind: "at" | "slash"; query: string; start: number } | null {
- const match = /(^|\s)([@/])([\w-]*)$/.exec(draft);
+ const match = /(^|\s)(?:@([\w./-]*)|\/([\w-]*))$/.exec(draft);
if (!match) return null;
+ const at = match[2] !== undefined;
return {
- kind: match[2] === "@" ? "at" : "slash",
- query: match[3].toLowerCase(),
+ kind: at ? "at" : "slash",
+ query: (at ? match[2] : match[3]).toLowerCase(),
start: match.index + match[1].length,
};
}
@@ -165,6 +176,7 @@ export default function PromptBar({
busy = false,
onStop,
history,
+ root,
}: {
variant?: string;
/** the self-running walkthrough; turn off when embedding in a real surface */
@@ -186,6 +198,9 @@ export default function PromptBar({
/** Earlier prompts, oldest first. ArrowUp on the first line of the draft
* walks back through them like a shell; ArrowDown walks forward again. */
history?: readonly string[];
+ /** The workspace this composer sends into. The @ picker searches it, and a
+ * picked file is mentioned by its path relative to it. */
+ root?: string;
}) {
const pill = variant === "Pill";
const catalog = models && models.length > 0 ? models : MODELS;
@@ -210,7 +225,11 @@ export default function PromptBar({
if (found && found.key !== model.key) setModel(found);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [modelKey, models]);
- const [attachments, setAttachments] = useState<string[]>([]);
+ const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [attachError, setAttachError] = useState<string | null>(null);
+ const [dragging, setDragging] = useState(false);
+ /* Workspace files matching the current @ query — live surfaces only. */
+ const [fileRows, setFileRows] = useState<{ key: string; name: string; desc: string }[]>([]);
const [connected, setConnected] = useState(false);
const [active, setActive] = useState(0);
const [listening, setListening] = useState(false);
@@ -229,6 +248,7 @@ export default function PromptBar({
const composerAnchorRef = useRef<HTMLDivElement>(null);
const controlsRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
+ const fileInputRef = useRef<HTMLInputElement>(null);
const measureRef = useRef<HTMLSpanElement>(null);
const modelRef = useRef<HTMLButtonElement>(null);
const rowRefs = useRef<(HTMLButtonElement | null)[]>([]);
@@ -254,9 +274,50 @@ export default function PromptBar({
const menu: "at" | "slash" | null = plusOpen ? "at" : token?.kind ?? null;
const query = plusOpen ? "" : token?.query ?? "";
+ /* The @ picker searches the workspace. Debounced, and every in-flight
+ * search is abandoned when the query moves on, so a slow walk over a large
+ * tree can never land on top of results for what is now typed. */
+ useEffect(() => {
+ if (demo || menu !== "at") return;
+ if (!query) {
+ setFileRows([]);
+ return;
+ }
+ const abort = new AbortController();
+ const timer = setTimeout(() => {
+ const params = new URLSearchParams({ q: query });
+ if (root) params.set("root", root);
+ fetch(`/api/fs?${params}`, { signal: abort.signal })
+ .then((res) => res.json())
+ .then((json: { matches?: string[] }) => {
+ setFileRows(
+ (json.matches ?? []).map((rel) => ({
+ key: `file:${rel}`,
+ name: rel.slice(rel.lastIndexOf("/") + 1),
+ desc: rel,
+ })),
+ );
+ })
+ .catch(() => {
+ /* aborted, or the workspace went away — keep the rows we have */
+ });
+ }, 90);
+ return () => {
+ abort.abort();
+ clearTimeout(timer);
+ };
+ }, [demo, menu, query, root]);
+
+ /* The walkthrough glides through a fixed cast of sources. A live composer
+ * offers the real attach action and whatever the workspace search found —
+ * an invented data source is worse than an empty menu. */
+ const atRows = demo
+ ? SOURCES.filter((s) => s.name.toLowerCase().includes(query))
+ : [SOURCES[0], ...fileRows];
+
const rows: { key: string; name: string; desc: string }[] =
menu === "at"
- ? SOURCES.filter((s) => s.name.toLowerCase().includes(query))
+ ? atRows
: menu === "slash"
? slashRows.filter((c) => c.name.slice(1).startsWith(query))
: [];
@@ -455,28 +516,62 @@ export default function PromptBar({
setModelOpen(false);
};
- const pick = (row: { key: string; name: string }) => {
- const source = SOURCES.find((s) => s.key === row.key);
- if (source?.attach) {
- setAttachments((current) => [...current, FILES[current.length % FILES.length]]);
- if (token) setDraft(draft.slice(0, token.start));
+ const pick = (row: { key: string; name: string; desc: string }) => {
+ const before = token ? draft.slice(0, token.start) : draft;
+ if (row.key === "attach") {
+ if (demo) {
+ const name = FILES[attachments.length % FILES.length];
+ setAttachments((current) => [...current, { id: `${name}-${current.length}`, name, path: name }]);
+ } else {
+ fileInputRef.current?.click();
+ }
+ setDraft(before);
+ } else if (row.key.startsWith("file:")) {
+ /* The harness reads `@[path]` out of the prompt text: an image becomes
+ * a native vision block, anything else stays a path it opens itself. */
+ setDraft(`${before}@[${row.desc}] `);
} else if (menu === "at") {
- setDraft(`${token ? draft.slice(0, token.start) : draft}@${row.name} `);
+ setDraft(`${before}@${row.name} `);
} else {
- setDraft(`${token ? draft.slice(0, token.start) : draft}${row.name} `);
+ setDraft(`${before}${row.name} `);
}
setPlusOpen(false);
setDismissed(false);
inputRef.current?.focus();
};
+ /* Bytes from a paste, a drop or the file picker. Uploaded one at a time so
+ * one refusal cannot take the others down with it. */
+ const attachFiles = async (files: File[]) => {
+ if (demo || files.length === 0) return;
+ setAttachError(null);
+ for (const file of files) {
+ try {
+ const attachment = await uploadAttachment(file);
+ setAttachments((current) => [...current, attachment]);
+ } catch (err) {
+ setAttachError(err instanceof Error ? err.message : String(err));
+ }
+ }
+ inputRef.current?.focus();
+ };
+
+ const removeAttachment = (id: string) => {
+ setAttachments((current) => {
+ releaseAttachments(current.filter((a) => a.id === id));
+ return current.filter((a) => a.id !== id);
+ });
+ };
+
const canSend = !disabled && (draft.trim().length > 0 || attachments.length > 0);
const showStop = busy && !canSend;
const send = () => {
if (!canSend) return;
- onSend?.(draft.trim());
+ onSend?.(withAttachmentMarkers(draft.trim(), attachments));
+ releaseAttachments(attachments);
setDraft("");
setAttachments([]);
+ setAttachError(null);
setHistoryIndex(-1);
stashRef.current = "";
closeMenus();
@@ -530,6 +625,11 @@ export default function PromptBar({
/>
{rows.map((row, i) => {
const source = menu === "at" ? SOURCES.find((s) => s.key === row.key) : undefined;
+ const mark = source ? (
+ source.brand ? BRANDS[source.brand] : <Icon size={15}>{GLYPHS[source.glyph ?? "clip"]}</Icon>
+ ) : row.key.startsWith("file:") ? (
+ <Icon size={15}>{GLYPHS.file}</Icon>
+ ) : null;
return (
<button
key={row.key}
@@ -545,10 +645,8 @@ export default function PromptBar({
onClick={() => pick(row)}
className="relative z-10 flex h-9 w-full items-center gap-2.5 rounded-[6px] px-2 text-left"
>
- {source && (
- <span className="flex size-5.5 shrink-0 items-center justify-center text-ink-2">
- {source.brand ? BRANDS[source.brand] : <Icon size={15}>{GLYPHS[source.glyph ?? "clip"]}</Icon>}
- </span>
+ {mark && (
+ <span className="flex size-5.5 shrink-0 items-center justify-center text-ink-2">{mark}</span>
)}
<span className="shrink-0 text-[12.5px] font-medium text-ink">
{row.name}
@@ -578,7 +676,11 @@ export default function PromptBar({
</div>
)}
<div className="mt-1 border-t border-line px-2 pt-1.5 pb-1 text-[11px] text-ink-3">
- {menu === "at" ? "Type to search sources & files" : "Type to search commands"}
+ {menu !== "at"
+ ? "Type to search commands"
+ : demo
+ ? "Type to search sources & files"
+ : "Type to search this workspace — or paste, drop and attach files"}
</div>
</div>
)}
@@ -660,12 +762,45 @@ export default function PromptBar({
{/* ── composer ───────────────────────────────────── */}
<div
- className={`relative isolate flex flex-col overflow-hidden border border-line bg-surface shadow-card transition-[border-color,border-radius] duration-150 focus-within:border-line-strong ${
+ onDragOver={(event) => {
+ /* Claim the drop only for files. Without preventDefault here the
+ * browser navigates away to the dropped file instead. */
+ if (demo || !event.dataTransfer.types.includes("Files")) return;
+ event.preventDefault();
+ setDragging(true);
+ }}
+ onDragLeave={(event) => {
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
+ setDragging(false);
+ }}
+ onDrop={(event) => {
+ const files = filesFrom(event.dataTransfer);
+ if (demo || files.length === 0) return;
+ event.preventDefault();
+ setDragging(false);
+ void attachFiles(files);
+ }}
+ className={`relative isolate flex flex-col overflow-hidden border bg-surface shadow-card transition-[border-color,border-radius] duration-150 focus-within:border-line-strong ${
+ dragging ? "border-accent-ink" : "border-line"
+ } ${
tall ? "gap-2.5 p-3.5" : "gap-1.5 p-1.5"
} ${
pill ? (attachments.length > 0 || wide ? "rounded-[24px]" : "rounded-full") : tall ? "rounded-[22px]" : "rounded-[14px]"
}`}
>
+ {/* The @ menu's attach row and the + button both open this. */}
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ hidden
+ onChange={(event) => {
+ void attachFiles(Array.from(event.target.files ?? []));
+ // Same file twice in a row is a real thing to want; without this
+ // the second pick fires no change event at all.
+ event.target.value = "";
+ }}
+ />
{/* rainbow glimm sweep — plays across the interior on model change.
explicit w/h: a <canvas> is a replaced element and won't stretch
to inset-0 alone, which feeds back into the shader's ResizeObserver. */}
@@ -685,20 +820,25 @@ export default function PromptBar({
{attachments.length > 0 && (
<div className={`flex flex-wrap gap-1.5 pt-0.5 ${pill ? "px-1" : "px-0.5"}`}>
- {attachments.map((file, i) => (
+ {attachments.map((file) => (
<span
- key={`${file}-${i}`}
+ key={file.id}
className={`flex h-6.5 items-center gap-1.5 bg-field py-1 pr-1 pl-1.5 text-[11.5px] text-ink-2 shadow-hairline ${
pill ? "rounded-full" : "rounded-chip"
}`}
style={{ animation: "pop-in 200ms cubic-bezier(0.23,1,0.32,1) both" }}
>
- <Icon size={12}><g><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></g></Icon>
- <span className="max-w-36 truncate">{file}</span>
+ {file.preview ? (
+ /* eslint-disable-next-line @next/next/no-img-element */
+ <img src={file.preview} alt="" className="-my-1 size-6 rounded-[4px] object-cover" />
+ ) : (
+ <Icon size={12}>{GLYPHS.file}</Icon>
+ )}
+ <span className="max-w-36 truncate">{file.name}</span>
<button
type="button"
- aria-label={`Remove ${file}`}
- onClick={() => setAttachments((current) => current.filter((_, j) => j !== i))}
+ aria-label={`Remove ${file.name}`}
+ onClick={() => removeAttachment(file.id)}
className={`-my-1 flex size-6 items-center justify-center text-ink-3 transition-colors duration-100 hover:bg-line/70 hover:text-ink ${
pill ? "rounded-full" : "rounded-[5px]"
}`}
@@ -710,6 +850,12 @@ export default function PromptBar({
</div>
)}
+ {attachError && (
+ <div className={`text-[11.5px] text-red ${pill ? "px-2" : "px-1"}`} role="status">
+ {attachError}
+ </div>
+ )}
+
<div
ref={controlsRef}
className={`grid items-end gap-x-1 gap-y-1.5 ${
@@ -743,6 +889,14 @@ export default function PromptBar({
setDismissed(false);
setPlusOpen(false);
}}
+ onPaste={(event) => {
+ /* Claim the paste only when it carries files. A text paste has
+ * to fall through untouched — that is Cmd-V doing its job. */
+ const files = filesFrom(event.clipboardData);
+ if (demo || files.length === 0) return;
+ event.preventDefault();
+ void attachFiles(files);
+ }}
onKeyDown={(event) => {
if (menu && rows.length > 0) {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
diff --git a/apps/native/components/site/ChatEmpty.tsx b/apps/native/components/site/ChatEmpty.tsx
index 5e85d2b2..51f3edc3 100644
--- a/apps/native/components/site/ChatEmpty.tsx
+++ b/apps/native/components/site/ChatEmpty.tsx
@@ -91,6 +91,7 @@ export default function EmptyState({
disabled={health !== null && !health.ok}
history={history}
commands={commands}
+ root={where}
/>
{health && !health.ok && (
<p className="mt-3 text-[12.5px] text-orange">
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index dde60f4a..00be6fce 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -873,6 +873,7 @@ export default function GraffHarness() {
placeholder={threadBusy ? "Queue a follow-up…" : "Follow up"}
models={models}
commands={commands[thread.id] ?? []}
+ root={cwdOf(thread)}
modelKey={threadModel}
onModelChange={(key: string) => changeModel(key, thread.id)}
onSend={(text: string) => void send(text, thread.id)}
diff --git a/apps/native/lib/attachments.test.ts b/apps/native/lib/attachments.test.ts
new file mode 100644
index 00000000..0817fc83
--- /dev/null
+++ b/apps/native/lib/attachments.test.ts
@@ -0,0 +1,58 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { filesFrom, isImageFile, marker, withAttachmentMarkers, type Attachment } from "./attachments.ts";
+
+const shot: Attachment = { id: "/tmp/a/shot.png", name: "shot.png", path: "/tmp/a/shot.png" };
+const notes: Attachment = { id: "/tmp/a/notes.md", name: "notes.md", path: "/tmp/a/notes.md" };
+
+test("markers are the @[path] form the harness stages vision blocks from", () => {
+ assert.equal(marker(shot), "@[/tmp/a/shot.png]");
+});
+
+test("withAttachmentMarkers appends one marker per attachment", () => {
+ assert.equal(withAttachmentMarkers("look at this", [shot]), "look at this @[/tmp/a/shot.png]");
+ assert.equal(
+ withAttachmentMarkers("compare", [shot, notes]),
+ "compare @[/tmp/a/shot.png] @[/tmp/a/notes.md]",
+ );
+});
+
+test("an attachment the draft already names is not sent twice", () => {
+ assert.equal(withAttachmentMarkers("see @[/tmp/a/shot.png] here", [shot]), "see @[/tmp/a/shot.png] here");
+});
+
+test("a draft with no attachments, and attachments with no draft, both survive", () => {
+ assert.equal(withAttachmentMarkers("just words", []), "just words");
+ assert.equal(withAttachmentMarkers("", [shot]), "@[/tmp/a/shot.png]");
+ assert.equal(withAttachmentMarkers(" ", []), " ");
+});
+
+test("isImageFile follows the media type, which is what decides the chip", () => {
+ assert.equal(isImageFile(new File([], "a.png", { type: "image/png" })), true);
+ assert.equal(isImageFile(new File([], "a.md", { type: "text/markdown" })), false);
+ assert.equal(isImageFile(new File([], "a.png")), false);
+});
+
+test("filesFrom reads a paste's items, and falls back to files on a drop", () => {
+ const png = new File([], "shot.png", { type: "image/png" });
+ const pasted = {
+ items: [
+ { kind: "string", getAsFile: () => null },
+ { kind: "file", getAsFile: () => png },
+ ],
+ files: [],
+ } as unknown as DataTransfer;
+ assert.deepEqual(filesFrom(pasted), [png]);
+
+ const dropped = { items: [], files: [png] } as unknown as DataTransfer;
+ assert.deepEqual(filesFrom(dropped), [png]);
+});
+
+test("a paste carrying only text yields nothing, so the composer lets it through", () => {
+ const textOnly = {
+ items: [{ kind: "string", getAsFile: () => null }],
+ files: [],
+ } as unknown as DataTransfer;
+ assert.deepEqual(filesFrom(textOnly), []);
+ assert.deepEqual(filesFrom(null), []);
+});
diff --git a/apps/native/lib/attachments.ts b/apps/native/lib/attachments.ts
new file mode 100644
index 00000000..7625f12d
--- /dev/null
+++ b/apps/native/lib/attachments.ts
@@ -0,0 +1,80 @@
+/** Composer attachments: pixels and files that arrive as bytes rather than as
+ * a path the agent could already open.
+ *
+ * The harness stages vision blocks from `@[path]` markers in the prompt text
+ * (`stageGuiImageAttachment`), so the browser cannot hand over the bytes
+ * directly — they are written to a temp file first and the prompt mentions
+ * that path. A non-image attachment goes through the same door: the marker
+ * stays literal text and the agent opens it with its own tools. */
+
+export type Attachment = {
+ /** Stable across re-renders; the temp path is unique enough to be the key. */
+ id: string;
+ /** What the chip shows — the original name, not the stamped temp one. */
+ name: string;
+ /** Absolute temp path, the thing `@[…]` names. */
+ path: string;
+ /** An object URL for image chips. Revoke it when the chip goes away. */
+ preview?: string;
+};
+
+/** Anything an image chip can meaningfully preview and the harness can stage.
+ * `isImagePath` in the harness reads the extension, so the type has to
+ * survive as one — a `.webp` pasted as `image/webp` stays a webp. */
+export function isImageFile(file: File): boolean {
+ return file.type.startsWith("image/");
+}
+
+/** The files carried by a paste or a drop. A copied screenshot arrives as an
+ * `image/*` item with an empty name; a copied *file* arrives with its own.
+ * Plain text pastes carry no files at all, which is why the caller must let
+ * the event through untouched when this comes back empty. */
+export function filesFrom(data: DataTransfer | null | undefined): File[] {
+ if (!data) return [];
+ const out: File[] = [];
+ // `items` is the only view that exposes a pasted screenshot; `files` is the
+ // only one some browsers populate on drop. Prefer items, fall back.
+ if (data.items && data.items.length > 0) {
+ for (const item of Array.from(data.items)) {
+ if (item.kind !== "file") continue;
+ const file = item.getAsFile();
+ if (file) out.push(file);
+ }
+ }
+ if (out.length === 0 && data.files) out.push(...Array.from(data.files));
+ return out;
+}
+
+/** Write one file to the harness-readable temp directory and describe it. */
+export async function uploadAttachment(file: File): Promise<Attachment> {
+ const body = new FormData();
+ body.append("file", file);
+ const res = await fetch("/api/attach", { method: "POST", body });
+ const json = (await res.json()) as { path?: string; name?: string; error?: string };
+ if (!res.ok || !json.path) throw new Error(json.error ?? `attach failed (${res.status})`);
+ return {
+ id: json.path,
+ name: json.name ?? file.name ?? "attachment",
+ path: json.path,
+ preview: isImageFile(file) ? URL.createObjectURL(file) : undefined,
+ };
+}
+
+/** The marker the harness looks for. */
+export function marker(attachment: Attachment): string {
+ return `@[${attachment.path}]`;
+}
+
+/** The prompt text as it goes on the wire: the draft, then a marker for every
+ * attachment the draft has not already named. Someone who typed the path by
+ * hand and also dropped the file should not send it twice. */
+export function withAttachmentMarkers(text: string, attachments: readonly Attachment[]): string {
+ const missing = attachments.filter((a) => !text.includes(marker(a))).map(marker);
+ if (missing.length === 0) return text;
+ return [text.trim(), ...missing].filter(Boolean).join(" ");
+}
+
+/** Object URLs outlive the component that made them; free them explicitly. */
+export function releaseAttachments(attachments: readonly Attachment[]): void {
+ for (const a of attachments) if (a.preview) URL.revokeObjectURL(a.preview);
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index 972aa99a..c7eaa6d3 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -10,7 +10,7 @@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts"
+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts"
},
"dependencies": {
"@streamdown/code": "^1.1.1",