Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent-tui): image attachments via Ctrl+V and --image

Akarshan Biswas9a6f791cb5b1
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index da8873d50..6caaa34e4 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -7,6 +7,7 @@ name = "Jan"
version = "0.8.4"
dependencies = [
"aes-gcm",
+ "arboard",
"async-trait",
"base64 0.22.1",
"chrono",
@@ -40,6 +41,7 @@ dependencies = [
"machine-uid",
"nix 0.30.1",
"once_cell",
+ "png 0.17.16",
"rand 0.8.7",
"ratatui",
"regex",
@@ -263,6 +265,27 @@ dependencies = [
"derive_arbitrary",
]
+[[package]]
+name = "arboard"
+version = "3.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"
+dependencies = [
+ "clipboard-win",
+ "image",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "parking_lot",
+ "percent-encoding",
+ "windows-sys 0.60.2",
+ "wl-clipboard-rs",
+ "x11rb",
+]
+
[[package]]
name = "ash"
version = "0.37.3+1.3.251"
@@ -637,6 +660,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
[[package]]
name = "bytes"
version = "1.12.1"
@@ -909,6 +938,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+[[package]]
+name = "clipboard-win"
+version = "5.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
+dependencies = [
+ "error-code",
+]
+
[[package]]
name = "codepage"
version = "0.1.2"
@@ -1971,6 +2009,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "error-code"
+version = "3.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"
+
[[package]]
name = "etcetera"
version = "0.8.0"
@@ -2055,6 +2099,12 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
+[[package]]
+name = "fax"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
+
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -2138,6 +2188,12 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
[[package]]
name = "flate2"
version = "1.1.9"
@@ -3201,6 +3257,20 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "moxcms",
+ "num-traits",
+ "png 0.18.1",
+ "tiff",
+]
+
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -3902,6 +3972,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
[[package]]
name = "muda"
version = "0.19.3"
@@ -4230,6 +4310,7 @@ dependencies = [
"block2",
"objc2",
"objc2-core-foundation",
+ "objc2-core-graphics",
"objc2-foundation",
]
@@ -4746,6 +4827,17 @@ dependencies = [
"pest",
]
+[[package]]
+name = "petgraph"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
+dependencies = [
+ "fixedbitset 0.5.7",
+ "hashbrown 0.15.5",
+ "indexmap 2.14.0",
+]
+
[[package]]
name = "phf"
version = "0.10.1"
@@ -5188,6 +5280,18 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
[[package]]
name = "quick-xml"
version = "0.31.0"
@@ -7707,7 +7811,7 @@ dependencies = [
"fancy-regex",
"filedescriptor",
"finl_unicode",
- "fixedbitset",
+ "fixedbitset 0.4.2",
"hex",
"lazy_static",
"libc",
@@ -7786,6 +7890,20 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "tiff"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg",
+]
+
[[package]]
name = "time"
version = "0.3.53"
@@ -8157,6 +8275,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "tree_magic_mini"
+version = "3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
+dependencies = [
+ "memchr",
+ "nom 8.0.0",
+ "petgraph",
+]
+
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -8674,6 +8803,19 @@ dependencies = [
"wayland-scanner",
]
+[[package]]
+name = "wayland-protocols-wlr"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "efd94963ed43cf9938a090ca4f7da58eb55325ec8200c3848963e98dc25b78ec"
+dependencies = [
+ "bitflags 2.13.0",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
[[package]]
name = "wayland-scanner"
version = "0.31.10"
@@ -9532,6 +9674,24 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+[[package]]
+name = "wl-clipboard-rs"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9651471a32e87d96ef3a127715382b2d11cc7c8bb9822ded8a7cc94072eb0a3"
+dependencies = [
+ "libc",
+ "log",
+ "os_pipe",
+ "rustix",
+ "thiserror 2.0.18",
+ "tree_magic_mini",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+]
+
[[package]]
name = "wrapcenum-derive"
version = "0.4.1"
@@ -9615,6 +9775,23 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "gethostname",
+ "rustix",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -9960,6 +10137,21 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "zune-core"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
+
[[package]]
name = "zvariant"
version = "4.2.0"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index d3ff617af..ced40bf1e 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -55,7 +55,7 @@ test-tauri = [
"deep-link",
"hardware",
]
-cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:tui-markdown", "dep:comfy-table"]
+cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:tui-markdown", "dep:comfy-table", "dep:arboard", "dep:png"]
[build-dependencies]
tauri-build = { version = "2.0.2", features = [] }
@@ -155,6 +155,8 @@ machine-uid = "0.5"
ratatui = { version = "0.30", optional = true, features = ["unstable-rendered-line-info"] }
tui-markdown = { version = "0.3.8", optional = true, default-features = false }
comfy-table = { version = "7.2", default-features = false, optional = true }
+arboard = { version = "3", optional = true, features = ["wayland-data-control"] }
+png = { version = "0.17", optional = true }
[dependencies.tauri]
version = "2.8.5"
diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rs
index ebb23eec6..2234c319c 100644
--- a/src-tauri/src/bin/jan-cli.rs
+++ b/src-tauri/src/bin/jan-cli.rs
@@ -176,6 +176,9 @@ enum AgentCommands {
/// Max turns per message (overrides [agent].max_turns; clamped 1..=400)
#[arg(long)]
max_turns: Option<u32>,
+ /// Image file to attach to the first message (repeatable)
+ #[arg(long = "image")]
+ images: Vec<String>,
#[command(flatten)]
providers: ProviderArgs,
},
@@ -442,8 +445,19 @@ async fn handle_agent(cmd: AgentCommands) {
task,
model,
max_turns,
+ images,
providers,
- } => cli_agent_ui(&project, task, model, max_turns, providers.into_overrides()).await,
+ } => {
+ cli_agent_ui(
+ &project,
+ task,
+ model,
+ max_turns,
+ images,
+ providers.into_overrides(),
+ )
+ .await
+ }
AgentCommands::Step {
project,
task,
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 03d1a72ea..c2ce01d35 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -69,12 +69,15 @@ pub(crate) fn parse_openai_messages(
.get("role")
.and_then(|v| v.as_str())
.ok_or("Each message must include a string 'role'")?;
- let content = msg
- .get("content")
- .and_then(|v| v.as_str())
- .ok_or("Each message must include 'content' as a string")?;
+ // Content is a plain string or an OpenAI multimodal content-part array
+ // (text + image_url); pass either through verbatim.
+ let content = match msg.get("content") {
+ Some(v @ serde_json::Value::String(_)) | Some(v @ serde_json::Value::Array(_)) => {
+ v.clone()
+ }
+ _ => return Err("Each message must include 'content' as a string or array".into()),
+ };
- // Keep upstream format minimal and predictable.
out.push(serde_json::json!({
"role": role,
"content": content
@@ -722,6 +725,25 @@ mod tests {
mpsc::unbounded_channel()
}
+ #[test]
+ fn parse_messages_passes_multimodal_content_array_through() {
+ let messages = json!([{
+ "role": "user",
+ "content": [
+ { "type": "text", "text": "look" },
+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AA" } },
+ ],
+ }]);
+ let out = parse_openai_messages(&messages).unwrap();
+ assert_eq!(out[0]["content"], messages[0]["content"]);
+ }
+
+ #[test]
+ fn parse_messages_rejects_missing_content() {
+ let messages = json!([{ "role": "user" }]);
+ assert!(parse_openai_messages(&messages).is_err());
+ }
+
#[test]
fn detects_provider_context_overflow_bodies() {
assert!(is_context_overflow_body(
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 77d92dfc9..42182eb53 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -145,7 +145,7 @@ pub fn cli_save_thread(
.iter()
.filter_map(|m| {
let role = m.get("role").and_then(|v| v.as_str())?;
- let content = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
+ let content = openai_content_text(m.get("content"));
Some(serde_json::json!({
"id": uuid::Uuid::new_v4().to_string(),
"object": "thread.message",
@@ -202,14 +202,29 @@ pub fn cli_set_project_model(agent_dir: &std::path::Path, model: &str) -> Result
set_model_in_agent_toml(&agent_dir.join("agent.toml"), model)
}
+/// Text of an OpenAI-shaped message `content`: the string as-is, or the joined
+/// `text` parts of a multimodal content array (image parts contribute nothing).
+fn openai_content_text(content: Option<&serde_json::Value>) -> String {
+ match content {
+ Some(serde_json::Value::String(s)) => s.clone(),
+ Some(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::<Vec<_>>()
+ .join(""),
+ _ => String::new(),
+ }
+}
+
/// Fallback thread title: the first user message, whitespace-collapsed and
/// truncated. Used only when no summarized title exists yet.
fn default_thread_title(history: &[serde_json::Value]) -> String {
let first_user = history
.iter()
.find(|m| m.get("role").and_then(|v| v.as_str()) == Some("user"))
- .and_then(|m| m.get("content").and_then(|v| v.as_str()))
- .unwrap_or("");
+ .map(|m| openai_content_text(m.get("content")))
+ .unwrap_or_default();
let collapsed = first_user.split_whitespace().collect::<Vec<_>>().join(" ");
if collapsed.is_empty() {
return "Agent chat".to_string();
@@ -1120,6 +1135,7 @@ pub async fn cli_agent_ui(
task: Option<String>,
model: Option<String>,
max_turns: Option<u32>,
+ images: Vec<String>,
overrides: ProviderOverrides,
) -> Result<(), String> {
let session = prepare_agent_session(project, model, max_turns, overrides)?;
@@ -1127,7 +1143,7 @@ pub async fn cli_agent_ui(
// desktop store, so continuing here never mutates desktop threads.
let project_root = resolve_project_root(project);
let agent_dir = project_root.join(".jan").join("agent");
- tui::run(session, agent_dir, project_root, task).await
+ tui::run(session, agent_dir, project_root, task, images).await
}
/// Render one `StreamEvent` for the terminal. Content tokens go to stdout so a
@@ -1246,6 +1262,31 @@ mod tests {
);
}
+ #[test]
+ fn openai_content_text_reads_multimodal_array() {
+ let content = serde_json::json!([
+ { "type": "text", "text": "describe" },
+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AA" } },
+ ]);
+ assert_eq!(openai_content_text(Some(&content)), "describe");
+ assert_eq!(openai_content_text(Some(&serde_json::json!("plain"))), "plain");
+ }
+
+ #[test]
+ fn default_thread_title_uses_multimodal_user_text() {
+ let history = serde_json::json!([{
+ "role": "user",
+ "content": [
+ { "type": "text", "text": "look at this" },
+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AA" } },
+ ],
+ }]);
+ assert_eq!(
+ default_thread_title(history.as_array().unwrap()),
+ "look at this"
+ );
+ }
+
#[test]
fn default_thread_title_truncates_and_falls_back() {
let long = "x".repeat(80);
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 5685a9003..5fd47d97b 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -238,6 +238,14 @@ 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,
+}
+
struct App {
model: String,
/// Orchestration handle for out-of-run model calls (the `/compact` command).
@@ -298,6 +306,8 @@ struct App {
/// expanding one that may sit above the pinned-to-bottom viewport).
reveal: Option<usize>,
input: String,
+ /// Images staged by `/image`, flushed into the next submitted user message.
+ pending_images: Vec<PendingImage>,
/// Caret position as a byte index into `input` (always on a char boundary).
cursor: usize,
/// Highlighted row in the slash-command hint popup (clamped to matches).
@@ -438,6 +448,7 @@ impl App {
expanded: std::collections::HashSet::new(),
reveal: None,
input: String::new(),
+ pending_images: Vec::new(),
cursor: 0,
slash_selected: 0,
slash_dismissed: false,
@@ -519,6 +530,7 @@ impl App {
self.reveal = None;
self.assistant_buf.clear();
self.pending_queue.clear();
+ self.pending_images.clear();
self.tokens = 0;
self.turn = (0, 0);
self.detail.clear();
@@ -778,13 +790,10 @@ impl App {
/// in the same input batch can't slip through as a second submit.
fn submit_user(&mut self, text: String) {
self.ensure_base_snapshot();
- self.history
- .push(serde_json::json!({ "role": "user", "content": text }));
- self.gap(Kind::User);
- self.push(Line::from(vec![
- Span::styled("› ", Style::new().light_magenta().bold()),
- Span::styled(text, Style::new().bold()),
- ]));
+ let images = std::mem::take(&mut self.pending_images);
+ let names: Vec<String> = images.iter().map(|i| i.name.clone()).collect();
+ self.history.push(build_user_message(&text, &images));
+ self.push_user_line(&text, &names);
self.status = Status::Running;
self.run_started = Some(Instant::now());
self.turn = (0, 0);
@@ -793,6 +802,42 @@ impl App {
self.persist();
}
+ /// Render a user turn: the prompt line, then one dotted connector row per
+ /// attached image ending in an `[IMAGE]` label (basename when known).
+ fn push_user_line(&mut self, text: &str, images: &[String]) {
+ self.gap(Kind::User);
+ self.push(Line::from(vec![
+ Span::styled("› ", Style::new().light_magenta().bold()),
+ Span::styled(text.to_string(), Style::new().bold()),
+ ]));
+ for name in images {
+ let label = if name.is_empty() {
+ "[IMAGE]".to_string()
+ } else {
+ format!("[IMAGE] {name}")
+ };
+ self.push(Line::from(vec![
+ Span::styled(" ┊ ", Style::new().dim()),
+ Span::styled(label, Style::new().cyan()),
+ ]));
+ }
+ }
+
+ /// Stage the OS clipboard's image for the next message, noting the result.
+ fn attach_clipboard_image(&mut self) {
+ match clipboard_image() {
+ Ok(img) => {
+ let name = img.name.clone();
+ self.pending_images.push(img);
+ self.note(&format!(
+ "attached {name} ({} image(s) pending)",
+ self.pending_images.len()
+ ));
+ }
+ Err(e) => self.note(&format!("no image in clipboard: {e}")),
+ }
+ }
+
fn body(&self) -> serde_json::Value {
serde_json::json!({
"model": self.model,
@@ -1889,6 +1934,7 @@ pub async fn run(
agent_dir: std::path::PathBuf,
project_root: PathBuf,
initial_task: Option<String>,
+ initial_images: Vec<String>,
) -> Result<(), String> {
let AgentSession {
args,
@@ -1912,6 +1958,12 @@ pub async fn run(
let repo_root = git::repo_root(&project_root);
let mut app = App::new(model, max_turns, agent_dir, project_root, repo_root);
app.args = Some(args.clone());
+ for path in &initial_images {
+ match load_image_file(path) {
+ Ok(img) => app.pending_images.push(img),
+ Err(e) => app.note(&format!("could not attach image: {e}")),
+ }
+ }
let res = chat_loop(
&mut terminal,
&args,
@@ -2355,6 +2407,11 @@ async fn handle_key(
KeyCode::Char('o') if ctrl => {
app.toggle_regions();
}
+ // Ctrl-V stages an image from the OS clipboard (terminal paste is
+ // text-only, so we read the clipboard directly) for the next message.
+ KeyCode::Char('v') if app.status == Status::Idle && ctrl => {
+ app.attach_clipboard_image();
+ }
KeyCode::Enter => {
if app.status == Status::Idle {
let text = app.input.trim().to_string();
@@ -2884,18 +2941,17 @@ fn rebuild_transcript(app: &mut App) {
let history = app.history.clone();
for m in &history {
let role = m.get("role").and_then(|v| v.as_str()).unwrap_or("");
- let text = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
- if text.is_empty() {
- continue;
- }
if role == "user" {
- app.gap(Kind::User);
- app.push(Line::from(vec![
- Span::styled("› ", Style::new().light_magenta().bold()),
- Span::styled(text.to_string(), Style::new().bold()),
- ]));
+ let (text, images) = user_content_parts(m.get("content").unwrap_or(&serde_json::Value::Null));
+ if text.is_empty() && images.is_empty() {
+ continue;
+ }
+ app.push_user_line(&text, &images);
} else if role == "assistant" {
- app.push_assistant_blocks(text);
+ let text = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
+ if !text.is_empty() {
+ app.push_assistant_blocks(text);
+ }
}
}
}
@@ -2960,11 +3016,7 @@ fn resume_thread(app: &mut App, id_arg: &str) {
app.history
.push(serde_json::json!({ "role": role, "content": text }));
if role == "user" {
- app.gap(Kind::User);
- app.push(Line::from(vec![
- Span::styled("› ", Style::new().light_magenta().bold()),
- Span::styled(text, Style::new().bold()),
- ]));
+ app.push_user_line(&text, &[]);
} else {
app.push_assistant_blocks(&text);
}
@@ -2979,6 +3031,147 @@ fn resume_thread(app: &mut App, id_arg: &str) {
app.note(&format!("resumed \"{title}\" ({count} messages)"));
}
+/// Infer an image MIME type from a file extension, defaulting to PNG.
+fn image_mime(path: &str) -> &'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() {
+ "jpg" | "jpeg" => "image/jpeg",
+ "gif" => "image/gif",
+ "webp" => "image/webp",
+ _ => "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;
+ let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
+ if bytes.is_empty() {
+ return Err(format!("{path}: empty file"));
+ }
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
+ let name = std::path::Path::new(path)
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("image")
+ .to_string();
+ Ok(PendingImage {
+ name,
+ data_url: format!("data:{};base64,{b64}", image_mime(path)),
+ })
+}
+
+/// Percent-decode a `file://` URI or plain path from clipboard text into a
+/// filesystem path. Takes the first line (uri-lists are newline-separated) and
+/// strips a `file://[host]` scheme; decodes `%XX` byte escapes.
+fn clipboard_path(text: &str) -> Option<String> {
+ let line = text.lines().find(|l| !l.trim().is_empty())?.trim();
+ let raw = line
+ .strip_prefix("file://localhost")
+ .or_else(|| line.strip_prefix("file://"))
+ .unwrap_or(line);
+ let bytes = raw.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%' && i + 2 < bytes.len() {
+ if let Ok(b) = u8::from_str_radix(&raw[i + 1..i + 3], 16) {
+ out.push(b);
+ i += 3;
+ continue;
+ }
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ String::from_utf8(out).ok().filter(|p| !p.is_empty())
+}
+
+/// Read an image from the OS clipboard into a `PendingImage`. Prefers raw image
+/// data (PNG-encoding it); falls back to treating clipboard text as an image
+/// file path or `file://` URI (as file managers and browsers put on the
+/// clipboard). Errors when neither yields an image.
+fn clipboard_image() -> Result<PendingImage, String> {
+ use base64::Engine;
+ let mut clip = arboard::Clipboard::new().map_err(|e| e.to_string())?;
+ let img = match clip.get_image() {
+ Ok(img) => img,
+ Err(image_err) => {
+ if let Some(path) = clip.get_text().ok().as_deref().and_then(clipboard_path) {
+ if std::path::Path::new(&path).is_file() {
+ return load_image_file(&path);
+ }
+ }
+ return Err(image_err.to_string());
+ }
+ };
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, img.width as u32, img.height as u32);
+ enc.set_color(png::ColorType::Rgba);
+ enc.set_depth(png::BitDepth::Eight);
+ let mut writer = enc.write_header().map_err(|e| e.to_string())?;
+ writer
+ .write_image_data(&img.bytes)
+ .map_err(|e| e.to_string())?;
+ }
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&png);
+ Ok(PendingImage {
+ name: "clipboard.png".to_string(),
+ data_url: format!("data:image/png;base64,{b64}"),
+ })
+}
+
+/// 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.
+fn user_content_parts(content: &serde_json::Value) -> (String, Vec<String>) {
+ match content {
+ serde_json::Value::String(s) => (s.clone(), Vec::new()),
+ serde_json::Value::Array(parts) => {
+ let mut text = String::new();
+ let mut images = Vec::new();
+ for p in parts {
+ match p.get("type").and_then(|v| v.as_str()) {
+ Some("text") => {
+ if let Some(t) = p.get("text").and_then(|v| v.as_str()) {
+ text.push_str(t);
+ }
+ }
+ Some("image_url") => images.push(String::new()),
+ _ => {}
+ }
+ }
+ (text, images)
+ }
+ _ => (String::new(), Vec::new()),
+ }
+}
+
/// Extract plain text from a stored thread message (`content` is an array of
/// `{type,text:{value}}` parts, or occasionally a bare string).
fn message_text(msg: &serde_json::Value) -> String {
@@ -3574,12 +3767,12 @@ fn footer(app: &App) -> Paragraph<'static> {
#[cfg(test)]
mod tests {
use super::{
- diff_lines, group_activity, group_detail_lines, group_summary, handle_key, handle_mouse,
- input_content_lines, is_table_separator, message_text,
- parse_command, render_table, run_command, running_group_row, split_reasoning,
+ build_user_message, clipboard_path, diff_lines, group_activity, group_detail_lines,
+ group_summary, handle_key, handle_mouse, image_mime, input_content_lines, is_table_separator, load_image_file,
+ message_text, parse_command, render_table, run_command, running_group_row, split_reasoning,
subagent_activity, subagent_name_from_run_id, summarize_result, tool_activity,
- tool_finished, transcript_top_padding, App, CurrentRun, Pending, SnapshotJob,
- DIFF_MAX_ROWS, SLASH_COMMANDS, SPINNER,
+ tool_finished, transcript_top_padding, user_content_parts, App, CurrentRun, Pending,
+ PendingImage, SnapshotJob, DIFF_MAX_ROWS, SLASH_COMMANDS, SPINNER,
};
use ratatui::crossterm::event::{
KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
@@ -3995,6 +4188,111 @@ mod tests {
line.spans.iter().map(|s| s.content.as_ref()).collect()
}
+ #[test]
+ fn image_mime_infers_from_extension() {
+ assert_eq!(image_mime("a.png"), "image/png");
+ assert_eq!(image_mime("a.JPG"), "image/jpeg");
+ assert_eq!(image_mime("a.jpeg"), "image/jpeg");
+ assert_eq!(image_mime("noext"), "image/png");
+ }
+
+ #[test]
+ fn clipboard_path_parses_file_uri_and_plain_path() {
+ assert_eq!(
+ clipboard_path("file:///home/u/my%20pic.png\n").as_deref(),
+ Some("/home/u/my pic.png")
+ );
+ assert_eq!(
+ clipboard_path("file://localhost/tmp/a.png").as_deref(),
+ Some("/tmp/a.png")
+ );
+ assert_eq!(clipboard_path("/tmp/b.jpg").as_deref(), Some("/tmp/b.jpg"));
+ assert_eq!(clipboard_path(" \n "), None);
+ }
+
+ #[test]
+ fn build_user_message_is_plain_string_without_images() {
+ let m = build_user_message("hi", &[]);
+ assert_eq!(m["content"], json!("hi"));
+ }
+
+ #[test]
+ fn build_user_message_wraps_text_and_image_parts() {
+ let imgs = vec![PendingImage {
+ name: "p.png".into(),
+ data_url: "data:image/png;base64,AAAA".into(),
+ }];
+ let m = build_user_message("look", &imgs);
+ let parts = m["content"].as_array().unwrap();
+ assert_eq!(parts[0], json!({ "type": "text", "text": "look" }));
+ assert_eq!(parts[1]["type"], "image_url");
+ assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAAA");
+ }
+
+ #[test]
+ fn build_user_message_omits_empty_text_part() {
+ let imgs = vec![PendingImage {
+ name: "p.png".into(),
+ data_url: "data:image/png;base64,AAAA".into(),
+ }];
+ let parts = build_user_message("", &imgs)["content"]
+ .as_array()
+ .unwrap()
+ .clone();
+ assert_eq!(parts.len(), 1);
+ assert_eq!(parts[0]["type"], "image_url");
+ }
+
+ #[test]
+ fn user_content_parts_splits_text_and_images() {
+ let content = json!([
+ { "type": "text", "text": "hello" },
+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,AA" } },
+ ]);
+ let (text, images) = user_content_parts(&content);
+ assert_eq!(text, "hello");
+ assert_eq!(images.len(), 1);
+ let (text, images) = user_content_parts(&json!("plain"));
+ assert_eq!(text, "plain");
+ assert!(images.is_empty());
+ }
+
+ #[test]
+ fn load_image_file_encodes_base64_data_url() {
+ let path = std::env::temp_dir().join(format!("jan_img_{}.png", uuid::Uuid::new_v4()));
+ std::fs::write(&path, [1u8, 2, 3, 4]).unwrap();
+ let img = load_image_file(path.to_str().unwrap()).unwrap();
+ assert!(img.data_url.starts_with("data:image/png;base64,"));
+ assert!(img.name.ends_with(".png"));
+ std::fs::remove_file(&path).ok();
+ }
+
+ #[test]
+ fn load_image_file_rejects_empty() {
+ let path = std::env::temp_dir().join(format!("jan_empty_{}.png", uuid::Uuid::new_v4()));
+ std::fs::write(&path, []).unwrap();
+ assert!(load_image_file(path.to_str().unwrap()).is_err());
+ std::fs::remove_file(&path).ok();
+ }
+
+ #[test]
+ fn submit_user_attaches_pending_images_and_renders_label() {
+ let mut app = test_app();
+ app.pending_images.push(PendingImage {
+ name: "shot.png".into(),
+ data_url: "data:image/png;base64,AAAA".into(),
+ });
+ app.submit_user("describe this".into());
+
+ let content = app.history.last().unwrap()["content"].as_array().unwrap();
+ assert_eq!(content[0]["type"], "text");
+ assert_eq!(content[1]["type"], "image_url");
+ assert!(app.pending_images.is_empty(), "pending images flushed");
+
+ let rendered: Vec<String> = app.transcript.iter().map(line_text).collect();
+ assert!(rendered.iter().any(|l| l.contains("[IMAGE] shot.png")));
+ }
+
#[test]
fn base_snapshot_is_queued_off_loop_not_run_inline() {
let mut app = test_app();
diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rs
index 06d9ec42d..d73432908 100644
--- a/src-tauri/src/core/server/tests.rs
+++ b/src-tauri/src/core/server/tests.rs
@@ -901,8 +901,18 @@ mod server_tests {
}
#[test]
- fn parse_openai_messages_non_string_content_errors() {
- let msgs = json!([{"role": "user", "content": [{"type": "text", "text": "hi"}]}]);
+ fn parse_openai_messages_passes_multimodal_array_through() {
+ let msgs = json!([{"role": "user", "content": [
+ {"type": "text", "text": "hi"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA"}},
+ ]}]);
+ let out = proxy::parse_openai_messages(&msgs).unwrap();
+ assert_eq!(out[0]["content"], msgs[0]["content"]);
+ }
+
+ #[test]
+ fn parse_openai_messages_non_string_non_array_content_errors() {
+ let msgs = json!([{"role": "user", "content": 42}]);
assert!(proxy::parse_openai_messages(&msgs).is_err());
}