Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): show queued attachment previews (#2045)
Max1f7761d9a3b5
diff --git a/docs/plans/2026-09-19-queued-attachment-previews.md b/docs/plans/2026-09-19-queued-attachment-previews.mdnew file mode 100644index 000000000..6e7f1f1fd--- /dev/null+++ b/docs/plans/2026-09-19-queued-attachment-previews.md@@ -0,0 +1,362 @@+# Queued attachment previews — implementation contract++Issue: https://github.com/avibe-bot/avibe/issues/2042+Owner authorization: "Implement issue #2042", 2026-09-19. This supersedes the earlier implementation hold recorded in the issue.+Orchestrator: ses69qdtzenet. Implementation session: sestava7bk3zw.+Base inspected: origin/master 8f09a61b03b7c2066266a05526ff0e9b61fd7b4f.++## Problem and chosen scope++A busy session already stores attachments on each queued message, but QueueRow renders only text and annotation stand-ins. A screenshot-only input can look empty or generic. The smallest complete fix is presentation plus evidence that the existing attachment path retains identity; no API, storage, dispatch, recall, or batching redesign is intended.++Design authority: avibe-docs branch `design/queued-message-attachments`, commit `5757864`, documents `docs/plans/2026-09-18-queued-message-attachments.md` and its `-handoff.md`, QMA 01–04 exports. The compact design source hash is `b80a2094c7e97a01cf81aa526e4078c4aa232a7c99d26a1a3dc4d0bd8ec865a0`. Read the isolated design worktree, not the primary design.pen, which does not contain these frames.++## Behavior contract++- Render `content.attachments` in source order beside text, within the existing queue row. All admitted attachments remain discoverable even when text is empty.+- The recognition image occupies 20 by 20 CSS pixels with cover cropping. Loading and unavailable states preserve that box. A collapsed attachment row has the same 36px height as a text-only row. Targets may use surrounding row padding without overlapping neighboring targets.+- Show at most three inline attachments on desktop, reducing capacity on narrow layouts (two at 390px) while retaining meaningful text and action width. An explicit `+N` discloses the remainder and offers collapse; text expansion does not disclose attachments.+- File chips use the same compact height, reducing to a type icon where needed. A touch/keyboard action must expose the complete filename even for unsupported preview types, a single attachment, and an unavailable image. Hover alone does not satisfy this property.+- Preview through existing media viewers. Queued image inspection is single-image mode and must remain so even when the same URL appears in the delivered transcript or the message transitions while open. Do not add queue items to the transcript gallery.+- Automatic media access uses the existing same-origin proxy policy. An arbitrary remote URL must not be fetched automatically. Explicit click-through behavior follows delivered attachments.+- Preserve annotation title/quote context. Available image previews replace the generic screenshot stand-in without hiding the annotation's identity.+- Viewing, disclosure, and text expansion do not remove, send, recall, reorder, or mutate a queued message. Message count, original remove ID, Send now behavior, and text-only recall eligibility are unchanged.+- Queue scroll body stays capped at 128px and composer remains reachable.+- Use existing tokens, primitives, and EN/ZH localization. No new dependency.++## Allowed boundaries++Implementation owns queue rendering, a small attachment component if needed, the existing viewer boundary when necessary for explicit single-image mode, translations, focused component tests, isolated browser fixtures, and this plan. Backend/API production code is out of scope unless a demonstrated defect requires a new decision. Existing API tests may be extended to verify the attachment identity contract.++## Acceptance and evidence++1. Every attachment on an admitted pending message is discoverable and inspectable with or without authored text.+2. Collapsed row geometry remains equal across attachment types, load states, themes, and supported widths; attachment disclosure is the only attachment action that expands the row.+3. Read-only preview operations preserve queue identity, attachment ordering, and all existing delivery actions.+4. Reload, switching away and back, and queue-to-transcript rendering preserve the same attachment identities without loss or duplication. API projection and dispatch evidence complements browser fixture evidence.+5. Arbitrary remote URLs are never auto-fetched; unavailable media stays identifiable without being described as a failed send.++Run focused Vitest tests, relevant lint, and the UI build. Use the existing hermetic Playwright fixture pattern for real desktop/mobile layout measurements, keyboard/touch interaction, viewer isolation, load failure, and the identity transitions above. Reuse existing backend upload/queue tests or add one focused contract case if coverage is missing; do not claim backend integrity from UI fixtures alone.++Owner acceptance after authorized deployment: queue text with an image, an image-only message, and mixed attachments while a session is busy; inspect inline and overflow previews; reload and return to the session; send the queue and compare delivered files; verify the composer remains usable on mobile. Workspace AGENTS.md names the cloud acceptance instance and retires this owner's local Incus workflow. Do not restart the user's local service or overwrite a shared test deployment as part of isolated verification.++## Delivery++One PR against master, closes #2042. Exact-head Codex review, all expected CI green, and zero unresolved threads required. The lane owns its fix watch; the orchestrator independently gates and checks scope. No merge or shared deployment without owner instruction. Record material deviations and validation evidence below as they land.++## What was built++- `ui/src/lib/messageAttachments.ts` reads `content.attachments` and decides, on+ its own, which URL may become an `<img>`: only a same-origin media-proxy URL,+ via the existing `isProxyMediaUrl`. The rule is a safety property, so it lives+ where a test can hold it without rendering a row. Round 2 made this the one+ read boundary for every attachment surface (see below).+- `ui/src/components/workbench/QueuedAttachments.tsx` draws the inline group and+ the disclosed remainder. Every target sits in the same 24px band the row's+ existing icon buttons occupy, with a 20px visual inside it, so no attachment —+ of any type, in any load state — can make a collapsed row taller. Capacity is+ chosen in CSS (three at `sm` and above, two below) with one `+N` per+ breakpoint, so `display:none` also keeps the hidden variants out of the tab+ order and the markup stays deterministic without a resize listener.+- `QueueRow` renders the group and the sheet as *siblings* of its text control,+ never children, so no preview or disclosure click can reach the expand/collapse+ handler. `flex-wrap` is added to the row only while disclosed.+- A wordless queued message takes its line from its files (`first filename`, or+ `X and N more`), which covers both the annotation-screenshot row and a plain+ image-only row; the generic "Screenshot" stand-in is suppressed only when at+ least one attachment actually renders. `annotationStandIn()` is untouched.+- `ImageViewerOpenOptions.isolated` makes single-image mode a *stated* property+ of the open call rather than an inference from the URL's absence from the+ gallery — the queue strip passes it, and the viewer records it in its own state+ at open time, so a gallery that grows under an open viewer cannot hand it+ paging controls.+- A failed image keeps its 20px slot, says so in its accessible name, and routes+ its click to the file viewer, which titles itself with the whole filename even+ for a type it cannot render. Same for a chip: the full name is one action away,+ not hover-only.++Deviation from the contract as written: none. No backend production change was+needed — the projection already carries the attachments, now proven below.++## Evidence++- Focused component tests: `ui/src/components/workbench/ChatQueueRow.test.tsx`+ (23 cases) and `ui/src/components/ui/image-viewer.test.tsx` (5 cases, including+ isolation surviving a gallery that grows under an open viewer). With the i18n+ and annotation suites: 64 tests across 7 files, all passing.+- Browser evidence: `npm run test:queue-attachments` — 22 tests, desktop and+ iPhone 13, all passing. Real `boundingBox` measurements (20px visual in a 24px+ target, row-height parity across all five row types, 128px queue body with the+ composer on screen), per-width capacity and matching `+N`, keyboard tab order+ and Enter-to-disclose without touching the text control's `aria-expanded`, a+ real tap on a touch device, viewer isolation against a gallery that *contains*+ the queued URL, and a genuinely aborted image request rather than a test-only+ failure prop.+- API contract: `tests/test_ui_session_stream.py::test_queued_projection_carries_the_uploaded_file_identity`+ — a real upload, a send that settles to `queued`, and the same+ `url` / `name` / `kind` / `mime` on both the live queue read and the bootstrap+ reload path, with the token still resolving to the uploaded bytes through+ `resolve_attachment_specs`. Full module: 65 passed.+- `npm run lint` (no baseline drift), `npm run typecheck:tests`, `npm run build`,+ `ruff check` on the changed Python file: all clean.++Residual manual checks, not covered here: light/dark theme parity was not+measured in the browser fixture (the fixture runs one theme); real+`/api/media/...` bytes and real annotation screenshots were served by route+fulfilment rather than by a running service; owner acceptance on a deployed+instance is still outstanding.++## Review round 1 — head f1e97c0c, Codex review 5253087669++One findings-bearing head. Three P2 findings, all verified against the code+before acting, all three a distinct root-cause class, so no circuit-breaker+threshold applies. The orchestrator independently re-inventoried the same three+and withdrew a fourth, alleged duplication in the disclosed sheet: the expanded+branch *replaces* the inline previews, so the sheet lists each attachment once.+No slicing or deletion was introduced for that withdrawn finding.++1. **Admitted attachment shape normalization.** Two producers write+ `content.attachments`: a Web upload records `{url, mime, kind}` (the proxy URL+ is minted at upload time), an IM inbound records `{token, name, mimetype,+ size}` (`core/handlers/message_handler`) and leaves the URL to the renderer.+ `public_delivery_payload` passes `content` through verbatim, so the second+ shape reached the queue as a chip with no URL behind it — a screenshot pasted+ into Feishu arrived nameless and unopenable. Fixed in `readQueuedAttachments`,+ which now mints `/api/media/<token>` when no URL is present and reads+ `mimetype` beside `mime`. The token is percent-encoded, which is what makes+ the minted URL satisfy `isProxyMediaUrl` by construction rather than by+ assumption. No backend change: the read boundary already owned this decision.+2. **Disclosure focus lifecycle.** The expanded branch mounted a different+ control in place of the `+N` the user had just activated, so browser focus+ fell to the document. Both width-specific controls now hold their position+ across the toggle and are relabelled in place; a row disclosed at a narrow+ width also keeps a way back after the window widens.+3. **Media action routing by URL trust.** A non-proxy URL was being handed to the+ in-app file viewer, which refuses to fetch a third-party host and can only+ answer "preview failed". It now uses the same explicit external link a+ delivered attachment uses (`FileCard`: `target="_blank" rel="noopener+ noreferrer"`), with the URL passed through untouched so a signed query still+ verifies. Nothing is fetched to paint the row.++Round-1 evidence: `ChatQueueRow.test.tsx` grows to 28 cases — focus retention at+both capacities, the external link including a signed query, the IM token shape,+and the token escape that keeps a minted URL inside the proxy route. The browser+suite grows to 14 cases x 2 projects = 28, adding two fixture rows (a signed+third-party link, an IM token pair): real focus assertions through expand and+collapse, a popup whose URL is byte-for-byte the signed one with a request+counter proving the row fetched nothing, and a token-minted thumbnail decoded to+`naturalWidth > 0`. Full UI unit suite 4561 passed / 321 files; `npm run lint`+with no baseline drift; `typecheck:tests` and `npm run build` clean.++Not changed, reported instead: `file-viewer-modal.tsx` builds its download href+as `${mediaUrl}?download=1` inline rather than through `mediaDownloadHref`, which+already handles an existing query. Pre-existing, unrelated to this PR, and after+fix 3 unreachable from the queue.++Superseded: this section originally recorded the delivered transcript renderer's+token-only attachment loss as out of this lane's scope. The orchestrator traced+the same root cause through the delivery projection and extended the scope to a+shared read boundary; round 2 below is that decision and its evidence.++## Review round 2 — supplemental scope, head 43475cca++Head `f1e97c0c` remains the only findings-bearing head: Codex review 5253087669,+three classes, all three replied to and resolved. Head `43475cca` took a clean+Codex pass ("Didn't find any major issues"). No circuit-breaker threshold applies.+An independent read-only reviewer's focus, token-shape and external-URL+observations name those same three root causes and add no reviewed head; reviewed+heads are counted from a review's own commit, not from `ReviewComment.commit`,+which moves with the diff.++The orchestrator then reproduced two further defects in an isolated pinned-head+copy and granted a bounded supplemental scope. Both are measurements, not+inferences, and both are now covered by tests that fail without the fix.++4. **One read boundary instead of three.** The queue row, the transcript row and+ the lightbox gallery each re-derived "is this an image, and may we fetch it"+ from the raw record. Round 1 fixed the queue's copy only, which is not enough+ for the contract's identity property: the projection passes `content` through+ verbatim, so a token-shaped attachment that the queue could now draw still+ disappeared from the transcript, which read `url` directly and skipped the row.+ `queuedAttachments.ts` became `messageAttachments.ts` — a neutral name for what+ it now is — and all three surfaces read through it. `width`/`height` cross the+ boundary so the transcript still reserves its box; source order is unchanged;+ the gallery's membership rule is `att.image`, so a third-party URL still cannot+ enter a list the viewer pages through; and the gallery is still built from the+ transcript alone, so a queued preview remains the isolated view it opens as.+ Reported and deliberately not built: no new flow for a record carrying neither+ URL nor token. The queue keeps its existing inert chip and the transcript keeps+ skipping it — no admitted producer writes that shape.+5. **Wrapped targets overlapping.** Measured at 390px: two stacked 24px bands 4px+ apart, each extended 6px above and below by `TARGET`'s `::after`, overlap by+ 8px — `elementFromPoint` three pixels under one thumbnail returned the file on+ the next line. The extensions are what make the target 36px for a finger, so+ the fix is the sheet's row gap, not the targets: 12px, which is exactly what+ two 6px extensions need to meet without crossing, and the same geometry the+ disclosure-to-sheet boundary already had. The 20px visual, the 24px band and+ the 36px collapsed row are unchanged. The separately reported disclosure-to-+ sheet overlap was measured at a 12px gap and is not a defect; nothing there+ was changed.+6. **A filename that could not be read.** `FileViewerModal`'s title used+ `truncate`: measured after a real mobile-emulated tap, `clientWidth` 220 against+ `scrollWidth` 653 with an ellipsis. For an unsupported type that title is the+ only place the name exists — the body can only say it cannot render the file —+ and a touch user has no hover to fall back on, so the complete name was+ unreachable. The title now wraps (`break-words`, which also breaks an unbroken+ run); the header is `items-start` and `shrink-0` so the icon and actions stay+ on the first line and the scrolling body is never squeezed by it. Nothing else+ in the modal changed — the pre-existing `?download=1` construction is still+ only reported.+7. **Whitespace-only text.** The row asked `!item.text`, so a stray space or a+ newline left by a paste counted as authored words and suppressed the filename+ summary, leaving a blank line. Judged on the trimmed value now, the same way+ empty text is judged elsewhere. The stored text is untouched; this decides what+ is shown, not what was written.++Round-2 evidence: `messageAttachments.test.ts` (8 cases) holds the boundary on its+own — both producer shapes, source order, dimensions, the token escape, the+gallery's membership rule, and what is not an attachment.+`MessageAttachmentIdentity.test.tsx` (4 cases) renders the same token-shaped image+and log through `QueueRow` and `MessageRow`: the same URL before and after+delivery, the log opened at the URL the delivered one links to, the uploader's+800x600 box still reserved, and no `<img>` at a third-party host on either+surface. `ChatQueueRow.test.tsx` grows to 31 with the whitespace cases. The+browser suite grows to 17 cases x 2 projects = 34, adding three fixture rows (20+attachments that genuinely wrap at both widths, a long unsupported filename, a+failed image with a long name): the wrapped-target test hit-tests the pixels just+outside each band and, with the 4px gap restored, reproduces the orchestrator's+finding exactly — a point below `wrap01.png` resolving to a `.log` on the next+line — then passes at 12px; the title tests measure the rendered box rather than+asserting text presence, requiring no horizontal clipping at any width and a+genuine wrap where one line cannot hold the name.++Full UI unit suite 4575 passed / 323 files; `npm run lint` with no baseline drift;+`typecheck:tests` and `npm run build` clean.++## Review round 3 — circuit breaker, head 9776b729++### Ledger++Codex reviews on PR #2045, counted by each review's own commit / originalCommit+rather than the mutable `ReviewComment.commit`:++| head | Codex evidence | findings |+| --- | --- | --- |+| `f1e97c0c09` | review 5253087669 | 3 — normalization, disclosure focus, URL trust |+| `43475ccaba` | issue comment 5736966752 | 0 — clean pass |+| `9776b729fc` | review 5253281275 | 1 — disclosure focus again (4051258561) |++Threads: 4 total, single page. Three resolved (two flagged outdated by the file+rename, not withdrawn); `PRRT_kwDOPbFPYs6j6qYW` unresolved and carrying the new+finding.++The focus class therefore appears on two findings-bearing heads. The intervening+clean pass does not reset the count — that head simply was not read for this+state. The breaker tripped, the lane stopped before any further edit, and the+orchestrator discharged it with the bounded decision recorded below. A future+repeated-class finding must stop again; this is not a waiver.++### Root cause of the whole class++Focus ownership was attached to a *layout's* DOM node instead of to one logical+disclosure action. Capacity was chosen in CSS, so one logical control existed as+two elements — `sm:hidden` and `hidden sm:flex` — and the third inline slot+existed as a `hidden sm:flex` wrapper. Two consequences, both reproduced in a+browser on an isolated archive of `9776b729` with exactly three attachments:++- Crossing the breakpoint turns the focused element into `display:none`. The+ browser blurs it and CSS cannot hand focus to the replacement: 390px expanded+ with focus on *Collapse attachments*, widened to 1024px, gives+ `document.activeElement === BODY`.+- The desktop control's mount condition was still `expanded || total > 3`, so at+ exactly three attachments collapsing from it unmounted it — the original+ `f1e97c0c` defect, alive in one region.++Round 1 fixed "unmounted on toggle" and asserted `activeElement` across expand and+collapse at each capacity, but its desktop case used `total = 5`, where the mount+condition is true regardless of `expanded`. The assertion passed for a reason that+does not generalise. jsdom has no media queries, so the breakpoint half was+invisible to every unit test by construction; it needs the browser suite, and the+browser suite asserted focus across both toggles but never across a viewport+change. The contract also named no focus destination for a control that+legitimately ceases to exist.++This is a local rendering/lifecycle defect. It is not a data-model or queue+redesign.++### Focus fallback contract++- One stable interactive disclosure button per row, its count and accessible name+ matching the current inline capacity. The same DOM element is retained whenever+ expand/collapse or a breakpoint change leaves a disclosure action available. Two+ focusable controls handing off between them is not an acceptable shape.+- When this control holds focus and a user action or a capacity change makes it+ unnecessary — `total = 3`, wide and collapsed — focus moves to the row's+ existing text control before the button is removed. The row text is the stable+ in-row inspection anchor. Focus never goes to Remove/Send and never falls to+ `document.body`; no empty `+0` control and no invisible focused element.+- The adjacent case in the same class is closed the same way: if narrowing drops+ the focused third inline attachment, focus moves to that same row-text anchor.+- Surviving attachment and disclosure nodes keep focus. Expanding or collapsing+ never duplicates an attachment. Focus that belongs to something outside this+ group is never moved. The original message removal/flush lifecycle is outside+ this local control policy.++### Scope decision++Allowed: `QueuedAttachments.tsx`, `QueueRow`'s text ref in `ChatPage.tsx`, the+focused tests and browser fixture, this document, and a small local capacity hook.+A `matchMedia('(min-width: 640px)')` **change** listener is explicitly approved as+the one authoritative capacity projection; the earlier in-code note rejecting a+resize listener conflated that with element measurement and per-pixel resize+handling, and is not a contract constraint. Still excluded: `ResizeObserver`,+layout remeasurement, any generalized focus framework, new dependencies, backend+or storage changes, and any other UI redesign. Capacity stays 2/3, and the compact+geometry, `+N` count, keyboard/touch behavior and i18n keys are unchanged.++### What round 3 built++Capacity became one number instead of two mirrored sets of classes. A+`matchMedia('(min-width: 640px)')` change listener holds `2` or `3` in state, and+that number drives both how many previews the collapsed line renders and whether+the disclosure has anything left to disclose. The disclosure is a single element+in a fixed child position, so React keeps the same DOM node — and therefore the+browser keeps focus on it — across expand, collapse and breakpoint changes alike.+The listener is not element measurement: it fires twice per crossing for the whole+page, reads no geometry, and does not scale with the number of queued rows.++Focus ownership is captured inside that listener (and inside the toggle handler),+because that is the last moment at which "who has focus right now" is still+answerable: once React has committed, a removed element has already taken focus to+the document with it. A `useLayoutEffect` then checks whether focus survived+inside the group; only if it did not does it call `onFocusEscape`, which+`QueueRow` wires to `.focus()` on its existing row-text control. The flag is set+nowhere else, so a group that never owned focus cannot take it from whoever does.++`QueueRow` gained a ref on the row-text element it already rendered. No new+control, no new state, no focus framework.++### Round 3 evidence++- 46 focused unit tests, including a controllable `matchMedia` mock that emits a+ real `change` event — jsdom has no media queries, which is why the CSS-driven+ half of this defect was invisible to every earlier unit test by construction.+ Eight of them cross the `sm` boundary in both directions.+- 48 browser tests across desktop (1280) and mobile (390), covering 639/640 exactly,+ a `data-focus-probe` stamp that proves the disclosure is the *same node* after a+ real resize, `activeElement` and Tab-continuation assertions for each case where a+ control ceases to exist, and the pre-existing geometry, hit-target and viewer tests.+- Both new guard families were mutation-proved: removing the focus transfer fails+ exactly the three row-text-anchor tests; forcing node replacement with a keyed+ remount fails exactly the two identity tests plus the reported sequence. The+ tests hold the invariant, not the mechanism.+- Lint (baseline, no drift), `tsc -b`, e2e tsconfig and `vite build` all clean.++## Status++- [x] Owner instruction and compact design recovered.+- [x] Isolated implementation branch created from current origin/master.+- [x] Implementation and focused validation.+- [x] Browser and API contract evidence.+- [ ] Exact-head Codex review and CI gate.+- [ ] Owner-approved merge and deployed acceptance.diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex e72c37361..7a45036bb 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -425,6 +425,105 @@ def test_workbench_dispatch_propagates_attachment_and_resolved_identity(assert Path(payload["files"][0]["path"]).read_bytes() == b"attachment-bytes"+def test_queued_projection_carries_the_uploaded_file_identity(isolated_state, tmp_path):+ """A queued message names the file it is waiting to send, in the shape the+ queue strip draws (issue #2042).++ The strip renders a thumbnail only for a same-origin ``/api/media/<token>``+ URL, and resolves the rest from ``content.attachments``. That makes three+ things a backend contract rather than a browser detail: the upload hands back+ that URL and a ``kind``, the queued projection still carries them on both the+ live queue read and the reload path, and the same token still resolves to the+ uploaded bytes — so the file previewed in the queue is the file that reaches+ the turn when it flushes.+ """++ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)+ client = app.test_client()+ headers = csrf_headers(client, "http://127.0.0.1:15131")+ upload = client.post(+ f"/api/sessions/{session_id}/attachments",+ data={"upload_id": "upload-id-queued-1"},+ files={"file": ("annotation-region.png", b"queued-image-bytes", "image/png")},+ headers=headers,+ base_url="http://127.0.0.1:15131",+ )+ assert upload.status_code == 201+ uploaded = upload.get_json()+ # Same-origin media proxy, not a remote URL: this is the one form the queue+ # row is allowed to put in an <img src>.+ assert uploaded["url"] == f"/api/media/{uploaded['token']}"+ assert uploaded["kind"] == "image"+ assert uploaded["name"] == "annotation-region.png"++ async def dispatch(payload):+ settled = _settle_reserved_delivery(payload, state="queued")+ return {+ "status_code": 202,+ "body": {"ok": True, "queued": True, "delivery_state": settled["state"]},+ }++ sent_attachment = {+ "token": uploaded["token"],+ "name": uploaded["name"],+ "mime": uploaded["mime"],+ "size": uploaded["size"],+ "kind": uploaded["kind"],+ "url": uploaded["url"],+ }+ with patch("vibe.internal_client.dispatch_async", AsyncMock(side_effect=dispatch)):+ response = client.post(+ f"/api/sessions/{session_id}/messages",+ json={"text": "", "content": {"text": "", "attachments": [sent_attachment]}},+ headers=headers,+ base_url="http://127.0.0.1:15131",+ environ_base={"REMOTE_ADDR": "127.0.0.1"},+ )+ assert response.status_code == 202+ assert response.get_json()["queued"] is True++ def queued_attachment(body: dict) -> dict:+ assert len(body["queued"]) == 1+ content = body["queued"][0]["content"]+ assert len(content["attachments"]) == 1+ return content["attachments"][0]++ # The live queue read and the reload path project the same identity — an+ # image-only queued row stays identifiable across a refresh.+ live = client.get(f"/api/sessions/{session_id}/queue")+ assert live.status_code == 200+ assert queued_attachment(live.get_json()) == sent_attachment++ with patch(+ "vibe.api.get_vibe_agents",+ return_value={"agents": [], "default_agent_name": None},+ ):+ bootstrap = client.get(f"/api/sessions/{session_id}/bootstrap")+ assert bootstrap.status_code == 200+ assert queued_attachment(bootstrap.get_json()) == sent_attachment++ # The previewed URL is fetchable same-origin, and the token the preview was+ # drawn from is the one the flush resolves into the agent turn.+ media = client.get(uploaded["url"])+ assert media.status_code == 200+ assert media.content == b"queued-image-bytes"++ from core.workbench_media import resolve_attachment_specs+ from storage.db import create_sqlite_engine++ with create_sqlite_engine().connect() as conn:+ specs = resolve_attachment_specs(+ conn,+ session_id=session_id,+ attachments=[queued_attachment(live.get_json())],+ )+ assert len(specs) == 1+ assert specs[0]["name"] == "annotation-region.png"+ assert Path(specs[0]["path"]).read_bytes() == b"queued-image-bytes"++def test_route_reads_the_materialized_message_id_for_a_merged_batch(isolated_state,tmp_path,diff --git a/ui/e2e/queue-attachments/README.md b/ui/e2e/queue-attachments/README.mdnew file mode 100644index 000000000..750df92ff--- /dev/null+++ b/ui/e2e/queue-attachments/README.md@@ -0,0 +1,29 @@+# Queued Attachment Previews Browser Regression++From `ui/`, install the existing Playwright Chromium browser with+`npx playwright install chromium`, then run `npm run test:queue-attachments`.++The command typechecks the fixture and tests, starts a dedicated Vite server on+loopback port 5216, and runs desktop and mobile Chromium in isolated browser+contexts. The real `QueueStrip` receives in-memory queued messages, and every+`/api/media/...` request is fulfilled by the test — including one deliberate+abort, which is how a failed image load is produced without a second code path.+No Avibe backend, credentials, or persistent application state is used.++The tests verify that a queued image paints at 20x20 and centred, that a row+with attachments is exactly as tall as a text-only row in every state, that the+inline run is capped at three attachments on desktop and two at 390px with a+`+N` that matches the width, that disclosure adds a second line and collapse+restores the original height, that the disclosed sheet lists every file in+order, that a queued image opens in a single-image viewer even though the+fixture's gallery contains the same URL, that an unavailable image keeps its+slot and surrenders its full filename to a tap, that the keyboard reaches the+previews in reading order and can work the disclosure without expanding the+message text, that inspecting attachments leaves the queue's rows, order, and+count untouched, and that the queue body stays at 128px with the composer on+screen. Failed traces are written under `e2e/.artifacts/queue-attachments/`.++For interactive inspection on a regular Vite dev server, open+`/e2e/queue-attachments/fixture.html`. Media URLs 404 there unless a backend is+running, which is itself the unavailable-image state. These fixtures are not+included in production builds.diff --git a/ui/e2e/queue-attachments/fixture.html b/ui/e2e/queue-attachments/fixture.htmlnew file mode 100644index 000000000..4fb7cf546--- /dev/null+++ b/ui/e2e/queue-attachments/fixture.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Queued Attachment Previews</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./fixture.tsx"></script>+ </body>+</html>diff --git a/ui/e2e/queue-attachments/fixture.tsx b/ui/e2e/queue-attachments/fixture.tsxnew file mode 100644index 000000000..7bd93b23d--- /dev/null+++ b/ui/e2e/queue-attachments/fixture.tsx@@ -0,0 +1,139 @@+import { useState } from 'react';+import { createRoot } from 'react-dom/client';++import { QueueStrip } from '../../src/components/workbench/ChatPage';+import { FileViewerProvider } from '../../src/components/ui/file-viewer';+import { ImageViewerProvider } from '../../src/components/ui/image-viewer';+import type { WorkbenchMessage } from '../../src/context/ApiContext';+import { ThemeProvider } from '../../src/context/ThemeProvider';+import '../../src/i18n';+import '../../src/index.css';++// The real queue strip with real attachment data, in a column the width of the+// chat one. Nothing here reaches an Avibe service: every `/api/media/...` request+// is answered by the spec's own route handler, which is also how a broken image+// is produced without inventing a second code path for failure.++const noop = () => undefined;++const media = (id: string, name: string, over: Record<string, unknown> = {}) => ({+ url: `/api/media/${id}`,+ name,+ kind: 'image',+ mime: 'image/png',+ ...over,+});++const queued = (id: string, text: string, attachments?: unknown[]): WorkbenchMessage =>+ ({+ id,+ type: 'queued',+ author: 'user',+ source: 'user',+ text,+ content: attachments ? { attachments } : {},+ metadata: {},+ created_at: '2026-09-19T00:00:00Z',+ }) as WorkbenchMessage;++const FIVE = [+ media('med_1', 'one.png'),+ media('med_2', 'two.png'),+ media('med_3', 'three.png'),+ { url: '/api/media/med_4', name: 'release-notes-2026-09.pdf', mime: 'application/pdf' },+ { url: '/api/media/med_5', name: 'console-log.txt', mime: 'text/plain' },+];++// The signed third-party link a delivered attachment can carry: not ours to+// fetch, and not ours to rewrite either — the query is part of the signature.+const SIGNED = 'https://files.example.com/spec.pdf?sig=abc123&expires=1789';++// Enough attachments that the disclosed sheet genuinely wraps onto several lines+// at BOTH widths — stacked targets are the only place their vertical extents can+// collide, and one line can never show that.+const WRAP = [+ ...Array.from({ length: 10 }, (_, i) => media(`med_w${i + 1}`, `wrap${String(i + 1).padStart(2, '0')}.png`)),+ ...Array.from({ length: 10 }, (_, i) => ({+ url: `/api/media/med_wf${i + 1}`,+ name: `wrap-attachment-${i + 11}.log`,+ mime: 'text/plain',+ })),+];++// A name no header can fit on one line, on a type no preview can render: the+// viewer's title is then the only place the filename exists at all, and a touch+// user has no hover to fall back on.+const LONG_FILE = 'q3-2026-customer-onboarding-migration-runbook-final-reviewed-v12.unknown';+const LONG_IMAGE = 'q3-2026-customer-onboarding-migration-runbook-screenshot-final-v12.png';++const QUEUE: WorkbenchMessage[] = [+ queued('q-text', 'A queued message with no files at all'),+ queued('q-image', '', [media('med_1', 'annotation-region.png')]),+ queued('q-mixed', 'Compare these against the spec', FIVE),+ queued('q-broken', '', [media('med_broken', 'console-log.png')]),+ queued('q-file', '', [{ url: '/api/media/med_5', name: 'console-log.txt', mime: 'text/plain' }]),+ queued('q-remote', '', [{ url: SIGNED, name: 'spec.pdf', mime: 'application/pdf' }]),+ // What an IM inbound actually writes (core/handlers/message_handler): a media+ // token and a mimetype, with the URL left to whoever renders it.+ queued('q-token', '', [+ { token: 'med_im1', name: 'feishu-screenshot.png', mimetype: 'image/png', size: 4096 },+ { token: 'med_im2', name: 'trace.log', mimetype: 'text/plain', size: 12 },+ ]),+ queued('q-wrap', '', WRAP),+ queued('q-longname', '', [+ { url: '/api/media/med_long', name: LONG_FILE, mime: 'application/octet-stream' },+ ]),+ // The same unreadable-name problem arriving the other way: an image that fails+ // to load hands its click to the very same viewer.+ queued('q-longbroken', '', [media('med_broken_long', LONG_IMAGE)]),+ // Exactly the count at which the disclosure is needed on one side of the `sm`+ // boundary and meaningless on the other: three hides one below 640px and hides+ // nothing above it. That is where a control legitimately ceases to exist, so it+ // is where focus has to be handed somewhere deliberate.+ queued('q-three', '', [+ media('med_1', 'first.png'),+ media('med_2', 'second.png'),+ media('med_3', 'third.png'),+ ]),+];++// The transcript gallery deliberately CONTAINS the queued image, so the spec can+// show that a queued preview opens on its own because it was asked to — not+// because its URL happened to be absent.+const GALLERY = ['/api/media/med_1', '/api/media/med_2'];++export function Fixture() {+ const [queue, setQueue] = useState(QUEUE);+ const [sent, setSent] = useState(0);+ return (+ // ThemeProvider is what the app puts above the chat, and the file viewer's+ // text renderer reads the theme — so a fixture without it would fail on a+ // file type the product handles perfectly well.+ <ThemeProvider>+ <ImageViewerProvider images={GALLERY}>+ <FileViewerProvider>+ <div className="flex h-dvh flex-col bg-background text-foreground">+ <div className="min-h-0 flex-1 overflow-y-auto p-4 text-[12px] text-muted">+ Transcript stand-in — the queue strip below is the surface under test.+ </div>+ <div data-testid="queue-fixture" data-sent={sent}>+ <QueueStrip+ queue={queue}+ onRemove={(id) => setQueue((rows) => rows.filter((row) => row.id !== id))}+ onRecall={noop}+ onSendNow={() => setSent((n) => n + 1)}+ />+ </div>+ {/* The composer's place in the layout: the strip must never push it+ off-screen, which is the reason the queue body is capped at all. */}+ <div data-testid="composer" className="shrink-0 px-4 py-3 md:px-8">+ <div className="mx-auto h-11 w-full max-w-[1080px] rounded-xl border border-border bg-surface-1" />+ </div>+ </div>+ </FileViewerProvider>+ </ImageViewerProvider>+ </ThemeProvider>+ );+}++createRoot(document.getElementById('root')!).render(<Fixture />);diff --git a/ui/e2e/queue-attachments/previews.spec.ts b/ui/e2e/queue-attachments/previews.spec.tsnew file mode 100644index 000000000..f58ee5074--- /dev/null+++ b/ui/e2e/queue-attachments/previews.spec.ts@@ -0,0 +1,621 @@+import { expect, test, type Locator, type Page } from '@playwright/test';++/**+ * Queued attachment previews, measured in a browser rather than inferred from+ * class names (issue #2042; contract:+ * docs/plans/2026-09-19-queued-attachment-previews.md).+ *+ * The geometry half needs a browser specifically. "A row with files is exactly+ * as tall as a row without" is a claim about resolved boxes: the thumbnail, the+ * chip, the `+N` pill and the row's own icon buttons are four independently+ * sized things sharing one line, and the breakpoint deciding how many of them+ * are drawn is a media query. Source alone answers neither question.+ *+ * The suite runs at a desktop width and at 390px, and every capacity assertion+ * states which of the two it is about.+ */++// A 1x1 PNG. Every allowed preview resolves to this, so a thumbnail that paints+// proves the row asked for its own URL — no byte of it comes off the network.+const PNG = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+ 'base64',+);++const META: Record<string, { name: string; content_type: string; ext: string }> = {+ med_1: { name: 'annotation-region.png', content_type: 'image/png', ext: 'png' },+ med_2: { name: 'two.png', content_type: 'image/png', ext: 'png' },+ med_3: { name: 'three.png', content_type: 'image/png', ext: 'png' },+ med_4: { name: 'release-notes-2026-09.pdf', content_type: 'application/pdf', ext: 'pdf' },+ med_5: { name: 'console-log.txt', content_type: 'text/plain', ext: 'txt' },+ med_im1: { name: 'feishu-screenshot.png', content_type: 'image/png', ext: 'png' },+ med_im2: { name: 'trace.log', content_type: 'text/plain', ext: 'log' },+ med_long: {+ name: 'q3-2026-customer-onboarding-migration-runbook-final-reviewed-v12.unknown',+ content_type: 'application/octet-stream',+ ext: 'unknown',+ },+};++const LONG_FILE = 'q3-2026-customer-onboarding-migration-runbook-final-reviewed-v12.unknown';+const LONG_IMAGE = 'q3-2026-customer-onboarding-migration-runbook-screenshot-final-v12.png';++// The fixture's queue, in order. Addressing rows by position rather than by text+// is what keeps the image-only rows — which have no text of their own — reachable.+const ORDER = [+ 'q-text',+ 'q-image',+ 'q-mixed',+ 'q-broken',+ 'q-file',+ 'q-remote',+ 'q-token',+ 'q-wrap',+ 'q-longname',+ 'q-longbroken',+ 'q-three',+];+const rowIndex = (id: string) => ORDER.indexOf(id);++const DESKTOP_CAPACITY = 3;+const NARROW_CAPACITY = 2;+const capacityOf = (page: Page) =>+ page.viewportSize()!.width >= 640 ? DESKTOP_CAPACITY : NARROW_CAPACITY;++const row = (page: Page, id: string) => page.locator('[data-queue-row="true"]').nth(rowIndex(id));++// `hidden` is display:none, so "how many are drawn at this width" is exactly+// "how many are visible" — no class-name reading required.+const visible = (locator: Locator) => locator.locator('visible=true');++const previews = (page: Page, id: string) => visible(row(page, id).locator('[data-queue-attachment]'));+const thumbs = (page: Page, id: string) =>+ visible(row(page, id).locator('[data-queue-attachment^="image"]'));+const moreButton = (page: Page, id: string) =>+ visible(row(page, id).locator('[data-queue-attachment-more="true"]'));++const boxOf = async (locator: Locator, what: string) => {+ const box = await locator.boundingBox();+ expect(box, `${what} should be laid out`).not.toBeNull();+ return box!;+};++// Touch where the device has it, mouse where it does not: the point of these two+// tests is that the full filename is reachable by an *action*, and on the mobile+// project that action is a real tap rather than a hover the device cannot make.+const activate = async (page: Page, locator: Locator) => {+ if (await page.evaluate(() => 'ontouchstart' in window)) await locator.tap();+ else await locator.click();+};++test.beforeEach(async ({ page }) => {+ // Broadest first: Playwright gives priority to the most recently registered+ // handler, so the specific routes below override this one.+ await page.route('**/api/media/**', (route) => {+ const path = new URL(route.request().url()).pathname;+ if (path.endsWith('/med_5') || path.endsWith('/med_im2')) {+ return route.fulfill({ status: 200, contentType: 'text/plain', body: 'queued log line\n' });+ }+ return route.fulfill({ status: 200, contentType: 'image/png', body: PNG });+ });+ await page.route('**/api/media/*/meta', (route) => {+ const id = new URL(route.request().url()).pathname.split('/').at(-2) ?? '';+ return route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ size: 12, ...(META[id] ?? { name: id, content_type: null, ext: null }) }),+ });+ });+ // A genuinely failed image load, produced by the transport rather than by a+ // test-only prop the product does not have.+ await page.route('**/api/media/med_broken**', (route) => route.abort('failed'));++ await page.goto('/e2e/queue-attachments/fixture.html');+ await expect(page.getByTestId('queue-fixture')).toBeVisible();+});++test('a queued image is visible, 20px, centred, and costs the row no height', async ({ page }) => {+ const plain = await boxOf(row(page, 'q-text'), 'the text-only row');+ const withImage = await boxOf(row(page, 'q-image'), 'the image-only row');+ const target = await boxOf(thumbs(page, 'q-image').first(), 'the thumbnail target');+ const thumb = await boxOf(thumbs(page, 'q-image').first().locator('span').first(), 'the thumbnail');++ // 20px of picture inside a 24px target: the visual is the size the design+ // asks for, and the thing a finger has to hit is the size the row's own icon+ // buttons already are.+ expect(Math.round(thumb.width)).toBe(20);+ expect(Math.round(thumb.height)).toBe(20);+ expect(Math.round(target.height)).toBe(24);+ // Same line, same height: the preview lives in the band those buttons occupy.+ expect(Math.round(withImage.height)).toBe(Math.round(plain.height));+ const centre = withImage.y + withImage.height / 2;+ expect(Math.abs(thumb.y + thumb.height / 2 - centre)).toBeLessThanOrEqual(1);++ // It is the file, not a stand-in for one: the row's own URL, actually decoded.+ const img = thumbs(page, 'q-image').first().locator('img');+ await expect(img).toHaveAttribute('src', '/api/media/med_1');+ await expect+ .poll(() => img.evaluate((el: HTMLImageElement) => el.naturalWidth))+ .toBeGreaterThan(0);+});++test('an image-only queued message still says what it is', async ({ page }) => {+ await expect(row(page, 'q-image')).toContainText('annotation-region.png');+});++test('the inline run is capped per width, and the disclosure counts what that width hides', async ({+ page,+}) => {+ const capacity = capacityOf(page);+ await expect(previews(page, 'q-mixed')).toHaveCount(capacity);++ // Exactly one `+N` is reachable at any one width, and it names the remainder+ // for that width rather than for the other one.+ await expect(moreButton(page, 'q-mixed')).toHaveCount(1);+ await expect(moreButton(page, 'q-mixed')).toHaveAttribute(+ 'aria-label',+ `Show ${5 - capacity} more attachments`,+ );++ // The previews took width from neither the text nor the row's actions.+ const strip = await boxOf(row(page, 'q-mixed'), 'the mixed row');+ const remove = await boxOf(+ row(page, 'q-mixed').getByRole('button', { name: 'Remove from queue' }),+ 'the remove button',+ );+ expect(remove.x + remove.width).toBeLessThanOrEqual(strip.x + strip.width + 1);+ await expect(row(page, 'q-mixed')).toContainText('Compare these against the spec');+});++test('every attachment type shares one row height, disclosed or not', async ({ page }) => {+ const heights = async () =>+ Promise.all(ORDER.map(async (id) => Math.round((await boxOf(row(page, id), id)).height)));+ const collapsed = await heights();+ expect(new Set(collapsed).size, `rows differed in height: ${collapsed.join(', ')}`).toBe(1);++ // Disclosure is the one attachment action allowed to make a row taller, and+ // only its own row.+ await moreButton(page, 'q-mixed').click();+ const disclosed = await heights();+ expect(disclosed[rowIndex('q-mixed')]).toBeGreaterThan(collapsed[rowIndex('q-mixed')]);+ expect(disclosed.filter((_, i) => i !== rowIndex('q-mixed'))).toEqual(+ collapsed.filter((_, i) => i !== rowIndex('q-mixed')),+ );++ await moreButton(page, 'q-mixed').click();+ expect(await heights()).toEqual(collapsed);+});++test('disclosing shows every file in order, and collapsing puts them back', async ({ page }) => {+ const sheet = row(page, 'q-mixed').locator('[data-queue-attachments="disclosed"]');++ await moreButton(page, 'q-mixed').click();+ const items = sheet.locator('[data-queue-attachment]');+ await expect(items).toHaveCount(5);+ expect(await items.evaluateAll((els) => els.map((el) => el.getAttribute('aria-label')))).toEqual([+ 'one.png · PNG',+ 'two.png · PNG',+ 'three.png · PNG',+ 'release-notes-2026-09.pdf · PDF',+ 'console-log.txt · TXT',+ ]);++ await moreButton(page, 'q-mixed').click();+ await expect(sheet).toHaveCount(0);+ await expect(previews(page, 'q-mixed')).toHaveCount(capacityOf(page));+});++test('a queued image opens on its own, even though the gallery holds it too', async ({ page }) => {+ await thumbs(page, 'q-image').first().click();++ const viewer = page.getByRole('dialog');+ await expect(viewer).toBeVisible();+ // The fixture's gallery contains `/api/media/med_1`, so an isolation that was+ // merely inferred from absence would hand this viewer paging controls.+ await expect(viewer.getByRole('button', { name: 'Next' })).toHaveCount(0);+ await expect(viewer.getByRole('button', { name: 'Previous' })).toHaveCount(0);+ await page.keyboard.press('ArrowRight');+ await expect(viewer.locator('img').first()).toHaveAttribute('src', '/api/media/med_1');++ await viewer.getByRole('button', { name: 'Close' }).click();+ await expect(viewer).toHaveCount(0);+});++test('an unavailable image keeps its slot and hands over its full filename', async ({ page }) => {+ await row(page, 'q-broken').scrollIntoViewIfNeeded();+ const slot = thumbs(page, 'q-broken').first();+ await expect(slot).toHaveAttribute('data-queue-attachment', 'image-unavailable');+ await expect(slot).toHaveAttribute('aria-label', 'console-log.png · PNG · Preview unavailable');++ const box = await boxOf(slot.locator('span').first(), 'the unavailable slot');+ expect(Math.round(box.width)).toBe(20);+ expect(Math.round(box.height)).toBe(20);+ expect(Math.round((await boxOf(row(page, 'q-broken'), 'the broken row')).height)).toBe(+ Math.round((await boxOf(row(page, 'q-text'), 'the text-only row')).height),+ );++ // Not hover-only: the complete name is one action away even on a touch device.+ await activate(page, slot);+ await expect(page.getByRole('dialog')).toContainText('console-log.png');+});++test('a single unsupported file exposes its whole name to a tap', async ({ page }) => {+ await row(page, 'q-file').scrollIntoViewIfNeeded();+ const chip = previews(page, 'q-file').first();+ await expect(chip).toHaveAttribute('aria-label', 'console-log.txt · TXT');++ await activate(page, chip);+ await expect(page.getByRole('dialog')).toContainText('console-log.txt');+});++test('keyboard reaches the previews in reading order and works the disclosure', async ({ page }) => {+ const capacity = capacityOf(page);+ const text = row(page, 'q-mixed').locator('div[role="button"]');+ await text.focus();+ await expect(text).toHaveAttribute('aria-expanded', 'false');++ const reached: (string | null)[] = [];+ for (let i = 0; i < capacity + 1; i += 1) {+ await page.keyboard.press('Tab');+ reached.push(+ await page.evaluate(+ () =>+ document.activeElement?.getAttribute('aria-label') ??+ document.activeElement?.getAttribute('data-queue-attachment-more') ??+ null,+ ),+ );+ }+ expect(reached.slice(0, capacity)).toEqual(+ ['one.png · PNG', 'two.png · PNG', 'three.png · PNG'].slice(0, capacity),+ );+ expect(reached[reached.length - 1]).toBe(`Show ${5 - capacity} more attachments`);++ await page.keyboard.press('Enter');+ await expect(row(page, 'q-mixed').locator('[data-queue-attachments="disclosed"]')).toHaveCount(1);+ // The row's own text control is exactly where it was: disclosing the files is+ // not expanding the message.+ await expect(text).toHaveAttribute('aria-expanded', 'false');+});++// Focus is not a class name: only the browser can say where it went after the+// button under it stopped existing. It used to fall to the document, which ends+// the keyboard user's position in the row.+test('the disclosure keeps keyboard focus through expand and collapse', async ({ page }) => {+ const collapsedLabel = `Show ${5 - capacityOf(page)} more attachments`;+ const control = moreButton(page, 'q-mixed');+ const sheet = row(page, 'q-mixed').locator('[data-queue-attachments="disclosed"]');++ await control.focus();+ await expect(control).toHaveAttribute('aria-label', collapsedLabel);++ await page.keyboard.press('Enter');+ await expect(sheet).toHaveCount(1);+ // The same element, relabelled — not a replacement that dropped focus.+ await expect(control).toBeFocused();+ await expect(control).toHaveAttribute('aria-label', 'Collapse attachments');++ await page.keyboard.press('Enter');+ await expect(sheet).toHaveCount(0);+ await expect(control).toBeFocused();+ await expect(control).toHaveAttribute('aria-label', collapsedLabel);+});++// Crossing `sm` is the other way the disclosure used to lose focus, and the one+// only a real browser can show: capacity lived in CSS, so one logical control was+// two elements and the crossing turned whichever held focus into `display:none`.+// A resize here is a real resize — the media query fires, and `activeElement` is+// read from the browser rather than inferred.+const NARROW = { width: 390, height: 780 };+const WIDE = { width: 1024, height: 780 };+const rowText = (page: Page, id: string) => row(page, id).locator('div[role="button"]');++test('the sm boundary switches capacity at exactly 640px', async ({ page }) => {+ await page.setViewportSize({ width: 639, height: 780 });+ await expect(previews(page, 'q-mixed')).toHaveCount(NARROW_CAPACITY);+ await expect(moreButton(page, 'q-mixed')).toHaveAttribute('aria-label', 'Show 3 more attachments');+ // Two attachments fit either way, so neither width offers a control that would+ // disclose nothing.+ await expect(moreButton(page, 'q-token')).toHaveCount(0);++ await page.setViewportSize({ width: 640, height: 780 });+ await expect(previews(page, 'q-mixed')).toHaveCount(DESKTOP_CAPACITY);+ await expect(moreButton(page, 'q-mixed')).toHaveAttribute('aria-label', 'Show 2 more attachments');+ await expect(moreButton(page, 'q-token')).toHaveCount(0);+});++test('the disclosure keeps focus, as one element, across a real resize', async ({ page }) => {+ await page.setViewportSize(NARROW);+ const control = moreButton(page, 'q-mixed');+ await control.focus();+ await expect(control).toHaveAttribute('aria-label', 'Show 3 more attachments');+ // Stamped on the live node: if the crossing swapped in a different element the+ // stamp goes with the old one, and the assertion below has nothing to match.+ await control.evaluate((el) => el.setAttribute('data-focus-probe', 'kept'));++ await page.setViewportSize(WIDE);++ await expect(page.locator('[data-focus-probe="kept"]')).toBeFocused();+ await expect(control).toHaveAttribute('aria-label', 'Show 2 more attachments');+ await expect(moreButton(page, 'q-mixed')).toHaveCount(1);++ await page.setViewportSize(NARROW);++ await expect(page.locator('[data-focus-probe="kept"]')).toBeFocused();+ await expect(control).toHaveAttribute('aria-label', 'Show 3 more attachments');+});++// The reported sequence, end to end.+test('collapsing with nothing left to hide hands focus to the row text', async ({ page }) => {+ await page.setViewportSize(NARROW);+ const control = moreButton(page, 'q-three');+ const sheet = row(page, 'q-three').locator('[data-queue-attachments="disclosed"]');++ await control.focus();+ await page.keyboard.press('Enter');+ await expect(sheet).toHaveCount(1);+ await expect(control).toBeFocused();++ // Widening leaves the control meaningful — it still says "collapse" — so it+ // keeps both its identity and its focus.+ await page.setViewportSize(WIDE);+ await expect(control).toBeFocused();+ await expect(control).toHaveAttribute('aria-label', 'Collapse attachments');++ await page.keyboard.press('Enter');++ // Three attachments all fit at this width, so the control is now genuinely+ // meaningless. It goes, and focus goes somewhere a keyboard user can continue+ // from — not to the document.+ await expect(sheet).toHaveCount(0);+ await expect(moreButton(page, 'q-three')).toHaveCount(0);+ await expect(rowText(page, 'q-three')).toBeFocused();+ await page.keyboard.press('Tab');+ await expect(page.locator('body')).not.toBeFocused();+});++test('widening past the last hidden attachment hands focus to the row text', async ({ page }) => {+ await page.setViewportSize(NARROW);+ const control = moreButton(page, 'q-three');+ await expect(control).toHaveAttribute('aria-label', 'Show 1 more attachments');+ await control.focus();++ await page.setViewportSize(WIDE);++ await expect(previews(page, 'q-three')).toHaveCount(3);+ await expect(moreButton(page, 'q-three')).toHaveCount(0);+ await expect(rowText(page, 'q-three')).toBeFocused();+});++test('narrowing past the third preview hands focus to the row text', async ({ page }) => {+ await page.setViewportSize(WIDE);+ await previews(page, 'q-mixed').nth(2).focus();++ await page.setViewportSize(NARROW);++ await expect(previews(page, 'q-mixed')).toHaveCount(NARROW_CAPACITY);+ await expect(rowText(page, 'q-mixed')).toBeFocused();+});++test('a surviving preview keeps its own focus through a resize', async ({ page }) => {+ await page.setViewportSize(WIDE);+ const first = previews(page, 'q-mixed').first();+ await first.focus();++ await page.setViewportSize(NARROW);++ await expect(first).toBeFocused();+});++// The transfer is conditional on this group having held focus. Someone part-way+// through the row's own actions is not dragged back to its text because an+// attachment control happened to disappear.+test('a resize leaves focus outside the attachment group alone', async ({ page }) => {+ await page.setViewportSize(NARROW);+ const remove = row(page, 'q-three').getByRole('button', { name: 'Remove from queue' });+ await remove.focus();++ await page.setViewportSize(WIDE);++ await expect(moreButton(page, 'q-three')).toHaveCount(0);+ await expect(remove).toBeFocused();+});++test('a third-party file is an explicit external link, never fetched for us', async ({ page }) => {+ const signed = 'https://files.example.com/spec.pdf?sig=abc123&expires=1789';+ let hits = 0;+ // Routed on the context so the popup is served too — the request never leaves+ // this machine, and the counter is what proves the row did not make one.+ await page.context().route('https://files.example.com/**', (route) => {+ hits += 1;+ return route.fulfill({ status: 200, contentType: 'text/html', body: '<title>spec</title>' });+ });++ await row(page, 'q-remote').scrollIntoViewIfNeeded();+ const chip = previews(page, 'q-remote').first();+ await expect(chip).toHaveAttribute('data-queue-attachment', 'file-external');+ await expect(chip).toHaveAttribute('target', '_blank');+ await expect(chip).toHaveAttribute('rel', 'noopener noreferrer');+ expect(hits, 'the row must not fetch a third-party host to paint').toBe(0);++ const [popup] = await Promise.all([page.waitForEvent('popup'), chip.click()]);+ // Byte-for-byte the URL we were given: a signature survives only if the query+ // is neither rewritten nor appended to.+ expect(popup.url()).toBe(signed);+ // And it did not land in the in-app viewer, which cannot fetch that host.+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await popup.close();+});++test('an IM inbound attachment previews from its token instead of going inert', async ({ page }) => {+ await row(page, 'q-token').scrollIntoViewIfNeeded();+ const img = thumbs(page, 'q-token').first().locator('img');++ await expect(img).toHaveAttribute('src', '/api/media/med_im1');+ await expect+ .poll(() => img.evaluate((el: HTMLImageElement) => el.naturalWidth))+ .toBeGreaterThan(0);+ await expect(row(page, 'q-token')).toContainText('feishu-screenshot.png');++ // The file beside it is an action, not a label nobody can open.+ const chip = previews(page, 'q-token').nth(1);+ await expect(chip).toHaveAttribute('data-queue-attachment', 'file');+ await activate(page, chip);+ await expect(page.getByRole('dialog')).toContainText('trace.log');+});++// The sheet stacks targets, and a target is taller than the 20px it shows: the+// shared 24px band is extended 6px above and below so a finger has 36px to land+// on. Two such bands 4px apart therefore overlap by 8px, and the overlap belongs+// to whichever one paints last — a tap just under one thumbnail opened the file+// on the next line. Only a browser can answer this: it is resolved pseudo-element+// geometry resolved against real hit-testing.+test('wrapped attachment targets do not reach into the line below', async ({ page }) => {+ await row(page, 'q-wrap').scrollIntoViewIfNeeded();+ await moreButton(page, 'q-wrap').click();+ const sheet = row(page, 'q-wrap').locator('[data-queue-attachments="disclosed"]');+ await expect(sheet).toHaveCount(1);++ const items = sheet.locator('[data-queue-attachment]');+ const boxes = await items.evaluateAll((els) =>+ els.map((el) => {+ const r = el.getBoundingClientRect();+ return { label: el.getAttribute('aria-label'), x: r.x, y: r.y, w: r.width, h: r.height };+ }),+ );++ // Genuinely wrapped, not a single line dressed up as one.+ const lines = [...new Set(boxes.map((b) => Math.round(b.y)))].sort((a, b) => a - b);+ expect(lines.length, `the sheet did not wrap: ${JSON.stringify(lines)}`).toBeGreaterThan(1);++ // Hit-testing, not arithmetic: ask the browser who owns the pixels just outside+ // each band, the way a finger does.+ const ownerAt = (x: number, y: number) =>+ page.evaluate(+ ([px, py]) =>+ (document.elementFromPoint(px, py) as HTMLElement | null)+ ?.closest('[data-queue-attachment]')+ ?.getAttribute('aria-label') ?? null,+ [x, y] as const,+ );++ const first = boxes.filter((b) => Math.round(b.y) === lines[0]);+ const second = boxes.filter((b) => Math.round(b.y) === lines[1]);+ for (const below of second.slice(0, 3)) {+ const above = first.find((b) => below.x < b.x + b.w && b.x < below.x + below.w);+ expect(above, 'expected a target directly above the wrapped one').toBeTruthy();+ const x = Math.round(Math.max(below.x, above!.x) + 2);++ // Three pixels under the upper band: its own target, never the one below it.+ expect(await ownerAt(x, Math.round(above!.y + above!.h) + 3)).toBe(above!.label);+ // ...and three pixels over the lower band: its own, never the one above.+ expect(await ownerAt(x, Math.round(below.y) - 3)).toBe(below.label);+ }++ // The number behind the behaviour above, stated so a future spacing change has+ // to think about it: 12px between lines is exactly what lets the two 6px+ // extensions meet without crossing.+ expect(Math.round(lines[1] - lines[0] - boxes[0].h)).toBe(12);+});++// The name on an unsupported type exists nowhere else — the body can only say it+// cannot render the file — so an ellipsis in the title makes it unreadable to a+// touch user with no hover. Presence in the DOM is not the property; fitting is.+const titleIsFullyReadable = async (page: Page) => {+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ const title = dialog.locator('h2').first();+ const measured = await title.evaluate((el) => {+ const style = getComputedStyle(el);+ // What this name would need on one line, measured rather than guessed — the+ // dialog is 768px wide on a desktop and ~220px on a phone, so whether the+ // name has to wrap at all is a property of the viewport, not of the name.+ const probe = document.createElement('span');+ probe.textContent = el.textContent;+ probe.style.cssText = `position:absolute;visibility:hidden;white-space:nowrap;font:${style.font}`;+ document.body.appendChild(probe);+ const intrinsic = probe.getBoundingClientRect().width;+ probe.remove();+ return {+ text: el.textContent ?? '',+ clientWidth: el.clientWidth,+ scrollWidth: el.scrollWidth,+ height: el.getBoundingClientRect().height,+ lineHeight: parseFloat(style.lineHeight),+ whiteSpace: style.whiteSpace,+ textOverflow: style.textOverflow,+ intrinsic,+ };+ });++ // Nothing clipped horizontally: every glyph is inside the box it is drawn in.+ expect(+ measured.scrollWidth,+ `title overflows its box: ${measured.scrollWidth} > ${measured.clientWidth}`,+ ).toBeLessThanOrEqual(measured.clientWidth + 1);+ // The mechanism that used to hide the tail is gone, at every width.+ expect(measured.whiteSpace).not.toBe('nowrap');+ expect(measured.textOverflow).not.toBe('ellipsis');+ // Where one line cannot hold the name — which is the case on the phone — it is+ // readable because it wrapped, not because it was short enough.+ if (measured.intrinsic > measured.clientWidth + 1) {+ expect(measured.height).toBeGreaterThan(measured.lineHeight * 1.5);+ }+ return measured.text;+};++test('a long unsupported filename is readable in full after a real tap', async ({ page }) => {+ await row(page, 'q-longname').scrollIntoViewIfNeeded();+ const chip = previews(page, 'q-longname').first();+ await expect(chip).toHaveAttribute('aria-label', `${LONG_FILE} · UNKNOWN`);++ await activate(page, chip);+ expect(await titleIsFullyReadable(page)).toContain(LONG_FILE);++ // The header grew; the body it shares the dialog with is still a usable size.+ const body = page.getByRole('dialog').locator('.vr-fileview-body');+ expect((await boxOf(body, 'the viewer body')).height).toBeGreaterThan(120);+});++test('a failed image with a long name is just as readable', async ({ page }) => {+ await row(page, 'q-longbroken').scrollIntoViewIfNeeded();+ const slot = thumbs(page, 'q-longbroken').first();+ await expect(slot).toHaveAttribute('data-queue-attachment', 'image-unavailable');++ await activate(page, slot);+ expect(await titleIsFullyReadable(page)).toContain(LONG_IMAGE);+});++test('inspecting files changes nothing about the queue itself', async ({ page }) => {+ const rows = page.locator('[data-queue-row="true"]');+ await expect(rows).toHaveCount(ORDER.length);+ await expect(page.getByText(`Queued · ${ORDER.length}`)).toBeVisible();++ await thumbs(page, 'q-image').first().click();+ await page.getByRole('dialog').getByRole('button', { name: 'Close' }).click();+ await moreButton(page, 'q-mixed').click();+ await moreButton(page, 'q-mixed').click();++ await expect(rows).toHaveCount(ORDER.length);+ await expect(page.getByText(`Queued · ${ORDER.length}`)).toBeVisible();+ await expect(page.getByTestId('queue-fixture')).toHaveAttribute('data-sent', '0');+ // Same rows, same order, same contents.+ await expect(row(page, 'q-image')).toContainText('annotation-region.png');+ await expect(row(page, 'q-mixed')).toContainText('Compare these against the spec');+});++test('the queue body stays capped and the composer stays on screen', async ({ page }) => {+ const body = page.locator('[data-queue-batch="true"]');+ await expect(body).toHaveCSS('max-height', '128px');++ const bounded = async () => {+ const box = await boxOf(body, 'the queue body');+ expect(box.height).toBeLessThanOrEqual(128);+ const composer = await boxOf(page.getByTestId('composer'), 'the composer');+ expect(composer.y + composer.height).toBeLessThanOrEqual(page.viewportSize()!.height + 1);+ };++ await bounded();+ await moreButton(page, 'q-mixed').click();+ await bounded();+});diff --git a/ui/e2e/queue-attachments/tsconfig.json b/ui/e2e/queue-attachments/tsconfig.jsonnew file mode 100644index 000000000..d68c87ac0--- /dev/null+++ b/ui/e2e/queue-attachments/tsconfig.json@@ -0,0 +1,8 @@+{+ "extends": "../../tsconfig.app.json",+ "compilerOptions": {+ "types": ["vite/client", "node"]+ },+ "include": ["*.ts", "*.tsx", "../../playwright.queue-attachments.config.ts", "../../agentation.d.ts"],+ "exclude": []+}diff --git a/ui/package.json b/ui/package.jsonindex fde4b78ba..0215f5945 100644--- a/ui/package.json+++ b/ui/package.json@@ -24,6 +24,7 @@"test:badge-triggers": "tsc -p e2e/badge-triggers/tsconfig.json --noEmit && playwright test --config playwright.badge-triggers.config.ts","test:project-order": "tsc -p e2e/project-order/tsconfig.json --noEmit && playwright test --config playwright.project-order.config.ts","test:session-dot": "tsc -p e2e/session-dot/tsconfig.json --noEmit && playwright test --config playwright.session-dot.config.ts",+ "test:queue-attachments": "tsc -p e2e/queue-attachments/tsconfig.json --noEmit && playwright test --config playwright.queue-attachments.config.ts","test:model-catalog": "tsc -p e2e/model-catalog/tsconfig.json --noEmit && playwright test --config playwright.model-catalog.config.ts","test:model-provider": "tsc -p e2e/model-provider/tsconfig.json --noEmit && playwright test --config playwright.model-provider.config.ts","test:onboarding-fidelity": "tsc -p e2e/onboarding-fidelity/tsconfig.json --noEmit && playwright test --config playwright.onboarding-fidelity.config.ts",diff --git a/ui/playwright.queue-attachments.config.ts b/ui/playwright.queue-attachments.config.tsnew file mode 100644index 000000000..931e3672a--- /dev/null+++ b/ui/playwright.queue-attachments.config.ts@@ -0,0 +1,22 @@+import { defineConfig, devices } from '@playwright/test';++// Hermetic: the dev server is bound to loopback and points at a dead backend+// port, and every `/api/media/...` request is fulfilled by the spec itself, so+// nothing here reaches a running Avibe service or writes to user state.+export default defineConfig({+ testDir: './e2e/queue-attachments',+ outputDir: './e2e/.artifacts/queue-attachments',+ workers: 1,+ retries: 0,+ use: { baseURL: 'http://127.0.0.1:5216', locale: 'en-US', trace: 'retain-on-failure' },+ webServer: {+ command: 'npm run dev -- --host 127.0.0.1 --port 5216 --strictPort',+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },+ url: 'http://127.0.0.1:5216/e2e/queue-attachments/fixture.html',+ reuseExistingServer: true,+ },+ projects: [+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },+ { name: 'mobile', use: { ...devices['iPhone 13'], browserName: 'chromium' } },+ ],+});diff --git a/ui/src/components/ui/file-viewer-modal.tsx b/ui/src/components/ui/file-viewer-modal.tsxindex b92ddcec9..f99ab357f 100644--- a/ui/src/components/ui/file-viewer-modal.tsx+++ b/ui/src/components/ui/file-viewer-modal.tsx@@ -99,10 +99,19 @@ export default function FileViewerModal({ target, onClose }: { target: FilePrevimobileSheetHeight="tall"className="flex h-[80vh] w-full max-w-3xl flex-col gap-0 overflow-hidden p-0">- <div className="flex items-center gap-2 border-b border-border px-4 py-3 pr-12">- <FileText className="size-4 shrink-0 text-muted" />+ {/* ``items-start`` and ``shrink-0``: the title below is allowed to wrap, so the+ icon and the actions stay on the first line beside it and the header keeps+ its full height instead of being squeezed by the scrolling body. */}+ <div className="flex shrink-0 items-start gap-2 border-b border-border px-4 py-3 pr-12">+ <FileText className="mt-px size-4 shrink-0 text-muted" /><div className="min-w-0 flex-1">- <DialogTitle className="truncate text-[13px] font-semibold text-foreground">{name || t('chat.media.preview')}</DialogTitle>+ {/* The name wraps rather than truncating. For an unsupported type this+ title is the only place the filename exists at all — the body can only+ say it cannot render the file — and a touch user has no hover to fall+ back on, so an ellipsis here means the complete name is unreadable.+ ``break-words`` also breaks an unbroken run, which is what a long+ extension-less name usually is. */}+ <DialogTitle className="break-words text-[13px] font-semibold leading-snug text-foreground">{name || t('chat.media.preview')}</DialogTitle>{metaLine && <div className="font-mono text-[10px] text-muted">{metaLine}</div>}</div>{text != null && (diff --git a/ui/src/components/ui/image-viewer-context.ts b/ui/src/components/ui/image-viewer-context.tsindex c24fdbbc4..684014876 100644--- a/ui/src/components/ui/image-viewer-context.ts+++ b/ui/src/components/ui/image-viewer-context.ts@@ -5,7 +5,15 @@ import * as React from 'react';// ``useImageViewer()`` returns null where no provider is mounted (e.g. the// agent-config editor preview), which makes the click a documented no-op.-type ImageViewerContextValue = { open: (src: string) => void };+// ``isolated`` opens the image on its own: the lightbox shows exactly that one+// src and never pages, whatever the session gallery happens to contain. A caller+// outside the transcript (the queue strip) needs that as a *stated* property —+// its URL not being in ``images`` today is an accident of when the message is+// sent, and would silently stop holding the moment the same file also appears in+// the transcript, or the queue flushes while the viewer is open.+export type ImageViewerOpenOptions = { isolated?: boolean };++type ImageViewerContextValue = { open: (src: string, options?: ImageViewerOpenOptions) => void };export const ImageViewerContext = React.createContext<ImageViewerContextValue | null>(null);diff --git a/ui/src/components/ui/image-viewer.test.tsx b/ui/src/components/ui/image-viewer.test.tsxnew file mode 100644index 000000000..c3dbe743e--- /dev/null+++ b/ui/src/components/ui/image-viewer.test.tsx@@ -0,0 +1,120 @@+/* @vitest-environment jsdom */++// The lightbox pages through the session's gallery. One caller — the queue strip+// — shows files that are NOT in that gallery and must not start paging through+// it when they arrive there, which happens on every flush. So "on its own" is a+// property of the open call, and these tests are what make it one.++import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { createInstance } from 'i18next';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import en from '../../i18n/en.json';+import { ImageViewerProvider } from './image-viewer';+import { useImageViewer, type ImageViewerOpenOptions } from './image-viewer-context';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++const GALLERY = ['/api/media/med_1', '/api/media/med_2', '/api/media/med_3'];++const Opener: React.FC<{ src: string; options?: ImageViewerOpenOptions }> = ({ src, options }) => {+ const viewer = useImageViewer();+ return (+ <button type="button" onClick={() => viewer?.open(src, options)}>+ open+ </button>+ );+};++const mount = (options?: ImageViewerOpenOptions, images: string[] = GALLERY) =>+ render(+ <I18nextProvider i18n={i18n}>+ <ImageViewerProvider images={images}>+ <Opener src={GALLERY[0]} options={options} />+ </ImageViewerProvider>+ </I18nextProvider>,+ );++const paging = () => ({+ next: screen.queryByLabelText('Next'),+ previous: screen.queryByLabelText('Previous'),+ counter: screen.queryByText('1 / 3'),+});++// The zoom stage observes its own box; jsdom has no layout to report.+beforeEach(() => {+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe('ImageViewerProvider — paging belongs to the gallery, not to every image', () => {+ it('pages through the gallery for an ordinary chat image', () => {+ mount();+ fireEvent.click(screen.getByText('open'));++ expect(paging().next).not.toBeNull();+ expect(paging().previous).not.toBeNull();+ expect(paging().counter).not.toBeNull();+ });++ // The same src, in the same gallery: only the open call differs.+ it('shows an isolated image on its own even when it is in the gallery', () => {+ mount({ isolated: true });+ fireEvent.click(screen.getByText('open'));++ expect(screen.getByRole('dialog')).toBeTruthy();+ expect(paging().next).toBeNull();+ expect(paging().previous).toBeNull();+ expect(paging().counter).toBeNull();+ });++ // What actually happens to a queued file: the queue flushes while the viewer+ // is open and the transcript — hence the gallery — grows to include it. An+ // isolated view must not acquire controls it was opened without.+ it('stays on its own when the gallery grows underneath it', () => {+ const view = mount({ isolated: true }, []);+ fireEvent.click(screen.getByText('open'));++ view.rerender(+ <I18nextProvider i18n={i18n}>+ <ImageViewerProvider images={GALLERY}>+ <Opener src={GALLERY[0]} options={{ isolated: true }} />+ </ImageViewerProvider>+ </I18nextProvider>,+ );++ expect(screen.getByRole('dialog')).toBeTruthy();+ expect(paging().next).toBeNull();+ expect(paging().counter).toBeNull();+ });++ // Arrow keys are the same faculty as the buttons, so they answer to the same+ // rule rather than to a second one that could drift from it.+ it('ignores the arrow keys for an isolated image', () => {+ mount({ isolated: true });+ fireEvent.click(screen.getByText('open'));++ fireEvent.keyDown(window, { key: 'ArrowRight' });++ expect(document.querySelector('img[src="/api/media/med_1"]')).not.toBeNull();+ expect(document.querySelector('img[src="/api/media/med_2"]')).toBeNull();+ });++ it('closes on Escape either way', () => {+ mount({ isolated: true });+ fireEvent.click(screen.getByText('open'));+ fireEvent.keyDown(window, { key: 'Escape' });++ expect(screen.queryByRole('dialog')).toBeNull();+ });+});diff --git a/ui/src/components/ui/image-viewer.tsx b/ui/src/components/ui/image-viewer.tsxindex db56dd0a3..f745c0ef6 100644--- a/ui/src/components/ui/image-viewer.tsx+++ b/ui/src/components/ui/image-viewer.tsx@@ -5,7 +5,7 @@ import { TransformWrapper, TransformComponent, type ReactZoomPanPinchRef } fromimport { Button } from '@/components/ui/button';import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';-import { ImageViewerContext } from './image-viewer-context';+import { ImageViewerContext, type ImageViewerOpenOptions } from './image-viewer-context';// A session-scoped image lightbox. ChatPage computes the ordered list of media-// proxy image URLs in the transcript and wraps the page in a provider; any chat@@ -31,10 +31,20 @@ export const ImageViewerProvider: React.FC<{ images: string[]; children: React.R// chat images don't re-render on every streaming tick. A clicked src that// isn't in the list (shouldn't happen for our own clean proxy URLs, but be// safe) still shows exactly what was clicked — paging just turns off for it.- const [src, setSrc] = React.useState<string | null>(null);+ //+ // ``isolated`` is recorded at open time rather than re-derived per render, so+ // an isolated view stays isolated for its whole life: the gallery growing to+ // include this src (the queue flushing into the transcript, say) cannot hand+ // it paging controls it was opened without.+ const [view, setView] = React.useState<{ src: string; isolated: boolean } | null>(null);+ const src = view?.src ?? null;- const open = React.useCallback((next: string) => setSrc(next), []);- const close = React.useCallback(() => setSrc(null), []);+ const open = React.useCallback(+ (next: string, options?: ImageViewerOpenOptions) =>+ setView({ src: next, isolated: options?.isolated === true }),+ [],+ );+ const close = React.useCallback(() => setView(null), []);// Controls the zoom/pan transform (wired to the desktop +/- buttons). The// wrapper is keyed on ``src`` so paging to another image remounts it back to 1x.const transformRef = React.useRef<ReactZoomPanPinchRef>(null);@@ -50,12 +60,15 @@ export const ImageViewerProvider: React.FC<{ images: string[]; children: React.R// close hit-test must also require the click to be inside the visible stage.const stageRef = React.useRef<HTMLDivElement>(null);- const index = src ? images.indexOf(src) : -1;+ // An isolated view is deliberately not looked up in the gallery at all, so it+ // reports no index — which turns off the arrows, the counter, and the keyboard+ // paging below through the one condition they already share.+ const index = src && !view?.isolated ? images.indexOf(src) : -1;const pageable = index >= 0 && images.length > 1;const step = React.useCallback((delta: number) => {if (index < 0 || images.length === 0) return;- setSrc(images[(index + delta + images.length) % images.length]);+ setView({ src: images[(index + delta + images.length) % images.length], isolated: false });},[index, images],);diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 3f9f32aab..dd52e5da9 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -22,6 +22,7 @@ import { isAgentActivityBoundaryMessage, isRetryableFailureNotice, isTerminalAgeimport { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';+import { readMessageAttachments } from '../../lib/messageAttachments';import {isVaultApprovalRequest,placeVaultProvisionRequests,@@ -132,6 +133,7 @@ import { hasInAppBackEntry } from '../../lib/navigationHistory';import { Composer, type ComposerAttachment, type ComposerHandle, type ComposerProps } from './Composer';import type { MentionReference } from '../../lib/mentions';import { QuickReplies } from './QuickReplies';+import { QueuedAttachmentGroup, QueuedAttachmentSheet } from './QueuedAttachments';import { ActivityCard, ActivityChip } from './AgentActivityGroup';import {activityGroupsForForeground,@@ -2635,12 +2637,12 @@ export const ChatPage: React.FC = () => {urls.push(u);}};+ // ``messages`` is the transcript alone — the queue is separate state — so the+ // gallery keeps containing delivered images only, and a queued preview stays+ // the isolated single-image view it opens as.for (const m of messages) {- const atts = (m.content as { attachments?: Array<Record<string, unknown>> })?.attachments;- if (Array.isArray(atts)) {- for (const a of atts) {- if (a?.kind === 'image' || String(a?.mime || '').startsWith('image/')) push(String(a?.url || ''));- }+ for (const att of readMessageAttachments(m.content)) {+ if (att.image) push(att.url);}if (m.text) {const re = /!\[[^\]]*\]\((\/api\/media\/[^)\s]+)\)/g;@@ -2981,6 +2983,14 @@ export const QueueRow: React.FC<{}> = ({ item, onRemove, onRecall }) => {const { t } = useTranslation();const [expanded, setExpanded] = useState(false);+ // The row's own focusable anchor. An attachment control that stops existing —+ // the disclosure once there is nothing left to disclose, or the third inline+ // preview once the window is too narrow for it — hands focus here rather than+ // letting the browser drop it to the document. It is the right destination+ // because it is the row's stable inspection control: still on the same row,+ // still about the same queued message, and harmless to activate by accident,+ // which Remove and Send are not.+ const textRef = useRef<HTMLDivElement>(null);// A plain selectable element (not a <button>) so desktop users can drag-select// the text; a click still toggles expand/collapse — unless the click ended a// text selection, in which case we leave the selection alone.@@ -3011,12 +3021,46 @@ export const QueueRow: React.FC<{// contract — so an annotation that is only a highlight or only a boxed region// has none, and would sit here as a title, a separator, and empty space.const standIn = annotationView && annotationStandIn(annotationView, item.text, hasAttachments);+ // The files waiting to be sent with this message, previewed on the row itself.+ // Held separately from ``hasAttachments`` above, which answers a different+ // question (can this row be recalled) and must keep answering it for an+ // attachment this renderer cannot draw.+ const attachments = readMessageAttachments(item.content);+ const [attachmentsOpen, setAttachmentsOpen] = useState(false);+ // A queued row whose author wrote no words: the files ARE the message, so the+ // first one names it. This is the same job the screenshot stand-in does, done+ // with the real thing — so the stand-in's generic word is only reached when+ // there is nothing renderable to name.+ //+ // "No words" is judged on trimmed text, the way empty text is judged everywhere+ // else: a lone newline or a space left over from a paste is not a message, and+ // a row carrying one would otherwise render a blank line where its filename+ // belongs. The stored text is untouched — this decides what to show, not what+ // was written.+ const showScreenshotStandIn = standIn?.kind === 'screenshot' && attachments.length === 0;+ const wordless = !item.text?.trim();+ const named = wordless && standIn?.kind !== 'quote' && attachments.length > 0 ? attachments[0] : null;+ const summary =+ named &&+ (attachments.length > 1+ ? t('chat.queue.attachments.summary', {+ name: named.name || t('chat.queue.attachments.untitled'),+ count: attachments.length - 1,+ })+ : named.name || t('chat.queue.attachments.untitled'));return (<divdata-queue-row="true"- className="relative flex items-start gap-2 px-2.5 py-1.5 transition-[background-color,box-shadow,border-radius] hover:z-10 hover:rounded-lg hover:bg-surface-1 hover:ring-1 hover:ring-border focus-within:z-10 focus-within:rounded-lg focus-within:bg-surface-1 focus-within:ring-1 focus-within:ring-border motion-reduce:transition-none"+ className={clsx(+ 'relative flex items-start gap-2 px-2.5 py-1.5 transition-[background-color,box-shadow,border-radius] hover:z-10 hover:rounded-lg hover:bg-surface-1 hover:ring-1 hover:ring-border focus-within:z-10 focus-within:rounded-lg focus-within:bg-surface-1 focus-within:ring-1 focus-within:ring-border motion-reduce:transition-none',+ // Wrapping is enabled only while the remainder is disclosed. A collapsed+ // row therefore cannot wrap at any width — the one thing that could make+ // it taller than a text-only row is off unless the reader asked for it.+ attachmentsOpen && 'flex-wrap',+ )}><div+ ref={textRef}role="button"tabIndex={0}onClick={toggle}@@ -3038,10 +3082,15 @@ export const QueueRow: React.FC<{<MessageSquareQuote className="size-[11px] shrink-0" />{t(annotationTitleKey(annotationView.direction))}</span>- {(item.text || standIn) && <span className="mr-2 text-[11px] text-muted">·</span>}+ {(!wordless || standIn?.kind === 'quote' || showScreenshotStandIn || summary) && (+ <span className="mr-2 text-[11px] text-muted">·</span>+ )}</>)}- {item.text}+ {/* Same trimmed judgement as ``wordless`` above, so a row whose text is+ only a stray newline neither draws a separator with nothing after it+ nor pushes its filename onto a second line once expanded. */}+ {wordless ? null : item.text}{standIn?.kind === 'quote' && (// The card's own quote treatment (pin + muted), flattened to the one// line the strip has room for.@@ -3050,13 +3099,24 @@ export const QueueRow: React.FC<{{standIn.quote}</span>)}- {standIn?.kind === 'screenshot' && (+ {showScreenshotStandIn && (<span className="inline-flex items-center gap-[5px] align-middle text-muted"><ImageIcon className="size-[11px] shrink-0" />{t('chat.annotation.screenshot')}</span>)}+ {summary && <span className="text-muted">{summary}</span>}</div>+ {/* A sibling of the text, never a child of it: a preview or a disclosure+ click cannot reach the expand/collapse handler above, so inspecting an+ attachment never also rewrites the row it is on. */}+ <QueuedAttachmentGroup+ attachments={attachments}+ expanded={attachmentsOpen}+ onToggle={() => setAttachmentsOpen((v) => !v)}+ onFocusEscape={() => textRef.current?.focus()}+ />+ {attachmentsOpen && <QueuedAttachmentSheet attachments={attachments} />}{canRecall && (<Buttontype="button"@@ -4516,27 +4576,27 @@ export const MessageRow = memo(function MessageRow({// User-uploaded attachments ride in ``content.attachments`` (agent-reply media// is rewritten inline into the text instead, handled by the Markdown renderer).- const rawAttachments = (message.content as { attachments?: Array<Record<string, unknown>> })?.attachments;- const messageAttachments = Array.isArray(rawAttachments) ? rawAttachments : [];+ // Read through the same boundary the queue strip uses, so an attachment that+ // was recognisable while queued is still the same file once delivered: an IM+ // inbound records a media token rather than a URL, and reading ``url`` directly+ // dropped those rows from the transcript entirely.+ const messageAttachments = readMessageAttachments(message.content);const attachmentsNode = messageAttachments.length > 0 ? (<div className="mt-2 flex flex-col gap-2">{messageAttachments.map((att, i) => {- const url = String(att?.url || '');- if (!url) return null;- // Only inline-render images served from our own media proxy; a non-proxy- // url falls back to a click-through FileCard so it can't auto-fetch a- // remote host.- const isImage =- (att?.kind === 'image' || String(att?.mime || '').startsWith('image/')) && isProxyMediaUrl(url);+ // Nothing to point at — no URL and no token to mint one from. Existing+ // behaviour: the transcript says nothing rather than offering a dead card.+ if (!att.url) return null;+ // ``att.image`` is already "an image AND served from our own media proxy";+ // anything else falls back to a click-through FileCard so the row can't+ // auto-fetch a remote host.// Server-supplied pixel size (added at upload time) reserves the box so a// freshly-loaded attachment never shifts the transcript.- const w = typeof att?.width === 'number' ? att.width : undefined;- const h = typeof att?.height === 'number' ? att.height : undefined;- return isImage ? (- <ChatImage key={i} src={url} alt={typeof att?.name === 'string' ? att.name : ''} width={w} height={h} />+ return att.image ? (+ <ChatImage key={i} src={att.url} alt={att.name} width={att.width} height={att.height} />) : (- <FileCard key={i} href={url}>- {typeof att?.name === 'string' ? att.name : 'file'}+ <FileCard key={i} href={att.url}>+ {att.name || 'file'}</FileCard>);})}diff --git a/ui/src/components/workbench/ChatQueueRow.test.tsx b/ui/src/components/workbench/ChatQueueRow.test.tsxindex ee2f9df7b..95b138d82 100644--- a/ui/src/components/workbench/ChatQueueRow.test.tsx+++ b/ui/src/components/workbench/ChatQueueRow.test.tsx@@ -1,10 +1,55 @@+/* @vitest-environment jsdom */++import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';import { createInstance } from 'i18next';import { renderToStaticMarkup } from 'react-dom/server';import { I18nextProvider, initReactI18next } from 'react-i18next';-import { describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// ``ChatPage`` reaches the composer's mention editor at import time, which reads+// ``matchMedia`` on the module's first evaluation — before any test body runs.+//+// The attachment group reads the `sm` breakpoint through the same API, so this+// mock is a real one for that query: a test picks a width by setting it, and+// crosses the breakpoint by dispatching the `change` event a browser dispatches.+// jsdom has no media queries of its own, which is exactly why the CSS version of+// this component had a focus defect no unit test could see.+const breakpoint = vi.hoisted(() => {+ const WIDE = '(min-width: 640px)';+ const listeners = new Set<(event: MediaQueryListEvent) => void>();+ const state = { wide: false };+ const media = {+ get matches() {+ return state.wide;+ },+ addEventListener: (_: string, fn: (event: MediaQueryListEvent) => void) => listeners.add(fn),+ removeEventListener: (_: string, fn: (event: MediaQueryListEvent) => void) => listeners.delete(fn),+ };+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn((query: string) =>+ query === WIDE ? media : { matches: false, addEventListener: () => {}, removeEventListener: () => {} },+ ),+ });+ return {+ state,+ emit: () => listeners.forEach((fn) => fn({ matches: state.wide } as MediaQueryListEvent)),+ };+});++const viewport = {+ /** Before a render: picks the width. After one: crosses the breakpoint. */+ set(wide: boolean) {+ if (breakpoint.state.wide === wide) return;+ breakpoint.state.wide = wide;+ act(() => breakpoint.emit());+ },+};import en from '../../i18n/en.json';import type { WorkbenchMessage } from '../../context/ApiContext';+import { FileViewerContext } from '../ui/file-viewer-context';+import { ImageViewerContext } from '../ui/image-viewer-context';import { AnnotationMessage } from './AnnotationMessage';import { QueueRow, QueueStrip } from './ChatPage';@@ -39,6 +84,41 @@ const queued = (over: Partial<WorkbenchMessage> = {}): WorkbenchMessage =>const renderQueued = (item: WorkbenchMessage) =>wrap(<QueueRow item={item} onRemove={() => undefined} onRecall={() => undefined} />);+afterEach(cleanup);+beforeEach(() => {+ breakpoint.state.wide = false;+});++// A live row under both viewers, so what an attachment click actually asks for+// is observable — the two handles are the whole boundary between the queue and+// the surfaces that inspect a file.+const mountQueued = (item: WorkbenchMessage, handlers: Partial<{+ onRemove: (id: string) => void;+ onRecall: (item: WorkbenchMessage) => void;+}> = {}) => {+ const openImage = vi.fn();+ const openFile = vi.fn();+ const view = render(+ <I18nextProvider i18n={i18n}>+ <ImageViewerContext.Provider value={{ open: openImage }}>+ <FileViewerContext.Provider value={{ open: openFile }}>+ <QueueRow+ item={item}+ onRemove={handlers.onRemove ?? (() => undefined)}+ onRecall={handlers.onRecall ?? (() => undefined)}+ />+ </FileViewerContext.Provider>+ </ImageViewerContext.Provider>+ </I18nextProvider>,+ );+ return { ...view, openImage, openFile };+};++const row = () => document.querySelector('[data-queue-row="true"]') as HTMLElement;+const thumbs = () => [...document.querySelectorAll('[data-queue-attachment^="image"]')] as HTMLElement[];+const chips = () => [...document.querySelectorAll('[data-queue-attachment^="file"]')] as HTMLElement[];+const more = () => [...document.querySelectorAll('[data-queue-attachment-more="true"]')] as HTMLElement[];+describe('QueueStrip — compatible queued messages read as one batch', () => {it('uses one shared bubble and reveals each original row boundary on hover or focus', () => {const html = wrap(@@ -109,11 +189,26 @@ describe('QueueRow — a queued annotation nobody wrote words for', () => {({ annotation, ...(attachments ? { attachments } : {}) }) as WorkbenchMessage['content'];const screenshot = [{ url: '/api/media/med_9a71c33f8b2e', name: 'annotation-region.png', kind: 'image' }];+ // The region itself is on the row now, so the word that stood in for it while+ // it could not be drawn gives way to the thing and its name. The annotation's+ // own identity — the title — is untouched by that.it('shows the boxed region a screenshot-only annotation is made of', () => {const html = renderQueued(wordless({ content: withAnnotation({ direction: 'user', action: 'created' }, screenshot) }),);expect(html).toContain('User annotation');+ expect(html).toContain('annotation-region.png');+ expect(html).toContain('src="/api/media/med_9a71c33f8b2e"');+ expect(html).not.toContain('Screenshot');+ });++ // …and when there is nothing renderable to put there, the word comes back+ // rather than leaving the title alone with a separator.+ it('keeps the generic label when the region cannot be drawn', () => {+ const html = renderQueued(+ wordless({ content: withAnnotation({ direction: 'user', action: 'created' }, ['not-an-object']) }),+ );+ expect(html).toContain('User annotation');expect(html).toContain('Screenshot');});@@ -173,3 +268,402 @@ describe('QueueRow — a queued annotation nobody wrote words for', () => {}});});++// The files waiting to be sent with a queued message. Until now the row drew+// only words, so an image-only input — the thing a Show Page annotation+// produces most often — arrived in the queue as an empty line.+describe('QueueRow — the files waiting to be sent with a queued message', () => {+ const media = (name: string, id: string) => ({ url: `/api/media/${id}`, name, kind: 'image' });+ const item = (attachments: unknown[], over: Partial<WorkbenchMessage> = {}) =>+ queued({ text: '', source: 'user', content: { attachments } as WorkbenchMessage['content'], ...over });+ const five = [+ media('one.png', 'med_1'),+ media('two.png', 'med_2'),+ media('three.png', 'med_3'),+ media('four.png', 'med_4'),+ media('five.png', 'med_5'),+ ];++ it('names an image-only queued message with its own file rather than a placeholder', () => {+ mountQueued(item([media('shot.png', 'med_1')]));++ expect(thumbs()).toHaveLength(1);+ expect(thumbs()[0].querySelector('img')?.getAttribute('src')).toBe('/api/media/med_1');+ expect(row().textContent).toContain('shot.png');+ });++ it('names the first file and counts the rest', () => {+ mountQueued(item([media('one.png', 'med_1'), media('two.png', 'med_2')]));+ expect(row().textContent).toContain('one.png and 1 more');+ });++ // A newline left behind by a paste, or a stray space, is not something the+ // author wrote — everywhere else empty text is judged on the trimmed value, and+ // this line has to agree or the row renders blank where its filename belongs.+ it.each([' ', '\n', ' \n '])('treats whitespace-only text as wordless (%j)', (text) => {+ mountQueued(item([media('one.png', 'med_1'), media('two.png', 'med_2')], { text }));+ expect(row().textContent?.trim()).toBe('one.png and 1 more');+ });++ it('leaves authored words in charge of the line and still previews the file', () => {+ mountQueued(item([media('shot.png', 'med_1')], { text: 'Compare these two' }));++ expect(row().textContent).toContain('Compare these two');+ expect(row().textContent).not.toContain('shot.png');+ expect(thumbs()).toHaveLength(1);+ });++ it('gives an ordinary file a named chip instead of a picture', () => {+ mountQueued(item([{ url: '/api/media/med_7', name: 'console-log.txt', mime: 'text/plain' }]));++ expect(thumbs()).toHaveLength(0);+ expect(chips()[0].getAttribute('aria-label')).toBe('console-log.txt · TXT');+ expect(document.querySelector('img')).toBeNull();+ });++ // The row paints without anyone asking it to, so an <img> here is an automatic+ // request. Only the same-origin media proxy is ever allowed to become one.+ it('never renders an image the browser would fetch from somewhere else', () => {+ mountQueued(item([{ url: 'https://example.com/remote.png', name: 'remote.png', kind: 'image' }]));++ expect(document.querySelector('img')).toBeNull();+ expect(chips()).toHaveLength(1);+ });++ // The in-app viewer refuses to fetch a host that is not ours, so it would only+ // ever say "preview failed" here. A delivered attachment in the same position+ // opens an external link, and so does this one.+ it('opens a third-party file the way a delivered one does, not in the viewer', () => {+ // A signed link carries its own query. The URL is handed over exactly as it+ // arrived — nothing appended, nothing rewritten — or the signature no longer+ // matches what the far end will check.+ const signed = 'https://files.example.com/spec.pdf?sig=abc123&expires=1789';+ const { openFile } = mountQueued(item([{ url: signed, name: 'spec.pdf', mime: 'application/pdf' }]));++ const chip = chips()[0];+ expect(chip.getAttribute('data-queue-attachment')).toBe('file-external');+ expect(chip.tagName).toBe('A');+ expect(chip.getAttribute('href')).toBe(signed);+ expect(chip.getAttribute('target')).toBe('_blank');+ expect(chip.getAttribute('rel')).toBe('noopener noreferrer');+ expect(chip.getAttribute('aria-label')).toBe('spec.pdf · PDF');++ fireEvent.click(chip);+ expect(openFile).not.toHaveBeenCalled();+ });++ // An IM inbound stores ``{token, mimetype}`` where a Web upload stores+ // ``{url, mime, kind}`` — the same media object, written by a different path.+ // A screenshot pasted into Feishu has to reach the Web queue as a picture, not+ // as a chip with nothing behind it.+ it('reads the token shape an IM inbound writes, not only the upload shape', () => {+ const { openImage } = mountQueued(+ item([+ { token: 'med_im1', name: 'screenshot.png', mimetype: 'image/png', size: 4096 },+ { token: 'med_im2', name: 'trace.log', mimetype: 'text/plain', size: 12 },+ ]),+ );++ expect(thumbs()).toHaveLength(1);+ expect(thumbs()[0].querySelector('img')?.getAttribute('src')).toBe('/api/media/med_im1');+ fireEvent.click(thumbs()[0]);+ expect(openImage).toHaveBeenCalledWith('/api/media/med_im1', { isolated: true });++ // And the file beside it is openable rather than inert.+ expect(chips()[0].getAttribute('data-queue-attachment')).toBe('file');+ expect(chips()[0].getAttribute('aria-label')).toBe('trace.log · LOG');+ });++ // The escape is what keeps a minted URL inside the media-proxy route, which is+ // the same test that decides whether it may become an <img> at all.+ it('does not let a token escape the media-proxy path', () => {+ mountQueued(item([{ token: '../secrets?x=1', name: 'odd.png', mimetype: 'image/png' }]));++ expect(thumbs()[0].querySelector('img')?.getAttribute('src')).toBe(+ '/api/media/..%2Fsecrets%3Fx%3D1',+ );+ });++ it('opens an image on its own, and a file in the file viewer', () => {+ const notes = { url: '/api/media/med_9', name: 'notes.pdf', mime: 'application/pdf' };+ const { openImage, openFile } = mountQueued(item([media('shot.png', 'med_1'), notes]));++ fireEvent.click(thumbs()[0]);+ // Stated, not inferred from the gallery's current contents: a queued file is+ // not in the transcript, and must stay un-pageable even once it is.+ expect(openImage).toHaveBeenCalledWith('/api/media/med_1', { isolated: true });++ fireEvent.click(chips()[0]);+ expect(openFile).toHaveBeenCalledWith({ url: '/api/media/med_9', name: 'notes.pdf' });+ });++ it('keeps the slot, the name and a way to read it when the picture will not load', () => {+ const { openFile } = mountQueued(item([media('console-log.png', 'med_1')]));+ const slot = () => thumbs()[0].querySelector('span')!.className;+ const before = slot();++ fireEvent.error(thumbs()[0].querySelector('img')!);++ expect(thumbs()).toHaveLength(1);+ expect(slot()).toBe(before);+ expect(thumbs()[0].getAttribute('data-queue-attachment')).toBe('image-unavailable');+ expect(thumbs()[0].getAttribute('aria-label')).toBe('console-log.png · PNG · Preview unavailable');+ // The picture is gone, so the filename has to be reachable by an action —+ // the viewer titles itself with it — not only by hovering the slot.+ fireEvent.click(thumbs()[0]);+ expect(openFile).toHaveBeenCalledWith({ url: '/api/media/med_1', name: 'console-log.png' });+ });++ // Capacity is one number now, so each width renders exactly the slots it has+ // room for and exactly one disclosure — rather than both widths' markup with+ // one of each pair hidden, which put unreachable controls in the tab order and+ // let a resize blur whichever one held focus.+ it.each([+ ['narrow', false, 2, 'Show 3 more attachments'],+ ['wide', true, 3, 'Show 2 more attachments'],+ ])('shows the %s inline run and counts exactly what it hides', (_width, wide, inline, label) => {+ viewport.set(wide as boolean);+ mountQueued(item(five));++ expect(thumbs()).toHaveLength(inline as number);+ expect(more()).toHaveLength(1);+ expect(more()[0].getAttribute('aria-label')).toBe(label);+ });++ // Nothing hidden, nothing disclosed: a `+0` control would be a focusable+ // element that promises something it cannot deliver.+ it.each([+ ['narrow', false, 2],+ ['wide', true, 3],+ ])('offers no disclosure when the %s run already holds everything', (_width, wide, count) => {+ viewport.set(wide as boolean);+ mountQueued(item(five.slice(0, count as number)));++ expect(thumbs()).toHaveLength(count as number);+ expect(more()).toHaveLength(0);+ });++ it('discloses the rest and collapses again without expanding the row text', () => {+ mountQueued(item(five));+ const text = row().querySelector('div[role="button"]')!;++ expect(row().className).not.toContain('flex-wrap');+ fireEvent.click(more()[0]);++ const sheet = document.querySelector('[data-queue-attachments="disclosed"]') as HTMLElement;+ expect(within(sheet).getAllByRole('button')).toHaveLength(5);+ // Source order, unchanged by being disclosed.+ expect(within(sheet).getAllByRole('button').map((b) => b.getAttribute('aria-label'))).toEqual(+ five.map((a) => `${a.name} · PNG`),+ );+ // The row wraps only now, and the text control is exactly as it was.+ expect(row().className).toContain('flex-wrap');+ expect(text.getAttribute('aria-expanded')).toBe('false');+ // The inline previews are gone — the sheet is the one place the files are+ // listed, so nothing is shown twice — and the one control stays put, now+ // offering the way back.+ expect(thumbs()).toHaveLength(5);+ expect(document.querySelector('[data-queue-attachments="inline"]')).toBeNull();+ expect(more()).toHaveLength(1);+ expect(more()[0].getAttribute('aria-label')).toBe('Collapse attachments');+ expect(more()[0].getAttribute('aria-expanded')).toBe('true');++ fireEvent.click(more()[0]);+ expect(document.querySelector('[data-queue-attachments="disclosed"]')).toBeNull();+ expect(row().className).not.toContain('flex-wrap');+ });++ // Unmounting the button under the user's finger is not a cosmetic problem: the+ // browser drops focus to the document, so the next Tab restarts from the top+ // of the page and the control they just used cannot be pressed again.+ it.each([+ ['narrow', false, 'Show 3 more attachments'],+ ['wide', true, 'Show 2 more attachments'],+ ])('leaves focus on the disclosure it was activated from (%s)', (_width, wide, collapsedLabel) => {+ viewport.set(wide as boolean);+ mountQueued(item(five));+ const control = more()[0];+ control.focus();++ fireEvent.click(control);++ expect(document.activeElement).toBe(control);+ expect(control.getAttribute('aria-label')).toBe('Collapse attachments');++ fireEvent.click(control);++ expect(document.activeElement).toBe(control);+ expect(control.getAttribute('aria-label')).toBe(collapsedLabel);+ });++ it('leaves the queued message itself alone while its files are inspected', () => {+ const onRemove = vi.fn();+ const onRecall = vi.fn();+ mountQueued(item(five), { onRemove, onRecall });++ fireEvent.click(thumbs()[0]);+ fireEvent.click(more()[0]);+ fireEvent.click(more()[0]);++ expect(onRemove).not.toHaveBeenCalled();+ expect(onRecall).not.toHaveBeenCalled();+ expect(screen.getByLabelText('Remove from queue')).toBeTruthy();+ });++ // Recall drops `content.attachments`, so it stays off for a row that carries+ // any — drawing them changes what the row shows, not what it can do.+ it('still refuses to recall a message that carries files', () => {+ mountQueued(item([media('shot.png', 'med_1')]));+ expect(screen.queryByLabelText('Recall to input')).toBeNull();++ cleanup();+ mountQueued(queued({ text: 'plain', source: 'user', content: {} as WorkbenchMessage['content'] }));+ expect(screen.getByLabelText('Recall to input')).toBeTruthy();+ });++ it('keeps every attachment target a real button outside the row text control', () => {+ mountQueued(item([media('a.png', 'med_1'), { url: '/api/media/med_2', name: 'b.txt' }]));++ for (const target of [...thumbs(), ...chips(), ...more()]) {+ expect(target.tagName).toBe('BUTTON');+ expect(target.getAttribute('type')).toBe('button');+ // A sibling of the text, never inside it: inspecting a file cannot also+ // toggle the row's expansion.+ expect(target.closest('div[role="button"]')).toBeNull();+ }+ });++ // No URL to open, so no action can work — the name is shown rather than put+ // behind one, and the row still counts it.+ it('still shows and counts a file it cannot open', () => {+ mountQueued(item([{ name: 'orphan.bin' }, media('shot.png', 'med_1')]));++ expect(chips()).toHaveLength(1);+ expect(chips()[0].tagName).toBe('SPAN');+ expect(chips()[0].textContent).toContain('orphan.bin');+ expect(row().textContent).toContain('orphan.bin and 1 more');+ });++ // Crossing `sm` is the second way focus used to be lost, and the one no unit+ // test could see while capacity lived in CSS: the element holding focus became+ // `display:none`, and CSS cannot hand focus to whatever replaces it. Every case+ // below is a boundary crossing, and each has exactly one right answer — the+ // same element keeps focus, or the row's text takes it. Never the document.+ describe('across the sm breakpoint', () => {+ const text = () => row().querySelector('div[role="button"]') as HTMLElement;+ const three = five.slice(0, 3);++ it('keeps one element, and its focus, while a disclosure is still needed', () => {+ mountQueued(item(five));+ const control = more()[0];+ control.focus();++ viewport.set(true);++ // Same node, not a same-looking replacement — that distinction is the+ // whole fix, and it is what keeps the browser's focus where it was.+ expect(more()).toHaveLength(1);+ expect(more()[0]).toBe(control);+ expect(document.activeElement).toBe(control);+ // …and it now states the number this width actually hides.+ expect(control.getAttribute('aria-label')).toBe('Show 2 more attachments');+ });++ it('carries focus back the other way too', () => {+ viewport.set(true);+ mountQueued(item(five));+ const control = more()[0];+ control.focus();++ viewport.set(false);++ expect(more()[0]).toBe(control);+ expect(document.activeElement).toBe(control);+ expect(control.getAttribute('aria-label')).toBe('Show 3 more attachments');+ });++ // The reported case, end to end: three attachments, expanded narrow, widened,+ // then collapsed. The control is meaningful right up to the collapse, and+ // meaningless the instant after it.+ it('hands focus to the row text when collapsing leaves nothing to disclose', () => {+ mountQueued(item(three));+ const control = more()[0];+ control.focus();++ fireEvent.click(control);+ expect(document.activeElement).toBe(control);++ viewport.set(true);+ expect(more()[0]).toBe(control);+ expect(document.activeElement).toBe(control);++ fireEvent.click(control);++ expect(more()).toHaveLength(0);+ expect(document.body.contains(control)).toBe(false);+ expect(document.activeElement).toBe(text());+ });++ it('hands focus to the row text when widening makes the +1 unnecessary', () => {+ mountQueued(item(three));+ expect(more()[0].getAttribute('aria-label')).toBe('Show 1 more attachments');+ more()[0].focus();++ viewport.set(true);++ expect(thumbs()).toHaveLength(3);+ expect(more()).toHaveLength(0);+ expect(document.activeElement).toBe(text());+ });++ it('hands focus to the row text when narrowing drops the third preview', () => {+ viewport.set(true);+ mountQueued(item(five));+ thumbs()[2].focus();++ viewport.set(false);++ expect(thumbs()).toHaveLength(2);+ expect(document.activeElement).toBe(text());+ });++ it('leaves a surviving preview holding its own focus', () => {+ viewport.set(true);+ mountQueued(item(five));+ const first = thumbs()[0];+ first.focus();++ viewport.set(false);++ expect(document.activeElement).toBe(first);+ });++ // The transfer is conditional on this group having had focus in the first+ // place. A user part-way through the row's own actions must not be dragged+ // back to its text because an attachment control happened to disappear.+ it('never takes focus from a control that is not its own', () => {+ mountQueued(item(three));+ const remove = screen.getByLabelText('Remove from queue');+ remove.focus();++ viewport.set(true);++ expect(more()).toHaveLength(0);+ expect(document.activeElement).toBe(remove);+ });++ // A mouse user has not focused the button, so collapsing it away must not+ // move focus either — there was none in the group to move.+ it('moves nothing when the disclosure is clicked without focus', () => {+ mountQueued(item(three));+ viewport.set(true);+ expect(more()).toHaveLength(0);++ viewport.set(false);+ fireEvent.click(more()[0]);+ fireEvent.click(more()[0]);++ expect(document.activeElement).toBe(document.body);+ });+ });+});diff --git a/ui/src/components/workbench/MessageAttachmentIdentity.test.tsx b/ui/src/components/workbench/MessageAttachmentIdentity.test.tsxnew file mode 100644index 000000000..3f9e4daff--- /dev/null+++ b/ui/src/components/workbench/MessageAttachmentIdentity.test.tsx@@ -0,0 +1,189 @@+/* @vitest-environment jsdom */++import { cleanup, fireEvent, render as mount, screen } from '@testing-library/react';+import { createInstance } from 'i18next';+import type { ReactElement } from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, describe, expect, it, vi } from 'vitest';++// ``ChatPage`` reaches the composer's mention editor at import time, which reads+// ``matchMedia`` on the module's first evaluation — before any test body runs.+// A mounted queue row also subscribes to the `sm` breakpoint, so the stub has to+// answer the whole `MediaQueryList` surface, not only ``matches``.+vi.hoisted(() => {+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn().mockReturnValue({+ matches: false,+ addEventListener: () => {},+ removeEventListener: () => {},+ }),+ });+});++import en from '../../i18n/en.json';+import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';+import { ToastProvider } from '../../context/ToastProvider';+import { FileViewerContext } from '../ui/file-viewer-context';+import { ImageViewerContext } from '../ui/image-viewer-context';+import { MessageRow, QueueRow } from './ChatPage';++// One message, two surfaces. A queued message and the delivered message it turns+// into carry the SAME ``content`` — the delivery projection passes it through+// verbatim — so anything either surface derives on its own is a place the two can+// disagree. They read through one boundary now, and these are the properties that+// boundary is there to hold.++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++afterEach(cleanup);++const render = (ui: ReactElement) =>+ renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ToastProvider>+ <MemoryRouter>{ui}</MemoryRouter>+ </ToastProvider>+ </I18nextProvider>,+ );++const session = (): WorkbenchSession =>+ ({+ id: 'ses_01J8XK5M8T',+ scope_id: 'scope-1',+ project_id: 'proj-1',+ title: 'Model Hub',+ agent_id: 'agt-1',+ agent_name: 'claude',+ agent_backend: 'claude_code',+ status: 'active',+ agent_status: 'idle',+ created_at: '2026-07-27T04:00:00Z',+ updated_at: '2026-07-27T04:00:00Z',+ metadata: {},+ }) as WorkbenchSession;++// Exactly what ``core/handlers/message_handler`` records for a screenshot and a+// log pasted into an IM channel: a media token and a mimetype, no URL.+const IM_CONTENT = {+ attachments: [+ { token: 'med_im1', name: 'feishu-screenshot.png', mimetype: 'image/png', size: 4096 },+ { token: 'med_im2', name: 'trace.log', mimetype: 'text/plain', size: 12 },+ ],+} as WorkbenchMessage['content'];++const message = (type: 'queued' | 'message'): WorkbenchMessage =>+ ({+ id: 'msg_01J8XK5M8T',+ type,+ author: 'user',+ source: 'user',+ text: '',+ content: IM_CONTENT,+ metadata: {},+ created_at: '2026-07-27T04:04:00Z',+ }) as WorkbenchMessage;++describe('attachment identity survives delivery', () => {+ it('shows the same token-shaped image and file before and after the flush', () => {+ const queued = render(+ <QueueRow item={message('queued')} onRemove={() => undefined} onRecall={() => undefined} />,+ );+ const delivered = render(+ <MessageRow message={message('message')} session={session()} messageFontSize={13} />,+ );++ // The same media object, named the same way on both sides. Before this+ // boundary existed the queue drew a nameless chip and the transcript dropped+ // the row entirely, because both read ``url`` and an IM inbound writes none.+ for (const html of [queued, delivered]) {+ expect(html).toContain('/api/media/med_im1');+ expect(html).toContain('feishu-screenshot.png');+ expect(html).toContain('trace.log');+ }++ // And each is still the right KIND of thing: the image is fetched as an+ // <img>, the log is a click-through, on both surfaces.+ expect(queued).toContain('data-queue-attachment="image"');+ expect(queued).toContain('data-queue-attachment="file"');+ expect(delivered).toContain('<img src="/api/media/med_im1"');+ expect(delivered).not.toContain('<img src="/api/media/med_im2"');+ expect(delivered).toContain('href="/api/media/med_im2"');+ });++ // The queue opens a file rather than linking to it, so its URL is in the click+ // and not in the markup. Same URL, asked for the same way.+ it('opens the queued log at the URL the delivered one links to', () => {+ const openFile = vi.fn();+ mount(+ <I18nextProvider i18n={i18n}>+ <ImageViewerContext.Provider value={{ open: vi.fn() }}>+ <FileViewerContext.Provider value={{ open: openFile }}>+ <QueueRow item={message('queued')} onRemove={() => undefined} onRecall={() => undefined} />+ </FileViewerContext.Provider>+ </ImageViewerContext.Provider>+ </I18nextProvider>,+ );++ fireEvent.click(screen.getByLabelText('trace.log · LOG'));+ expect(openFile).toHaveBeenCalledWith({ url: '/api/media/med_im2', name: 'trace.log' });+ });++ it('keeps the uploader-supplied box on the delivered image', () => {+ // Reserving the box is what stops the transcript jumping when the bytes+ // land, so the dimensions have to cross the boundary with the URL.+ const delivered = render(+ <MessageRow+ message={+ {+ ...message('message'),+ content: {+ attachments: [+ { url: '/api/media/med_1', name: 'shot.png', mime: 'image/png', kind: 'image', width: 800, height: 600 },+ ],+ } as WorkbenchMessage['content'],+ } as WorkbenchMessage+ }+ session={session()}+ messageFontSize={13}+ />,+ );+ expect(delivered).toMatch(/aspect-ratio:\s*800\s*\/\s*600/);+ });++ it('does not inline-render a third-party image on either surface', () => {+ const remote = {+ attachments: [{ url: 'https://files.example.com/a.png?sig=abc', name: 'a.png', mime: 'image/png' }],+ } as WorkbenchMessage['content'];++ const queued = render(+ <QueueRow+ item={{ ...message('queued'), content: remote } as WorkbenchMessage}+ onRemove={() => undefined}+ onRecall={() => undefined}+ />,+ );+ const delivered = render(+ <MessageRow+ message={{ ...message('message'), content: remote } as WorkbenchMessage}+ session={session()}+ messageFontSize={13}+ />,+ );++ // Neither surface may paint an <img> at a host that is not ours: the fetch+ // would happen the moment the row renders, with nobody asking for it.+ for (const html of [queued, delivered]) {+ expect(html).not.toContain('<img src="https://files.example.com');+ expect(html).toContain('a.png');+ }+ });+});diff --git a/ui/src/components/workbench/QueuedAttachments.tsx b/ui/src/components/workbench/QueuedAttachments.tsxnew file mode 100644index 000000000..6b317c95e--- /dev/null+++ b/ui/src/components/workbench/QueuedAttachments.tsx@@ -0,0 +1,315 @@+import * as React from 'react';+import { useTranslation } from 'react-i18next';+import clsx from 'clsx';+import { ChevronDown, FileText, Image as ImageIcon, ImageOff } from 'lucide-react';++import { useFileViewer } from '@/components/ui/file-viewer-context';+import { useImageViewer } from '@/components/ui/image-viewer-context';+import { isProxyMediaUrl } from '@/lib/mediaProxy';+import type { MessageAttachment } from '@/lib/messageAttachments';++// What a queued message's attachments look like on the one line the queue strip+// gives them. Design: avibe-docs `design/queued-message-attachments` QMA 01–04;+// contract: docs/plans/2026-09-19-queued-attachment-previews.md.+//+// Why this is not `ChatImage` / `FileCard`: those two are the *transcript's*+// attachment treatment — a 352x240 image and a 240px-wide card. A queue row is+// 36px tall and has to stay 36px tall, so the recognition unit here is a 20x20+// thumbnail and a 20px single-line chip. What is shared with the transcript is+// the part that matters for correctness: the same same-origin proxy test+// deciding what may be fetched at all, and the same two viewers for inspecting+// a file.++// "console-log.png · PNG", plus "· Preview unavailable" once an image is known+// not to render. The name is data and the state is i18n, joined the way the file+// viewer's own meta line joins them.+const useAccessibleName = () => {+ const { t } = useTranslation();+ return React.useCallback(+ (att: MessageAttachment, unavailable: boolean) => {+ const name = att.name || t('chat.queue.attachments.untitled');+ const ext = att.name.includes('.') ? (att.name.split('.').pop() || '').toUpperCase() : '';+ return [name, ext || null, unavailable ? t('chat.queue.attachments.previewUnavailable') : null]+ .filter(Boolean)+ .join(' · ');+ },+ [t],+ );+};++// Every target sits in the same 24px band the row's icon buttons already use, so+// no attachment — of any type, in any load state — can make a collapsed row+// taller than a text-only one. The visual inside it is 20px; the band plus+// ``after`` grows the hit area to 24x36 CSS px, which consumes exactly the 4px+// gap to each neighbour without overlapping it.+const TARGET =+ 'relative flex h-6 shrink-0 items-center rounded-[5px] text-muted transition-colors hover:text-foreground ' ++ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-cyan/40 ' ++ "after:absolute after:-inset-x-0.5 after:-inset-y-1.5 after:content-['']";++const PILL = 'flex h-5 items-center gap-1 rounded-[5px] border px-1';++const Thumb: React.FC<{ att: MessageAttachment }> = ({ att }) => {+ const label = useAccessibleName();+ const imageViewer = useImageViewer();+ const fileViewer = useFileViewer();+ // One state, one meaning: the browser told us this src does not render. The+ // slot keeps its geometry either way; only the glyph and the name change.+ const [failed, setFailed] = React.useState(false);+ const name = label(att, failed);+ return (+ <button+ type="button"+ // A failed thumbnail hands its click to the file viewer instead: that is+ // where the complete filename is readable without hovering, which is the+ // only place left to read it once the picture is gone.+ onClick={() =>+ failed+ ? fileViewer?.open({ url: att.url, name: att.name })+ : imageViewer?.open(att.url, { isolated: true })+ }+ aria-label={name}+ title={name}+ data-queue-attachment={failed ? 'image-unavailable' : 'image'}+ className={TARGET}+ >+ <span className="relative flex size-5 items-center justify-center overflow-hidden rounded-[4px] border border-border bg-surface-3">+ {/* Under the picture, so the slot is never empty: this is what shows+ while the image is still loading and what remains when it fails. */}+ {failed ? (+ <ImageOff className="size-[11px]" aria-hidden="true" />+ ) : (+ <ImageIcon className="size-[11px]" aria-hidden="true" />+ )}+ {!failed && (+ <img+ src={att.url}+ alt=""+ loading="lazy"+ decoding="async"+ onError={() => setFailed(true)}+ className="absolute inset-0 size-full object-cover"+ />+ )}+ </span>+ </button>+ );+};++const Chip: React.FC<{ att: MessageAttachment }> = ({ att }) => {+ const { t } = useTranslation();+ const label = useAccessibleName();+ const fileViewer = useFileViewer();+ const name = label(att, false);+ const pill = clsx(PILL, 'border-border bg-surface-3 text-[10.5px]');+ const body = (+ <>+ <FileText className="size-[11px] shrink-0" aria-hidden="true" />+ {/* A narrow layout shrinks the name back towards the type glyph rather+ than taking width from the text and the row's actions. The complete+ name is never hover-only: the viewer this chip opens puts it in its+ title, including for a type it cannot render and a URL it won't fetch. */}+ <span className="max-w-[52px] truncate sm:max-w-[88px]">+ {att.name || t('chat.queue.attachments.untitled')}+ </span>+ </>+ );+ if (!att.url) {+ // Nothing to open. The name still belongs on the row, so it is shown rather+ // than put behind an action that cannot work.+ return (+ <span data-queue-attachment="file-inert" title={name} className={clsx(TARGET, 'after:hidden')}>+ <span className={pill}>{body}</span>+ </span>+ );+ }+ if (!isProxyMediaUrl(att.url)) {+ // A third-party URL is opened the way a delivered attachment opens one: the+ // `FileCard`'s plain external link. The in-app viewer deliberately refuses+ // to fetch a host that is not ours, so routing this there would reach a+ // modal that can only ever say "preview failed" — the name would be+ // readable, but the file would not.+ return (+ <a+ href={att.url}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={name}+ title={name}+ data-queue-attachment="file-external"+ className={TARGET}+ >+ <span className={pill}>{body}</span>+ </a>+ );+ }+ return (+ <button+ type="button"+ onClick={() => fileViewer?.open({ url: att.url, name: att.name })}+ aria-label={name}+ title={name}+ data-queue-attachment="file"+ className={TARGET}+ >+ <span className={pill}>{body}</span>+ </button>+ );+};++const Item: React.FC<{ att: MessageAttachment }> = ({ att }) =>+ att.image ? <Thumb att={att} /> : <Chip att={att} />;++const Disclosure: React.FC<{+ count: number;+ expanded: boolean;+ onToggle: () => void;+}> = ({ count, expanded, onToggle }) => {+ const { t } = useTranslation();+ const label = expanded+ ? t('chat.queue.attachments.collapse')+ : t('chat.queue.attachments.showMore', { count });+ return (+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={expanded}+ aria-label={label}+ title={label}+ data-queue-attachment-more="true"+ className={TARGET}+ >+ <span className={clsx(PILL, 'border-border-strong bg-muted-soft font-mono text-[10px] font-bold')}>+ {!expanded && t('chat.queue.attachments.more', { count })}+ <ChevronDown className={clsx('size-[9px] shrink-0', expanded && 'rotate-180')} aria-hidden="true" />+ </span>+ </button>+ );+};++// How many attachments fit on the collapsed line: three at a desktop width, two+// below `sm`.+//+// This is one number, read once, rather than two mirrored sets of classes. The+// CSS version made a *layout* own focus: one logical disclosure existed as two+// elements (`sm:hidden` / `hidden sm:flex`) and the third slot as a+// `hidden sm:flex` wrapper, so crossing the breakpoint turned whichever one held+// focus into `display:none`. The browser blurs such an element and CSS cannot+// hand focus to its replacement, so focus fell to the document — the same defect+// as unmounting a focused button, reached by a different route.+//+// This is a media-query *change* listener, not element measurement: it fires+// twice per breakpoint crossing for the whole page, reads no geometry, and does+// not grow with the number of rows in the strip.+const WIDE_QUERY = '(min-width: 640px)'; // the `sm` token+const INLINE_CAPACITY = { narrow: 2, wide: 3 };++const readWide = () =>+ typeof window !== 'undefined' && Boolean(window.matchMedia?.(WIDE_QUERY).matches);++// The inline group, between the row's text and its actions.+//+// Exactly one disclosure button exists per row, and it is the same DOM element+// for as long as a disclosure action is available at all — across expand,+// collapse and breakpoint changes alike. When it stops being available, focus is+// handed to `onFocusEscape` rather than left on a hidden node or dropped.+export const QueuedAttachmentGroup: React.FC<{+ attachments: MessageAttachment[];+ expanded: boolean;+ onToggle: () => void;+ /**+ * Where focus goes when this group loses the element that was holding it — the+ * row's own text control. Only ever called when focus was inside this group+ * immediately before the change that removed it.+ */+ onFocusEscape?: () => void;+}> = ({ attachments, expanded, onToggle, onFocusEscape }) => {+ const root = React.useRef<HTMLDivElement>(null);+ // Set immediately before a change that may remove the focused node, read once+ // the new DOM is committed. Nothing else sets it, so a group that did not own+ // focus can never take it from whoever does.+ const held = React.useRef(false);+ const hold = React.useCallback(() => {+ const active = document.activeElement;+ held.current = Boolean(active && root.current?.contains(active));+ }, []);++ // `hold()` runs inside the listener, while the DOM that is about to change is+ // still the one on screen. That is the only moment at which "who has focus+ // right now" is still answerable — by the time React has committed, a removed+ // element has already taken focus to the document with it.+ const [wide, setWide] = React.useState(readWide);+ React.useEffect(() => {+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;+ const media = window.matchMedia(WIDE_QUERY);+ // Reconcile anything that moved between the first render and this effect.+ // No focus bookkeeping: nothing was removed under a user yet.+ setWide(media.matches);+ const onChange = (event: MediaQueryListEvent) => {+ hold();+ setWide(event.matches);+ };+ media.addEventListener('change', onChange);+ return () => media.removeEventListener('change', onChange);+ }, [hold]);+ const capacity = wide ? INLINE_CAPACITY.wide : INLINE_CAPACITY.narrow;++ React.useLayoutEffect(() => {+ if (!held.current) return;+ held.current = false;+ // The element survived the change, so the browser kept focus on it and there+ // is nothing to move.+ if (root.current?.contains(document.activeElement)) return;+ onFocusEscape?.();+ });++ const total = attachments.length;+ const hiddenCount = Math.max(0, total - capacity);+ if (total === 0) return null;+ return (+ <div+ ref={root}+ className="flex shrink-0 items-center gap-1"+ data-queue-attachments={expanded ? 'expanded' : 'inline'}+ >+ {/* Disclosing replaces the inline previews rather than adding to them: the+ sheet below lists every attachment exactly once, in source order. */}+ {!expanded && attachments.slice(0, capacity).map((att, i) => <Item key={i} att={att} />)}+ {/* Rendered whenever there is something to disclose or something disclosed,+ always in this position, so the button a keyboard user is standing on+ keeps its identity through the toggle and through a resize. */}+ {(expanded || hiddenCount > 0) && (+ <Disclosure+ count={hiddenCount}+ expanded={expanded}+ onToggle={() => {+ hold();+ onToggle();+ }}+ />+ )}+ </div>+ );+};++// The disclosed remainder: the same row wrapped onto a second line, not a second+// strip — ordering, identity and the row's own actions are untouched, and the+// queue's existing 128px scroll body absorbs the extra height.+//+// The row gap is 12px, not the 4px used between neighbours on one line, and the+// difference is a hit-testing fact rather than a spacing preference: `TARGET`+// extends each 24px band by 6px above and below, so two stacked targets claim+// 12px of vertical space between their bands. Give them 4px and the extensions+// overlap by 8px — measured at 390px, a tap three pixels below one thumbnail+// opened the file on the next line. At 12px they meet exactly and never cross,+// which is the same geometry the disclosure-to-sheet boundary already has.+export const QueuedAttachmentSheet: React.FC<{ attachments: MessageAttachment[] }> = ({ attachments }) => (+ <div+ data-queue-attachments="disclosed"+ className="order-last mt-1 flex w-full basis-full flex-wrap items-center gap-x-1 gap-y-3"+ >+ {attachments.map((att, i) => (+ <Item key={i} att={att} />+ ))}+ </div>+);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 5821d2fbf..7938fcfd2 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4329,7 +4329,15 @@"title": "Queued · {{count}}","sendNow": "Send now","recall": "Recall to input",- "remove": "Remove from queue"+ "remove": "Remove from queue",+ "attachments": {+ "untitled": "Attachment",+ "previewUnavailable": "Preview unavailable",+ "summary": "{{name}} and {{count}} more",+ "more": "+{{count}}",+ "showMore": "Show {{count}} more attachments",+ "collapse": "Collapse attachments"+ }}},"vaults": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 956e6b014..2faeda57c 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4329,7 +4329,15 @@"title": "排队中 · {{count}}","sendNow": "立即发送","recall": "撤回到输入框",- "remove": "移出队列"+ "remove": "移出队列",+ "attachments": {+ "untitled": "附件",+ "previewUnavailable": "预览不可用",+ "summary": "{{name}} 及其余 {{count}} 个",+ "more": "+{{count}}",+ "showMore": "显示其余 {{count}} 个附件",+ "collapse": "收起附件"+ }}},"vaults": {diff --git a/ui/src/lib/messageAttachments.test.ts b/ui/src/lib/messageAttachments.test.tsnew file mode 100644index 000000000..ff2af7b35--- /dev/null+++ b/ui/src/lib/messageAttachments.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import { readMessageAttachments } from './messageAttachments';++// The shared read boundary every attachment surface goes through. The properties+// here are the ones the queue row, the transcript row and the lightbox gallery+// all depend on, so they are held once rather than three times.++const content = (attachments: unknown) => ({ attachments });++// What ``core/handlers/message_handler`` writes for a file that arrived over an+// IM channel, and what ``public_delivery_payload`` then passes through verbatim.+const IM_IMAGE = { token: 'med_im1', name: 'feishu-screenshot.png', mimetype: 'image/png', size: 4096 };+const IM_FILE = { token: 'med_im2', name: 'trace.log', mimetype: 'text/plain', size: 12 };+// What ``vibe/ui_server`` writes for a Web upload: the proxy URL already minted.+const WEB_IMAGE = { url: '/api/media/med_1', name: 'shot.png', mime: 'image/png', kind: 'image', width: 800, height: 600 };++describe('readMessageAttachments — both producer shapes read as one', () => {+ it('mints a proxy URL from a token, and reads mimetype beside mime', () => {+ const [image, file] = readMessageAttachments(content([IM_IMAGE, IM_FILE]));++ expect(image).toMatchObject({ url: '/api/media/med_im1', name: 'feishu-screenshot.png', image: true });+ // A text file names itself the same way; it is simply not something to fetch+ // as an <img>.+ expect(file).toMatchObject({ url: '/api/media/med_im2', name: 'trace.log', image: false });+ });++ it('keeps a Web upload reading exactly as before, dimensions included', () => {+ // Server-supplied pixel size is what lets the transcript reserve the box+ // before the bytes arrive, so it has to survive the boundary.+ expect(readMessageAttachments(content([WEB_IMAGE]))[0]).toEqual({+ url: '/api/media/med_1',+ name: 'shot.png',+ image: true,+ width: 800,+ height: 600,+ });+ });++ it('preserves source order across mixed shapes', () => {+ const out = readMessageAttachments(content([IM_FILE, WEB_IMAGE, IM_IMAGE]));+ expect(out.map((a) => a.name)).toEqual(['trace.log', 'shot.png', 'feishu-screenshot.png']);+ });++ // The escape is what makes the minted URL satisfy the proxy test by+ // construction rather than by hope: it covers exactly the ``/ ? #`` that would+ // otherwise push the path out of the route.+ it('does not let a token escape the media-proxy path', () => {+ const [att] = readMessageAttachments(content([{ token: '../secrets?x=1', mimetype: 'image/png' }]));+ expect(att.url).toBe('/api/media/..%2Fsecrets%3Fx%3D1');+ expect(att.image).toBe(true);+ });++ // The gallery's whole membership rule is ``att.image``: an arbitrary remote URL+ // must never end up in a list the lightbox pages through, because paging would+ // fetch it.+ it('refuses to call a third-party image fetchable', () => {+ const [att] = readMessageAttachments(+ content([{ url: 'https://files.example.com/a.png?sig=abc', name: 'a.png', mime: 'image/png' }]),+ );+ expect(att.image).toBe(false);+ expect(att.url).toBe('https://files.example.com/a.png?sig=abc');+ });++ it('counts every admitted element, and ignores what is not one', () => {+ // A record with neither URL nor token still occupies its place — the number+ // of things on a row has to be the number of things in the message — while a+ // string or a null is not an attachment at all.+ const out = readMessageAttachments(content([{ name: 'orphan.bin' }, 'nope', null, IM_FILE]));+ expect(out.map((a) => a.name)).toEqual(['orphan.bin', 'trace.log']);+ expect(out[0].url).toBe('');+ });++ it('reads nothing out of content that has no attachments', () => {+ expect(readMessageAttachments(undefined)).toEqual([]);+ expect(readMessageAttachments({})).toEqual([]);+ expect(readMessageAttachments(content('not-an-array'))).toEqual([]);+ });+});diff --git a/ui/src/lib/messageAttachments.ts b/ui/src/lib/messageAttachments.tsnew file mode 100644index 000000000..748fb774f--- /dev/null+++ b/ui/src/lib/messageAttachments.ts@@ -0,0 +1,78 @@+import { isProxyMediaUrl } from '@/lib/mediaProxy';++// The one place a message's ``content.attachments`` is turned into something the+// UI can draw. Every surface that shows a user's files reads it here — the queue+// strip, the transcript row, and the lightbox gallery — because the same message+// passes through all three as it is queued, flushed and delivered, and a file+// that is recognisable in one of them has to stay recognisable in the next.+//+// Pure, and separate from the components that draw it, for the same reason+// ``annotationView`` is: the rule about which URL may become an <img> is a safety+// property, and belongs somewhere a test can hold it on its own.++export type MessageAttachment = {+ url: string;+ name: string;+ /** True only when the file is an image AND its URL is one we may fetch. */+ image: boolean;+ /** Server-supplied pixel size, when the producer recorded one. */+ width?: number;+ height?: number;+};++const asRecord = (value: unknown): Record<string, unknown> | null =>+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;++const asString = (value: unknown): string => (typeof value === 'string' ? value : '');++const asSize = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;++// A message carries its attachments in one of two shapes, because two different+// paths write them: a Web upload records ``{url, mime, kind, width, height}``+// (``vibe/ui_server`` mints the proxy URL at upload time), while an IM inbound+// records ``{token, name, mimetype, size}`` (``core/handlers/message_handler``)+// and leaves the URL to whoever renders it. The delivery projection passes+// ``content`` through verbatim, so the second shape survives the flush intact and+// reaches every surface below exactly as it was written. Both name the same media+// object, so both are read into the one shape the UI draws — otherwise a+// screenshot pasted into Feishu would be a nameless, unopenable chip on the+// queue and then vanish from the transcript entirely.+const mediaUrl = (record: Record<string, unknown>): string => {+ const url = asString(record.url);+ if (url) return url;+ const token = asString(record.token);+ // ``encodeURIComponent`` here is not cosmetic: it is what makes the minted URL+ // satisfy ``isProxyMediaUrl`` by construction, since the escape covers exactly+ // the ``/ ? #`` that would otherwise push the path outside the proxy route.+ return token ? `/api/media/${encodeURIComponent(token)}` : '';+};++// Reads the attachments in source order. Every admitted element produces an+// entry — one with no usable URL still counts and still carries its name,+// because the number of things on a row has to be the number of things in the+// message. What each surface then does with a URL-less entry is its own+// decision, not this function's.+export function readMessageAttachments(content: unknown): MessageAttachment[] {+ const raw = asRecord(content)?.attachments;+ if (!Array.isArray(raw)) return [];+ const out: MessageAttachment[] = [];+ for (const entry of raw) {+ const record = asRecord(entry);+ if (!record) continue;+ const url = mediaUrl(record);+ const mime = asString(record.mime) || asString(record.mimetype);+ // Only a same-origin media-proxy URL is rendered as an <img>: an arbitrary+ // remote URL would be fetched by the browser the moment the row paints, and+ // neither a queue row nor a transcript row paints because anyone asked it to.+ const image = (record.kind === 'image' || mime.startsWith('image/')) && isProxyMediaUrl(url);+ out.push({+ url,+ name: asString(record.name),+ image,+ width: asSize(record.width),+ height: asSize(record.height),+ });+ }+ return out;+}