Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): admit inline images by pixel size, not only bytes

vastsa49f23668d7c7
diff --git a/apps/desktop/electron/main/prompt-attachments.ts b/apps/desktop/electron/main/prompt-attachments.ts
index 81c908c1f..7063434b1 100644
--- a/apps/desktop/electron/main/prompt-attachments.ts
+++ b/apps/desktop/electron/main/prompt-attachments.ts
@@ -22,8 +22,10 @@ import {
ErrorCodes,
formatFileInsert,
formatPromptPathText,
+ imageExceedsInlineDimensions,
isSvgAttachment,
locateInlinePromptPaths,
+ probeImageDimensions,
SVG_MIME_TYPE,
MAX_INLINE_IMAGE_BYTES,
type AgentPromptAttachment,
@@ -271,13 +273,20 @@ export async function preparePromptAttachments(
}
const size = statSync(source.absolute).size;
- const inline = supportsVision && size <= MAX_INLINE_IMAGE_BYTES;
- const bytes = inline ? await readFile(source.absolute) : undefined;
+ const read = supportsVision && size <= MAX_INLINE_IMAGE_BYTES
+ ? await readFile(source.absolute)
+ : undefined;
+ // A provider rejects an image past its pixel limit even when the bytes are
+ // small; it takes the `@path` fallback instead of poisoning history (#1913).
+ const bytes = read && !imageExceedsInlineDimensions(probeImageDimensions(read))
+ ? read
+ : undefined;
+ const inline = bytes !== undefined;
const ref =
source.root === "attachment" && attachment.path.trim().startsWith("attachments/")
? attachment.path.trim()
- : bytes
- ? ensureAttachmentBlob(dataRoot, bytes)
+ : read
+ ? ensureAttachmentBlob(dataRoot, read)
: await ensureAttachmentBlobFromFile(dataRoot, source.absolute);
// The user's own position for this image: the draft named its path between
// words, so the text stays in the prompt and the transcript renders the
diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjs
index e27e6ab92..3e94257c3 100644
--- a/apps/desktop/test/composer-paste-files.test.mjs
+++ b/apps/desktop/test/composer-paste-files.test.mjs
@@ -265,7 +265,7 @@ test("file picker exposes files only", () => {
test("large image attachments avoid whole-file startup reads", () => {
assert.match(attachments, /async function hashFile\(path: string\)/);
assert.match(attachments, /createReadStream\(path\)/);
- assert.match(attachments, /const inline = supportsVision && size <= MAX_INLINE_IMAGE_BYTES/);
+ assert.match(attachments, /const read = supportsVision && size <= MAX_INLINE_IMAGE_BYTES/);
assert.match(attachments, /await copyFile\(source, target, fsConstants\.COPYFILE_EXCL\)/);
assert.doesNotMatch(attachments, /const bytes = readFileSync\(source\.absolute\)/);
assert.match(history, /const size = \(await stat\(canonical\)\)\.size/);
diff --git a/apps/desktop/test/prompt-inline-attachments.test.mjs b/apps/desktop/test/prompt-inline-attachments.test.mjs
index 9dc7e8367..dbaf3f52c 100644
--- a/apps/desktop/test/prompt-inline-attachments.test.mjs
+++ b/apps/desktop/test/prompt-inline-attachments.test.mjs
@@ -41,6 +41,28 @@ test("an image the draft named inline records that text and keeps its place", as
assert.equal(appendPromptFallbackPaths(content, [prepared]), content);
});
+test("an image past the pixel limit takes the path fallback instead of inline bytes", async (t) => {
+ const { data, path } = await fixture(t);
+ // A small, valid PNG header for a 780 x 14182 full-page screenshot (#1913).
+ const tall = Buffer.from(png);
+ tall.writeUInt32BE(780, 16);
+ tall.writeUInt32BE(14182, 20);
+ await writeFile(path, tall);
+ const attachment = { path, name: "pasted-a.png", kind: "image", mimeType: "image/png" };
+ const [prepared] = await preparePromptAttachments(
+ data,
+ sessionId,
+ undefined,
+ [attachment],
+ true,
+ "look at this",
+ );
+ assert.equal(prepared.message.kind, "image");
+ assert.match(prepared.message.ref, /^attachments\//);
+ assert.equal(prepared.inlineData, undefined);
+ assert.ok(appendPromptFallbackPaths("look at this", [prepared]).includes(prepared.fallbackPath));
+});
+
test("an image the prompt does not name inline keeps the trailing position", async (t) => {
const { data, path } = await fixture(t);
const attachment = { path, name: "pasted-a.png", kind: "image", mimeType: "image/png" };
diff --git a/crates/host-core/src/tools/image_dimensions.rs b/crates/host-core/src/tools/image_dimensions.rs
new file mode 100644
index 000000000..4c9938e43
--- /dev/null
+++ b/crates/host-core/src/tools/image_dimensions.rs
@@ -0,0 +1,147 @@
+//! Header-only pixel size probe for images Read inlines (issue #1913).
+//!
+//! A provider rejects an image whose pixel size is too large with a
+//! non-retriable 400 even when its bytes are small (a 780 x 14182 full-page
+//! screenshot). Once Read returns such an image it is persisted and replayed on
+//! every later request, so Read refuses it up front. Mirrors
+//! `packages/shared/src/image-dimensions.ts`; no image decoder is needed.
+
+/// Longest edge, in pixels, an inlined image may have. Matches
+/// `MAX_INLINE_IMAGE_EDGE_PX` in `packages/shared/src/image-dimensions.ts`.
+pub(crate) const MAX_INLINE_IMAGE_EDGE_PX: u32 = 8000;
+
+fn u16_be(bytes: &[u8], offset: usize) -> Option<u32> {
+ let pair = bytes.get(offset..offset + 2)?;
+ Some(u32::from(u16::from_be_bytes([pair[0], pair[1]])))
+}
+
+fn u16_le(bytes: &[u8], offset: usize) -> Option<u32> {
+ let pair = bytes.get(offset..offset + 2)?;
+ Some(u32::from(u16::from_le_bytes([pair[0], pair[1]])))
+}
+
+fn u24_le(bytes: &[u8], offset: usize) -> Option<u32> {
+ let triple = bytes.get(offset..offset + 3)?;
+ Some(u32::from_le_bytes([triple[0], triple[1], triple[2], 0]))
+}
+
+fn u32_be(bytes: &[u8], offset: usize) -> Option<u32> {
+ let quad = bytes.get(offset..offset + 4)?;
+ Some(u32::from_be_bytes([quad[0], quad[1], quad[2], quad[3]]))
+}
+
+fn png_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
+ if bytes.get(12..16)? != b"IHDR" {
+ return None;
+ }
+ Some((u32_be(bytes, 16)?, u32_be(bytes, 20)?))
+}
+
+fn gif_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
+ Some((u16_le(bytes, 6)?, u16_le(bytes, 8)?))
+}
+
+fn webp_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
+ match bytes.get(12..16)? {
+ b"VP8X" => Some((u24_le(bytes, 24)? + 1, u24_le(bytes, 27)? + 1)),
+ b"VP8L" if bytes.get(20) == Some(&0x2f) => {
+ let bits = u32::from_le_bytes(bytes.get(21..25)?.try_into().ok()?);
+ Some(((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1))
+ }
+ b"VP8 " if bytes.get(23..26)? == [0x9d, 0x01, 0x2a] => {
+ Some((u16_le(bytes, 26)? & 0x3fff, u16_le(bytes, 28)? & 0x3fff))
+ }
+ _ => None,
+ }
+}
+
+/// Walk JPEG marker segments up to the first start-of-frame header.
+fn jpeg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
+ let mut offset = 2;
+ loop {
+ if *bytes.get(offset)? != 0xff {
+ return None;
+ }
+ let marker = *bytes.get(offset + 1)?;
+ match marker {
+ 0xff => offset += 1,
+ 0x01 | 0xd0..=0xd7 => offset += 2,
+ // Entropy-coded data starts without a frame header: nothing to read.
+ 0xd9 | 0xda => return None,
+ 0xc0..=0xcf if !matches!(marker, 0xc4 | 0xc8 | 0xcc) => {
+ return Some((u16_be(bytes, offset + 7)?, u16_be(bytes, offset + 5)?));
+ }
+ _ => {
+ let length = u16_be(bytes, offset + 2)? as usize;
+ if length < 2 {
+ return None;
+ }
+ offset += 2 + length;
+ }
+ }
+ }
+}
+
+/// `(width, height)` from a PNG, JPEG, GIF, or WebP header, or `None` when the
+/// bytes are not a recognized image or the header is cut short.
+pub(crate) fn probe_image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
+ if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
+ png_dimensions(bytes)
+ } else if bytes.starts_with(b"\xff\xd8\xff") {
+ jpeg_dimensions(bytes)
+ } else if bytes.starts_with(b"GIF8") {
+ gif_dimensions(bytes)
+ } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
+ webp_dimensions(bytes)
+ } else {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn png(width: u32, height: u32) -> Vec<u8> {
+ let mut bytes = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR".to_vec();
+ bytes.extend(width.to_be_bytes());
+ bytes.extend(height.to_be_bytes());
+ bytes.extend([8, 2, 0, 0, 0]);
+ bytes
+ }
+
+ #[test]
+ fn reads_png_gif_and_jpeg_headers() {
+ assert_eq!(probe_image_dimensions(&png(780, 14182)), Some((780, 14182)));
+ let gif = [b"GIF89a".as_slice(), &[0x40, 0x01, 0xc8, 0x00, 0, 0, 0]].concat();
+ assert_eq!(probe_image_dimensions(&gif), Some((320, 200)));
+ let mut jpeg = vec![0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0, 0];
+ jpeg.extend([0xff, 0xc0, 0x00, 0x11, 0x08, 0x05, 0xea, 0x06, 0x98, 0x03]);
+ assert_eq!(probe_image_dimensions(&jpeg), Some((1688, 1514)));
+ }
+
+ #[test]
+ fn reads_webp_headers() {
+ let mut vp8x = b"RIFF\x00\x00\x00\x00WEBPVP8X".to_vec();
+ vp8x.extend([0; 8]);
+ vp8x.extend([0x0b, 0x03, 0x00, 0x65, 0x37, 0x00]);
+ assert_eq!(probe_image_dimensions(&vp8x), Some((780, 14182)));
+ let bits: u32 = (780 - 1) | ((1000 - 1) << 14);
+ let mut vp8l = b"RIFF\x00\x00\x00\x00WEBPVP8L\x00\x00\x00\x00\x2f".to_vec();
+ vp8l.extend(bits.to_le_bytes());
+ assert_eq!(probe_image_dimensions(&vp8l), Some((780, 1000)));
+ let mut vp8 = b"RIFF\x00\x00\x00\x00WEBPVP8 ".to_vec();
+ vp8.extend([
+ 0, 0, 0, 0, 0, 0, 0, 0x9d, 0x01, 0x2a, 0x0c, 0x03, 0xe8, 0x03,
+ ]);
+ assert_eq!(probe_image_dimensions(&vp8), Some((780, 1000)));
+ }
+
+ #[test]
+ fn unknown_or_truncated_headers_have_no_dimensions() {
+ assert_eq!(probe_image_dimensions(b"plain text"), None);
+ assert_eq!(probe_image_dimensions(&png(10, 10)[..20]), None);
+ assert_eq!(probe_image_dimensions(b"\xff\xd8\xff\xda\x00\x02"), None);
+ assert_eq!(probe_image_dimensions(b"\xff\xd8\xffgarbage"), None);
+ }
+}
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 44e59a27d..d1ee12cfb 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -26,6 +26,7 @@ use crate::workspace::{
mod grep_rg;
pub mod hashline;
pub mod ignore_rules;
+mod image_dimensions;
pub mod shell;
pub use hashline::{HashlineContext, HashlineStore};
@@ -1437,6 +1438,19 @@ fn read_image_block(
format!("{display} does not look like a valid {mime} image"),
));
}
+ // A small file can still exceed the pixel size providers accept; inlining
+ // it would fail every later request that replays this result (#1913).
+ if let Some((width, height)) = image_dimensions::probe_image_dimensions(&bytes) {
+ let limit = image_dimensions::MAX_INLINE_IMAGE_EDGE_PX;
+ if width.max(height) > limit {
+ return Err((
+ "TOOL_FAILED".into(),
+ format!(
+ "{display} is {width}x{height} px; images whose longest edge exceeds {limit} px are not inlined"
+ ),
+ ));
+ }
+ }
use base64::Engine as _;
let data = base64::engine::general_purpose::STANDARD.encode(&bytes);
Ok(json!({
@@ -3913,7 +3927,7 @@ mod tests {
// Minimal real signatures so the sniffing branch is exercised.
let png = b"\x89PNG\r\n\x1a\nfake-png-body";
let jpeg = b"\xff\xd8\xff\xe0fake-jpeg-body";
- let gif = b"GIF89afake-gif-body";
+ let gif = b"GIF89a\x01\x00\x01\x00fake-gif-body";
let webp = b"RIFF\x00\x00\x00\x00WEBPVP8 fake-webp-body";
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.png"), png).unwrap();
@@ -4000,6 +4014,43 @@ mod tests {
assert_eq!(error.0, "TOOL_FAILED");
}
+ #[tokio::test]
+ async fn read_refuses_images_past_the_pixel_limit() {
+ // A small, valid PNG header for a 780 x 14182 full-page screenshot.
+ let mut tall = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR".to_vec();
+ tall.extend(780u32.to_be_bytes());
+ tall.extend(14182u32.to_be_bytes());
+ tall.extend([8, 2, 0, 0, 0]);
+ let mut wide = tall.clone();
+ wide[16..24].copy_from_slice(&[0, 0, 0x1f, 0x40, 0, 0, 0x03, 0x0c]);
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("page.png"), &tall).unwrap();
+ std::fs::write(dir.path().join("edge.png"), &wide).unwrap();
+
+ let result = execute_tool(
+ Some(dir.path()),
+ None,
+ "Read",
+ &serde_json::json!({ "path": "page.png" }),
+ 5_000,
+ )
+ .await;
+ assert!(!result.ok);
+ assert_eq!(result.error_code.as_deref(), Some("TOOL_FAILED"));
+ assert!(result.content.to_string().contains("780x14182 px"));
+
+ // Exactly at the limit is still inlined.
+ let result = execute_tool(
+ Some(dir.path()),
+ None,
+ "Read",
+ &serde_json::json!({ "path": "edge.png" }),
+ 5_000,
+ )
+ .await;
+ assert!(result.ok, "8000 x 780 should inline: {}", result.content);
+ }
+
#[tokio::test]
async fn security_denylist_blocks_read_write_edit_and_hides_search_results() {
let dir = tempfile::tempdir().unwrap();
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 1aa790497..ff14d6526 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -139,7 +139,8 @@ transcript-read API. The core runs no title completion of its own.
boundary, persist image bytes by SHA-256, and retain only attachment refs in
the durable user message. Only an image that is within the 10 MB inline
bound for a vision model is read into memory; larger images use streamed
- hashing/copying and the existing safe path fallback
+ hashing/copying and the existing safe path fallback. An image whose header
+ reports a longest edge above 8000 px (D675) also takes the path fallback
A `pi-desktop://session/<id>` link in the draft is resolved in the same step
into a bounded excerpt attachment: the same project only, the current
conversation dropped before any read, and the runtime quotes it to the model
@@ -817,7 +818,10 @@ attachment, scratch, and project roots. Each image remains subject to the 10 MB
safety bound, and restored history has a 30 MB aggregate raw-byte budget.
The newest refs are considered first; all eligible images remain image blocks
when the history fits, while over-budget or oversized images become safe
-`@path` fallbacks. An image whose message names it inline (`inlinePath`) is
+`@path` fallbacks; so do images whose header reports a longest edge above
+8000 px (D675). Every provider request also replaces any image block past that
+pixel limit, in user prompts and tool results alike, with a text notice naming
+its size, so a session that already holds one recovers. An image whose message names it inline (`inlinePath`) is
spliced back into the prompt at that position, so a restored turn keeps the
order the user wrote. Reads are bounded by the admitted file size. Base64 is
transient and never restored into durable UI messages or transcript records.
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 9713cc201..349cd79b2 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -336,6 +336,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.
| D669 | `@` queries search past a truncated file index | **Amend D124: while the 8000-entry `fs/index` snapshot is truncated, a non-empty `@` query is also searched over the root's full listing through the read-only Electron channel `pi-desktop/fs/search` once typing pauses, and its best 50 rows merge with the local matches. A complete index never searches. Remote sessions keep their snapshot. No host RPC, storage, or schema change.** | The shallowest-8000-entry index left a script several folders down matching no query at all, even though the truncation note invited the reader to refine it (issue #1781). |
| D671 | Inline generative UI visualizations | **Amend D114: local sessions get a second host-owned contained root `<data_dir>/visualizations/<sessionId>/` for `.html` fragments only (Read/Write/Edit, auto-allowed like scratch, never in remote or contract sessions). A standalone `::visualize{"path","title"}` reply line renders the fragment inline through a sandboxed `pi-genui://session/<sid>/<file>` iframe (`sandbox="allow-scripts"`, strict CSP, no network). Builtin skill `pi-desktop/visualize`. No schema change.** | Interactive explanations need an embedded page; ADR gen-ui-inline-visualization. |
| D674 | Per-turn changed-files summary under a finished reply | **A completed reply whose turn recorded workspace review changes renders one read-only `TurnChangesCard` below its answer and above `entryExtra`, built only from that turn's message-owned `details.review` records (no new capture, IPC, or persistence). Rows merge edits per path (`D` if the turn ends by deleting, else `A` if any edit created the file, else `M`; counts summed; rolled-back files stay listed and struck through). Up to four files use relaxed rows, more use dense rows, and rows past 12 fold into `+N more`. Clicking a row opens Review on that file's recorded changes; the per-call review rows and the Review tab are unchanged.** | Issue #1891, design 10 (adaptive density): the per-call review rows answer "what did this call change", and Review answers it for the whole session, but nothing answered "what did this turn change" without counting rows. |
+| D675 | Inline images are admitted by pixel size as well as bytes | **Amend D361: an image whose PNG/JPEG/GIF/WebP header reports a longest edge above `MAX_INLINE_IMAGE_EDGE_PX` (8000) is never inlined. Host Read refuses it with `TOOL_FAILED`; prompt attachments and restored history take the existing `@path` fallback; and the runtime's last provider view replaces any such image block (user or tool result) with a text notice naming its size. The probe reads headers only (no decoder); unknown dimensions keep the byte-only rule. No protocol, schema, or persisted-format change.** | Issue #1913: a 1.89 MB, 780 x 14182 full-page screenshot passed every byte check, the provider rejected it with a non-retriable 400, and replay made every later request in that session fail. Dropping is deterministic for the same bytes, so the request prefix and prompt caching stay stable; resampling would need an image decoder and is deferred. |
## M0. Model catalog decisions
@@ -8016,3 +8017,26 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
The per-call review rows and the Review tab otherwise keep their behavior.
- Covered by `apps/desktop/test/turn-changes-card.test.mjs`. See
`04-ux/08-component-spec.md` §4.4 and E2E-CHAT-turn-changed-files-summary.
+
+## 2026-10-28 — Pixel-size image admission (D675)
+
+- D675 adds a header-only pixel-size probe (`packages/shared/src/image-dimensions.ts`,
+ mirrored in `crates/host-core/src/tools/image_dimensions.rs`) for PNG, JPEG,
+ GIF, and WebP. An image whose longest edge exceeds 8000 px is not inlined
+ (issue #1913).
+- Host Read refuses such a file with `TOOL_FAILED` and a message naming its
+ size, so it never enters history. Prompt attachments and restored history
+ keep the image ref and send the existing `@path` fallback instead of bytes.
+- `convertToLlm` replaces any remaining oversized image block (older sessions,
+ plugin or MCP results) with `[Image omitted: WxH px exceeds the 8000 px
+ longest-edge limit for model input.]`, which recovers a session that already
+ fails every request. The same bytes always produce the same notice, so
+ prompt caching is unaffected.
+- Images whose dimensions cannot be read keep the previous byte-only rule.
+ Resampling an oversized image instead of dropping it needs a decoder and is
+ not part of this change.
+- Covered by `packages/shared/src/image-dimensions.test.ts`,
+ `packages/agent-runtime/src/image-admission.test.ts`,
+ `packages/agent-runtime/src/attachment-history.test.ts`,
+ `apps/desktop/test/prompt-inline-attachments.test.mjs`, and host-core
+ `tools::image_dimensions` / `read_refuses_images_past_the_pixel_limit` tests.
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 82dbf5f7c..b8fa938bc 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -112,6 +112,7 @@ pi 消费排队输入时保留渲染器提供的消息 id;即使补充输入
6. 在 Electron main 的会话绑定路径边界上校验结构化附件,按 SHA-256 持久化
图片字节,持久用户消息中只保留附件引用。只有处于视觉模型 10 MB 内联上限
之内的图片才会被读进内存;更大的图片走流式哈希/复制以及既有的安全路径回退。
+ 文件头显示最长边超过 8000 px 的图片(D675)同样走路径回退。
草稿内联命名过位置的图片会把那段 `@path` 文本作为 `inlinePath` 随持久消息和
sidecar 附件传递;运行时据此把图片块放在用户写下的位置,而不是统一追加在提示文本之后
草稿里的 `pi-desktop://session/<id>` 链接在同一步骤里解析成有界摘录附件:只限
@@ -623,7 +624,9 @@ Goal 批准所承诺的内容与 Plan 批准所承诺的内容完全相同:`mo
同样的重复还会让下一个边界的估算翻倍,并让备用模型拿到的末行无法被 `continue()` 续跑(D620)。
- 视觉运行时只从会话绑定的附件、scratch 与项目根目录中水合持久化的图片引用。
处于 10 MB 内联安全上限之内的图片会成为临时的 pi-ai 图片块;超限或不可用的
- 图片则退化为安全的 `@path` 回退。消息里内联命名过位置的图片(`inlinePath`)
+ 图片则退化为安全的 `@path` 回退;文件头显示最长边超过 8000 px 的图片(D675)
+ 同样如此。每次提供商请求还会把超过该像素上限的图片块(用户提示与工具结果都算)
+ 替换成写明尺寸的文本说明,因此已经带着这种图片的会话也能恢复。消息里内联命名过位置的图片(`inlinePath`)
会按那个位置拼回提示内容,重启后仍是用户写下的顺序。超限历史的水合会直接复制文件,不会先把内容
读进内存。Base64 绝不会被还原进持久的 UI 消息或转录记录。
- 失败的助理消息仍然是持久的诊断记录条目,但
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index bb8c2fea6..cbacd7afe 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -339,6 +339,7 @@
| D669 | `@` 查询越过被截断的文件索引 | **修订 D124:8000 条的 `fs/index` 快照被截断时,非空的 `@` 查询会在输入停顿后,通过只读的 Electron 通道 `pi-desktop/fs/search` 在该根目录的完整清单中搜索,最好的 50 行与本地匹配合并。完整的索引从不搜索。远程会话保持使用快照。不改变主机 RPC、存储或 schema。** | 只保留最浅 8000 条的索引,会让深几层目录里的脚本对任何查询都匹配不到,而截断提示还在邀请用户细化查询(issue #1781)。 |
| D671 | 对话内联生成式 UI 可视化 | **修订 D114:本地会话新增第二个由宿主拥有的受控根目录 `<data_dir>/visualizations/<sessionId>/`,仅用于 `.html` 片段(Read/Write/Edit,与 scratch 一样免确认,远程会话和合约会话中不提供)。回复中单独一行 `::visualize{"path","title"}` 会通过沙箱化的 `pi-genui://session/<sid>/<file>` iframe(`sandbox="allow-scripts"`、严格 CSP、无网络)内联渲染该片段。内置 skill `pi-desktop/visualize`。不改变 schema。** | 交互式讲解需要内嵌页面;见 ADR gen-ui-inline-visualization。 |
| D674 | 已完成回复下方的按轮文件变更汇总 | **回合记录了工作区审核变更的已完成回复,会在回答下方、`entryExtra` 上方渲染一张只读的 `TurnChangesCard`,只由该回合消息拥有的 `details.review` 记录构建(不新增采集、IPC 或持久化)。按路径合并多次编辑(回合以删除结束为 `D`,否则有创建即为 `A`,其余为 `M`;计数累加;已回滚文件保留并显示删除线)。不超过四个文件用宽松行,更多用密集行,超过 12 行折叠为 `+N more`。点击一行会在审阅中打开该文件的记录变更;逐次调用的审核行和审阅选项卡保持不变。** | Issue #1891,设计 10(自适应密度):逐次调用的审核行回答“这次调用改了什么”,审阅回答整个会话的问题,但回答“这一轮改了什么”仍需自己数工具行。 |
+| D675 | 内联图片同时按像素尺寸与字节准入 | **修订 D361:PNG/JPEG/GIF/WebP 文件头显示最长边超过 `MAX_INLINE_IMAGE_EDGE_PX`(8000)的图片永不内联。Host Read 以 `TOOL_FAILED` 拒绝;提示附件与恢复的历史走既有的 `@path` 回退;运行时在最后的提供商视图中把这类图片块(用户或工具结果)替换为写明尺寸的文本说明。探测只读文件头(无解码器);读不出尺寸时保留仅按字节的规则。不改变协议、schema 或持久化格式。** | Issue #1913:一张 1.89 MB、780 x 14182 的整页截图通过了所有字节检查,提供商以不可重试的 400 拒绝,重放使该会话此后每个请求都失败。同样的字节总是被同样地丢弃,请求前缀与提示缓存保持稳定;重采样需要图像解码器,留待以后。 |
## M0. 模型目录决策
@@ -5585,3 +5586,22 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
状态。逐次调用的审核行和审阅选项卡的其他行为不变。
- 由 `apps/desktop/test/turn-changes-card.test.mjs` 覆盖。见
`04-ux/08-component-spec.md` §4.4 与 E2E-CHAT-turn-changed-files-summary。
+
+## 2026-10-28 — 按像素尺寸准入图片(D675)
+
+- D675 新增只读文件头的像素尺寸探测(`packages/shared/src/image-dimensions.ts`,
+ 在 `crates/host-core/src/tools/image_dimensions.rs` 中镜像),支持 PNG、JPEG、
+ GIF 与 WebP。最长边超过 8000 px 的图片不会内联(issue #1913)。
+- Host Read 以 `TOOL_FAILED` 拒绝这类文件,并在消息中写明尺寸,因此它不会进入
+ 历史。提示附件与恢复的历史保留图片引用,但发送既有的 `@path` 回退而不是字节。
+- `convertToLlm` 会把剩余的超限图片块(旧会话、插件或 MCP 结果)替换为
+ `[Image omitted: WxH px exceeds the 8000 px longest-edge limit for model
+ input.]`,从而恢复已经每次请求都失败的会话。同样的字节总是产生同样的说明,
+ 提示缓存不受影响。
+- 读不出尺寸的图片保留原先仅按字节的规则。把超限图片重采样而不是丢弃需要解码器,
+ 不在本次改动范围内。
+- 由 `packages/shared/src/image-dimensions.test.ts`、
+ `packages/agent-runtime/src/image-admission.test.ts`、
+ `packages/agent-runtime/src/attachment-history.test.ts`、
+ `apps/desktop/test/prompt-inline-attachments.test.mjs` 以及 host-core 的
+ `tools::image_dimensions` / `read_refuses_images_past_the_pixel_limit` 测试覆盖。
diff --git a/packages/agent-runtime/src/attachment-history.test.ts b/packages/agent-runtime/src/attachment-history.test.ts
index 48c22ebf6..c764edbc7 100644
--- a/packages/agent-runtime/src/attachment-history.test.ts
+++ b/packages/agent-runtime/src/attachment-history.test.ts
@@ -55,6 +55,31 @@ describe("hydrateAttachmentHistory", () => {
});
});
+ it("keeps the path fallback for an image past the pixel limit (#1913)", async () => {
+ await withTempDir(async (tmp) => {
+ const imgPath = resolve(tmp, "page.png");
+ const header = Buffer.alloc(33);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]).copy(header);
+ header.write("IHDR", 12, "latin1");
+ header.writeUInt32BE(780, 16);
+ header.writeUInt32BE(14182, 20);
+ await writeFile(imgPath, header);
+ const history = [
+ userMessage("msg-1", [
+ { name: "page.png", ref: imgPath, kind: "image", mimeType: "image/png", size: 33 },
+ ]),
+ ];
+
+ const hydrated = await hydrateAttachmentHistory(history, {
+ projectPath: tmp,
+ supportsVision: true,
+ });
+
+ expect(hydrated[0]?.attachments?.[0]?.data).toBeUndefined();
+ expect(hydrated[0]?.content).toContain(imgPath);
+ });
+ });
+
it("preserves historical image turns beyond ten messages when within the default byte budget", async () => {
await withTempDir(async (tmp) => {
const history: UiMessage[] = [];
diff --git a/packages/agent-runtime/src/attachment-history.ts b/packages/agent-runtime/src/attachment-history.ts
index f5bcdc54f..d7a332bc4 100644
--- a/packages/agent-runtime/src/attachment-history.ts
+++ b/packages/agent-runtime/src/attachment-history.ts
@@ -5,9 +5,11 @@ import { copyFile, mkdir, open, realpath, stat } from "node:fs/promises";
import { isAbsolute, relative, resolve } from "node:path";
import {
formatFileInsert,
+ imageExceedsInlineDimensions,
isSvgAttachment,
MAX_INLINE_IMAGE_BYTES,
MAX_INLINED_IMAGE_HISTORY_BYTES,
+ probeImageDimensions,
SVG_MIME_TYPE,
type MessageAttachment,
type UiMessage,
@@ -204,6 +206,9 @@ export async function hydrateAttachmentHistory(
try {
const bytes = await readFileAtRecordedSize(item.canonicalPath!, item.size!);
if (!bytes) return;
+ // An image past the provider's pixel limit keeps the path fallback, as
+ // a fresh prompt does, instead of failing every replay (#1913).
+ if (imageExceedsInlineDimensions(probeImageDimensions(bytes))) return;
item.attachment = {
...item.attachment,
data: bytes.toString("base64"),
diff --git a/packages/agent-runtime/src/image-admission.test.ts b/packages/agent-runtime/src/image-admission.test.ts
new file mode 100644
index 000000000..f0e0d67d2
--- /dev/null
+++ b/packages/agent-runtime/src/image-admission.test.ts
@@ -0,0 +1,81 @@
+import type { Message } from "@earendil-works/pi-ai";
+import type { UiMessage } from "@pi-desktop/shared";
+import { describe, expect, it } from "vitest";
+import { omitOversizedImages } from "./image-admission.js";
+import { convertToLlm } from "./pi-runtime-messages.js";
+import { toolResultFromUi } from "./runtime.js";
+
+function pngBase64(width: number, height: number): string {
+ const bytes = Buffer.alloc(33);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]).copy(bytes);
+ bytes.write("IHDR", 12, "latin1");
+ bytes.writeUInt32BE(width, 16);
+ bytes.writeUInt32BE(height, 20);
+ return bytes.toString("base64");
+}
+
+const TALL = pngBase64(780, 14182);
+const NORMAL = pngBase64(1688, 1514);
+const NOTICE =
+ "[Image omitted: 780x14182 px exceeds the 8000 px longest-edge limit for model input.]";
+
+describe("omitOversizedImages", () => {
+ it("replaces an oversized image in a user prompt and keeps its position", () => {
+ const messages: Message[] = [{
+ role: "user",
+ content: [
+ { type: "text", text: "before" },
+ { type: "image", data: TALL, mimeType: "image/png" },
+ { type: "image", data: NORMAL, mimeType: "image/png" },
+ ],
+ timestamp: 1,
+ }];
+ const [user] = omitOversizedImages(messages);
+ expect(user?.content).toEqual([
+ { type: "text", text: "before" },
+ { type: "text", text: NOTICE },
+ { type: "image", data: NORMAL, mimeType: "image/png" },
+ ]);
+ expect(messages[0]?.content).toHaveLength(3);
+ expect((messages[0]?.content as Array<{ type: string }>)[1]?.type).toBe("image");
+ });
+
+ it("returns the same array when every image is admissible", () => {
+ const messages: Message[] = [
+ { role: "user", content: "plain text", timestamp: 1 },
+ {
+ role: "user",
+ content: [
+ { type: "image", data: NORMAL, mimeType: "image/png" },
+ { type: "image", data: "not-an-image", mimeType: "image/png" },
+ ],
+ timestamp: 2,
+ },
+ ];
+ expect(omitOversizedImages(messages)).toBe(messages);
+ });
+
+ it("heals a restored session whose Read result holds an oversized image", () => {
+ const row = {
+ id: "tool-1",
+ role: "tool",
+ content: "",
+ toolName: "read",
+ toolCallId: "call-1",
+ toolStatus: "done",
+ toolResult: {
+ path: "page.png",
+ text: "Image file page.png (1890000 bytes, image/png); the image is attached to this result.",
+ images: [{ data: TALL, mimeType: "image/png" }],
+ },
+ } as unknown as UiMessage;
+ const restored = toolResultFromUi(row, 1);
+ expect(restored.content.some((block) => block.type === "image")).toBe(true);
+
+ const [outgoing] = convertToLlm([restored]);
+ expect(outgoing?.role).toBe("toolResult");
+ const content = outgoing?.content as Array<{ type: string; text?: string }>;
+ expect(content.some((block) => block.type === "image")).toBe(false);
+ expect(content.at(-1)).toEqual({ type: "text", text: NOTICE });
+ });
+});
diff --git a/packages/agent-runtime/src/image-admission.ts b/packages/agent-runtime/src/image-admission.ts
new file mode 100644
index 000000000..71825402f
--- /dev/null
+++ b/packages/agent-runtime/src/image-admission.ts
@@ -0,0 +1,47 @@
+/**
+ * Last-view pixel admission for provider image blocks (issue #1913).
+ *
+ * Host Read and prompt attachments refuse an oversized image before it is
+ * persisted, but older sessions, plugin and MCP tool results can still carry
+ * one. A provider rejects such an image with a non-retriable 400, and every
+ * later request replays it, so the session can never continue. Replacing the
+ * block with a notice is deterministic for the same bytes: the request prefix
+ * stays stable across turns and prompt caching keeps working.
+ */
+import type { Message } from "@earendil-works/pi-ai";
+import {
+ imageExceedsInlineDimensions,
+ omittedImageNotice,
+ probeBase64ImageDimensions,
+} from "@pi-desktop/shared";
+
+type ContentBlock = Exclude<Message["content"], string>[number];
+
+function admittedBlocks<T extends ContentBlock>(content: T[]): T[] {
+ let next: T[] | undefined;
+ content.forEach((block, index) => {
+ if (block.type !== "image" || typeof block.data !== "string") return;
+ const dimensions = probeBase64ImageDimensions(block.data);
+ if (!imageExceedsInlineDimensions(dimensions)) return;
+ next ??= content.slice();
+ next[index] = { type: "text", text: omittedImageNotice(dimensions) } as T;
+ });
+ return next ?? content;
+}
+
+/**
+ * Replace every image whose known pixel size exceeds the provider limit with
+ * a text notice. Returns the input array when nothing was replaced.
+ */
+export function omitOversizedImages(messages: Message[]): Message[] {
+ let next: Message[] | undefined;
+ messages.forEach((message, index) => {
+ if (message.role !== "user" && message.role !== "toolResult") return;
+ if (!Array.isArray(message.content)) return;
+ const content = admittedBlocks(message.content as ContentBlock[]);
+ if (content === message.content) return;
+ next ??= messages.slice();
+ next[index] = { ...message, content } as Message;
+ });
+ return next ?? messages;
+}
diff --git a/packages/agent-runtime/src/pi-runtime-messages.ts b/packages/agent-runtime/src/pi-runtime-messages.ts
index a595da960..e4a96b737 100644
--- a/packages/agent-runtime/src/pi-runtime-messages.ts
+++ b/packages/agent-runtime/src/pi-runtime-messages.ts
@@ -1,6 +1,7 @@
import type { Message } from "@earendil-works/pi-ai";
import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { omitOversizedImages } from "./image-admission.js";
export type CompactionSummaryMessage = {
role: "compactionSummary";
@@ -145,7 +146,9 @@ export function convertToLlm(messages: AgentMessage[]): Message[] {
break;
}
}
- return converted;
+ // Every provider request passes through here, including restored history
+ // that already holds an image the provider would reject (issue #1913).
+ return omitOversizedImages(converted);
}
function asProviderMessage(message: unknown): Message {
diff --git a/packages/shared/src/image-dimensions.test.ts b/packages/shared/src/image-dimensions.test.ts
new file mode 100644
index 000000000..261705b19
--- /dev/null
+++ b/packages/shared/src/image-dimensions.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from "vitest";
+import {
+ imageExceedsInlineDimensions,
+ MAX_INLINE_IMAGE_EDGE_PX,
+ omittedImageNotice,
+ probeBase64ImageDimensions,
+ probeImageDimensions,
+} from "./image-dimensions.js";
+
+function png(width: number, height: number): Uint8Array {
+ const bytes = new Uint8Array(33);
+ bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]);
+ bytes.set([0x49, 0x48, 0x44, 0x52], 12);
+ const view = new DataView(bytes.buffer);
+ view.setUint32(16, width);
+ view.setUint32(20, height);
+ bytes.set([8, 2, 0, 0, 0], 24);
+ return bytes;
+}
+
+/** A JPEG whose frame header follows `segments` APP1 blocks of `exifBytes`. */
+function jpeg(width: number, height: number, exifBytes = 16, segments = 1): Uint8Array {
+ const app1 = [0xff, 0xe1, ((exifBytes + 2) >> 8) & 0xff, (exifBytes + 2) & 0xff];
+ const sof = [0xff, 0xc2, 0, 17, 8, height >> 8, height & 0xff, width >> 8, width & 0xff, 3];
+ const segment = app1.length + exifBytes;
+ const bytes = new Uint8Array(2 + segment * segments + sof.length + 9);
+ bytes.set([0xff, 0xd8], 0);
+ for (let index = 0; index < segments; index++) bytes.set(app1, 2 + segment * index);
+ bytes.set(sof, 2 + segment * segments);
+ return bytes;
+}
+
+function gif(width: number, height: number): Uint8Array {
+ return new Uint8Array([
+ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
+ width & 0xff, width >> 8, height & 0xff, height >> 8, 0, 0, 0,
+ ]);
+}
+
+function riff(chunk: string, payload: number[]): Uint8Array {
+ const bytes = new Uint8Array(16 + payload.length);
+ bytes.set([...Buffer.from("RIFF"), 0, 0, 0, 0, ...Buffer.from("WEBP"), ...Buffer.from(chunk)]);
+ bytes.set(payload, 16);
+ return bytes;
+}
+
+function base64(bytes: Uint8Array): string {
+ return Buffer.from(bytes).toString("base64");
+}
+
+describe("image dimension probe", () => {
+ it("reads PNG, GIF, and JPEG headers", () => {
+ expect(probeImageDimensions(png(780, 14182))).toEqual({ width: 780, height: 14182 });
+ expect(probeImageDimensions(gif(320, 200))).toEqual({ width: 320, height: 200 });
+ expect(probeImageDimensions(jpeg(1688, 1514))).toEqual({ width: 1688, height: 1514 });
+ });
+
+ it("reads every WebP variant", () => {
+ const vp8x = riff("VP8X", [0, 0, 0, 0, 0, 0, 0, 0, 0x0b, 0x03, 0x00, 0x65, 0x37, 0x00]);
+ expect(probeImageDimensions(vp8x)).toEqual({ width: 780, height: 14182 });
+ // VP8L packs (width - 1) and (height - 1) into 14-bit fields.
+ const bits = (780 - 1) | ((1000 - 1) << 14);
+ const vp8l = riff("VP8L", [0, 0, 0, 0, 0x2f, bits & 0xff, (bits >> 8) & 0xff, (bits >> 16) & 0xff, (bits >>> 24) & 0xff]);
+ expect(probeImageDimensions(vp8l)).toEqual({ width: 780, height: 1000 });
+ const vp8 = riff("VP8 ", [0, 0, 0, 0, 0, 0, 0, 0x9d, 0x01, 0x2a, 0x0c, 0x03, 0xe8, 0x03]);
+ expect(probeImageDimensions(vp8)).toEqual({ width: 780, height: 1000 });
+ });
+
+ it("returns undefined for unknown or truncated data", () => {
+ expect(probeImageDimensions(new TextEncoder().encode("not an image"))).toBeUndefined();
+ expect(probeImageDimensions(png(10, 10).slice(0, 20))).toBeUndefined();
+ expect(probeImageDimensions(new Uint8Array([0xff, 0xd8, 0xff, 0xda, 0, 2]))).toBeUndefined();
+ expect(probeBase64ImageDimensions("%%%")).toBeUndefined();
+ });
+
+ it("probes base64, including a JPEG whose frame sits past a large EXIF block", () => {
+ expect(probeBase64ImageDimensions(base64(png(780, 14182)))).toEqual({ width: 780, height: 14182 });
+ const deep = jpeg(9000, 600, 60_000, 2);
+ expect(deep.length).toBeGreaterThan(70_000);
+ expect(probeBase64ImageDimensions(base64(deep))).toEqual({ width: 9000, height: 600 });
+ });
+});
+
+describe("image dimension admission", () => {
+ it("rejects only a known longest edge above the limit", () => {
+ expect(imageExceedsInlineDimensions({ width: 780, height: 14182 })).toBe(true);
+ expect(imageExceedsInlineDimensions({ width: MAX_INLINE_IMAGE_EDGE_PX, height: 10 })).toBe(false);
+ expect(imageExceedsInlineDimensions({ width: 1688, height: 1514 })).toBe(false);
+ expect(imageExceedsInlineDimensions(undefined)).toBe(false);
+ });
+
+ it("names the omitted image's size", () => {
+ expect(omittedImageNotice({ width: 780, height: 14182 })).toBe(
+ "[Image omitted: 780x14182 px exceeds the 8000 px longest-edge limit for model input.]",
+ );
+ });
+});
diff --git a/packages/shared/src/image-dimensions.ts b/packages/shared/src/image-dimensions.ts
new file mode 100644
index 000000000..ebbeb8d31
--- /dev/null
+++ b/packages/shared/src/image-dimensions.ts
@@ -0,0 +1,171 @@
+/**
+ * Pixel-geometry admission for images sent to a model (issue #1913).
+ *
+ * The byte bound in `attachment-limits.ts` does not stop a small but very
+ * tall image (a full-page screenshot, 780 x 14182) that providers reject with
+ * a non-retriable 400. Once such an image is in history every later request
+ * replays it, so admission reads the pixel size from the file header without
+ * a decoder and keeps an oversized image out of the provider request.
+ */
+
+/**
+ * Longest image edge, in pixels, admitted into a provider request. Anthropic
+ * documents 8000 px as a hard rejection limit; other vision endpoints reject
+ * or fail on far smaller extremes. Host-core's Read tool mirrors this value.
+ */
+export const MAX_INLINE_IMAGE_EDGE_PX = 8000;
+
+export type ImageDimensions = { width: number; height: number };
+
+function u16be(bytes: Uint8Array, offset: number): number {
+ return (bytes[offset]! << 8) | bytes[offset + 1]!;
+}
+
+function u16le(bytes: Uint8Array, offset: number): number {
+ return bytes[offset]! | (bytes[offset + 1]! << 8);
+}
+
+function u24le(bytes: Uint8Array, offset: number): number {
+ return bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16);
+}
+
+function u32be(bytes: Uint8Array, offset: number): number {
+ return (
+ bytes[offset]! * 0x1000000 +
+ ((bytes[offset + 1]! << 16) | (bytes[offset + 2]! << 8) | bytes[offset + 3]!)
+ );
+}
+
+function ascii(bytes: Uint8Array, offset: number, text: string): boolean {
+ if (bytes.length < offset + text.length) return false;
+ for (let index = 0; index < text.length; index++) {
+ if (bytes[offset + index] !== text.charCodeAt(index)) return false;
+ }
+ return true;
+}
+
+function pngDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+ if (bytes.length < 24 || !ascii(bytes, 12, "IHDR")) return undefined;
+ return { width: u32be(bytes, 16), height: u32be(bytes, 20) };
+}
+
+function gifDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+ if (bytes.length < 10) return undefined;
+ return { width: u16le(bytes, 6), height: u16le(bytes, 8) };
+}
+
+function webpDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+ if (ascii(bytes, 12, "VP8X") && bytes.length >= 30) {
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
+ }
+ if (ascii(bytes, 12, "VP8L") && bytes.length >= 25 && bytes[20] === 0x2f) {
+ const bits =
+ bytes[21]! | (bytes[22]! << 8) | (bytes[23]! << 16) | (bytes[24]! << 24);
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
+ }
+ if (
+ ascii(bytes, 12, "VP8 ") &&
+ bytes.length >= 30 &&
+ bytes[23] === 0x9d &&
+ bytes[24] === 0x01 &&
+ bytes[25] === 0x2a
+ ) {
+ return { width: u16le(bytes, 26) & 0x3fff, height: u16le(bytes, 28) & 0x3fff };
+ }
+ return undefined;
+}
+
+/** Walk JPEG marker segments up to the first start-of-frame header. */
+function jpegDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+ let offset = 2;
+ while (offset + 3 < bytes.length) {
+ if (bytes[offset] !== 0xff) return undefined;
+ const marker = bytes[offset + 1]!;
+ if (marker === 0xff) {
+ offset += 1;
+ continue;
+ }
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
+ offset += 2;
+ continue;
+ }
+ // Entropy-coded data starts without a frame header: nothing to read.
+ if (marker === 0xd9 || marker === 0xda) return undefined;
+ const length = u16be(bytes, offset + 2);
+ if (length < 2) return undefined;
+ const isFrame =
+ marker >= 0xc0 &&
+ marker <= 0xcf &&
+ marker !== 0xc4 &&
+ marker !== 0xc8 &&
+ marker !== 0xcc;
+ if (isFrame) {
+ if (offset + 9 > bytes.length) return undefined;
+ return { width: u16be(bytes, offset + 7), height: u16be(bytes, offset + 5) };
+ }
+ offset += 2 + length;
+ }
+ return undefined;
+}
+
+/**
+ * Pixel size from a PNG, JPEG, GIF, or WebP header, or `undefined` when the
+ * bytes are not a recognized image or the header is cut short.
+ */
+export function probeImageDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+ if (ascii(bytes, 0, "\x89PNG\r\n\x1a\n")) return pngDimensions(bytes);
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
+ return jpegDimensions(bytes);
+ }
+ if (ascii(bytes, 0, "GIF8")) return gifDimensions(bytes);
+ if (ascii(bytes, 0, "RIFF") && ascii(bytes, 8, "WEBP")) return webpDimensions(bytes);
+ return undefined;
+}
+
+function decodeBase64Prefix(data: string, chars: number): Uint8Array | undefined {
+ const prefix = data.slice(0, chars - (chars % 4)).replace(/=+$/, "");
+ try {
+ const binary = atob(prefix.length % 4 === 1 ? prefix.slice(0, -1) : prefix);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index++) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+ return bytes;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Header-only bytes cover every format except a JPEG with a large EXIF block. */
+const BASE64_HEADER_CHARS = 87_384;
+
+/** `probeImageDimensions` for a base64 payload, decoding only what it needs. */
+export function probeBase64ImageDimensions(data: string): ImageDimensions | undefined {
+ const head = decodeBase64Prefix(data, BASE64_HEADER_CHARS);
+ if (!head) return undefined;
+ const dimensions = probeImageDimensions(head);
+ if (dimensions || data.length <= BASE64_HEADER_CHARS) return dimensions;
+ const isJpeg = head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff;
+ if (!isJpeg) return undefined;
+ const full = decodeBase64Prefix(data, data.length + 4);
+ return full ? probeImageDimensions(full) : undefined;
+}
+
+/**
+ * Whether known dimensions exceed what a provider request admits. Unknown
+ * dimensions are not a rejection: the byte bound and the provider still
+ * judge an image this probe cannot read.
+ */
+export function imageExceedsInlineDimensions(
+ dimensions: ImageDimensions | undefined,
+): dimensions is ImageDimensions {
+ return (
+ dimensions !== undefined &&
+ Math.max(dimensions.width, dimensions.height) > MAX_INLINE_IMAGE_EDGE_PX
+ );
+}
+
+/** Text that takes an omitted image's place so the model knows it existed. */
+export function omittedImageNotice(dimensions: ImageDimensions): string {
+ return `[Image omitted: ${dimensions.width}x${dimensions.height} px exceeds the ${MAX_INLINE_IMAGE_EDGE_PX} px longest-edge limit for model input.]`;
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index cb2b9d1af..1c05c1633 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -55,6 +55,7 @@ export * from "./github-feedback.js";
export * from "./network-proxy.js";
export * from "./attachment-limits.js";
export * from "./attachment-formats.js";
+export * from "./image-dimensions.js";
export * from "./speech.js";
export * from "./gen-ui.js";
export * from "./image-generation.js";