Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): accept content-part user messages on the stream-json channel
thinhlpg08f88a4aca8a
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex 4c88a9bcd..1de322e4d 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -204,12 +204,24 @@ thing that can answer a permission request and it needs to be reading them.| Message | Shape || --- | --- || Follow-up turn | `{"type":"user","text":"also check the tests"}` |+| Follow-up turn with an image | `{"type":"user","content":[{"type":"text","text":"what changed here?"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo..."}}]}` || Permission answer | `{"type":"permission","request_id":"perm-1","decision":"allow_once"}` || Stop the run | `{"type":"abort"}` |-A follow-up joins the run at the next turn boundary. `decision` is `allow_once`, `allow_always`, or-`deny`, and each `request_id` is answerable once. A line that parses as none of these is reported-as an `input_error` record and skipped, so one bad line cannot end a healthy run.+A follow-up joins the run at the next turn boundary. A `user` message carries either `text` or+`content`, not both. `content` is the OpenAI content-part array: `text` parts and `image_url` parts+whose `url` is a base64 `data:` URL. The run shares no filesystem with a client, so a path would+only work for a client on the same machine. The parts reach the provider exactly as written -- they+are not re-encoded -- and `init.input_content_parts` publishes the caps before a client sends+anything: at most 5 MiB decoded per image, 10 MiB across a message's images, 8 images per message,+and 16 MiB for one input line. Only `image/png`, `image/jpeg`, `image/gif` and `image/webp` are+accepted. A line over the cap is rejected without being parsed, and `input_error.line` carries at+most the first 4 KiB of it, with `line_truncated: true`: a rejected line can be as large as the cap+it crossed.++`decision` is `allow_once`, `allow_always`, or `deny`, and each `request_id` is answerable once. A+line that parses as none of these is reported as an `input_error` record and skipped, so one bad+line cannot end a healthy run.<Callout type="info">Closing stdin is not an abort -- the run finishes and still prints its `result`. But it does end the@@ -223,7 +235,7 @@ The first line of a `stream-json` run is always an `init` record, printed beforeevent:```json-{"type":"init","protocol_version":1,"session_id":"3f7a91c2-4e5d-4a6b-8c7d-0e1f2a3b4c5d","model":"tokamak-1-preview","cwd":"/home/me/app","tools":["read","write","bash"],"input_kinds":["user","abort","permission"]}+{"type":"init","protocol_version":1,"session_id":"3f7a91c2-4e5d-4a6b-8c7d-0e1f2a3b4c5d","model":"tokamak-1-preview","cwd":"/home/me/app","tools":["read","write","bash"],"input_kinds":["user","abort","permission"],"input_content_parts":{"mime_types":["image/png","image/jpeg","image/gif","image/webp"],"max_image_bytes":5242880,"max_message_image_bytes":10485760,"max_images":8,"max_line_bytes":16777216,"max_echo_bytes":4096}}```| Field | Notes |@@ -234,6 +246,7 @@ event:| `cwd` | The project root the run's tools are confined to. `null` when the run was given none || `tools` | The tool names the request advertises, in the order it sends them. The tool array is the head of the cached request prefix, so the order is part of the payload, not a detail || `input_kinds` | The `type` values this run accepts on stdin. Empty when the run was not asked to read stdin, so "nothing can be sent back" is an answer rather than a missing field |+| `input_content_parts` | The content-part form of `user` and the caps a client must stay inside: `mime_types`, `max_image_bytes`, `max_message_image_bytes`, `max_images`, plus the channel-wide `max_line_bytes` and `max_echo_bytes`. `null` when the run reads no stdin. Additive, so a client that reads only `input_kinds` is unaffected |One stream has no handshake: a run that fails before a model is resolved (nothing configured, nousable provider) prints the terminal `result` alone, with `error.code` set to `setup_error`. Therediff --git a/protocol/schema.json b/protocol/schema.jsonindex 688e21fd9..4036f5433 100644--- a/protocol/schema.json+++ b/protocol/schema.json@@ -866,6 +866,17 @@"items": {"type": "string"}+ },+ "input_content_parts": {+ "description": "The content-part form of the `user` message, when this run accepts it:\nthe caps a client must stay inside and the image types it may send.\n`null` when the run reads no stdin -- there is no channel to describe --\nwhich is also why this is additively separate from `input_kinds`: a\nclient that reads only the kinds still learns `user`, and one that\nnegotiates the caps gets them from the same record.",+ "anyOf": [+ {+ "$ref": "#/$defs/InputContentParts"+ },+ {+ "type": "null"+ }+ ]}},"required": [@@ -877,6 +888,57 @@"input_kinds"]},+ "InputContentParts": {+ "description": "The caps on a `user` message's content-part array, as `init` advertises them.\n\nA client that sends an image is sending bytes into a channel with no\nbackpressure, so the limits are part of the handshake rather than something\nto discover by being rejected. Each is the cap the parser enforces: this is\nthe same constant, not a copy of it.",+ "type": "object",+ "properties": {+ "mime_types": {+ "description": "The image types an `image_url` part may name, as MIME types.",+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "max_image_bytes": {+ "description": "Most decoded bytes one image may carry.",+ "type": "integer",+ "format": "uint",+ "minimum": 0+ },+ "max_message_image_bytes": {+ "description": "Most decoded bytes across the images of one message.",+ "type": "integer",+ "format": "uint",+ "minimum": 0+ },+ "max_images": {+ "description": "Most images one message may carry.",+ "type": "integer",+ "format": "uint",+ "minimum": 0+ },+ "max_line_bytes": {+ "description": "Most bytes one input line may occupy. Applies to every kind, not just\n`user`: the cap is the reader's, before anything is parsed.",+ "type": "integer",+ "format": "uint",+ "minimum": 0+ },+ "max_echo_bytes": {+ "description": "Most bytes of a rejected line `input_error` echoes back.",+ "type": "integer",+ "format": "uint",+ "minimum": 0+ }+ },+ "required": [+ "mime_types",+ "max_image_bytes",+ "max_message_image_bytes",+ "max_images",+ "max_line_bytes",+ "max_echo_bytes"+ ]+ },"RunResult": {"description": "The envelope itself. A struct rather than a `json!` literal so the fields\nserialize in declaration order: `serde_json`'s map is sorted, which would\nprint this contract alphabetically and bury `result` in the middle.","type": "object",@@ -1056,25 +1118,40 @@"type": "string"},"line": {- "description": "The line that was rejected, so the client can match it to what it wrote.",+ "description": "The line that was rejected, so the client can match it to what it wrote.\nTruncated to [`MAX_ECHO_BYTES`], because a rejected line may be as large\nas [`MAX_LINE_BYTES`] and echoing it whole would hand the client back the\ncost the cap just removed.","type": "string"+ },+ "line_truncated": {+ "description": "True when `line` is a prefix of what the client sent, so a client that\nmatches on the echo knows why it is short.",+ "type": "boolean"}},"required": ["type","message",- "line"+ "line",+ "line_truncated"]},"InputLine": {"description": "One input line, as the wire shape: the three [`INPUT_KINDS`], with the fields\neach carries. The wire shape is a serde type rather than a hand-rolled walk\nover a `Value` so the protocol schema can be derived from it -- `jan cli\nagent schema` publishes this shape, and a hand-written copy of it would be\ncorrect only until the parser moved.\n\nThe `type` field is read separately, before deserializing: an unknown kind is\nreported against [`INPUT_KINDS`], which is the list `init` advertises.","oneOf": [{- "description": "A follow-up turn for the run in flight.",+ "description": "A follow-up turn for the run in flight: `text`, or `content` as an\nOpenAI content-part array. Exactly one of the two, which JSON Schema\ncannot state, so the doc says it and the parser enforces it. A\ncontent-part message carries text parts and `image_url` parts, whose URL\nis a base64 `data:` URL -- the run shares no filesystem with a client.","type": "object","properties": {"text": {- "type": "string"+ "type": [+ "string",+ "null"+ ]+ },+ "content": {+ "type": [+ "array",+ "null"+ ],+ "items": true},"type": {"type": "string",@@ -1082,8 +1159,7 @@}},"required": [- "type",- "text"+ "type"]},{diff --git a/src-tauri/jan-cli/tests/stream_json_init.rs b/src-tauri/jan-cli/tests/stream_json_init.rsindex e3de63a25..fd2907393 100644--- a/src-tauri/jan-cli/tests/stream_json_init.rs+++ b/src-tauri/jan-cli/tests/stream_json_init.rs@@ -220,6 +220,27 @@ fn assert_handshake(first: &serde_json::Value, project: &Path) {serde_json::json!(["user", "abort", "permission"]),"a client is told what it may send back");+ // The caps travel with the kinds, so a client that sends an image reads the+ // limits off the handshake instead of discovering them by rejection. Pinned+ // as literals: this is the published contract, not this build's internals.+ let parts = &first["input_content_parts"];+ assert_eq!(+ parts["mime_types"],+ serde_json::json!(["image/png", "image/jpeg", "image/gif", "image/webp"]),+ "a client is told which image types it may send"+ );+ assert_eq!(+ parts,+ &serde_json::json!({+ "mime_types": ["image/png", "image/jpeg", "image/gif", "image/webp"],+ "max_image_bytes": 5_242_880,+ "max_message_image_bytes": 10_485_760,+ "max_images": 8,+ "max_line_bytes": 16_777_216,+ "max_echo_bytes": 4_096,+ }),+ "the advertised caps are the ones the parser enforces"+ );}#[test]diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 01795bd86..98955b4f6 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -25,6 +25,8 @@ pub mod telemetry;pub mod terminal_setup;pub mod tokamak;mod tui;+/// The user-message wire shape, shared by the TUI and the headless channel.+mod user_message;pub mod usage_view;pub mod updater;pub mod worktree;@@ -739,10 +741,11 @@ use crate::core::agent::r#loop::{use tauri_plugin_agent_tools::workspace;use crate::core::cli::providers::{load_provider_configs, ProviderOverrides};use crate::core::cli::run_report::{- ndjson_line, Init, OutputFormat, PermissionDecisionRecord, RunReport,+ ndjson_line, Init, InputContentParts, OutputFormat, PermissionDecisionRecord, RunReport,};use crate::core::cli::stream_input::{parse_input_line, InputErrorRecord, InputFormat, InputMessage, StreamInput, INPUT_KINDS,+ MAX_ECHO_BYTES, MAX_LINE_BYTES,};use crate::core::mcp::models::McpSettings;use std::collections::HashMap;@@ -2101,7 +2104,19 @@ async fn init_record(} else {Vec::new()};- Init::new(session_id, model, cwd, tools, input_kinds)+ // The caps go with the kinds: a client that can send an image should learn+ // the limits from the handshake rather than by having a message rejected.+ let input_content_parts = input_format+ .is_stream_json()+ .then(InputContentParts::current);+ Init::new(+ session_id,+ model,+ cwd,+ tools,+ input_kinds,+ input_content_parts,+ )}/// A rendered tool schema's name, out of the OpenAI `{"type":"function",@@ -2176,6 +2191,10 @@ async fn apply_input_line(input.queue_user(text);Ok(InputFlow::Continue)}+ InputMessage::UserParts(parts) => {+ input.queue_user_parts(parts);+ Ok(InputFlow::Continue)+ }InputMessage::Abort => {input.abort();Ok(InputFlow::Stop)@@ -2197,17 +2216,30 @@ async fn apply_input_line(}}+/// One line from the client, bounded.+struct ClientLine {+ text: String,+ /// True when the line went past [`MAX_LINE_BYTES`] and was cut: `text` is+ /// then the echo-sized prefix, and the line is rejected without being+ /// parsed.+ oversized: bool,+}+/// Client lines, read on a detached OS thread.////// Not `tokio::io::stdin`: that parks the read on the runtime's blocking pool,/// which shutdown waits for, so a client that keeps stdin open -- which is what/// a duplex client does for the whole run -- leaves the process alive after its/// terminal record has been printed. A plain thread dies with the process.-fn stdin_lines() -> mpsc::UnboundedReceiver<String> {+///+/// The read is bounded rather than line-at-a-time: a line is only as long as+/// the client says it is, and `BufRead::lines` would hold whatever arrives in+/// memory before the cap could be applied to it.+fn stdin_lines() -> mpsc::UnboundedReceiver<ClientLine> {let (tx, rx) = mpsc::unbounded_channel();std::thread::spawn(move || {- use std::io::BufRead as _;- for line in std::io::stdin().lock().lines().map_while(Result::ok) {+ let mut reader = std::io::stdin().lock();+ while let Ok(Some(line)) = read_bounded_line(&mut reader) {if tx.send(line).is_err() {return;}@@ -2216,6 +2248,54 @@ fn stdin_lines() -> mpsc::UnboundedReceiver<String> {rx}+/// Read one line, keeping at most [`MAX_LINE_BYTES`] of it and discarding the+/// rest rather than growing to hold it.+///+/// A line over the cap keeps only its first [`MAX_ECHO_BYTES`]: it can never be+/// parsed, so the only use its bytes have left is the echo in `input_error`.+/// Cutting there can split a character, which is why the kept bytes go through+/// `from_utf8_lossy` -- the echo is for a human, and a line that is over the cap+/// is already being refused.+fn read_bounded_line<R: std::io::BufRead>(+ reader: &mut R,+) -> std::io::Result<Option<ClientLine>> {+ let mut bytes: Vec<u8> = Vec::new();+ let mut oversized = false;+ let mut saw_any = false;+ loop {+ let available = match reader.fill_buf()? {+ [] => break,+ buf => buf,+ };+ saw_any = true;+ let newline = available.iter().position(|b| *b == b'\n');+ let take = newline.map_or(available.len(), |i| i + 1);+ if !oversized {+ let room = MAX_LINE_BYTES.saturating_sub(bytes.len());+ if take <= room {+ bytes.extend_from_slice(&available[..take]);+ } else {+ bytes.truncate(MAX_ECHO_BYTES.min(bytes.len()));+ oversized = true;+ }+ }+ reader.consume(take);+ if newline.is_some() {+ break;+ }+ }+ if !saw_any {+ return Ok(None);+ }+ while matches!(bytes.last(), Some(b'\n') | Some(b'\r')) {+ bytes.pop();+ }+ Ok(Some(ClientLine {+ text: String::from_utf8_lossy(&bytes).into_owned(),+ oversized,+ }))+}+/// Consume client messages until `abort` or end of input.////// End of input is not an abort: a client that has said everything it means to@@ -2224,12 +2304,21 @@ fn stdin_lines() -> mpsc::UnboundedReceiver<String> {/// latched and anything already waiting is released -- see/// [`strand_pending_permissions`].async fn read_input_lines(- mut lines: mpsc::UnboundedReceiver<String>,+ mut lines: mpsc::UnboundedReceiver<ClientLine>,input: Arc<StreamInput>,registry: PermissionRegistry,format: OutputFormat,) {while let Some(line) = lines.recv().await {+ if line.oversized {+ report_input_error(+ format,+ &format!("line is over the {MAX_LINE_BYTES} byte cap"),+ &line.text,+ );+ continue;+ }+ let line = line.text;if line.trim().is_empty() {continue;}@@ -2256,7 +2345,10 @@ async fn read_input_lines(/// the text is what the client needs to decide whether to send it again.fn report_dropped_follow_ups(input: &StreamInput, format: OutputFormat) {for turn in input.take_queued() {- let text = turn["content"].as_str().unwrap_or_default().to_string();+ // The text, whether it arrived as a string or as content parts: an+ // image-only follow-up reads as empty here, which is all this report+ // needs to say about it.+ let text = crate::core::cli::user_message::text_of_content(&turn["content"]);report_input_error(format, "run ended before this follow-up was read", &text);}}@@ -2608,7 +2700,12 @@ mod tests {];let (lines_tx, lines) = mpsc::unbounded_channel();for line in script {- lines_tx.send(line.to_string()).expect("reader is alive");+ lines_tx+ .send(ClientLine {+ text: line.to_string(),+ oversized: false,+ })+ .expect("reader is alive");}drop(lines_tx);read_input_lines(@@ -2670,7 +2767,7 @@ mod tests {.insert("perm-1".to_string(), answer_tx);// No lines at all: the client opened the pipe and closed it again.- let (lines_tx, lines) = mpsc::unbounded_channel::<String>();+ let (lines_tx, lines) = mpsc::unbounded_channel::<ClientLine>();drop(lines_tx);read_input_lines(lines,@@ -2726,6 +2823,70 @@ mod tests {}}+ /// A content-part follow-up reaches the queue as the client wrote it: the+ /// same parts `upstream.rs` hands the provider, not a re-encoding of them.+ #[tokio::test]+ async fn a_content_part_follow_up_is_queued_verbatim() {+ let input = Arc::new(StreamInput::default());+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let parts = serde_json::json!([+ { "type": "text", "text": "what is in this shot?" },+ { "type": "image_url",+ "image_url": { "url": "data:image/png;base64,QUJD", "detail": "high" } }+ ]);+ let line = serde_json::json!({ "type": "user", "content": parts }).to_string();+ let (lines_tx, lines) = mpsc::unbounded_channel();+ lines_tx+ .send(ClientLine {+ text: line,+ oversized: false,+ })+ .expect("reader is alive");+ drop(lines_tx);+ read_input_lines(lines, Arc::clone(&input), registry, OutputFormat::Json).await;++ let queued = input.take_queued();+ assert_eq!(queued.len(), 1, "the follow-up is queued as one turn");+ assert_eq!(queued[0]["role"], "user");+ assert_eq!(queued[0]["content"], parts);+ }++ /// A line over the cap is refused without being parsed, and what the reader+ /// keeps of it is bounded: the cap exists so the bytes are not carried on.+ #[test]+ fn a_line_over_the_cap_is_refused_and_its_echo_bounded() {+ let mut bytes = vec![b'x'; MAX_LINE_BYTES + 1024];+ bytes.push(b'\n');+ bytes.extend_from_slice(br#"{"type":"user","text":"after"}"#);+ let mut reader = std::io::BufReader::new(std::io::Cursor::new(bytes));++ let first = read_bounded_line(&mut reader).unwrap().expect("a line");+ assert!(first.oversized);+ assert_eq!(first.text.len(), MAX_ECHO_BYTES, "the echo, not the line");+ // Resynchronised on the next line rather than treating the overflow as+ // the end of input.+ let second = read_bounded_line(&mut reader)+ .unwrap()+ .expect("the line after the overflow");+ assert!(!second.oversized);+ assert_eq!(second.text, r#"{"type":"user","text":"after"}"#);+ assert!(read_bounded_line(&mut reader).unwrap().is_none());+ }++ /// The rejected echo the client sees is the bounded one, so a client that+ /// matches on `input_error.line` still can.+ #[test]+ fn an_over_cap_line_is_reported_with_a_truncated_echo() {+ let line = "x".repeat(MAX_ECHO_BYTES * 3);+ let record = serde_json::to_value(InputErrorRecord::new("line is over the cap", &line))+ .expect("a JSON record");+ assert_eq!(+ record["line"].as_str().expect("a string").len(),+ MAX_ECHO_BYTES+ );+ assert_eq!(record["line_truncated"], serde_json::json!(true));+ }+/// A queued follow-up the run never reached is reported rather than/// vanishing, so the client knows to send it again.#[test]diff --git a/src-tauri/src/core/cli/protocol_schema.rs b/src-tauri/src/core/cli/protocol_schema.rsindex 749d3b80f..b1ff079b6 100644--- a/src-tauri/src/core/cli/protocol_schema.rs+++ b/src-tauri/src/core/cli/protocol_schema.rs@@ -241,6 +241,7 @@ mod tests {None,Vec::new(),Vec::new(),+ None,)).unwrap(),serde_json::to_value(report).unwrap(),diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex 6ef282c2a..dbb43ac4c 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -283,6 +283,50 @@ pub(crate) struct Init {/// `type` tags. Empty when the run does not read stdin at all, which is/// the honest answer for a read-only stream: nothing can be sent back.input_kinds: Vec<&'static str>,+ /// The content-part form of the `user` message, when this run accepts it:+ /// the caps a client must stay inside and the image types it may send.+ /// `null` when the run reads no stdin -- there is no channel to describe --+ /// which is also why this is additively separate from `input_kinds`: a+ /// client that reads only the kinds still learns `user`, and one that+ /// negotiates the caps gets them from the same record.+ input_content_parts: Option<InputContentParts>,+}++/// The caps on a `user` message's content-part array, as `init` advertises them.+///+/// A client that sends an image is sending bytes into a channel with no+/// backpressure, so the limits are part of the handshake rather than something+/// to discover by being rejected. Each is the cap the parser enforces: this is+/// the same constant, not a copy of it.+#[derive(serde::Serialize, schemars::JsonSchema)]+pub(crate) struct InputContentParts {+ /// The image types an `image_url` part may name, as MIME types.+ mime_types: Vec<&'static str>,+ /// Most decoded bytes one image may carry.+ max_image_bytes: usize,+ /// Most decoded bytes across the images of one message.+ max_message_image_bytes: usize,+ /// Most images one message may carry.+ max_images: usize,+ /// Most bytes one input line may occupy. Applies to every kind, not just+ /// `user`: the cap is the reader's, before anything is parsed.+ max_line_bytes: usize,+ /// Most bytes of a rejected line `input_error` echoes back.+ max_echo_bytes: usize,+}++impl InputContentParts {+ pub(crate) fn current() -> Self {+ use super::stream_input;+ Self {+ mime_types: super::user_message::IMAGE_MIME_TYPES.to_vec(),+ max_image_bytes: stream_input::MAX_IMAGE_BYTES,+ max_message_image_bytes: stream_input::MAX_MESSAGE_IMAGE_BYTES,+ max_images: stream_input::MAX_IMAGES,+ max_line_bytes: stream_input::MAX_LINE_BYTES,+ max_echo_bytes: stream_input::MAX_ECHO_BYTES,+ }+ }}impl Init {@@ -292,6 +336,7 @@ impl Init {cwd: Option<String>,tools: Vec<String>,input_kinds: Vec<&'static str>,+ input_content_parts: Option<InputContentParts>,) -> Self {Self {kind: "init",@@ -301,6 +346,7 @@ impl Init {cwd,tools,input_kinds,+ input_content_parts,}}}@@ -504,8 +550,15 @@ mod tests {documented_tags_after(&doc, "the CLI rather than by the loop: ");let minted = [- serde_json::to_value(Init::new("id", "m", Some("/tmp".to_string()), Vec::new(), Vec::new()))- .unwrap(),+ serde_json::to_value(Init::new(+ "id",+ "m",+ Some("/tmp".to_string()),+ Vec::new(),+ Vec::new(),+ None,+ ))+ .unwrap(),serde_json::to_value(RunReport::default().finish(None, None, "m", 1, None)).unwrap(),serde_json::to_value(PermissionDecisionRecord::new("req",@@ -568,6 +621,7 @@ mod tests {Some("/tmp/project".to_string()),vec!["read".to_string(), "write".to_string()],vec!["user", "abort", "permission"],+ Some(InputContentParts::current()),)).unwrap();assert_eq!(@@ -580,6 +634,18 @@ mod tests {"cwd": "/tmp/project","tools": ["read", "write"],"input_kinds": ["user", "abort", "permission"],+ // The caps a client stays inside, as the wire carries them.+ // Pinned as literals in both places a client reads them from:+ // here the record, and in the CLI's own suite the handshake as+ // it actually reaches stdout.+ "input_content_parts": {+ "mime_types": ["image/png", "image/jpeg", "image/gif", "image/webp"],+ "max_image_bytes": 5_242_880,+ "max_message_image_bytes": 10_485_760,+ "max_images": 8,+ "max_line_bytes": 16_777_216,+ "max_echo_bytes": 4_096,+ },}));}@@ -595,10 +661,14 @@ mod tests {Some("/tmp".to_string()),Vec::new(),Vec::new(),+ None,)).unwrap();assert_eq!(out["input_kinds"], serde_json::json!([]));assert_eq!(out["input_kinds"].as_array().unwrap().len(), 0);+ // And no caps to describe: there is no channel for them to bound, so a+ // client reads `null` rather than a limit that applies to nothing.+ assert!(out["input_content_parts"].is_null(), "{out}");}/// A run given no project root reports none. The alternative -- a path@@ -606,8 +676,15 @@ mod tests {/// to?" with a directory nothing is confined to.#[test]fn init_without_a_project_root_reports_cwd_absent() {- let out =- serde_json::to_value(Init::new("id", "m", None, Vec::new(), Vec::new())).unwrap();+ let out = serde_json::to_value(Init::new(+ "id",+ "m",+ None,+ Vec::new(),+ Vec::new(),+ None,+ ))+ .unwrap();assert!(out["cwd"].is_null(), "{out}");}diff --git a/src-tauri/src/core/cli/stream_input.rs b/src-tauri/src/core/cli/stream_input.rsindex 7781a1172..009abea6b 100644--- a/src-tauri/src/core/cli/stream_input.rs+++ b/src-tauri/src/core/cli/stream_input.rs@@ -17,6 +17,12 @@//! A line that parses as none of them is reported as an `input_error` record//! and skipped: the reader is a peer process's output, so one bad line must not//! be able to end a run that is otherwise healthy.+//!+//! A `user` line carries either `text` or `content`, an OpenAI content-part+//! array, so a client can send an image without a filesystem in common with the+//! run ([`super::user_message`] holds the shape both paths build). Parts are+//! passed through verbatim; the caps below are what a line is measured against+//! first, because an unbounded channel is a denial of service on the run.use std::collections::VecDeque;use std::sync::atomic::{AtomicBool, Ordering};@@ -24,6 +30,25 @@ use std::sync::Mutex;use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use tokio::sync::Notify;+/// Most bytes one line may occupy. The reader stops accumulating at this point+/// and discards the rest of the line, so a client that sends a gigabyte costs+/// the cap in memory rather than the gigabyte.+pub(crate) const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;++/// Most decoded bytes one `image_url` part may carry.+pub(crate) const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024;++/// Most decoded bytes across the images of one message.+pub(crate) const MAX_MESSAGE_IMAGE_BYTES: usize = 10 * 1024 * 1024;++/// Most images one message may carry.+pub(crate) const MAX_IMAGES: usize = 8;++/// Most bytes of a rejected line echoed back in `input_error`. A rejected line+/// may be as large as [`MAX_LINE_BYTES`], and echoing it whole would move the+/// cost the cap just removed from the parser onto the client's own reader.+pub(crate) const MAX_ECHO_BYTES: usize = 4 * 1024;+/// How a non-interactive run is spoken to.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]pub enum InputFormat {@@ -52,6 +77,9 @@ pub(crate) const INPUT_KINDS: [&str; 3] = ["user", "abort", "permission"];pub(crate) enum InputMessage {/// A follow-up turn for the run in flight.User(String),+ /// A follow-up turn whose content is an OpenAI content-part array, already+ /// validated against the caps and passed through as the client wrote it.+ UserParts(Vec<serde_json::Value>),/// Stop the run; the terminal envelope still reports what it had produced.Abort,/// The answer to a `permission_request` this run emitted.@@ -72,8 +100,17 @@ pub(crate) enum InputMessage {#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]#[serde(tag = "type", rename_all = "snake_case")]pub(crate) enum InputLine {- /// A follow-up turn for the run in flight.- User { text: String },+ /// A follow-up turn for the run in flight: `text`, or `content` as an+ /// OpenAI content-part array. Exactly one of the two, which JSON Schema+ /// cannot state, so the doc says it and the parser enforces it. A+ /// content-part message carries text parts and `image_url` parts, whose URL+ /// is a base64 `data:` URL -- the run shares no filesystem with a client.+ User {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ text: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ content: Option<Vec<serde_json::Value>>,+ },/// Stop the run; the terminal envelope still reports what it had produced.Abort,/// The answer to a `permission_request` this run emitted.@@ -118,12 +155,20 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {));}match serde_json::from_value::<InputLine>(value).map_err(|e| e.to_string())? {- InputLine::User { text } => {- if text.trim().is_empty() {- return Err("'user' text is empty".to_string());+ InputLine::User { text, content } => match (text, content) {+ (Some(_), Some(_)) => Err("'user' takes 'text' or 'content', not both".to_string()),+ (None, None) => Err("'user' needs 'text' or 'content'".to_string()),+ (Some(text), None) => {+ if text.trim().is_empty() {+ return Err("'user' text is empty".to_string());+ }+ Ok(InputMessage::User(text))}- Ok(InputMessage::User(text))- }+ (None, Some(parts)) => {+ check_user_content(&parts)?;+ Ok(InputMessage::UserParts(parts))+ }+ },InputLine::Abort => Ok(InputMessage::Abort),InputLine::Permission {request_id,@@ -135,6 +180,74 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {}}+/// Validate a client's content-part array before it is queued.+///+/// The parts are passed through verbatim afterwards -- the shape is the model's,+/// and re-encoding it here would be a second place to get it wrong -- so this is+/// where every refusal lives: a part type that is not `text` or `image_url`, a+/// part missing the field its type requires, an image type outside+/// [`IMAGE_MIME_TYPES`](super::user_message::IMAGE_MIME_TYPES), and each cap.+fn check_user_content(parts: &[serde_json::Value]) -> Result<(), String> {+ if parts.is_empty() {+ return Err("'user' content is empty".to_string());+ }+ let mut images = 0usize;+ let mut image_bytes = 0usize;+ let mut has_text = false;+ for part in parts {+ let kind = part+ .get("type")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "every content part needs a string 'type'".to_string())?;+ match kind {+ "text" => {+ let text = part+ .get("text")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "a 'text' part needs a string 'text'".to_string())?;+ has_text |= !text.trim().is_empty();+ }+ "image_url" => {+ let url = part+ .get("image_url")+ .and_then(|v| v.get("url"))+ .and_then(|v| v.as_str())+ .ok_or_else(|| {+ "an 'image_url' part needs a string 'image_url.url'".to_string()+ })?;+ // The decoded length, not the payload's: base64 inflates by+ // 4/3, so a payload under the cap can be an image over it.+ let (_, decoded) = super::user_message::data_url_mime_and_len(url)?;+ if decoded > MAX_IMAGE_BYTES {+ return Err(format!(+ "image is {decoded} bytes decoded, over the {MAX_IMAGE_BYTES} byte cap"+ ));+ }+ images += 1;+ if images > MAX_IMAGES {+ return Err(format!("message carries more than {MAX_IMAGES} images"));+ }+ image_bytes += decoded;+ if image_bytes > MAX_MESSAGE_IMAGE_BYTES {+ return Err(format!(+ "images total {image_bytes} bytes decoded, over the \+ {MAX_MESSAGE_IMAGE_BYTES} byte cap"+ ));+ }+ }+ other => {+ return Err(format!(+ "unsupported content part '{other}' (text, image_url)"+ ))+ }+ }+ }+ if !has_text && images == 0 {+ return Err("'user' content carries neither text nor an image".to_string());+ }+ Ok(())+}+/// A rejected input line, reported on stdout. Deliberately *not* a/// [`StreamEvent::Error`](crate::core::agent::events::StreamEvent::Error): the/// report folds that into the run's outcome, so a typo in one line would mark@@ -148,19 +261,39 @@ pub(crate) struct InputErrorRecord<'a> {kind: &'static str,message: &'a str,/// The line that was rejected, so the client can match it to what it wrote.+ /// Truncated to [`MAX_ECHO_BYTES`], because a rejected line may be as large+ /// as [`MAX_LINE_BYTES`] and echoing it whole would hand the client back the+ /// cost the cap just removed.line: &'a str,+ /// True when `line` is a prefix of what the client sent, so a client that+ /// matches on the echo knows why it is short.+ line_truncated: bool,}impl<'a> InputErrorRecord<'a> {pub(crate) fn new(message: &'a str, line: &'a str) -> Self {+ let echoed = echo_prefix(line);Self {kind: "input_error",message,- line,+ line: echoed,+ line_truncated: echoed.len() < line.len(),}}}+/// The first [`MAX_ECHO_BYTES`] of `line`, cut at a character boundary.+fn echo_prefix(line: &str) -> &str {+ if line.len() <= MAX_ECHO_BYTES {+ return line;+ }+ let mut end = MAX_ECHO_BYTES;+ while !line.is_char_boundary(end) {+ end -= 1;+ }+ &line[..end]+}+/// What the reader task and the run share: the queue the steering handshake/// drains, and the abort latch the run selects on.#[derive(Default)]@@ -177,6 +310,14 @@ impl StreamInput {.push_back(serde_json::json!({ "role": "user", "content": text }));}+ /// Queue a follow-up whose content is a content-part array, as the client+ /// wrote it: the `user` message the run appends is the client's own parts,+ /// not a re-encoding of them.+ pub(crate) fn queue_user_parts(&self, parts: Vec<serde_json::Value>) {+ self.lock()+ .push_back(serde_json::json!({ "role": "user", "content": parts }));+ }+/// Hand the queue to a steering handshake. Empty is the normal answer: the/// loop asks at every turn boundary whether anything is waiting.pub(crate) fn take_queued(&self) -> Vec<serde_json::Value> {@@ -276,8 +417,37 @@ mod tests {("not json at all", "not JSON"),(r#"{"text":"hi"}"#, "missing string field 'type'"),(r#"{"type":"steer","text":"hi"}"#, "unknown type 'steer'"),- (r#"{"type":"user"}"#, "missing field `text`"),+ (r#"{"type":"user"}"#, "'user' needs 'text' or 'content'"),+ (+ r#"{"type":"user","text":"a","content":[{"type":"text","text":"b"}]}"#,+ "'user' takes 'text' or 'content', not both",+ ),(r#"{"type":"user","text":" "}"#, "is empty"),+ (r#"{"type":"user","content":[]}"#, "content is empty"),+ (+ r#"{"type":"user","content":[{"type":"audio","audio":{"url":"x"}}]}"#,+ "unsupported content part 'audio'",+ ),+ (+ r#"{"type":"user","content":[{"type":"text"}]}"#,+ "a 'text' part needs a string 'text'",+ ),+ (+ r#"{"type":"user","content":[{"type":"image_url","image_url":{}}]}"#,+ "needs a string 'image_url.url'",+ ),+ (+ r#"{"type":"user","content":[{"type":"image_url","image_url":{"url":"/tmp/a.png"}}]}"#,+ "must be a data: URL",+ ),+ (+ r#"{"type":"user","content":[{"type":"image_url","image_url":{"url":"data:image/svg+xml;base64,QUJD"}}]}"#,+ "unsupported image type",+ ),+ (+ r#"{"type":"user","content":[{"type":"text","text":" "}]}"#,+ "carries neither text nor an image",+ ),(r#"{"type":"permission","decision":"deny"}"#, "missing field `request_id`"),(r#"{"type":"permission","request_id":"p"}"#, "missing field `decision`"),(@@ -290,6 +460,96 @@ mod tests {}}+ /// A line carrying an image with no text at all is a message, not a typo:+ /// the model reads the image and nothing else.+ #[test]+ fn an_image_only_message_is_accepted() {+ let line = r#"{"type":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,QUJD"}}]}"#;+ let message = parse_input_line(line).expect("an image-only message");+ let InputMessage::UserParts(parts) = message else {+ panic!("expected parts, got {message:?}");+ };+ assert_eq!(parts.len(), 1);+ assert_eq!(parts[0]["type"], "image_url");+ }++ /// A content-part message is accepted and carried as written: the parts the+ /// client sent are the parts that reach the request, extensions included.+ #[test]+ fn content_parts_are_carried_as_written() {+ let line = r#"{"type":"user","content":[+ {"type":"text","text":"what changed here?","cache_control":{"type":"ephemeral"}},+ {"type":"image_url","image_url":{"url":"data:image/jpeg;base64,QUJD","detail":"high"}}+ ]}"#;+ let InputMessage::UserParts(parts) = parse_input_line(line).expect(line) else {+ panic!("expected parts");+ };+ assert_eq!(parts.len(), 2);+ assert_eq!(parts[0]["cache_control"]["type"], "ephemeral");+ assert_eq!(parts[1]["image_url"]["detail"], "high");+ assert_eq!(parts[1]["image_url"]["url"], "data:image/jpeg;base64,QUJD");+ }++ /// Each cap is enforced on the decoded size, the count, and the total, and+ /// the refusal names the cap it crossed.+ #[test]+ fn the_content_caps_are_enforced() {+ let image = |bytes: usize| -> serde_json::Value {+ let payload = "A".repeat(bytes / 3 * 4);+ serde_json::json!({+ "type": "image_url",+ "image_url": { "url": format!("data:image/png;base64,{payload}") }+ })+ };+ let message = |parts: Vec<serde_json::Value>| {+ serde_json::json!({ "type": "user", "content": parts }).to_string()+ };++ let over_one = parse_input_line(&message(vec![image(MAX_IMAGE_BYTES + 3)]))+ .expect_err("over the per-image cap");+ assert!(over_one.contains("over the 5242880 byte cap"), "{over_one}");++ let at_one = message(vec![image(MAX_IMAGE_BYTES)]);+ assert!(+ parse_input_line(&at_one).is_ok(),+ "exactly at the cap is inside it"+ );++ let too_many = message(vec![image(3); MAX_IMAGES + 1]);+ let err = parse_input_line(&too_many).expect_err("over the image count");+ assert!(err.contains("more than 8 images"), "{err}");++ let over_total = message(vec![image(MAX_IMAGE_BYTES); 3]);+ let err = parse_input_line(&over_total).expect_err("over the message total");+ assert!(err.contains("over the 10485760 byte cap"), "{err}");+ }++ /// The echo in a rejection is bounded: the client sent a line whose size+ /// was already refused, and handing it all back would move the cost the cap+ /// removed from the parser onto the client's reader.+ #[test]+ fn a_rejected_line_is_echoed_truncated() {+ let line = "y".repeat(MAX_ECHO_BYTES + 1);+ let record = serde_json::to_value(InputErrorRecord::new("nope", &line)).expect("record");+ assert_eq!(record["line"].as_str().map(str::len), Some(MAX_ECHO_BYTES));+ assert_eq!(record["line_truncated"], serde_json::json!(true));++ let short = serde_json::to_value(InputErrorRecord::new("nope", "bad")).expect("record");+ assert_eq!(short["line"], serde_json::json!("bad"));+ assert_eq!(short["line_truncated"], serde_json::json!(false));+ }++ /// Truncation cuts on a character boundary: the echo is text a client+ /// prints, and half a code point would be a decoding error there.+ #[test]+ fn the_echo_cuts_on_a_character_boundary() {+ let line = "é".repeat(MAX_ECHO_BYTES);+ let record = serde_json::to_value(InputErrorRecord::new("nope", &line)).expect("record");+ let echoed = record["line"].as_str().expect("a string");+ assert!(echoed.len() <= MAX_ECHO_BYTES);+ assert!(line.starts_with(echoed));+ }+#[test]fn queued_turns_drain_once_and_in_order() {let input = StreamInput::default();@@ -304,6 +564,19 @@ mod tests {assert!(input.take_queued().is_empty());}+ /// A parts turn queues beside a text turn as the same kind of message: same+ /// role, same position, content as an array instead of a string.+ #[test]+ fn a_parts_turn_queues_as_the_same_message_kind() {+ let input = StreamInput::default();+ let parts = vec![serde_json::json!({ "type": "text", "text": "hi" })];+ input.queue_user_parts(parts.clone());+ let drained = input.take_queued();+ assert_eq!(drained.len(), 1);+ assert_eq!(drained[0]["role"], "user");+ assert_eq!(drained[0]["content"], serde_json::json!(parts));+ }+/// The latch, not just the notification: an abort landing before the run/// parks on it must still be seen, or the client's stop is swallowed.#[tokio::test]diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 2b4cd4513..e145cde05 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -47,6 +47,7 @@ use super::agent_status::AgentStatusReporter;use super::brand;use super::journal::{self, DisplayEntry, ReasoningSeg};use super::mcp::McpServerEntry;+use super::user_message::{build_user_message, image_mime, image_mime_of, PendingImage, MAX_IMAGE_BYTES};use super::worktree::Worktree;use super::{is_user_turn, sort_threads_recent, AgentSession, ResumeRequest, ResumeTarget, SessionLimits,@@ -1565,14 +1566,6 @@ struct Checkpoint {sha: String,}-/// An image staged by `/image <path>`, sent with the next user message as an-/// OpenAI `image_url` content part. `name` is the basename shown in the-/// transcript; `data_url` is the `data:<mime>;base64,...` payload.-struct PendingImage {- name: String,- data_url: String,-}-/// One entry in the file-path hint popup triggered by typing `@`.struct PathHintItem {/// Display path (relative to project root).@@ -16685,32 +16678,6 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value, verb: &str) {}}-/// Largest image accepted from a path or the clipboard, before base64 (which-/// inflates it by 4/3).-const MAX_IMAGE_BYTES: u64 = 20 * 1024 * 1024;--/// Infer an image MIME type from a file extension. `None` when the extension is-/// not a known image type.-fn image_mime_of(path: &str) -> Option<&'static str> {- let ext = std::path::Path::new(path)- .extension()- .and_then(|e| e.to_str())- .unwrap_or("")- .to_ascii_lowercase();- match ext.as_str() {- "png" => Some("image/png"),- "jpg" | "jpeg" => Some("image/jpeg"),- "gif" => Some("image/gif"),- "webp" => Some("image/webp"),- _ => None,- }-}--/// Infer an image MIME type from a file extension, defaulting to PNG.-fn image_mime(path: &str) -> &'static str {- image_mime_of(path).unwrap_or("image/png")-}-/// Read an image file into a `PendingImage` (base64 data URL + basename).fn load_image_file(path: &str) -> Result<PendingImage, String> {use base64::Engine;@@ -16821,26 +16788,6 @@ fn clipboard_image() -> Result<PendingImage, String> {})}-/// Build the OpenAI-shaped user message: a plain string with no images, else a-/// content-part array (text first, then `image_url` parts) matching the desktop-/// web-app wire shape.-fn build_user_message(text: &str, images: &[PendingImage]) -> serde_json::Value {- if images.is_empty() {- return serde_json::json!({ "role": "user", "content": text });- }- let mut parts = Vec::with_capacity(images.len() + 1);- if !text.is_empty() {- parts.push(serde_json::json!({ "type": "text", "text": text }));- }- for img in images {- parts.push(serde_json::json!({- "type": "image_url",- "image_url": { "url": img.data_url, "detail": "auto" }- }));- }- serde_json::json!({ "role": "user", "content": parts })-}-/// Split a user message's `content` into display text and one label per attached/// image. Handles plain-string content and the `image_url` content-part array;/// data-URL parts carry no filename, so their label is empty.diff --git a/src-tauri/src/core/cli/user_message.rs b/src-tauri/src/core/cli/user_message.rsnew file mode 100644index 000000000..8c7531853--- /dev/null+++ b/src-tauri/src/core/cli/user_message.rs@@ -0,0 +1,229 @@+//! The user-message wire shape, shared by the two paths that build one.+//!+//! A user message is either a plain string or an OpenAI content-part array+//! (text first, then `image_url` parts) -- the shape the desktop web-app sends,+//! which `upstream.rs` passes through verbatim. Two callers build one: the TUI,+//! which stages images a human attached, and the headless channel, which+//! forwards parts a client sent. The TUI's builder lives here so the channel+//! does not write the conversion a second time; the channel passes a client's+//! own parts through untouched and only *validates* them, using the MIME+//! allowlist and the `data:` URL reader below.++/// An image staged for the next user message: the basename shown in the+/// transcript, and the `data:<mime>;base64,...` URL that goes on the wire.+pub(crate) struct PendingImage {+ pub(crate) name: String,+ pub(crate) data_url: String,+}++/// Largest image a human may stage from a path or the clipboard, before base64+/// (which inflates it by 4/3). The headless channel caps its own input+/// separately and lower: a client is not a person attaching a screenshot.+pub(crate) const MAX_IMAGE_BYTES: u64 = 20 * 1024 * 1024;++/// The image types a message may carry. One list, two readers: [`image_mime_of`]+/// maps a file extension onto it, and the headless channel validates a client's+/// stated MIME against it -- a client that names its own type gets no silent+/// fallback, because relabelling into a format the model was never sent is+/// worse than rejecting the line.+pub(crate) const IMAGE_MIME_TYPES: [&str; 4] =+ ["image/png", "image/jpeg", "image/gif", "image/webp"];++/// Infer an image MIME type from a file extension. `None` when the extension is+/// not a known image type.+pub(crate) fn image_mime_of(path: &str) -> Option<&'static str> {+ let ext = std::path::Path::new(path)+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or("")+ .to_ascii_lowercase();+ match ext.as_str() {+ "png" => Some("image/png"),+ "jpg" | "jpeg" => Some("image/jpeg"),+ "gif" => Some("image/gif"),+ "webp" => Some("image/webp"),+ _ => None,+ }+}++/// Infer an image MIME type from a file extension, defaulting to PNG.+pub(crate) fn image_mime(path: &str) -> &'static str {+ image_mime_of(path).unwrap_or("image/png")+}++/// Build the OpenAI-shaped user message: a plain string with no images, else a+/// content-part array (text first, then `image_url` parts).+pub(crate) fn build_user_message(text: &str, images: &[PendingImage]) -> serde_json::Value {+ if images.is_empty() {+ return serde_json::json!({ "role": "user", "content": text });+ }+ let mut parts = Vec::with_capacity(images.len() + 1);+ if !text.is_empty() {+ parts.push(serde_json::json!({ "type": "text", "text": text }));+ }+ for img in images {+ parts.push(serde_json::json!({+ "type": "image_url",+ "image_url": { "url": img.data_url, "detail": "auto" }+ }));+ }+ serde_json::json!({ "role": "user", "content": parts })+}++/// The text a user message carries, for the transcript and for reporting a+/// follow-up a run ended before reading. Handles both forms: the plain string,+/// and the `text` parts of a content-part array. An image part contributes no+/// text, so a message that is only an image reads as empty.+pub(crate) fn text_of_content(content: &serde_json::Value) -> String {+ match content {+ serde_json::Value::String(s) => s.clone(),+ serde_json::Value::Array(parts) => parts+ .iter()+ .filter(|p| p.get("type").and_then(|v| v.as_str()) == Some("text"))+ .filter_map(|p| p.get("text").and_then(|v| v.as_str()))+ .collect(),+ _ => String::new(),+ }+}++/// Split an `image_url` part's URL into its MIME type and base64 payload, and+/// report the decoded size -- measured arithmetically, so a 5 MB image is not+/// decoded into a second 5 MB buffer just to be measured.+///+/// Only the `data:` form is accepted: a path would work on one host only, and a+/// remote or containerised client could not send one at all.+pub(crate) fn data_url_mime_and_len(url: &str) -> Result<(&str, usize), String> {+ let rest = url+ .strip_prefix("data:")+ .ok_or_else(|| "image url must be a data: URL".to_string())?;+ let (meta, payload) = rest+ .split_once(',')+ .ok_or_else(|| "data: URL has no payload".to_string())?;+ let mime = meta+ .strip_suffix(";base64")+ .ok_or_else(|| "data: URL must be base64-encoded".to_string())?;+ if !IMAGE_MIME_TYPES.contains(&mime.to_ascii_lowercase().as_str()) {+ return Err(format!(+ "unsupported image type '{mime}' ({})",+ IMAGE_MIME_TYPES.join(", ")+ ));+ }+ Ok((mime, base64_decoded_len(payload)?))+}++/// Decoded size of a base64 payload without decoding it. `4/3` of the payload is+/// the real size, which is what the caps are measured against: the line cap is a+/// weak proxy for it, since base64 inflates whatever it encodes.+pub(crate) fn base64_decoded_len(payload: &str) -> Result<usize, String> {+ if payload.len() % 4 != 0 {+ return Err("base64 payload length is not a multiple of 4".to_string());+ }+ let padding = payload.bytes().rev().take_while(|b| *b == b'=').count();+ if padding > 2 {+ return Err("base64 payload has too much padding".to_string());+ }+ if !payload+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'=')+ {+ return Err("base64 payload has a character outside the alphabet".to_string());+ }+ Ok(payload.len() / 4 * 3 - padding)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn image(name: &str, url: &str) -> PendingImage {+ PendingImage {+ name: name.to_string(),+ data_url: url.to_string(),+ }+ }++ #[test]+ fn a_message_without_images_stays_a_plain_string() {+ assert_eq!(+ build_user_message("hello", &[]),+ serde_json::json!({ "role": "user", "content": "hello" })+ );+ }++ #[test]+ fn a_message_with_images_is_text_first_then_image_parts() {+ let message = build_user_message("what is this?", &[image("a.png", "data:image/png;base64,AA")]);+ assert_eq!(+ message,+ serde_json::json!({+ "role": "user",+ "content": [+ { "type": "text", "text": "what is this?" },+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AA", "detail": "auto" } }+ ]+ })+ );+ }++ #[test]+ fn empty_text_is_omitted_when_an_image_carries_the_message() {+ let message = build_user_message("", &[image("a.png", "data:image/png;base64,AA")]);+ let parts = message["content"].as_array().expect("parts");+ assert_eq!(parts.len(), 1);+ assert_eq!(parts[0]["type"], "image_url");+ }++ #[test]+ fn text_of_content_reads_both_forms() {+ assert_eq!(text_of_content(&serde_json::json!("plain")), "plain");+ assert_eq!(+ text_of_content(&serde_json::json!([+ { "type": "text", "text": "look " },+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AA" } },+ { "type": "text", "text": "here" }+ ])),+ "look here"+ );+ }++ #[test]+ fn a_data_url_yields_its_mime_and_decoded_length() {+ // "QUJD" is "ABC": 3 bytes.+ assert_eq!(+ data_url_mime_and_len("data:image/png;base64,QUJD").unwrap(),+ ("image/png", 3)+ );+ // "QQ==" is "A": 1 byte, two padding bytes.+ assert_eq!(+ data_url_mime_and_len("data:image/jpeg;base64,QQ==").unwrap(),+ ("image/jpeg", 1)+ );+ }++ #[test]+ fn only_the_four_declared_mime_types_are_accepted() {+ for refused in [+ "data:image/svg+xml;base64,QUJD",+ "data:text/plain;base64,QUJD",+ "data:application/pdf;base64,QUJD",+ ] {+ let err = data_url_mime_and_len(refused).expect_err(refused);+ assert!(err.contains("unsupported image type"), "{refused}: {err}");+ }+ }++ #[test]+ fn paths_and_malformed_data_urls_are_refused() {+ for (url, marker) in [+ ("/tmp/shot.png", "must be a data: URL"),+ ("data:image/png;base64", "has no payload"),+ ("data:image/png,QUJD", "must be base64-encoded"),+ ("data:image/png;base64,QQQ", "not a multiple of 4"),+ ("data:image/png;base64,Q!==", "outside the alphabet"),+ ("data:image/png;base64,A===", "too much padding"),+ ] {+ let err = data_url_mime_and_len(url).expect_err(url);+ assert!(err.contains(marker), "{url}: {err} lacks {marker}");+ }+ }+}