diff --git a/AGENTS.md b/AGENTS.md index 832c7456d..26c693ead 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,6 +127,8 @@ app/api/ stt/route.ts POST audio (+scope) → 202 { jobId } | GET ?scope= live jobs (lib/stt-jobs.ts) stt/[jobId]/route.ts GET job state | POST retry with kept audio | DELETE ?claim= claim/discard stt/[jobId]/audio/route.ts GET the kept recording (audio/* only) for playback + uploads/route.ts POST { id, host, name, size, type } start/resume a composer upload (SSE-mode path of the browser link's `up_start`) → { received, done } + uploads/[id]/route.ts PUT ?offset=N raw body ≤ 1 MiB, answered once the host acked it (409 `upload_offset` with { received }) | DELETE abort worktrees/route.ts GET/POST/DELETE git worktrees lib/ @@ -139,6 +141,7 @@ lib/ local-bootstrap.ts web server side of the local link: `localLinkUrl`, `ensureLocalHostLink` (the `local` record + `host.json`) host-login.ts `host.json` (`loginHost`, `readHostLogin`) and `isLoopbackHost`, shared by the daemon and local-bootstrap session-ops.ts file-reading half of the session/project routes, run on the owning host's daemon (this machine's too) + uploads.ts daemon side of composer uploads: `StagedUploads` (staging dir `/omp-web/uploads/`, offset writes, 24 h sweep, attach into the session's `local/uploads/`), `sanitizeUploadName`, `sessionLocalRoot` link-protocol.ts link messages, codec, binary blob frames, close codes, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox`, `LinkSender`/`PartJoiner` (pieces, fair sending) hub.ts main side: the link's upgrade and `websocket` handler (`handleLinkUpgrade`, `hostLinkSocket`), `RemoteHost`, `getHost`, `listHosts`, adoption of live children (`reattach`/`adopt`), orphans, `freezeHostLinks`, `hosts` change events daemon.ts daemon side: `runHostDaemon` (reconnect, buffering, op dispatch, hello with each child's `{sessionId, cwd, pending}`; follows a `host.json` url or token change when a dial fails; loopback redials at most 3 s apart) @@ -299,8 +302,8 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri `IDLE_DESTROY_MS` (10 min) and `DISCONNECT_DESTROY_MS` (`OMP_WEB_DISCONNECT_DESTROY_MS`, 2 min, `0` disables). The shorter one only fires once a session has been genuinely abandoned — no `onEvent` listener, no - run in flight, no startup handshake, no unanswered `send()`. The last - `onEvent` detach *starts* that window rather than exposing the last frame's, + run in flight, no startup handshake, no unanswered `send()` or command preparation. + The last `onEvent` detach *starts* that window rather than exposing the last frame's, so a reload reattaching seconds later does not 409. Both are fed by `resetIdleTimer()`, the single activity choke point for `send()` and every child frame: adding a new call path must route activity through it. @@ -347,7 +350,8 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri design `docs/specs/2026-10-31-websocket-link-design.md`). **Text frames** carry the messages (hub → daemon one per frame; daemon → hub newline-separated batches flushed every 16 ms or at one 256 KiB piece), **binary frames** carry large op - results (daemon → hub, before the `res` naming them). Every line except + results (daemon → hub, before the `res` naming them) and, from v6, upload bytes + (hub → daemon, `up:`). Every line except `hello`/`welcome`/`ack`/`ping`/`pong` has a per-direction `seq`; `ack {ack}` is a message: the first line of every daemon frame, and the hub answers every uplink frame (v5: binary ones too) with exactly one. **Pieces and fair sending @@ -409,10 +413,13 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri field or a message type receivers skip is fine; a changed type or meaning, or a newly required field, needs a new version. Receivers skip unknown message types (acking their `seq`) and answer unknown ops 501 `unknown_op`, from v3 on. - v4 (the WebSocket link) dropped v3 before any release. v5 (pieces) keeps v4: - `MIN_LINK_PROTOCOL_VERSION` is 4 and `LINK_PROTOCOL_VERSION` 5 (literal + v4 (the WebSocket link) dropped v3 before any release. v5 (pieces) keeps v4; + v6 (uploads: hub → daemon binary frames, `upload_ack`, `uploadStart`/ + `uploadAbort`/`uploadAttach`) keeps v4 and v5: + `MIN_LINK_PROTOCOL_VERSION` is 4 and `LINK_PROTOCOL_VERSION` 6 (literal one-liners: the deploy script parses them with `sed`); a v4 daemon gets no - `part`, whole lines and no unacked window (`link.sender.parts`). Main keeps at least N-1, and + `part`, whole lines and no unacked window (`link.sender.parts`); a v4/v5 + daemon gets 426 for uploads. Main keeps at least N-1, and dropping one is an explicit decision (a hello outside the range gets close 4426 with `{"serverVersion":N}`, a pre-WebSocket daemon's POST gets 426). Once the WebSocket experiments end, the first version @@ -1152,6 +1159,84 @@ during the wait. `GhostMirror`), not ChatInput state: re-rendering the composer per ghost change was the dominant per-keystroke cost. +### Composer file uploads (`docs/specs/2026-11-02-file-uploads-design.md`) +- Images and text files go inline while they fit the inline budgets + (`lib/image-attachments.ts`, `lib/chat-attachments.ts`); every other file, + an image switched to **As file**, and anything over a budget is uploaded + (2 GiB per file, 20 per message, `lib/upload-limits.ts`, browser-safe). + The composer re-checks the inline budget per chip on every render, so an + image's decoded size comes from `attachedImageBytes` (scanned once per + image object), never a fresh base64 scan. +- Uploads land in a staging dir on the **session's host** (the daemon), not on + main: a new chat has no session yet. The prompt command carries + `uploads: [id]`; `runAgentCommand` (`lib/agent-command.ts`) attaches each + through the host op `uploadAttach` (hard link into + `/local/uploads/`, never overwriting; copy on EXDEV) and appends + the "Attached files" block with `local://` URL and absolute path. Ids stay + registered until the prompt reaches omp, so a retried send reuses the attach. + Attachment preparation uses the wrapper's pending-command protection too, so + disconnect and idle cleanup cannot dispose a submitted prompt's session while + a slow copy is still running. Later commands await the send fence before + selecting/replacing the wrapper, so Stop and an Advisor change cannot overtake it; + a command through any registry alias of the same wrapper (`getRpcSessionKeys`) + waits too. The Attached files block can push a prompt past the host link's + line cap: the transport then refuses it before queueing with 413 + `request_too_large`, and the uploads stay registered for a shorter resend. +- Bytes are forwarded, never re-encoded: the browser sends binary frames + `[n][id][payload]` (≤ `pieceBytes`) as `LinkSender` blob units keyed + `up:`; `lib/browser-link.ts` accepts them only for uploads that link + started and hands the same bytes to `forwardUploadFrame` (`lib/uploads.ts`) with + that link's sink; frames are forwarded only while it is the upload's current + sink, so a WS sender superseded by an HTTP resume or newer start is refused; + `forwardUploadFrame` queues them as blob units on the host link (link v6; `hostVersion < 6` + → 426 `host_upgrade_required` on a remote host, `host_restart_required` on + `local`: an in-place upgrade keeps a running v4/v5 daemon, which is inside + `[MIN, LINK]`, so "This machine" needs `ompweb-host` restarted). Blob units + are outside both links' line windows; the worker's per-upload + `UPLOAD_WINDOW_BYTES` credit, refilled by the daemon's `upload_ack`, is the + flow control, and main enforces it: a frame putting `sent - received` over + `UPLOAD_WINDOW_BYTES + pieceBytes` stops the upload with 429 + `upload_window_exceeded` (frames dropped until the next start; the socket + stays open). Binary frames are not resent: after a browser-link drop or a + web-server restart the worker re-sends `up_start {id, n, …}` (same id, `n` = + a worker-wide increasing sequence) and continues from the host's `received` in + the answer `up_ack {…, start: n}`. Each start has a fresh sink whose progress, + completion and errors retain `start: n`, including messages already queued + before a Retry. The worker ignores any mismatched generation before applying + an ack or error. On main the latest concurrent start wins; earlier starts + still answer their callers. + Each host `uploadStart` also carries a fresh UUIDv4 `attempt`; the daemon + echoes it on progress, completion and error `upload_ack`s. Main discards + superseded-attempt acks even if they arrive after the newer start's reply. + Receipt replay and a start of an already-attached upload both require a + regular-file target; a missing or directory target gets `upload_missing`. + Receipt publication is atomic, and start/attach/abort controls share one + per-id queue so an abort cannot be undone by an earlier attach's receipt. + A start that finds the upload aborted sends + `uploadAbort` to the host and answers 404 `upload_missing`. A host-link drop + fails each in-flight upload with 503 `host_offline`; the chip's Retry (same + id) resumes. No auto-retry. +- Limits on main: at most 32 unfinished uploads per owner (429 + `too_many_uploads`); an unfinished entry idle 10 min (no start, frame or ack) + is dropped from the registry (a later `up_start` re-registers it). The worker + fails an upload no start answer or ack advances for `UPLOAD_STALL_MS` (120 s) + with 504 `upload_stalled` and forgets it without aborting it on the host, so + Retry resumes. Page navigation settles pending WebSocket-upload promises before + the worker's `bye`: a composer retained by bfcache shows Retry after restoration, + not a permanently uploading chip. This does not automatically resume navigation. + The daemon's `sweep` deletes staged files older than 24 h and aborts open uploads + idle (no start/write) over 24 h (`STAGED_MAX_AGE_MS`). + `uploadAttach` has a 10-minute op timeout (a 2 GiB EXDEV copy), not + `opTimeoutMs`. +- Error codes: composer uploads use `upload_id_conflict` (another upload has + this id); `upload_conflict` stays the file manager's. +- SSE mode uses the same registry over HTTP (`/api/uploads`). Upload owner = + `requestOwner(req)` (`lib/web-auth.ts`), the browser link's owner too; attach + requires the same owner and the session's host. +- The registry is in memory: a main restart loses finished-but-unsent uploads + ("attach the file again"); unfinished ones resume. Switching chats aborts + in-flight uploads; drafts keep only finished ones (`sessionStorage`). + ### Voice transcription jobs (`lib/stt-jobs.ts`, `/api/stt`, `hooks/useDictation.ts`) - The browser never waits on the STT endpoint: `POST /api/stt` keeps the recording in memory and starts a job; the hook polls `GET /api/stt/[jobId]` diff --git a/CHANGELOG.md b/CHANGELOG.md index 345edfc49..aa06908fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,11 +13,16 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **ompweb as a single binary, with no Node or npm.** Each release now also carries `ompweb-linux-x64`, `ompweb-linux-arm64`, `ompweb-darwin-x64`, `ompweb-darwin-arm64` (`.tar.gz`) and `ompweb-windows-x64` (`.zip`): one `ompweb` program with the web files beside it. It takes the same options and environment variables as the npm `ompweb`, and runs the daemon too (`ompweb host`). It has no tray, service installers or in-app update: the README's "Single binary" section shows the service units, and Settings → System links the release page when an update is out. Build one with `npm run build:binary`. - **Binary prereleases from `main`.** Each commit on `main` that passes CI is published as a GitHub prerelease titled with its build time in ISO 8601 UTC (for example `2026-11-01T10:30:00Z`; tag `20261101T103000Z-`) with the five single-binary archives. Prereleases are never marked latest, publish no npm package and trigger no update notice. - **Settings → Hosts shows link protocol versions.** Each host shows the link protocol version its daemon speaks, and the page shows the version this web app expects. +- **Attach any file to a message, up to 2 GiB each.** The composer no longer refuses archives, PDFs or other binary files, and images are no longer capped at 5 MB per message. A file that cannot go inline is uploaded to the session's `local://` directory (`local/uploads/`) on the machine the session runs on, and the message tells the agent its `local://` URL and absolute path. Each image has an **Inline / As file** switch: Inline sends it with the message as before (omp resizes it for the model), As file keeps the exact bytes. An image too large to go inline switches to As file by itself. Uploads stream in chunks over the browser connection (or over HTTP in SSE mode) and on to the host, and show progress on each chip; Send waits until they finish. Over the browser's WebSocket connection, an upload resumes by itself after that connection drops or the web server restarts; in SSE mode, when the server loses the host's link, or when an upload makes no progress for 2 minutes, the chip shows an error and its **Retry** continues from what the host already has. Update ompweb on the server first, then on its hosts: a host on an older build shows "Update ompweb on the session's host to attach files" when a file is attached. After an in-place upgrade, "This machine" takes uploads only once the ompweb host service (`ompweb-host`) is restarted, and the chip says so; restarting it ends the runs on this machine. - **Keep a host running with the single binary.** The README's "Keep a host running as a service" section has a systemd user unit (Linux), a logon scheduled task (Windows) and, for macOS, a restart script to run in tmux: launchd jobs cannot use the login keychain and SSH agent that omp sessions need. In tmux, macOS Local Network privacy blocks the daemon from LAN addresses, so link it to a URL that does not resolve to one (the server's public URL, or a VPN or tailnet name). - **Session search shows where each session matched.** While searching the sidebar, the arrow beside a session lists its matches one per line, best match first and newest first among equals, ten at a time with **Load more…**. Matches in the messages of the open conversation are highlighted, typos and partial words included (thinking, tool output and math are not searched; link addresses and image descriptions do not count), and clicking a match opens its session, scrolls to it and marks it as the current one, like the browser's find. Closing or clearing the search removes the highlights. Browsers without the CSS Custom Highlight API (before Chrome 105, Safari 17.2 or Firefox 140) still jump to the match but do not paint it. ### Fixes & Improvements +- **Uploads no longer leave submitted messages or restored pages stuck.** A slow attachment copy keeps its session alive even after you switch chats. Commands that change Advisor wait until that preparation is dispatched before they may replace the session's child. Returning through browser Back/Forward shows Retry for an interrupted upload instead of leaving Send permanently blocked. +- **Attachment retries no longer accept missing files or stale upload errors.** An attachment removed or replaced by a directory is reported as missing before it is marked complete. Failed receipt writes leave the staged file available to retry without creating a duplicate, and cancellation cannot be undone by an attachment still finishing. Replies from earlier upload attempts no longer fail a newer Retry. Retrying also waits for failed-write cleanup, so an old attempt cannot delete the new attempt's staged files. +- **A conflicting upload start no longer interrupts the original file.** Reusing an upload ID with another filename or MIME type is rejected before changing the active transfer, so the original upload continues normally. +- **PDFs stay file attachments when the browser omits their MIME type.** Filenames ending in `.pdf` (any case) no longer have their raw contents inserted into the prompt as text. - **The dictation waveform no longer stays flat while you speak.** The meter's audio context was created only after the microphone opened; when that took longer than the click's activation window, the browser kept the context suspended and the bars showed silence even though the recording and transcription were fine. The context now starts inside the click. - **Streaming replies use about a sixth of the bandwidth.** ompweb now asks omp (18.13.2 or later) for only what changed in a streaming reply instead of the whole reply several times a second, and the browser rebuilds the reply itself. In one measured reply the live stream fell from 232 KB to 91 KB, and the reply updates themselves from 178 KB to 30 KB, so replies keep up on slow mobile links. A tab opened mid-reply, a reconnect and a restarted server still show the whole reply. An older omp keeps sending whole replies and works as before. - **The host link is now one WebSocket**, with fewer requests and large results sent in the same connection. A reverse proxy in front of ompweb must forward WebSocket upgrades on `/api/hosts/link` (see the README's hosts section). Update ompweb on the server first, then on its hosts: a host linked with an earlier build of this release shows **needs upgrade** until it is updated. diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index c49b65ef0..c7ee93199 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -2,6 +2,7 @@ import { getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { commandErrorResponse, runAgentCommand } from "@/lib/agent-command"; import { parseJsonWithinLimit } from "@/lib/bounded-form-data"; import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments"; +import { requestOwner } from "@/lib/web-auth"; /** Stamp when the handler had the request and when it answered, so the browser * can split network time from server time. */ @@ -28,7 +29,7 @@ export async function POST( // body, which is forwarded to omp verbatim) and only matters when this // request spawns or replaces the session's omp process. const advisor = new URL(req.url).searchParams.get("advisor") === "1"; - return timed(receivedAt, await runAgentCommand(id, body, advisor)); + return timed(receivedAt, await runAgentCommand(id, body, advisor, requestOwner(req))); } catch (error) { return timed(receivedAt ?? Date.now(), commandErrorResponse(error)); } diff --git a/app/api/uploads/[id]/route.ts b/app/api/uploads/[id]/route.ts new file mode 100644 index 000000000..19c166a10 --- /dev/null +++ b/app/api/uploads/[id]/route.ts @@ -0,0 +1,29 @@ +import { readBodyWithinLimit } from "@/lib/bounded-form-data"; +import { abortUpload, putUploadChunk, uploadErrorResponse } from "@/lib/uploads"; +import { requestOwner } from "@/lib/web-auth"; + +type Params = { params: Promise<{ id: string }> }; + +/** Largest PUT body: cut into pieceBytes frames and answered once the host acked its end (spec U4). */ +const MAX_CHUNK_BYTES = 1024 * 1024; + +/** PUT /api/uploads/?offset=N → {received, done}: the next bytes of the upload, at the host's offset (else 409 + * upload_offset with `received`). */ +export async function PUT(req: Request, { params }: Params) { + try { + const { id } = await params; + const raw = new URL(req.url).searchParams.get("offset") ?? ""; + const offset = Number(raw); + if (!/^\d+$/.test(raw) || !Number.isSafeInteger(offset)) return Response.json({ error: "offset must be a byte offset", code: "invalid_request" }, { status: 400 }); + const body = await readBodyWithinLimit(req, MAX_CHUNK_BYTES); + return Response.json(await putUploadChunk(id, requestOwner(req), offset, body)); + } catch (error) { + return uploadErrorResponse(error); + } +} + +/** DELETE /api/uploads/: cancel the upload and delete its staged file. */ +export async function DELETE(req: Request, { params }: Params) { + await abortUpload((await params).id, requestOwner(req)); + return new Response(null, { status: 204 }); +} diff --git a/app/api/uploads/route.ts b/app/api/uploads/route.ts new file mode 100644 index 000000000..82bcc64db --- /dev/null +++ b/app/api/uploads/route.ts @@ -0,0 +1,21 @@ +import { parseJsonWithinLimit } from "@/lib/bounded-form-data"; +import { isRecord } from "@/lib/type-guards"; +import { startUpload, uploadErrorResponse } from "@/lib/uploads"; +import { requestOwner } from "@/lib/web-auth"; + +/** The HTTP form waits on each chunk's ack in its PUT: a start has no one to tell. */ +const NO_SINK = { ack() {}, error() {} }; + +/** POST /api/uploads {id, host, name, size, type} → {received}: open, or resume, an upload on `host` (spec U4, the + * HTTP form of `up_start`). */ +export async function POST(req: Request) { + try { + const body = await parseJsonWithinLimit(req, 16 * 1024); + if (!isRecord(body)) return Response.json({ error: "Invalid upload", code: "invalid_request" }, { status: 400 }); + const { id, host, name, size, type } = body; + // startUpload checks every field's type. + return Response.json(await startUpload({ id, hostId: host, owner: requestOwner(req), name, size, type, sink: NO_SINK } as Parameters[0])); + } catch (error) { + return uploadErrorResponse(error); + } +} diff --git a/components/ChatInput-draft-attachments.ts b/components/ChatInput-draft-attachments.ts index b4fb8d6ef..6a6bbe004 100644 --- a/components/ChatInput-draft-attachments.ts +++ b/components/ChatInput-draft-attachments.ts @@ -6,6 +6,8 @@ export interface AttachedImage { data: string; // base64, no prefix mimeType: string; previewUrl: string; // object URL for display + /** The picked file, so a switch to As file uploads its exact bytes; absent for one restored from a draft. */ + file?: File; } export type AttachedTextFile = AttachedTextFileData; diff --git a/components/ChatInput-uploads.tsx b/components/ChatInput-uploads.tsx new file mode 100644 index 000000000..0e7945de2 --- /dev/null +++ b/components/ChatInput-uploads.tsx @@ -0,0 +1,200 @@ +"use client"; + +import React from "react"; +import { AlertCircle, File as FileIcon, Loader2, RotateCw, X } from "lucide-react"; +import type { ChatDraftUpload } from "@/lib/draft-store"; +import { UploadFailedError } from "@/lib/event-stream"; +import { formatUploadSize } from "@/lib/upload-limits"; +import { translate, useI18n } from "@/lib/i18n"; +import { formatApiError } from "@/lib/i18n/api-error"; + +// Composer attachments sent As file (docs/specs/2026-11-02-file-uploads-design.md U2): uploaded to the target host on +// attach, then named by id in the prompt. + +export interface AttachedUpload { + id: string; + name: string; + size: number; + hostId: string; + /** The picked file, to retry or switch back to Inline with; null for one restored from a draft (finished). */ + file: File | null; + /** Bytes the host has. */ + received: number; + status: "uploading" | "done" | "error"; + error: string | null; + /** An image sent As file: its thumbnail (an object URL). */ + previewUrl: string | null; +} + +export function draftUploadsToAttachedUploads(uploads: ChatDraftUpload[] | undefined): AttachedUpload[] { + return (uploads ?? []).map((upload) => ({ ...upload, file: null, received: upload.size, status: "done", error: null, previewUrl: null })); +} + +/** Only finished uploads go into a draft: one in flight is lost with the page (spec U2). */ +export function attachedUploadsToDraftUploads(uploads: AttachedUpload[]): ChatDraftUpload[] { + return uploads.filter((upload) => upload.status === "done").map(({ id, name, size, hostId }) => ({ id, name, size, hostId })); +} + +/** The upload ids for a send callback: an argument only when there are some (images otherwise stay the last). */ +export function uploadArgs(uploads: AttachedUpload[]): [] | [string[]] { + return uploads.length ? [uploads.map((upload) => upload.id)] : []; +} + +/** What a refused send puts back into its draft, besides text and images. */ +export function uploadRecovery(uploads: AttachedUpload[]): { uploads?: ChatDraftUpload[] } { + return uploads.length ? { uploads: attachedUploadsToDraftUploads(uploads) } : {}; +} + +export function uploadErrorMessage(error: unknown): string { + return error instanceof UploadFailedError ? formatApiError({ error: error.message, code: error.code }) : translate("chatInput.uploadFailed"); +} + +const percentOf = (upload: AttachedUpload) => (upload.size > 0 ? Math.floor((upload.received * 100) / upload.size) : 100); + +function ChipButton({ label, onClick, children, style }: { label: string; onClick: () => void; children: React.ReactNode; style?: React.CSSProperties }) { + return ( + + ); +} + +function ProgressBar({ upload }: { upload: AttachedUpload }) { + const { t } = useI18n(); + const percent = percentOf(upload); + return ( + + ); +} + +/** A file sent As file: progress while it uploads, then its size; on failure a retry. Remove aborts it. */ +export function UploadChip({ upload, onRemove, onRetry }: { upload: AttachedUpload; onRemove: () => void; onRetry: () => void }) { + const { t } = useI18n(); + const failed = upload.status === "error"; + return ( +
+ + {failed + ? + + {upload.name} + + + {failed ? t("chatInput.uploadFailed") : upload.status === "uploading" ? `${percentOf(upload)}%` : formatUploadSize(upload.size)} + + {failed && upload.file && ( + + + )} + + + {upload.status === "uploading" && } +
+ ); +} + +/** + * An image chip: its thumbnail, an Inline / As file switch, and remove. `upload` is set while it goes As file (progress, + * failure and retry as on a file chip). `canSwitch` false: the other mode is not available (too large to send inline, + * or no file to upload). + */ +export function ImageChip({ previewUrl, upload, canSwitch, onSwitch, onRemove, onRetry }: { + previewUrl: string | null; + upload: AttachedUpload | null; + canSwitch: boolean; + onSwitch: () => void; + onRemove: () => void; + onRetry?: () => void; +}) { + const { t } = useI18n(); + const failed = upload?.status === "error"; + return ( +
+
+ {previewUrl && } + + {upload?.status === "uploading" && } +
+ {failed && upload?.file && onRetry && ( + + + )} + + +
+ ); +} diff --git a/components/ChatInput.clipboard-image.test.mjs b/components/ChatInput.clipboard-image.test.mjs index 97ea8aa9f..69f5fb2e0 100644 --- a/components/ChatInput.clipboard-image.test.mjs +++ b/components/ChatInput.clipboard-image.test.mjs @@ -90,9 +90,10 @@ function clipboardImage(type, bytes) { const PLUS_MENU = /More actions|chatInput\.plusMenu/; const PASTE_ITEM = /Paste image|chatInput\.pasteImage/; const FAILURE = /No image could be pasted|chatInput\.clipboardImageFailed/; -const SKIPPED = /skipped|chatInput\.attachmentImagesSkipped/; +const AS_FILE = /too large to send inline|chatInput\.imagesAsFile/; +const SWITCH_TO_INLINE = /Switch to Inline|chatInput\.imageSwitchToInline/; // Any notice the composer raises about the batch it was handed. -const NOTICE = /No image could be pasted|skipped|chatInput\.(clipboardImageFailed|attachmentImagesSkipped)/; +const NOTICE = /No image could be pasted|too large to send inline|chatInput\.(clipboardImageFailed|imagesAsFile)/; function previews(container) { return [...container.querySelectorAll("img")].filter((img) => img.getAttribute("src")?.startsWith("blob:")); @@ -163,14 +164,14 @@ test("attaches a clipboard image through the shared composer attachment path", a assert.equal(screen.queryByRole("menuitem", { name: PASTE_ITEM }), null); }); -test("keeps the pasted image inside the same byte cap as the file picker", async () => { +test("an oversized pasted image goes As file, as from the file picker", async () => { setClipboard({ read: async () => [clipboardImage("image/png", MAX_ATTACHED_IMAGE_BYTES + 1)] }); const container = await pasteFromClipboard(renderComposer()); - // Rejected before any preview URL exists, exactly like an oversized drop. - assert.equal(previews(container).length, 0); - assert.equal(objectUrls.created.length, 0); - assert.match(container.textContent, SKIPPED); + // Past the inline budget it is uploaded instead (spec U2): its chip keeps the thumbnail. + assert.equal(previews(container).length, 1); + assert.match(container.textContent, AS_FILE); + assert.ok(screen.getByRole("button", { name: SWITCH_TO_INLINE })); }); test("reports a clean failure when the clipboard holds no image", async () => { @@ -206,17 +207,17 @@ test("reports a clean failure when the clipboard read is denied", async () => { assert.match(container.textContent, FAILURE); }); -test("keeps one oversized clipboard image from displacing an in-range one", async () => { +test("an oversized clipboard image goes As file beside an in-range one that stays inline", async () => { setClipboard({ read: async () => [ clipboardImage("image/png", MAX_ATTACHED_IMAGE_BYTES + 1), clipboardImage("image/png", 8), ], }); - const container = await pasteFromClipboard(renderComposer()); + const container = await pasteFromClipboard(renderComposer(), () => objectUrls.created.length >= 2); - assert.equal(previews(container).length, 1, "only the in-range image is attached"); - assert.equal(objectUrls.created.length, 1); + assert.equal(previews(container).length, 2, "both are attached"); + assert.equal(screen.getAllByRole("button", { name: SWITCH_TO_INLINE }).length, 1, "only the oversized one As file"); }); test("revokes pasted image previews on unmount", async () => { diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 580d6f73c..7c8c858d3 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -25,6 +25,19 @@ import { revokeImagePreview, textFileToDraftFile, } from "./ChatInput-draft-attachments"; +import { + attachedUploadsToDraftUploads, + draftUploadsToAttachedUploads, + ImageChip, + UploadChip, + uploadArgs, + uploadErrorMessage, + uploadRecovery, + type AttachedUpload, +} from "./ChatInput-uploads"; +import { discardUpload, newUploadId, uploadFile, type UploadHandle } from "@/lib/event-stream"; +import { MAX_UPLOAD_BYTES, MAX_UPLOADS_PER_MESSAGE } from "@/lib/upload-limits"; +import { LOCAL_HOST_ID } from "@/lib/project-ordering"; import { BUILTIN_SLASH_COMMAND_DEFS, CLIENT_BUILTIN_COMMAND_NAMES, @@ -49,14 +62,13 @@ import { ComposerModeStatus, ModelErrorBanner, QueuedActionButton } from "./Chat import { CHAT_COLUMN_MAX_WIDTH } from "@/lib/chat-layout"; import { composeMessageWithTextAttachments, - describeTextAttachmentSkip, - formatAttachmentBytes, MAX_ATTACHED_TEXT_FILES, selectTextAttachments, } from "@/lib/chat-attachments"; import { - MAX_ATTACHED_IMAGE_BYTES, + attachedImageBytes, MAX_ATTACHED_IMAGES, + MAX_TOTAL_ATTACHED_IMAGE_BYTES, validateOutgoingPrompt, } from "@/lib/image-attachments"; import { @@ -139,6 +151,17 @@ function formatUsageLimitLabel( return t("chatInput.slowMode.wrapUpReset", { time }); } +/** A file's bytes as base64, without the data URL's prefix. */ +function readBase64(file: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + // result is "data:;base64," + reader.onload = () => resolve((reader.result as string).split(",")[1]); + reader.onerror = reject; + reader.readAsDataURL(file); + }); +} + export type { AttachedImage, AttachedTextFile } from "./ChatInput-draft-attachments"; export { filterModelOptions } from "./ChatInput-model-options"; export { ModelErrorBanner } from "./ChatInput-banners"; @@ -150,16 +173,17 @@ const TOOL_PRESET_OPTIONS: Array<{ value: ToolPreset; descriptionKey: string }> ]; interface Props { - /** Only a rejected submission is restored; completed/superseded runs must not be replayed. */ - onSend: (message: string, images?: AttachedImage[]) => Promise; + /** Only a rejected submission is restored; completed/superseded runs must not be replayed. `uploads`: the ids of + * files sent As file, passed only when there are some. */ + onSend: (message: string, images?: AttachedImage[], uploads?: string[]) => Promise; /** Ghost-text word completion for the draft (omp `predict_word`); absent = no ghost text. */ onPredictWord?: PredictWord; onPredictWordFeedback?: PredictWordFeedback; onAbort: () => void; /** Steer/follow-up callbacks resolve false when omp refused the message. */ - onSteer?: (message: string, images?: AttachedImage[]) => Promise; - onFollowUp?: (message: string, images?: AttachedImage[]) => Promise; - onPromptWithStreamingBehavior?: (message: string, behavior: "steer" | "followUp", images?: AttachedImage[]) => Promise; + onSteer?: (message: string, images?: AttachedImage[], uploads?: string[]) => Promise; + onFollowUp?: (message: string, images?: AttachedImage[], uploads?: string[]) => Promise; + onPromptWithStreamingBehavior?: (message: string, behavior: "steer" | "followUp", images?: AttachedImage[], uploads?: string[]) => Promise; isStreaming: boolean; /** Refuse submission without treating a pending history edit as a model run. */ submissionBlocked?: boolean; @@ -225,6 +249,8 @@ interface Props { onBuiltinCommand?: (message: string) => Promise; onAudioUnlock?: () => void; draftKey?: string; + /** The host files sent As file are uploaded to: the session's, or the new chat's (this machine when absent). */ + uploadHostId?: string; /** Backend-confirmed ownership relocation, distinct from navigating to a draft. */ draftIdentityMove?: { from: string; to: string; sourceDraft?: ChatDraft }; /** Session working directory — enables the @ file autocomplete menu */ @@ -351,6 +377,7 @@ export const ChatInput = memo(forwardRef(function ChatIn onRemoveQueuedMessage, onPromoteQueuedToSteer, draftKey = "new:unassigned", + uploadHostId = LOCAL_HOST_ID, draftIdentityMove, cwd, activeGoal, @@ -423,9 +450,14 @@ export const ChatInput = memo(forwardRef(function ChatIn const [attachedTextFiles, setAttachedTextFiles] = useState(() => ( draftKey ? draftFilesToAttachedFiles(getDraft(draftKey)?.files) : [] )); + const [attachedUploads, setAttachedUploads] = useState(() => ( + draftKey ? draftUploadsToAttachedUploads(getDraft(draftKey)?.uploads) : [] + )); const [attachError, setAttachError] = useState(null); + /** An informational note about the last batch (images that went As file). */ + const [attachNotice, setAttachNotice] = useState(null); const trimmedValue = value.trimStart(); - const bashMode = attachedImages.length === 0 && attachedTextFiles.length === 0 && trimmedValue.startsWith("!"); + const bashMode = attachedImages.length === 0 && attachedTextFiles.length === 0 && attachedUploads.length === 0 && trimmedValue.startsWith("!"); const bashExcluded = bashMode && trimmedValue.startsWith("!!"); const [slashMenuOpen, setSlashMenuOpen] = useState(false); const [slashActiveIndex, setSlashActiveIndex] = useState(0); @@ -483,10 +515,17 @@ export const ChatInput = memo(forwardRef(function ChatIn const pendingImageCountRef = useRef(0); const pendingTextFileCountRef = useRef(0); const pendingTextFileBytesRef = useRef(0); + const pendingImageBytesRef = useRef(0); + const attachedUploadsRef = useRef(attachedUploads); + /** Uploads in flight, by id: a chip's removal aborts its handle. */ + const uploadHandlesRef = useRef(new Map()); + const uploadHostIdRef = useRef(uploadHostId); submissionBlockedRef.current = submissionBlocked; valueRef.current = value; attachedImagesRef.current = attachedImages; attachedTextFilesRef.current = attachedTextFiles; + attachedUploadsRef.current = attachedUploads; + uploadHostIdRef.current = uploadHostId; const insertTextAtCursor = useCallback((text: string) => { const ta = textareaRef.current; @@ -563,46 +602,100 @@ export const ChatInput = memo(forwardRef(function ChatIn }, })); - const processImageFiles = useCallback(async (files: File[]) => { - const remaining = Math.max( - 0, - MAX_ATTACHED_IMAGES - attachedImagesRef.current.length - pendingImageCountRef.current, + const patchUpload = useCallback((id: string, patch: Partial) => { + setAttachedUploads((prev) => prev.map((upload) => (upload.id === id ? { ...upload, ...patch } : upload))); + }, []); + + /** Uploads the chip's file to its host; a retry resumes at the host's offset (same id). */ + const runUpload = useCallback((upload: AttachedUpload) => { + if (!upload.file) return; + const { id, size } = upload; + let shownPercent = -1; + const handle = uploadFile(upload.file, upload.hostId, (received) => { + // One render per whole percent: the host acks up to every 16 ms. + const percent = Math.floor((received * 100) / Math.max(1, size)); + if (percent === shownPercent) return; + shownPercent = percent; + patchUpload(id, { received }); + }, id); + uploadHandlesRef.current.set(id, handle); + const settle = (patch: Partial) => { + // Removed or switched meanwhile: its abort ended it. + if (uploadHandlesRef.current.get(id) !== handle) return; + uploadHandlesRef.current.delete(id); + patchUpload(id, patch); + }; + handle.promise.then( + () => settle({ status: "done", received: size, error: null }), + (error: unknown) => settle({ status: "error", error: uploadErrorMessage(error) }), ); - const imageFiles = files - .filter((file) => file.type.startsWith("image/") && file.size <= MAX_ATTACHED_IMAGE_BYTES) - .slice(0, remaining); - if (!imageFiles.length) { - if (files.length > 0) { - setAttachError( - remaining === 0 - ? t("chatInput.attachmentImageLimit", { count: MAX_ATTACHED_IMAGES }) - : t("chatInput.attachmentImagesSkipped", { count: files.length, size: formatAttachmentBytes(MAX_ATTACHED_IMAGE_BYTES) }), - ); + }, [patchUpload]); + + /** Attaches files As file and starts their uploads: up to MAX_UPLOAD_BYTES each, MAX_UPLOADS_PER_MESSAGE in all + * (the only refusals left, spec U2). `previewUrls[i]`: an image's thumbnail, made here when missing. Returns how + * many were attached. */ + const attachAsFiles = useCallback((files: File[], previewUrls: string[] = []): number => { + const room = Math.max(0, MAX_UPLOADS_PER_MESSAGE - attachedUploadsRef.current.length); + const fitting = files.flatMap((file, i) => (file.size <= MAX_UPLOAD_BYTES ? [{ file, previewUrl: previewUrls[i] }] : [])); + const added = fitting.slice(0, room).map(({ file, previewUrl }): AttachedUpload => ({ + id: newUploadId(), + name: file.name, + size: file.size, + hostId: uploadHostIdRef.current, + file, + received: 0, + status: "uploading", + error: null, + previewUrl: previewUrl ?? (file.type.startsWith("image/") ? URL.createObjectURL(file) : null), + })); + if (fitting.length < files.length) { + setAttachError(t("chatInput.attachmentUploadTooLarge", { count: files.length - fitting.length, size: `${MAX_UPLOAD_BYTES / 1024 ** 3} GB` })); + } else if (added.length < fitting.length) { + setAttachError(t("chatInput.attachmentUploadLimit", { count: MAX_UPLOADS_PER_MESSAGE })); + } + if (added.length === 0) return 0; + // Counted at once: another batch in the same tick sees these. + attachedUploadsRef.current = [...attachedUploadsRef.current, ...added]; + setAttachedUploads((prev) => [...prev, ...added]); + added.forEach(runUpload); + return added.length; + }, [runUpload, t]); + + /** Whether `bytes` more of images (`extra` more of them) still fit the inline budget the send checks. */ + const fitsInline = useCallback((bytes: number, extra = 0): boolean => { + const images = attachedImagesRef.current; + const used = images.reduce((total, image) => total + attachedImageBytes(image), 0) + pendingImageBytesRef.current; + return images.length + pendingImageCountRef.current + extra < MAX_ATTACHED_IMAGES && used + bytes <= MAX_TOTAL_ATTACHED_IMAGE_BYTES; + }, []); + + /** Images go Inline while the message's inline budget has room; the rest go As file, with a notice. */ + const processImageFiles = useCallback(async (files: File[]) => { + const imageFiles: File[] = []; + const asFiles: File[] = []; + let inlineBytes = 0; + for (const file of files) { + if (fitsInline(inlineBytes + file.size, imageFiles.length)) { + imageFiles.push(file); + inlineBytes += file.size; + } else { + asFiles.push(file); } - return; } + const switched = attachAsFiles(asFiles); + if (switched > 0) setAttachNotice(t("chatInput.imagesAsFile", { count: switched })); + if (!imageFiles.length) return; const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; pendingImageCountRef.current += imageFiles.length; + pendingImageBytesRef.current += inlineBytes; const created: AttachedImage[] = []; try { const newImages = await Promise.all( - imageFiles.map( - (file) => - new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - const result = reader.result as string; - // result is "data:;base64," - const base64 = result.split(",")[1]; - const image = { data: base64, mimeType: file.type, previewUrl: URL.createObjectURL(file) }; - created.push(image); - resolve(image); - }; - reader.onerror = reject; - reader.readAsDataURL(file); - }) - ) + imageFiles.map(async (file) => { + const image: AttachedImage = { data: await readBase64(file), mimeType: file.type, previewUrl: URL.createObjectURL(file), file }; + created.push(image); + return image; + }), ); // The composer was cleared/sent while the reads were in flight — // drop the batch instead of re-appending stale attachments. @@ -626,29 +719,21 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachError(t("chatInput.attachmentImageReadFailed")); } finally { pendingImageCountRef.current -= imageFiles.length; + pendingImageBytesRef.current -= inlineBytes; } - }, []); + }, [attachAsFiles, fitsInline, t]); + /** Text is inlined while it fits the text budget; past it, when it turns out binary, and always for a PDF (omp reads + * it as a document; its decoded bytes are not text), it goes As file. */ const processTextFiles = useCallback(async (files: File[]) => { - const remaining = Math.max( - 0, - MAX_ATTACHED_TEXT_FILES - attachedTextFilesRef.current.length - pendingTextFileCountRef.current, - ); // In-flight batches reserve their bytes too, so two overlapping drops // cannot each fit under the aggregate budget on their own. - const { accepted: textFiles, tooLarge, overBudget } = selectTextAttachments(files, { + const { accepted: textFiles } = selectTextAttachments(files.filter((file) => file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)), { usedBytes: attachedTextFilesRef.current.reduce((total, file) => total + file.size, 0) + pendingTextFileBytesRef.current, usedSlots: attachedTextFilesRef.current.length + pendingTextFileCountRef.current, }); - // Report every dropped candidate, not just an entirely rejected batch: a - // drop of several files can lose some to the budget while accepting others. - const limitMessage = remaining === 0 && files.length > 0 - ? t("chatInput.attachmentTextFilesLimit", { count: MAX_ATTACHED_TEXT_FILES }) - : describeTextAttachmentSkip({ tooLarge, overBudget }); - if (!textFiles.length) { - if (files.length > 0) setAttachError(limitMessage ?? t("chatInput.attachmentFilesSkipped", { count: files.length })); - return; - } + attachAsFiles(files.filter((file) => !textFiles.includes(file))); + if (!textFiles.length) return; const revision = attachmentRevisionRef.current; const identityRevision = attachmentIdentityRevisionRef.current; pendingTextFileCountRef.current += textFiles.length; @@ -668,27 +753,22 @@ export const ChatInput = memo(forwardRef(function ChatIn // Binary content cannot be inlined into the prompt: NUL bytes, or // U+FFFD replacement characters left by mis-decoded binary (e.g. // UTF-16 text read as UTF-8). - const newFiles = readFiles.filter( - (file) => !file.content.includes("\u0000") && !file.content.includes("\uFFFD"), - ); - const skipped = textFiles.length - newFiles.length; + const binary = readFiles.map((file) => file.content.includes("\u0000") || file.content.includes("\uFFFD")); + const newFiles = readFiles.filter((_, index) => !binary[index]); + attachAsFiles(textFiles.filter((_, index) => binary[index])); setAttachedTextFiles((prev) => [ ...prev, ...(identityRevision !== attachmentIdentityRevisionRef.current ? newFiles : newFiles.slice(0, Math.max(0, MAX_ATTACHED_TEXT_FILES - prev.length))), ]); - setAttachError( - limitMessage - ?? (skipped > 0 ? t("chatInput.attachmentBinarySkipped", { count: skipped }) : null), - ); } catch { setAttachError(t("chatInput.attachmentTextReadFailed")); } finally { pendingTextFileCountRef.current -= textFiles.length; pendingTextFileBytesRef.current -= textFiles.reduce((total, file) => total + file.size, 0); } - }, []); + }, [attachAsFiles, t]); const processFiles = useCallback((files: File[]) => { const imageFiles = files.filter((file) => file.type.startsWith("image/")); @@ -706,21 +786,12 @@ export const ChatInput = memo(forwardRef(function ChatIn // Start the read in the click gesture: Safari requires user activation. const items = await navigator.clipboard.read(); const files: File[] = []; - let oversized = 0; for (const item of items) { const type = item.types.find((type) => type.startsWith("image/")); if (!type) continue; try { - const blob = await item.getType(type); - // Drop an oversized clipboard image here rather than handing it on. - // The picker's Files are lazy and disk-backed; a clipboard entry is - // already whole in RAM, so keeping several alive at once would hold - // the entire clipboard before any cap had run. - if (blob.size > MAX_ATTACHED_IMAGE_BYTES) { - oversized += 1; - continue; - } - files.push(new File([blob], "clipboard-image", { type })); + // One past the inline budget goes As file, as from the picker. + files.push(new File([await item.getType(type)], "clipboard-image", { type })); } catch { // One entry can disappear between the `types` snapshot and the read // (NotFoundError). Keep whatever the other items yielded. @@ -728,14 +799,7 @@ export const ChatInput = memo(forwardRef(function ChatIn } if (revision !== attachmentRevisionRef.current) return; if (files.length) processFilesRef.current(files); - else if (oversized) { - setAttachError( - t("chatInput.attachmentImagesSkipped", { - count: oversized, - size: formatAttachmentBytes(MAX_ATTACHED_IMAGE_BYTES), - }), - ); - } else setAttachError(t("chatInput.clipboardImageFailed")); + else setAttachError(t("chatInput.clipboardImageFailed")); } catch { if (revision === attachmentRevisionRef.current) setAttachError(t("chatInput.clipboardImageFailed")); } @@ -756,6 +820,7 @@ export const ChatInput = memo(forwardRef(function ChatIn return next; }); setAttachError(null); + setAttachNotice(null); }, []); const removeTextFile = useCallback((index: number) => { @@ -774,6 +839,74 @@ export const ChatInput = memo(forwardRef(function ChatIn setAttachedTextFiles([]); }, []); + /** Removing a chip aborts its upload, or has the host delete what it staged. */ + const removeUpload = useCallback((id: string) => { + const handle = uploadHandlesRef.current.get(id); + uploadHandlesRef.current.delete(id); + if (handle) handle.abort(); + else discardUpload(id); + setAttachedUploads((prev) => { + const removed = prev.find((upload) => upload.id === id); + if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl); + return prev.filter((upload) => upload.id !== id); + }); + setAttachError(null); + setAttachNotice(null); + }, []); + + const retryUpload = useCallback((id: string) => { + const upload = attachedUploadsRef.current.find((each) => each.id === id); + if (!upload?.file || upload.status !== "error") return; + patchUpload(id, { status: "uploading", error: null }); + runUpload(upload); + }, [patchUpload, runUpload]); + + /** Inline -> As file: the image's file (rebuilt from its bytes for one restored from a draft) is uploaded instead. */ + const switchImageToFile = useCallback((image: AttachedImage) => { + const file = image.file ?? new File( + [Uint8Array.from(atob(image.data), (char) => char.charCodeAt(0))], + `image.${image.mimeType.slice("image/".length)}`, + { type: image.mimeType }, + ); + if (!attachAsFiles([file], [image.previewUrl])) return; + setAttachedImages((prev) => prev.filter((each) => each !== image)); + }, [attachAsFiles]); + + /** As file -> Inline, while it fits the inline budget: its upload is dropped. */ + const switchUploadToInline = useCallback(async (upload: AttachedUpload) => { + const { id, file, previewUrl } = upload; + if (!file || !previewUrl || !fitsInline(file.size)) return; + const revision = attachmentRevisionRef.current; + pendingImageCountRef.current += 1; + pendingImageBytesRef.current += file.size; + try { + const data = await readBase64(file); + if (attachmentRevisionRef.current !== revision || !attachedUploadsRef.current.some((each) => each.id === id)) return; + const handle = uploadHandlesRef.current.get(id); + uploadHandlesRef.current.delete(id); + if (handle) handle.abort(); + else discardUpload(id); + setAttachedUploads((prev) => prev.filter((each) => each.id !== id)); + setAttachedImages((prev) => [...prev, { data, mimeType: file.type, previewUrl, file }]); + } catch { + setAttachError(t("chatInput.attachmentImageReadFailed")); + } finally { + pendingImageCountRef.current -= 1; + pendingImageBytesRef.current -= file.size; + } + }, [fitsInline, t]); + + /** After a send the uploads belong to the prompt: the chips go, what the host staged stays. Any still in flight + * (a cleared composer) is aborted. */ + const clearUploads = useCallback(() => { + for (const handle of uploadHandlesRef.current.values()) handle.abort(); + uploadHandlesRef.current.clear(); + setAttachedUploads((prev) => { + for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); + return []; + }); + }, []); + const clearInput = useCallback(() => { setValue(""); setAtQuery(null); @@ -783,12 +916,14 @@ export const ChatInput = memo(forwardRef(function ChatIn if (draftKeyRef.current && draftKeyRef.current !== draftKey) clearDraft(draftKeyRef.current); clearImages(); clearTextFiles(); + clearUploads(); + setAttachNotice(null); // Invalidate any attachment reads still in flight. attachmentRevisionRef.current += 1; if (textareaRef.current) { textareaRef.current.style.height = "auto"; } - }, [clearImages, clearTextFiles, draftKey]); + }, [clearImages, clearTextFiles, clearUploads, draftKey]); useLayoutEffect(() => { if (!draftKey || draftKeyRef.current !== draftKey) return; @@ -796,10 +931,11 @@ export const ChatInput = memo(forwardRef(function ChatIn value, images: attachedImages.map(imageToDraftImage), files: attachedTextFiles.map(textFileToDraftFile), + uploads: attachedUploadsToDraftUploads(attachedUploads), }; persistedDraftRef.current = draft; setDraft(draftKey, draft); - }, [attachedImages, attachedTextFiles, draftKey, value]); + }, [attachedImages, attachedTextFiles, attachedUploads, draftKey, value]); useLayoutEffect(() => { const previousDraftKey = draftKeyRef.current; @@ -847,6 +983,11 @@ export const ChatInput = memo(forwardRef(function ChatIn }); return [...draftFilesToAttachedFiles(draft?.files), ...added]; }); + // The same composer's uploads stay; the transferred draft's finished ones join them once. + setAttachedUploads((current) => [ + ...draftUploadsToAttachedUploads(draft?.uploads).filter((upload) => !current.some((each) => each.id === upload.id)), + ...current, + ]); setQueuedDeleteTarget(null); return; } @@ -857,6 +998,7 @@ export const ChatInput = memo(forwardRef(function ChatIn attachmentRevisionRef.current += 1; draftRecoveryIdentityRef.current = { key: draftKey }; setAttachError(null); + setAttachNotice(null); setQueuedDeleteTarget(null); if (previousDraftKey) { @@ -864,6 +1006,7 @@ export const ChatInput = memo(forwardRef(function ChatIn value: valueRef.current, images: attachedImagesRef.current.map(imageToDraftImage), files: attachedTextFilesRef.current.map(textFileToDraftFile), + uploads: attachedUploadsToDraftUploads(attachedUploadsRef.current), }); } @@ -878,6 +1021,14 @@ export const ChatInput = memo(forwardRef(function ChatIn return draftImagesToAttachedImages(draft?.images); }); setAttachedTextFiles(draftFilesToAttachedFiles(draft?.files)); + // shortcut: an upload still in flight is lost on a switch, as on a reload; keep its handle across drafts if users + // switch chats mid-upload often. + for (const handle of uploadHandlesRef.current.values()) handle.abort(); + uploadHandlesRef.current.clear(); + setAttachedUploads((prev) => { + for (const upload of prev) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); + return draftUploadsToAttachedUploads(draft?.uploads); + }); }, [draftKey, draftIdentityMove]); useLayoutEffect(() => subscribeDraftRecovery((key, recovery) => { @@ -889,6 +1040,10 @@ export const ChatInput = memo(forwardRef(function ChatIn if (images.length) { setAttachedImages((prev) => [...prev, ...draftImagesToAttachedImages(images)]); } + const uploads = draftUploadsToAttachedUploads(recovery.uploads); + if (uploads.length) { + setAttachedUploads((prev) => [...prev, ...uploads.filter((upload) => !prev.some((each) => each.id === upload.id))]); + } setAtQuery(null); setSlashMatch(null); setHistoryMenuOpen(false); @@ -918,8 +1073,11 @@ export const ChatInput = memo(forwardRef(function ChatIn }, []); useEffect(() => { + const uploadHandles = uploadHandlesRef.current; return () => { attachedImagesRef.current.forEach(revokeImagePreview); + for (const handle of uploadHandles.values()) handle.abort(); + for (const upload of attachedUploadsRef.current) if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl); }; }, []); @@ -936,6 +1094,16 @@ export const ChatInput = memo(forwardRef(function ChatIn return error !== null; }, []); + /** Send waits for every upload (spec U2): refused with a banner while one is in flight or failed. */ + const rejectsPendingUploads = useCallback((): boolean => { + const uploads = attachedUploadsRef.current; + const failed = uploads.filter((upload) => upload.status === "error").length; + const uploading = uploads.filter((upload) => upload.status === "uploading").length; + if (failed) setAttachError(t("chatInput.uploadsFailedBlock", { count: failed })); + else if (uploading) setAttachError(t("chatInput.uploadsWaiting", { count: uploading })); + return failed + uploading > 0; + }, [t]); + /** Run a client builtin. True once handled; the composer is cleared only on * success and only if it still holds what was sent (the user may have * started typing while the command ran). */ @@ -953,7 +1121,7 @@ export const ChatInput = memo(forwardRef(function ChatIn * rather than drop them. False when `msg` is not `/btw`. */ const sendSideQuestion = useCallback((msg: string, overrideText?: string): boolean => { if (!/^\/btw(\s|$)/.test(msg) || !onBuiltinCommand) return false; - if (attachedImagesRef.current.length || attachedTextFilesRef.current.length) { + if (attachedImagesRef.current.length || attachedTextFilesRef.current.length || attachedUploadsRef.current.length) { toast.error(t("btw.attachmentsUnsupported")); return true; } @@ -964,12 +1132,13 @@ export const ChatInput = memo(forwardRef(function ChatIn const handleSend = useCallback(async (overrideText?: string) => { const raw = overrideText ?? value; const msg = raw.trim(); - if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length) return; + if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) return; if (submissionBlockedRef.current || isStreaming) return; onAudioUnlock?.(); if (sendSideQuestion(msg, overrideText)) return; + if (rejectsPendingUploads()) return; const composedMessage = composeMessageWithTextAttachments(msg, attachedTextFilesRef.current); - if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && msg.startsWith("/") && onBuiltinCommand) { + if (!attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length && msg.startsWith("/") && onBuiltinCommand) { const expansion = expandWebSlashCommand(msg); if (expansion.kind === "expand" && rejectsOversizedPrompt(expansion.prompt, attachedImagesRef.current)) return; if (await runBuiltinCommand(msg, overrideText)) return; @@ -978,8 +1147,8 @@ export const ChatInput = memo(forwardRef(function ChatIn if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; const key = draftKeyRef.current; const images = attachedImagesRef.current.length ? attachedImagesRef.current : undefined; - const recovery = { text: composedMessage, images: images?.map(imageToDraftImage) }; - const pending = onSend(composedMessage, images); + const recovery = { text: composedMessage, images: images?.map(imageToDraftImage), ...uploadRecovery(attachedUploadsRef.current) }; + const pending = onSend(composedMessage, images, ...uploadArgs(attachedUploadsRef.current)); clearInput(); try { const result = await pending; @@ -991,7 +1160,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (key) recoverDraft(key, recovery); throw error; } - }, [value, isStreaming, onBuiltinCommand, onSend, clearInput, onAudioUnlock, rejectsOversizedPrompt, runBuiltinCommand, sendSideQuestion]); + }, [value, isStreaming, onBuiltinCommand, onSend, clearInput, onAudioUnlock, rejectsOversizedPrompt, rejectsPendingUploads, runBuiltinCommand, sendSideQuestion]); const { isRecording, isPaused, @@ -1431,17 +1600,19 @@ export const ChatInput = memo(forwardRef(function ChatIn if (submissionBlockedRef.current) return; const raw = overrideText ?? value; const msg = raw.trim(); - if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length) return; + if (!msg && !attachedImagesRef.current.length && !attachedTextFilesRef.current.length && !attachedUploadsRef.current.length) return; if (sendSideQuestion(msg, overrideText)) return; + if (rejectsPendingUploads()) return; const images = attachedImagesRef.current.length ? attachedImagesRef.current : undefined; + const uploads = uploadArgs(attachedUploadsRef.current); // The queue callbacks resolve false when omp refused the message: it goes - // back, text and images together, to the draft it was sent from, even if - // the user has typed or switched sessions since. + // back, text and attachments together, to the draft it was sent from, even + // if the user has typed or switched sessions since. const key = draftKeyRef.current; - const keptImages = images?.map(imageToDraftImage); + const kept = { images: images?.map(imageToDraftImage), ...uploadRecovery(attachedUploadsRef.current) }; const recoverOnFailure = (queued: Promise, text: string) => { void Promise.resolve(queued).then((ok) => { - if (ok === false && key) recoverDraft(key, { text, images: keptImages }); + if (ok === false && key) recoverDraft(key, { text, ...kept }); }); }; const files = attachedTextFilesRef.current; @@ -1463,7 +1634,7 @@ export const ChatInput = memo(forwardRef(function ChatIn if (expansion.kind === "expand") { const prompt = composeMessageWithTextAttachments(expansion.prompt, files); if (rejectsOversizedPrompt(prompt, attachedImagesRef.current)) return; - recoverOnFailure(onPromptWithStreamingBehavior(prompt, streamingBehavior, images), prompt); + recoverOnFailure(onPromptWithStreamingBehavior(prompt, streamingBehavior, images, ...uploads), prompt); clearInput(); return; } @@ -1476,27 +1647,33 @@ export const ChatInput = memo(forwardRef(function ChatIn } const prompt = composeMessageWithTextAttachments(msg, files); if (rejectsOversizedPrompt(prompt, attachedImagesRef.current)) return; - recoverOnFailure(onPromptWithStreamingBehavior(prompt, streamingBehavior, images), prompt); + recoverOnFailure(onPromptWithStreamingBehavior(prompt, streamingBehavior, images, ...uploads), prompt); clearInput(); return; } const composedMessage = composeMessageWithTextAttachments(msg, files); if (rejectsOversizedPrompt(composedMessage, attachedImagesRef.current)) return; if (mode === "steer" && onSteer) { - recoverOnFailure(onSteer(composedMessage, images), composedMessage); + recoverOnFailure(onSteer(composedMessage, images, ...uploads), composedMessage); } else if (mode === "followup" && onFollowUp) { - recoverOnFailure(onFollowUp(composedMessage, images), composedMessage); + recoverOnFailure(onFollowUp(composedMessage, images, ...uploads), composedMessage); } clearInput(); - }, [value, onPromptWithStreamingBehavior, onSteer, onFollowUp, clearInput, onAudioUnlock, t, advisorEnabled, rejectsOversizedPrompt, sendSideQuestion]); + }, [value, onPromptWithStreamingBehavior, onSteer, onFollowUp, clearInput, onAudioUnlock, t, advisorEnabled, rejectsOversizedPrompt, rejectsPendingUploads, sendSideQuestion]); // A typed message or attachment during a run is a queued follow-up — and so // is a dictation in progress: the primary button must take the same state it // would have if the composer already held text. Keep Stop as the action // while the composer is empty and nothing is being recorded. const dictationCapturing = isRecording || isPaused || isReviewing; + const hasAttachments = attachedImages.length > 0 || attachedTextFiles.length > 0 || attachedUploads.length > 0; + const uploadingCount = attachedUploads.filter((upload) => upload.status === "uploading").length; + const failedUploadCount = attachedUploads.filter((upload) => upload.status === "error").length; + const uploadsBlockSend = uploadingCount + failedUploadCount > 0; + const imageUploads = attachedUploads.filter((upload) => upload.previewUrl !== null); + const fileUploads = attachedUploads.filter((upload) => upload.previewUrl === null); const primaryActionQueuesMessage = isStreaming - && (Boolean(value.trim()) || attachedImages.length > 0 || attachedTextFiles.length > 0 || dictationCapturing) + && (Boolean(value.trim()) || hasAttachments || dictationCapturing) && Boolean(onFollowUp); // The button follows the same Settings choice as Enter: soft keyboards have no // Enter to submit with, so this button is how touch devices steer. @@ -2114,7 +2291,7 @@ export const ChatInput = memo(forwardRef(function ChatIn {compactResultText} )} - {/* Image previews */} + {/* Attachment notices and previews */} {attachError && (
(function ChatIn {attachError}
)} - {attachedImages.length > 0 && ( + {attachNotice && !attachError && ( +
+ {attachNotice} +
+ )} + {(attachedImages.length > 0 || imageUploads.length > 0) && (
{attachedImages.map((img, i) => ( -
- - -
+ switchImageToFile(img)} + onRemove={() => removeImage(i)} + /> + ))} + {imageUploads.map((upload) => ( + void switchUploadToInline(upload)} + onRemove={() => removeUpload(upload.id)} + onRetry={() => retryUpload(upload.id)} + /> ))}
)} - {attachedTextFiles.length > 0 && ( + {(attachedTextFiles.length > 0 || fileUploads.length > 0) && (
{attachedTextFiles.map((file, i) => (
(function ChatIn
))} + {fileUploads.map((upload) => ( + removeUpload(upload.id)} onRetry={() => retryUpload(upload.id)} /> + ))}
)} @@ -3596,22 +3777,24 @@ export const ChatInput = memo(forwardRef(function ChatIn type="button" className="composer-primary-action" onClick={isRecording || isPaused || isReviewing ? () => stopAndFinishDictation("send") : () => void handleSend()} - disabled={submissionBlocked || isTranscribing || !(isRecording || isPaused || isReviewing || value.trim() || attachedImages.length || attachedTextFiles.length)} - title={isRecording || isPaused || isReviewing ? t("chatInput.sendDictation") : t("chatInput.send")} + disabled={submissionBlocked || isTranscribing || uploadsBlockSend || !(isRecording || isPaused || isReviewing || value.trim() || hasAttachments)} + title={uploadsBlockSend + ? (failedUploadCount > 0 ? t("chatInput.uploadsFailedBlock", { count: failedUploadCount }) : t("chatInput.uploadsWaiting", { count: uploadingCount })) + : isRecording || isPaused || isReviewing ? t("chatInput.sendDictation") : t("chatInput.send")} style={{ display: "flex", alignItems: "center", gap: 6, - background: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || attachedImages.length || attachedTextFiles.length) ? "var(--accent-strong)" : "var(--bg-panel)", + background: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || hasAttachments) ? "var(--accent-strong)" : "var(--bg-panel)", border: "none", borderRadius: 8, - color: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || attachedImages.length || attachedTextFiles.length) ? "var(--on-accent)" : "var(--text-dim)", - cursor: submissionBlocked ? "not-allowed" : isTranscribing ? "wait" : (isRecording || isPaused || isReviewing || value.trim() || attachedImages.length || attachedTextFiles.length) ? "pointer" : "not-allowed", + color: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || hasAttachments) ? "var(--on-accent)" : "var(--text-dim)", + cursor: submissionBlocked || uploadsBlockSend ? "not-allowed" : isTranscribing ? "wait" : (isRecording || isPaused || isReviewing || value.trim() || hasAttachments) ? "pointer" : "not-allowed", fontSize: 12, fontWeight: 600, - boxShadow: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || attachedImages.length || attachedTextFiles.length) ? "var(--shadow-card)" : "none", + boxShadow: (isRecording || isPaused || isReviewing || isTranscribing || value.trim() || hasAttachments) ? "var(--shadow-card)" : "none", transition: "background var(--dur-fast) var(--ease-out-warm), box-shadow var(--dur-fast) var(--ease-out-warm)", }} > - {isTranscribing ? ( + {isTranscribing || uploadingCount > 0 ? (