graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Fix native multi-file attach timeouts without blocking the composer
justrach6b23ae9b8347
diff --git a/apps/native/components/primitives/ComposerAttachments.tsx b/apps/native/components/primitives/ComposerAttachments.tsxindex bba23a35..b240dcdd 100644--- a/apps/native/components/primitives/ComposerAttachments.tsx+++ b/apps/native/components/primitives/ComposerAttachments.tsx@@ -5,13 +5,17 @@ import { createPortal } from "react-dom";import type { Attachment } from "@/lib/attachments";import { Icon, GLYPHS } from "./prompt-demo";-export default function ComposerAttachments({ attachments, pill, onRemove }: {- attachments: readonly Attachment[]; pill: boolean; onRemove(id: string): void;+export type FailedAttach = { id: string; name: string; error: string };++export default function ComposerAttachments({ attachments, failed = [], pill, onRemove, onRetryFailed, onDismissFailed }: {+ attachments: readonly Attachment[]; failed?: readonly FailedAttach[]; pill: boolean;+ onRemove(id: string): void; onRetryFailed?(id: string): void; onDismissFailed?(id: string): void;}) {const [previewId, setPreviewId] = useState<string | null>(null);const preview = attachments.find(file => file.id === previewId && file.preview);+ const chips = attachments.length > 0 || failed.length > 0;return <>- {attachments.length > 0 && <div className={`flex flex-wrap gap-1.5 pt-0.5 ${pill ? "px-1" : "px-0.5"}`}>+ {chips && <div className={`flex flex-wrap gap-1.5 pt-0.5 ${pill ? "px-1" : "px-0.5"}`}>{attachments.map(file => <span 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" }}>@@ -27,7 +31,19 @@ export default function ComposerAttachments({ attachments, pill, onRemove }: {<Icon size={10} strokeWidth={2.5}><path d="M18 6L6 18M6 6l12 12" /></Icon></button></span>)}+ {failed.map(file => <span key={file.id}+ className={`flex h-6.5 max-w-full items-center gap-1 bg-field py-1 pr-1 pl-1.5 text-[11.5px] text-red shadow-hairline ${pill ? "rounded-full" : "rounded-chip"}`}+ role="status">+ <span className="max-w-36 truncate" title={file.error}>{file.name}</span>+ {onRetryFailed && <button type="button" aria-label={`Retry ${file.name}`} onClick={() => onRetryFailed(file.id)}+ className={`flex h-6 items-center px-1.5 text-[11px] text-ink-2 hover:bg-hover hover:text-ink ${pill ? "rounded-full" : "rounded-[5px]"}`}>Retry</button>}+ <button type="button" aria-label={`Remove ${file.name}`} onClick={() => (onDismissFailed ?? onRemove)(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]"}`}>+ <Icon size={10} strokeWidth={2.5}><path d="M18 6L6 18M6 6l12 12" /></Icon>+ </button>+ </span>)}</div>}+ {failed.length > 0 && <p className={`text-[11.5px] text-red ${pill ? "px-2" : "px-1"}`} role="status">{failed[failed.length - 1]?.error}</p>}{preview && <AttachmentPreview key={preview.id} file={preview} onClose={() => setPreviewId(null)} />}</>;}diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsxindex e51e0b4d..97fb643d 100644--- a/apps/native/components/primitives/PromptBar.tsx+++ b/apps/native/components/primitives/PromptBar.tsx@@ -290,17 +290,23 @@ export default function PromptBar({inputRef.current?.focus();};+ const [failedAttaches, setFailedAttaches] = useState<{ id: string; name: string; error: string; file: File }[]>([]);+const attachFiles = async (files: File[]) => {if (demo || files.length === 0) return;- setAttachError(null); setUploads(count => count + files.length);- for (const file of files) {+ setAttachError(null);+ setUploads(count => count + files.length);+ await Promise.all(files.map(async (file, index) => {+ const id = `${file.name || "attachment"}-${Date.now()}-${index}`;try {const attachment = await uploadAttachment(file);setAttachments((current) => [...current, attachment]);} catch (err) {- setAttachError(err instanceof Error ? err.message : String(err));+ const error = err instanceof Error ? err.message : String(err);+ setFailedAttaches((current) => [...current, { id, name: file.name || "attachment", error, file }]);+ setAttachError(error);} finally { setUploads(count => count - 1); }- }+ }));if (inputRef.current?.closest("[data-promptbar]")?.contains(document.activeElement)) inputRef.current.focus();};@@ -311,6 +317,22 @@ export default function PromptBar({});};+ const retryFailed = (id: string) => {+ const job = failedAttaches.find((item) => item.id === id);+ if (!job) return;+ setFailedAttaches((current) => current.filter((item) => item.id !== id));+ setAttachError(null);+ void attachFiles([job.file]);+ };++ const dismissFailed = (id: string) => {+ setFailedAttaches((current) => {+ const next = current.filter((item) => item.id !== id);+ setAttachError(next.at(-1)?.error ?? null);+ return next;+ });+ };+const canSend = !disabled && uploads === 0 && (draft.trim().length > 0 || attachments.length > 0);const showStop = busy;const steerArm = useSteerArm(busy && !disabled, onSteerQueued);@@ -321,6 +343,7 @@ export default function PromptBar({releaseAttachments(attachments);setDraft("");setAttachments([]);+ setFailedAttaches([]);setAttachError(null);setHistoryIndex(-1);stashRef.current = "";@@ -424,10 +447,11 @@ export default function PromptBar({{draft}</span>- <ComposerAttachments attachments={attachments} pill={pill} onRemove={removeAttachment} />+ <ComposerAttachments attachments={attachments} failed={failedAttaches} pill={pill}+ onRemove={removeAttachment} onRetryFailed={retryFailed} onDismissFailed={dismissFailed} />{uploads > 0 && <p role="status" className="px-2 text-xs text-ink-3">Adding {uploads} {uploads === 1 ? "file" : "files"}…</p>}- {attachError && (+ {attachError && failedAttaches.length === 0 && (<div className={`text-[11.5px] text-red ${pill ? "px-2" : "px-1"}`} role="status">{attachError}</div>diff --git a/apps/native/lib/attachments.test.ts b/apps/native/lib/attachments.test.tsindex adf1d1cf..f42d6f43 100644--- a/apps/native/lib/attachments.test.ts+++ b/apps/native/lib/attachments.test.ts@@ -88,28 +88,69 @@ test("the attach row keeps the pointer gesture so the file dialog can open", ()assert.equal(attachRowKeepsUserActivation("file:notes.md"), false);});+function hangUntilAbort(signal?: AbortSignal): Promise<never> {+ if (!signal) return Promise.reject(new Error("expected abort signal"));+ return new Promise((_, reject) => {+ const fail = () => reject(signal.reason ?? new DOMException("The operation was aborted.", "TimeoutError"));+ if (signal.aborted) {+ fail();+ return;+ }+ signal.addEventListener("abort", fail, { once: true });+ });+}++function okAttach(name: string): Response {+ return Response.json({ path: `/tmp/x/${name}`, name });+}+test("uploadAttachment times out instead of hanging the composer", async () => {const file = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });const original = globalThis.fetch;+ globalThis.fetch = (async (_url: unknown, init?: { signal?: AbortSignal }) => hangUntilAbort(init?.signal)) as typeof fetch;+ try {+ await assert.rejects(() => uploadAttachment(file, 15), /Adding shot\.png timed out/);+ } finally {+ globalThis.fetch = original;+ }+});++test("a hung first upload does not block a later file from completing", async () => {+ const hung = new File([new Uint8Array([1])], "stuck.png", { type: "image/png" });+ const later = new File([new Uint8Array([1])], "ok.png", { type: "image/png" });+ const original = globalThis.fetch;+ let calls = 0;globalThis.fetch = (async (_url: unknown, init?: { signal?: AbortSignal }) => {- const signal = init?.signal;- if (!signal) throw new Error("expected abort signal");- await new Promise((_, reject) => {- const fail = () => reject(signal.reason ?? new DOMException("The operation was aborted.", "TimeoutError"));- if (signal.aborted) {- fail();- return;- }- const timer = setTimeout(fail, 100);- signal.addEventListener("abort", () => {- clearTimeout(timer);- fail();- }, { once: true });- });- throw new Error("unreachable");+ calls += 1;+ if (calls === 1) return hangUntilAbort(init?.signal);+ return okAttach("ok.png");+ }) as typeof fetch;+ try {+ const pendingHung = uploadAttachment(hung, 80);+ const finished = await uploadAttachment(later, 80);+ assert.equal(finished.name, "ok.png");+ await assert.rejects(pendingHung, /Adding stuck\.png timed out/);+ } finally {+ globalThis.fetch = original;+ }+});++test("partial multi-file failure names the failed file and keeps the successful one", async () => {+ const bad = new File([new Uint8Array([1])], "notes.md", { type: "text/markdown" });+ const good = new File([new Uint8Array([1])], "shot.png", { type: "image/png" });+ const original = globalThis.fetch;+ let calls = 0;+ globalThis.fetch = (async () => {+ calls += 1;+ if (calls === 1) return Response.json({ error: "not stored" }, { status: 500 });+ return okAttach("shot.png");}) as typeof fetch;try {- await assert.rejects(() => uploadAttachment(file, 15), /timed out/);+ const results = await Promise.allSettled([uploadAttachment(bad, 80), uploadAttachment(good, 80)]);+ assert.equal(results[0]?.status, "rejected");+ assert.match((results[0] as PromiseRejectedResult).reason.message, /notes\.md/);+ assert.equal(results[1]?.status, "fulfilled");+ assert.equal((results[1] as PromiseFulfilledResult<{ name: string }>).value.name, "shot.png");} finally {globalThis.fetch = original;}diff --git a/apps/native/lib/attachments.ts b/apps/native/lib/attachments.tsindex cecf1ef6..1ccf8b21 100644--- a/apps/native/lib/attachments.ts+++ b/apps/native/lib/attachments.ts@@ -53,25 +53,35 @@ export function attachRowKeepsUserActivation(rowKey: string): boolean {/** Generous: a large paste should finish, but a hung HTTP/1.1 slot must not. */export const ATTACH_TIMEOUT_MS = 30_000;-function attachFailure(err: unknown): Error {+export function attachTimeoutMessage(name: string): string {+ return `Adding ${name.trim() || "the file"} timed out. Try again.`;+}++function attachFailure(err: unknown, name: string): Error {if (err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError")) {- return new Error("Adding the file timed out. Try again.");+ return new Error(attachTimeoutMessage(name));}- return err instanceof Error ? err : new Error(String(err));+ const detail = err instanceof Error ? err.message : String(err);+ const label = name.trim();+ return new Error(label ? `${label}: ${detail}` : detail);}/** Write one file to the harness-readable temp directory and describe it. */-export async function uploadAttachment(file: File, timeoutMs = ATTACH_TIMEOUT_MS): Promise<Attachment> {+export async function uploadAttachment(file: File, timeoutMs = ATTACH_TIMEOUT_MS, signal?: AbortSignal): Promise<Attachment> {const body = new FormData();body.append("file", file);+ const timeout = AbortSignal.timeout(timeoutMs);+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;let res: Response;try {- res = await fetch("/api/attach", { method: "POST", body, signal: AbortSignal.timeout(timeoutMs) });+ res = await fetch("/api/attach", { method: "POST", body, signal: combined });} catch (err) {- throw attachFailure(err);+ throw attachFailure(err, file.name ?? "");}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})`);+ if (!res.ok || !json.path) {+ throw attachFailure(new Error(json.error ?? `attach failed (${res.status})`), file.name ?? "");+ }return {id: json.path,name: json.name ?? file.name ?? "attachment",