From d2c4567eb0c191374059d8f5cdc9444334e322c2 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 00:15:13 -0500 Subject: [PATCH 01/21] M6: instances pasted from Figma link to mains pasted earlier (#2022) The .fig import now keeps each main's Figma identity (layer guid on the main and every layer in it, library key when present) in the node's plugin data as fig.* keys, and instances keep their main's guid as fig.main. The paste reads the file key from the clipboard's figmeta span and stamps it as fig.file. When the mains an instance uses are not in the pasted layers, adopt_pasted matches them with components the file already holds (same guid and file, or same library key) and links the instance and its layers to them. No match keeps today's result with one warning in the paste result. fig.* keys are not named in the .fig export's plugin-data note. Reverse order (mains pasted after their instances) is deferred. pack_canvas (and the export schema) are exposed so engine tests can build synthetic payloads. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/assets/library.rs | 55 ++++++ crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/edit/clipboard.rs | 52 +++++- .../engine/src/design_paste_relink_tests.rs | 166 ++++++++++++++++++ crates/engine/src/lib.rs | 2 + crates/format/src/fig.rs | 4 +- crates/format/src/fig/export.rs | 19 +- crates/format/src/fig/export/layer.rs | 2 +- crates/format/src/fig/export_tests.rs | 2 + crates/format/src/fig/map/layer.rs | 4 + crates/format/src/fig/paste_relink_tests.rs | 55 ++++++ crates/format/src/rest.rs | 37 ++++ docs/file-format-parity.md | 7 +- 13 files changed, 392 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/design_paste_relink_tests.rs create mode 100644 crates/format/src/fig/paste_relink_tests.rs diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index d9107ad63..8b8be7e1b 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1208,6 +1208,58 @@ fn merge_components( Ok(remote) } +/// Match the mains of `src` (a design app's paste) that nothing else covers with the components of +/// `doc` that carry the same Figma identity: the same `fig.guid` from the same file (`fig.file`, +/// both absent counts as the same), or the same library `fig.key` from anywhere. A hit links the +/// main and each of its layers carrying a `fig.guid` to the layer of `doc`'s component with that +/// guid, so instances and their per-layer sources point into the component already there. +fn relink_by_identity( + doc: &Document, + src: &Document, + mains: &BTreeSet, + map: &BTreeMap, + remote: &mut BTreeMap, +) { + let todo: Vec = mains + .iter() + .copied() + .filter(|m| !map.contains_key(m) && !remote.contains_key(m) && src.node(*m).is_some_and(|n| n.plugin_data.contains_key("fig.guid"))) + .collect(); + if todo.is_empty() { + return; + } + let pasted: BTreeSet = map.values().copied().collect(); + let mut by_guid: BTreeMap<(Option<&str>, &str), NodeId> = BTreeMap::new(); + let mut by_key: BTreeMap<&str, NodeId> = BTreeMap::new(); + for n in doc.nodes() { + if !matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) || pasted.contains(&n.id) || doc.is_remote(n.id) { + continue; + } + if let Some(g) = n.plugin_data.get("fig.guid") { + by_guid.entry((n.plugin_data.get("fig.file").map(String::as_str), g.as_str())).or_insert(n.id); + } + if let Some(k) = n.plugin_data.get("fig.key") { + by_key.entry(k.as_str()).or_insert(n.id); + } + } + for m in todo { + let Some(theirs) = src.node(m) else { continue }; + let guid = theirs.plugin_data.get("fig.guid").map(String::as_str).unwrap_or_default(); + let found = by_guid + .get(&(theirs.plugin_data.get("fig.file").map(String::as_str), guid)) + .or_else(|| theirs.plugin_data.get("fig.key").and_then(|k| by_key.get(k.as_str()))); + let Some(&mine) = found else { continue }; + let layers: BTreeMap<&str, NodeId> = + doc.subtree(mine).into_iter().filter_map(|i| Some((doc.node(i)?.plugin_data.get("fig.guid")?.as_str(), i))).collect(); + remote.insert(m, mine); + for l in src.subtree(m) { + if let Some(&target) = src.node(l).and_then(|n| n.plugin_data.get("fig.guid")).and_then(|g| layers.get(g.as_str())) { + remote.entry(l).or_insert(target); + } + } + } +} + /// When layers copied from another document `src` are pasted into `doc` (`map`: their ids → the /// pasted ids), point the instances among them at mains of `doc`: library copies are shared with /// (or brought along as) `doc`'s copies of the same library assets; components `src` publishes as @@ -1261,6 +1313,9 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>, } } } + // Mains copied from a design app that this file already holds (pasted earlier): found by the + // identity recorded on them, layer by layer. + relink_by_identity(doc, src, &mains, map, &mut remote); // Point the pasted layers at those mains; what stays behind gets ids of its own. let mut behind: BTreeMap = BTreeMap::new(); let mut follow = |doc: &mut Document, id: NodeId| -> NodeId { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index efcb0fc52..6985fc5eb 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -19,7 +19,7 @@ pub(crate) use props::{edit_region_fills, fill_regions}; mod select; pub(crate) use clipboard::apply_copied_props; -pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into}; +pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, design_clipboard_file, paste_into}; use clipboard::{copy, copy_props, copy_props_of, cut, paste, paste_design_layers, paste_over, paste_props, paste_replace}; use props::{ batch_rename, effect_add, effect_copy, effect_paste, find_replace, paint_copy, paint_list, paint_paste, paint_set, pattern_fill, reparent, set, diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index 150a3b577..dfdf8122e 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -89,6 +89,27 @@ pub fn design_clipboard_buffer(html: &str) -> Option> { figcraft_format::fig::is_fig(&bytes).then_some(bytes) } +/// The markers around the copy's metadata (base64 of a JSON object) in the clipboard's HTML. +const META_OPEN: &str = "(figmeta)"; + +const META_CLOSE: &str = "(/figmeta)"; + +/// The key of the file the layers were copied from, from the metadata span of the clipboard's +/// HTML; a copy's layer ids are only unique within that file. `None` when the HTML has none. +pub fn design_clipboard_file(html: &str) -> Option { + use base64::Engine as _; + let start = html.find(META_OPEN)? + META_OPEN.len(); + let len = html.get(start..)?.find(META_CLOSE)?; + let b64: String = html.get(start..start + len)?.chars().filter(|c| !c.is_ascii_whitespace()).collect(); + if b64.len() > 64 * 1024 { + return None; + } + let bytes = + base64::engine::general_purpose::STANDARD.decode(&b64).or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&b64)).ok()?; + let meta: Value = serde_json::from_slice(&bytes).ok()?; + meta.get("fileKey").and_then(Value::as_str).filter(|k| !k.is_empty() && k.len() <= 128).map(str::to_string) +} + /// Paste design layers from clipboard HTML or base64 `data`: decode and reject missing, /// invalid or oversized data, load a temporary `.fig`, take its top-level page layers, /// store them as a foreign-file clipboard source with a bumped layers generation, then @@ -100,7 +121,20 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { (None, Some(d)) => clip_base64(&d).ok_or_else(|| bad(CMD, "`data` is not base64 of at most 256 MB"))?, (None, None) => return Err(bad(CMD, "pass `html` or `data`")), }; - let other = crate::cmd::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + let file_key = + string(p, "html").as_deref().and_then(design_clipboard_file).or_else(|| string(p, "fileKey").filter(|k| !k.is_empty() && k.len() <= 128)); + let mut other = crate::cmd::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + if let Some(key) = &file_key { + // Layer ids are unique within one file only: mains keep the file they came from. + let ids: Vec = other.doc.ids().collect(); + for id in ids { + if let Ok(n) = other.doc.get_mut(id) + && n.plugin_data.contains_key("fig.guid") + { + n.plugin_data.insert("fig.file".into(), key.clone()); + } + } + } let doc = std::sync::Arc::new(other.doc); let tops: Vec = doc.pages.iter().filter_map(|pg| doc.node(*pg)).flat_map(|pg| pg.children.iter().copied()).collect(); if tops.is_empty() { @@ -139,8 +173,20 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { if !missing.is_empty() { out["missingImages"] = json!(missing); } - if !other.issues.is_empty() { - out["warnings"] = json!(other.issues); + let mut warnings: Vec = other.issues.clone(); + { + let d = s.doc()?; + let unlinked = pasted + .iter() + .flat_map(|r| d.subtree(*r)) + .filter_map(|i| d.node(i)) + .any(|n| matches!(&n.kind, NodeKind::Instance { component, .. } if !d.contains(*component))); + if unlinked { + warnings.push("instances of components not in this file stay unlinked (paste their main components first)".into()); + } + } + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } Ok(out) } diff --git a/crates/engine/src/design_paste_relink_tests.rs b/crates/engine/src/design_paste_relink_tests.rs new file mode 100644 index 000000000..3b652b2cd --- /dev/null +++ b/crates/engine/src/design_paste_relink_tests.rs @@ -0,0 +1,166 @@ +//! Instances pasted from another design app link to the mains pasted earlier (#2022). The paste +//! carries the mains the instances use in a hidden canvas; those mains are matched with the +//! components this file already holds by the identity recorded on them at their own paste (the +//! layer guid within one file, or the library key). Payloads are synthetic, built in code. + +use base64::Engine as _; +use figcraft_format::fig::kiwi::Kv; +use serde_json::json; + +use figcraft_doc::NodeKind; + +use super::{NodeId, Session, params}; +use crate::cmd::edit::{CLIP_CLOSE, CLIP_OPEN}; + +const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; + +type Fields = Vec<(&'static str, Kv<'static>)>; + +fn o(f: Fields) -> Kv<'static> { + Kv::Object(f) +} + +fn g(local: u64) -> Kv<'static> { + o(vec![("sessionID", Kv::Uint(1)), ("localID", Kv::Uint(local))]) +} + +fn xy(x: f32, y: f32) -> Kv<'static> { + o(vec![("x", Kv::Float(x)), ("y", Kv::Float(y))]) +} + +fn node(id: u64, parent: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Fields) -> Kv<'static> { + let mut v = vec![("guid", if id == 0 { o(vec![("sessionID", Kv::Uint(0)), ("localID", Kv::Uint(0))]) } else { g(id) })]; + if let Some((p, pos)) = parent { + let pg = if p == 0 { o(vec![("sessionID", Kv::Uint(0)), ("localID", Kv::Uint(0))]) } else { g(p) }; + v.push(("parentIndex", o(vec![("guid", pg), ("position", Kv::Str(pos.into()))]))); + } + v.push(("type", Kv::Enum(ty))); + v.push(("name", Kv::Str(name.into()))); + v.append(&mut more); + o(v) +} + +fn main_nodes(parent: u64, id: u64, key: Option<&'static str>) -> Vec> { + let mut f = vec![("size", xy(40.0, 20.0))]; + if let Some(k) = key { + f.push(("key", Kv::Str(k.into()))); + } + vec![node(id, Some((parent, "!")), "SYMBOL", "Button", f), node(id + 1, Some((id, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])] +} + +/// A paste of the main alone, as the first copy. +fn payload_main(id: u64, key: Option<&'static str>) -> Vec> { + let mut v = vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])]; + v.extend(main_nodes(1, id, key)); + v +} + +/// A paste of an instance of the main `id`, whose definition travels in the hidden canvas. +fn payload_instance(id: u64, key: Option<&'static str>, with_main: bool) -> Vec> { + let mut v = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(id))]))]), + ]; + if with_main { + v.extend(main_nodes(2, id, key)); + } + v +} + +fn html(nodes: Vec>, file: &str) -> String { + let bytes = figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(nodes))])).expect("packs"); + let meta = B64.encode(json!({"fileKey": file}).to_string()); + format!( + r#""#, + B64.encode(bytes) + ) +} + +fn paste(s: &mut Session, html: String) -> serde_json::Value { + // A paste goes into the selected frame: the main just pasted is not a place for its instances. + s.execute("select.set", &json!({"ids": []})).expect("clears"); + s.execute("edit.pasteDesignLayers", &json!({ "html": html })).expect("pastes") +} + +fn ids(r: &serde_json::Value) -> Vec { + r["ids"].as_array().unwrap().iter().filter_map(params::id_of).collect() +} + +fn components(s: &Session) -> Vec { + s.doc().unwrap().nodes().filter(|n| matches!(n.kind, NodeKind::Component { .. })).map(|n| n.id).collect() +} + +fn instance_main(s: &Session, instance: NodeId) -> NodeId { + match &s.doc().unwrap().node(instance).unwrap().kind { + NodeKind::Instance { component, .. } => *component, + k => panic!("not an instance: {k:?}"), + } +} + +#[test] +fn instances_pasted_after_their_mains_link_to_them() { + let mut s = Session::new(); + let a = paste(&mut s, html(payload_main(20, None), "F1")); + let main = ids(&a)[0]; + assert_eq!(components(&s), [main]); + let r = paste(&mut s, html(payload_instance(20, None, true), "F1")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main, "the instance shows the main pasted first"); + assert_eq!(components(&s), [main], "no second component came along"); + let doc = s.doc().unwrap(); + let face = doc.node(copy).unwrap().children[0]; + let source = doc.node(face).unwrap().source.expect("the layer is linked to the main's layer"); + assert!(doc.is_ancestor(main, source), "inside the main"); + assert!(r.get("warnings").is_none_or(|w| w.as_array().is_some_and(|w| w.is_empty())), "{r}"); + s.execute("select.set", &json!({"ids": [copy]})).unwrap(); + s.execute("component.goToMain", &json!({"id": copy})).expect("goToMain succeeds"); +} + +#[test] +fn one_undo_removes_the_pasted_instance_and_keeps_the_main() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + assert!(s.undo().unwrap()); + let doc = s.doc().unwrap(); + assert!(!doc.contains(copy)); + assert!(doc.contains(main)); + assert_eq!(components(&s), [main]); +} + +#[test] +fn a_main_from_another_figma_file_is_not_matched_by_guid_alone() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let r = paste(&mut s, html(payload_instance(20, None, true), "F2")); + let copy = ids(&r)[0]; + assert_ne!(instance_main(&s, copy), main, "the same guid in another file is another component"); +} + +#[test] +fn the_same_library_key_links_whatever_the_guids() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + let r = paste(&mut s, html(payload_instance(77, Some("btn"), true), "F2")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main); +} + +#[test] +fn an_instance_whose_main_never_arrives_stays_as_today() { + let mut s = Session::new(); + let r = paste(&mut s, html(payload_instance(20, None, true), "F1")); + let copy = ids(&r)[0]; + let main = instance_main(&s, copy); + assert!(!s.doc().unwrap().contains(main), "the main stayed behind"); + let warnings = r["warnings"].to_string(); + assert!(warnings.contains("stay unlinked"), "{warnings}"); + s.execute("component.restoreMain", &json!({"id": copy})).expect("the main can be restored"); +} + +/// The export schema, with the library `key` field the payloads of a library's components carry. +fn schema() -> String { + figcraft_format::fig::EXPORT_SCHEMA.replacen("message NodeChange ", "message NodeChange string key=9999, ", 1) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..54d14bae8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -279,6 +279,8 @@ mod datafill_tests; #[cfg(test)] mod default_props_tests; #[cfg(test)] +mod design_paste_relink_tests; +#[cfg(test)] mod design_paste_tests; #[cfg(test)] mod dev_measurements_tests; diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index f7547c3d0..21c3ada49 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -34,6 +34,8 @@ mod map; mod missing_image_tests; mod network; #[cfg(test)] +mod paste_relink_tests; +#[cfg(test)] mod paste_style_tests; #[cfg(test)] mod prop_value_tests; @@ -68,7 +70,7 @@ use std::sync::Arc; use figcraft_doc::{Document, FileKind}; -pub use export::export; +pub use export::{SCHEMA as EXPORT_SCHEMA, export, pack_canvas}; use crate::FormatError; use kiwi::{Kv, Schema}; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index f00de3606..364fbd7bc 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -69,7 +69,7 @@ const AUX: u32 = 2; /// The schema written into every file: `enum Name A=value …`, `struct Name type field, …` (every /// field, in order) and `message Name type field=id, …`, with the names, kinds and numbers the /// format gives them. Only what the export writes. -pub(super) const SCHEMA: &str = " +pub const SCHEMA: &str = " enum MessageType JOIN_START=0 NODE_CHANGES=1 enum NodePhase CREATED=0 REMOVED=1 enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31 @@ -199,11 +199,7 @@ message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4 pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec), FormatError> { let mut x = Exporter::new(doc); let message = x.message(); - let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); - let schema = Schema::parse(SCHEMA).map_err(fail)?; - let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; - let body = encode::message(&schema, root, &message).map_err(fail)?; - let canvas = canvas(&encode::schema(&schema), &body)?; + let canvas = pack_canvas(SCHEMA, &message)?; let background = doc.pages.first().and_then(|p| doc.node(*p)).and_then(|p| match &p.kind { NodeKind::Page { background, .. } => Some(*background), _ => None, @@ -212,6 +208,17 @@ pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec< Ok((bytes, x.warnings)) } +/// A `canvas.fig` holding `message` (a `Message` of the kiwi schema `schema_source`, normally +/// [`SCHEMA`]), as the design apps put it on the clipboard. Lets synthetic payloads be built +/// outside this crate. +pub fn pack_canvas(schema_source: &str, message: &Kv) -> Result, FormatError> { + let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); + let schema = Schema::parse(schema_source).map_err(fail)?; + let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; + let body = encode::message(&schema, root, message).map_err(fail)?; + canvas(&encode::schema(&schema), &body) +} + fn too_large() -> FormatError { FormatError::Io("the document is too large for a .fig file".into()) } diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index b4fda9138..51aeffe1c 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -306,7 +306,7 @@ impl<'d> Exporter<'d> { { self.warn("Dev Mode annotations, statuses, resources, measurements and code links were left out"); } - if !n.plugin_data.is_empty() { + if n.plugin_data.keys().any(|k| !k.starts_with("fig.")) { self.warn("plugin data was left out"); } } diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9651a1025..3e9ac1994 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -754,6 +754,8 @@ fn canon(doc: &Document) -> Vec { .map(|id| { let mut n = doc.node(*id).unwrap().clone(); normalize(&mut n, &ix); + // The identity the import keeps of a file's components (#2022) is not written back. + n.plugin_data.retain(|k, _| !k.starts_with("fig.")); let mut v = serde_json::to_value(&n).unwrap(); // Written even when it's the identity: near-identity read back must compare. v["transform"] = serde_json::json!(n.transform.as_coeffs()); diff --git a/crates/format/src/fig/map/layer.rs b/crates/format/src/fig/map/layer.rs index e3de96368..8dbad0e01 100644 --- a/crates/format/src/fig/map/layer.rs +++ b/crates/format/src/fig/map/layer.rs @@ -184,6 +184,8 @@ impl<'a> Mapper<'a> { if own == "SYMBOL" && inst.is_none() { self.mapped_mains.insert(id.to_string()); } + let is_main = inst.is_none() && (own == "SYMBOL" || (own == "FRAME" && view.flag("isStateGroup") == Some(true))); + let lib_key = view.str("key").filter(|k| is_main && !k.is_empty() && k.len() <= 256); let mut o = Obj::new(); o.insert("id".into(), json!(rest_id)); // Private provenance for the .fig importer; ordinary REST import ignores it. @@ -197,6 +199,8 @@ impl<'a> Mapper<'a> { "slotContent": inst.is_some_and(|i| i.slot_content), // A size the instance gives this layer itself (kept when the instance relays out). "sizeOverride": entries.iter().any(|e| e.entry == Entry::Override && e.row.get("size").is_some()), + // The library key of a published main (components pasted later match by it). + "key": lib_key, }), ); o.insert("type".into(), json!(ty)); diff --git a/crates/format/src/fig/paste_relink_tests.rs b/crates/format/src/fig/paste_relink_tests.rs new file mode 100644 index 000000000..38ed48242 --- /dev/null +++ b/crates/format/src/fig/paste_relink_tests.rs @@ -0,0 +1,55 @@ +//! Layers pasted from another design app keep the identity they had there (#2022): a main's guid +//! (and its library key) lands in its plugin data, on the main and on every layer in it, so +//! instances pasted later can link to it. Built in code from synthetic payloads. + +use figcraft_doc::{Document, Node, NodeKind}; + +use super::kiwi::Kv; +use super::tests::{arr, canvas, g, node, o, s, schema, xy}; +use super::try_import; + +fn import(nodes: Vec>) -> Document { + let bytes = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])); + try_import(&bytes, "Pasted layers").expect("design data").expect("it imports").0 +} + +fn named<'a>(doc: &'a Document, name: &str) -> &'a Node { + doc.nodes().find(|n| n.name == name).expect(name) +} + +#[test] +fn a_pasted_main_records_its_figma_identity() { + let doc = import(vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(20, Some((1, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0)), ("key", s("btn"))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + node(30, Some((1, "\"")), "RECTANGLE", "Loose", vec![("size", xy(5.0, 5.0))]), + ]); + let main = named(&doc, "Button"); + assert!(matches!(main.kind, NodeKind::Component { .. })); + assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); + assert_eq!(main.plugin_data.get("fig.key").map(String::as_str), Some("btn")); + let face = named(&doc, "Face"); + assert_eq!(face.plugin_data.get("fig.guid").map(String::as_str), Some("1:21"), "every layer of a main"); + assert!(!face.plugin_data.contains_key("fig.key")); + assert!(named(&doc, "Loose").plugin_data.is_empty(), "layers outside mains record nothing"); +} + +#[test] +fn a_cached_main_in_the_internal_canvas_is_an_instance_main_in_the_store() { + let doc = import(vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]), + node(30, Some((1, "!")), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(20))]))]), + node(20, Some((2, "!")), "SYMBOL", "Button", vec![("size", xy(40.0, 20.0))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ]); + let copy = doc.nodes().find(|n| n.name == "Copy").expect("the instance"); + let NodeKind::Instance { component, .. } = ©.kind else { panic!("the top is not an instance: {:?}", copy.kind) }; + assert!(doc.is_remote(*component), "its main is in the library store"); + let main = doc.node(*component).expect("main"); + assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); + assert_eq!(copy.plugin_data.get("fig.main").map(String::as_str), Some("1:20")); +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 99acbab2f..ded2d27de 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -593,6 +593,9 @@ impl<'a> Ctx<'a> { if let Some(sources) = &mut self.fig_sources { sources.record(id, j, primary); } + if primary && self.fig_sources.is_some() { + self.record_identity(id, rid, ty, j); + } } match ty { "INSTANCE" => self.instances.push((id, j)), @@ -1131,6 +1134,40 @@ impl<'a> Ctx<'a> { } } + /// Keep the file's own identity of a main (and of every layer in it) in the layer's plugin data, + /// so instances pasted later can find mains pasted earlier: `fig.guid` (unique within one + /// file), `fig.key` (a library component's key, unique everywhere). Instances keep their + /// main's guid as `fig.main`. Only layers the file really holds (not the copies an instance + /// expands) are recorded. + fn record_identity(&mut self, id: NodeId, rest_id: &str, ty: &str, j: &Value) { + let meta = j.get(FIG_SOURCE_FIELD); + if meta.and_then(|m| m.get("expanded")).and_then(Value::as_bool) != Some(false) || rest_id.starts_with('I') || rest_id.len() > 41 { + return; + } + let is_main = matches!(ty, "COMPONENT" | "COMPONENT_SET"); + let in_main = is_main + || self + .doc + .ancestors(id) + .into_iter() + .any(|a| self.doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))); + let main = (ty == "INSTANCE").then(|| text(j, "componentId")).flatten().filter(|m| m.len() <= 41); + if !in_main && main.is_none() { + return; + } + let key = meta.and_then(|m| m.get("key")).and_then(Value::as_str).filter(|k| is_main && !k.is_empty()); + let Some(n) = self.doc.node_mut(id) else { return }; + if in_main { + n.plugin_data.insert("fig.guid".into(), rest_id.into()); + } + if let Some(k) = key { + n.plugin_data.insert("fig.key".into(), k.into()); + } + if let Some(m) = main { + n.plugin_data.insert("fig.main".into(), m.into()); + } + } + fn resolve_swap_defaults(&mut self) { for (owner, name, rest_id) in std::mem::take(&mut self.swap_defaults) { let Some(c) = self.component(&rest_id) else { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a90038427..bc0017f71 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (`.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (pasting an instance copied from a design app links it to its main component when that main was pasted earlier, matched by the identity kept on the main (#2022); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -39,8 +39,8 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only within the same file, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only within the same file, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | ## Export @@ -196,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-09 | minor | M6, #2022: instances copied from a design app link to mains pasted earlier. The importer records each main's layer guids (and its library key) as `fig.*` plugin data, the paste reads the file key from the clipboard metadata, and the paste matches the mains an instance uses with components already in the file by guid within the same file or by library key, linking the instance and its layers to them; before, the main came along as a library copy the paste dropped, so the instance showed "Main component deleted". No match keeps the old result with a note. `fig.*` plugin data is not named in the `.fig` export's plugin-data note. Mains pasted after their instances are not relinked yet. | | 2026-11-08 | minor | M6, #2097 follow-up: per-point vector corner radii take the scale of the row supplying `vectorData`, including nested instance rows; override and derived rows are not scaled twice. Network caching distinguishes the instance scale even when resizing gives two vectors the same final box. Synthetic tests cover missing/unit factors, half/double scale, derived size alone, overridden and derived vector data, nested scale and equal-size cache separation. Layer-radius fallback remains the separate #2115 change. Numbers unchanged. | | 2026-11-08 | patch | #2097 / #2100: scaled-instance lengths reset to the unscaled main value survive export/import as explicit overrides. Dimensionless values and zero do not gain scale overrides. Exported factors stay within the importer's 0.001–1000 range; larger or smaller ratios use explicit values instead. Effect/grid payload rows above an inherited style link take precedence at their own scale, including nested instances and empty-list clears, without detaching styles. Synthetic regressions cover corners, dashes/shadows, layout/grids and bounds, typography and styled runs, linked text and nested styles. Numbers unchanged. | | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | From bc9bbb1d587e192e122956e4e724e92625c66b31 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 00:39:10 -0500 Subject: [PATCH 02/21] M6: Figma identity only on pasted mains, scoped to their file, and dropped from copies (#2141 review) Only a clipboard paste records fig.* plugin data now (fig::try_import_pasted); File > Open, Import and the CLI record none, so opened files no longer carry it or take its size. A fig.guid match needs fig.file on both sides, so unrelated files with the same small guid never link. Copies FigCraft makes (instance roots and layers, duplicates, Create component, Detach, copies of another file's layers) drop fig.guid, fig.key and fig.file. Pasted instances get fig.file too, and the metadata span is length-checked before it is copied. Tests added for variants, nested instances, duplicates and opened files. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.1 reviewed; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/doc/src/lib.rs | 23 ++- crates/doc/src/node.rs | 17 ++ .../engine/src/assets/components/instances.rs | 2 + crates/engine/src/assets/components/sync.rs | 2 + crates/engine/src/assets/library.rs | 18 +- crates/engine/src/bound_alpha_tests.rs | 2 +- crates/engine/src/cmd/component.rs | 2 + crates/engine/src/cmd/component/instance.rs | 1 + crates/engine/src/cmd/edit/clipboard.rs | 18 +- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/file/load.rs | 8 +- .../engine/src/design_paste_relink_tests.rs | 174 ++++++++++++++++++ crates/format/src/fig.rs | 17 +- crates/format/src/fig/export_tests.rs | 2 - crates/format/src/fig/paste_relink_tests.rs | 4 +- crates/format/src/rest.rs | 25 ++- docs/file-format-parity.md | 8 +- 17 files changed, 295 insertions(+), 30 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 81760d718..f13d543f8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -874,7 +874,21 @@ impl Document { let nid = self.alloc_id(); map.insert(n.id, nid); } - self.paste_nodes(&src_nodes, &map, id, parent, index) + let root = self.paste_nodes(&src_nodes, &map, id, parent, index)?; + self.drop_figma_identity_in(root); + Ok(root) + } + + /// Drop the Figma identity (see [`Node::drop_figma_identity`]) from `root` and every layer under + /// it. For copies FigCraft makes of layers. + pub fn drop_figma_identity_in(&mut self, root: NodeId) { + for i in self.subtree(root) { + if self.node(i).is_some_and(Node::has_figma_identity) + && let Some(n) = self.node_mut(i) + { + n.drop_figma_identity(); + } + } } /// Deep-copy each of `ids`' subtrees to the end of `parent`, in order, returning the new root @@ -891,7 +905,12 @@ impl Document { } trees.push((id, src_nodes)); } - trees.into_iter().map(|(id, src_nodes)| self.paste_nodes(&src_nodes, &map, id, parent, None)).collect() + let roots: Vec = + trees.into_iter().map(|(id, src_nodes)| self.paste_nodes(&src_nodes, &map, id, parent, None)).collect::>()?; + for r in &roots { + self.drop_figma_identity_in(*r); + } + Ok(roots) } /// Insert copies of `nodes` (a subtree rooted at `root`, from this or another document) with ids diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 5b90b3bff..7c6e81961 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -669,7 +669,24 @@ mod guides_key { } } +/// The plugin-data keys that tie a main to the file it was pasted from (`fig.guid`, `fig.key`, +/// `fig.file`); `fig.main` (an instance's pointer at its main) is not among them. +pub const FIGMA_IDENTITY_KEYS: [&str; 3] = ["fig.guid", "fig.key", "fig.file"]; + impl Node { + /// Drop the Figma identity of a pasted main from this layer: a copy FigCraft makes is not that + /// main, and a second layer holding the identity would take later pastes. Keeps `fig.main`. + pub fn drop_figma_identity(&mut self) { + for k in FIGMA_IDENTITY_KEYS { + self.plugin_data.remove(k); + } + } + + /// Whether this layer carries a Figma identity (see [`Node::drop_figma_identity`]). + pub fn has_figma_identity(&self) -> bool { + FIGMA_IDENTITY_KEYS.iter().any(|k| self.plugin_data.contains_key(*k)) + } + /// A node with Figma's defaults for its kind. pub fn new(id: NodeId, kind: NodeKind, name: impl Into, width: f64, height: f64) -> Self { let fills = match &kind { diff --git a/crates/engine/src/assets/components/instances.rs b/crates/engine/src/assets/components/instances.rs index 9e596e8eb..50549a9f7 100644 --- a/crates/engine/src/assets/components/instances.rs +++ b/crates/engine/src/assets/components/instances.rs @@ -41,6 +41,8 @@ pub fn create_instance_at(doc: &mut Document, component: NodeId, parent: NodeId, root.interactions.clear(); // So do the variable modes the main sets (see `Document::inherited_modes`). root.var_modes.clear(); + // The instance is not the main the file's pasted layers were matched to. + root.drop_figma_identity(); doc.insert(root, parent, index)?; sync_instance(doc, id); Ok(id) diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index 7b34c33c2..1101335f0 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -150,6 +150,8 @@ fn copy_layers( n.parent = Some(parent); n.children = orig.children.iter().filter_map(|c| map.get(c).copied()).collect(); n.source = Some(*s); + // The main's Figma identity stays on the main. + n.drop_figma_identity(); n.overrides.clear(); n.prop_refs.clear(); let prev = old.get(&nid); diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 8b8be7e1b..6990bede2 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1209,8 +1209,8 @@ fn merge_components( } /// Match the mains of `src` (a design app's paste) that nothing else covers with the components of -/// `doc` that carry the same Figma identity: the same `fig.guid` from the same file (`fig.file`, -/// both absent counts as the same), or the same library `fig.key` from anywhere. A hit links the +/// `doc` that carry the same Figma identity: the same `fig.guid` from the same known file +/// (`fig.file`, present on both), or the same library `fig.key` from anywhere. A hit links the /// main and each of its layers carrying a `fig.guid` to the layer of `doc`'s component with that /// guid, so instances and their per-layer sources point into the component already there. fn relink_by_identity( @@ -1229,14 +1229,16 @@ fn relink_by_identity( return; } let pasted: BTreeSet = map.values().copied().collect(); - let mut by_guid: BTreeMap<(Option<&str>, &str), NodeId> = BTreeMap::new(); + let mut by_guid: BTreeMap<(&str, &str), NodeId> = BTreeMap::new(); let mut by_key: BTreeMap<&str, NodeId> = BTreeMap::new(); for n in doc.nodes() { if !matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) || pasted.contains(&n.id) || doc.is_remote(n.id) { continue; } - if let Some(g) = n.plugin_data.get("fig.guid") { - by_guid.entry((n.plugin_data.get("fig.file").map(String::as_str), g.as_str())).or_insert(n.id); + if let Some(g) = n.plugin_data.get("fig.guid") + && let Some(f) = n.plugin_data.get("fig.file") + { + by_guid.entry((f.as_str(), g.as_str())).or_insert(n.id); } if let Some(k) = n.plugin_data.get("fig.key") { by_key.entry(k.as_str()).or_insert(n.id); @@ -1245,8 +1247,10 @@ fn relink_by_identity( for m in todo { let Some(theirs) = src.node(m) else { continue }; let guid = theirs.plugin_data.get("fig.guid").map(String::as_str).unwrap_or_default(); - let found = by_guid - .get(&(theirs.plugin_data.get("fig.file").map(String::as_str), guid)) + let found = theirs + .plugin_data + .get("fig.file") + .and_then(|f| by_guid.get(&(f.as_str(), guid))) .or_else(|| theirs.plugin_data.get("fig.key").and_then(|k| by_key.get(k.as_str()))); let Some(&mine) = found else { continue }; let layers: BTreeMap<&str, NodeId> = diff --git a/crates/engine/src/bound_alpha_tests.rs b/crates/engine/src/bound_alpha_tests.rs index fb15425db..d1fc6c40e 100644 --- a/crates/engine/src/bound_alpha_tests.rs +++ b/crates/engine/src/bound_alpha_tests.rs @@ -116,7 +116,7 @@ fn a_fig_round_trip_keeps_the_alpha_once() { ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": "tint"})); ex(&mut s, "fill.set", json!({"ids": [r.0], "index": 0, "opacity": 0.5})); let (bytes, _) = figcraft_format::fig::export(s.doc().unwrap(), None).unwrap(); - let back = crate::cmd::file::load_fig(&bytes, "x").unwrap().unwrap().doc; + let back = crate::cmd::file::load_fig_with(&bytes, "x", false).unwrap().unwrap().doc; let n = back.nodes().find(|n| !n.bound.is_empty()).unwrap(); let a = n.fills[0].solid_color().unwrap().a; assert!(near(a, HALF * 0.5), "{a}"); diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs index e0b2e02f4..189910da0 100644 --- a/crates/engine/src/cmd/component.rs +++ b/crates/engine/src/cmd/component.rs @@ -396,6 +396,8 @@ fn create(s: &mut Session, p: &Value) -> Result { let n = doc.get_mut(target)?; let was_group = matches!(n.kind, NodeKind::Group); n.kind = NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }; + // A new component is not the main it was made from. + n.drop_figma_identity(); if was_group { n.fills.clear(); n.clip = false; diff --git a/crates/engine/src/cmd/component/instance.rs b/crates/engine/src/cmd/component/instance.rs index 86af6d54b..873c2e299 100644 --- a/crates/engine/src/cmd/component/instance.rs +++ b/crates/engine/src/cmd/component/instance.rs @@ -31,6 +31,7 @@ pub(super) fn detach(s: &mut Session, p: &Value) -> Result { keep_main_modes(doc, i)?; let n = doc.get_mut(i)?; n.kind = NodeKind::Frame; + n.drop_figma_identity(); n.source = None; n.overrides.clear(); n.prop_refs.remove("mainComponent"); diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs index dfdf8122e..db1a42405 100644 --- a/crates/engine/src/cmd/edit/clipboard.rs +++ b/crates/engine/src/cmd/edit/clipboard.rs @@ -100,10 +100,12 @@ pub fn design_clipboard_file(html: &str) -> Option { use base64::Engine as _; let start = html.find(META_OPEN)? + META_OPEN.len(); let len = html.get(start..)?.find(META_CLOSE)?; - let b64: String = html.get(start..start + len)?.chars().filter(|c| !c.is_ascii_whitespace()).collect(); - if b64.len() > 64 * 1024 { + let span = html.get(start..start + len)?; + // Checked before the span is copied: the HTML may be hundreds of megabytes. + if span.len() > 64 * 1024 { return None; } + let b64: String = span.chars().filter(|c| !c.is_ascii_whitespace()).collect(); let bytes = base64::engine::general_purpose::STANDARD.decode(&b64).or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&b64)).ok()?; let meta: Value = serde_json::from_slice(&bytes).ok()?; @@ -123,13 +125,14 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result { }; let file_key = string(p, "html").as_deref().and_then(design_clipboard_file).or_else(|| string(p, "fileKey").filter(|k| !k.is_empty() && k.len() <= 128)); - let mut other = crate::cmd::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; + let mut other = + crate::cmd::file::load_fig_with(&bytes, "Pasted layers", true).ok_or_else(|| bad(CMD, "the data is not copied design layers"))??; if let Some(key) = &file_key { // Layer ids are unique within one file only: mains keep the file they came from. let ids: Vec = other.doc.ids().collect(); for id in ids { if let Ok(n) = other.doc.get_mut(id) - && n.plugin_data.contains_key("fig.guid") + && (n.plugin_data.contains_key("fig.guid") || n.plugin_data.contains_key("fig.main")) { n.plugin_data.insert("fig.file".into(), key.clone()); } @@ -269,7 +272,12 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re if let Some(r) = nodes.first_mut() { r.transform = doc.world_transform(into).inverse() * shift * r.transform; } - out.push(doc.paste_nodes(&nodes, &map, *root, into, None)?); + let pasted = doc.paste_nodes(&nodes, &map, *root, into, None)?; + // Layers from a file of this app are copies, not the mains pasted from the design app. + if clip.source_doc != 0 { + doc.drop_figma_identity_in(pasted); + } + out.push(pasted); all.extend(map); } // Board connectors pasted with what they join join the pasted copies. diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0ed12b8d3..f52c1a38c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -34,7 +34,7 @@ use load::font_report; pub use load::{MAX_DOCUMENT_FILE, load, load_bytes, load_path}; #[cfg(test)] pub(crate) use load::{installed_family, sketch_line}; -pub(crate) use load::{load_fig, read_capped, recovered, recovered_from, variables_param, write}; +pub(crate) use load::{load_fig_with, read_capped, recovered, recovered_from, variables_param, write}; pub use open::MAX_RECENT; #[cfg(test)] use open::append_pages; diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index 3e917d5dd..fed7cc727 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -391,7 +391,13 @@ fn installed_fonts_first() { /// Gives `None` when `bytes` are not a `.fig` file. Then other readers can try. pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option> { - let r = figcraft_format::fig::try_import(bytes, name)?; + load_fig_with(bytes, name, false) +} + +/// [`load_fig`]; `pasted`: the bytes are layers pasted from the clipboard, whose mains keep their +/// Figma identity so instances pasted later can link to them. +pub(crate) fn load_fig_with(bytes: &[u8], name: &str, pasted: bool) -> Option> { + let r = if pasted { figcraft_format::fig::try_import_pasted(bytes, name)? } else { figcraft_format::fig::try_import(bytes, name)? }; Some(r.map_err(|e| EngineError::Other(e.to_string())).map(|(mut doc, warnings)| { link_instances(&mut doc); installed_fonts_first(); diff --git a/crates/engine/src/design_paste_relink_tests.rs b/crates/engine/src/design_paste_relink_tests.rs index 3b652b2cd..372529fde 100644 --- a/crates/engine/src/design_paste_relink_tests.rs +++ b/crates/engine/src/design_paste_relink_tests.rs @@ -160,6 +160,180 @@ fn an_instance_whose_main_never_arrives_stays_as_today() { s.execute("component.restoreMain", &json!({"id": copy})).expect("the main can be restored"); } +/// A component set of two variants (`v1`, `v2`; each with one layer after it) under `parent`. +fn set_nodes(parent: u64, set: u64, v1: u64, v2: u64) -> Vec> { + let flag = vec![("isStateGroup", Kv::Bool(true)), ("size", xy(100.0, 20.0))]; + let mut v = vec![node(set, Some((parent, "!")), "FRAME", "Button", flag)]; + for (at, id, name) in [("!", v1, "State=Default"), ("\"", v2, "State=Hover")] { + v.push(node(id, Some((set, at)), "SYMBOL", name, vec![("size", xy(40.0, 20.0))])); + v.push(node(id + 1, Some((id, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])); + } + v +} + +fn page_nodes() -> Vec> { + vec![node(0, None, "DOCUMENT", "Document", vec![]), node(1, Some((0, "!")), "CANVAS", "Page", vec![])] +} + +fn hidden_canvas() -> Kv<'static> { + node(2, Some((0, "~")), "CANVAS", "Internal", vec![("internalOnly", Kv::Bool(true))]) +} + +fn instance_of(id: u64, main: u64, parent: u64, pos: &'static str) -> Kv<'static> { + node(id, Some((parent, pos)), "INSTANCE", "Copy", vec![("size", xy(40.0, 20.0)), ("symbolData", o(vec![("symbolID", g(main))]))]) +} + +fn sets(s: &Session) -> usize { + s.doc().unwrap().nodes().filter(|n| matches!(n.kind, NodeKind::ComponentSet { .. })).count() +} + +#[test] +fn a_variant_instance_links_to_the_set_pasted_earlier() { + let mut s = Session::new(); + let mut first = page_nodes(); + first.extend(set_nodes(1, 20, 21, 23)); + paste(&mut s, html(first, "F1")); + let before = components(&s); + assert_eq!(before.len(), 2); + assert_eq!(sets(&s), 1); + let mut second = page_nodes(); + second.push(hidden_canvas()); + second.push(instance_of(30, 23, 1, "!")); + second.extend(set_nodes(2, 20, 21, 23)); + let r = paste(&mut s, html(second, "F1")); + let main = instance_main(&s, ids(&r)[0]); + assert!(before.contains(&main), "the instance's main is a variant already in the file"); + assert_eq!(s.doc().unwrap().node(main).unwrap().name, "State=Hover"); + assert_eq!(components(&s), before, "no variant came along"); + assert_eq!(sets(&s), 1, "no second set came along"); +} + +#[test] +fn a_nested_instance_inside_a_pasted_main_links_too() { + let mut s = Session::new(); + let outer = |parent: u64| { + vec![ + node(20, Some((parent, "!")), "SYMBOL", "Outer", vec![("size", xy(80.0, 40.0))]), + node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(80.0, 40.0))]), + instance_of(25, 40, 20, "\""), + ] + }; + let inner = |parent: u64, pos: &'static str| { + vec![ + node(40, Some((parent, pos)), "SYMBOL", "Inner", vec![("size", xy(40.0, 20.0))]), + node(41, Some((40, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ] + }; + let mut first = page_nodes(); + + first.extend(outer(1)); + first.extend(inner(1, "\"")); + paste(&mut s, html(first, "F1")); + let main = s.doc().unwrap().nodes().find(|n| n.name == "Outer").unwrap().id; + let before = components(&s); + let mut second = page_nodes(); + second.push(hidden_canvas()); + second.push(instance_of(30, 20, 1, "!")); + second.extend(outer(2)); + second.extend(inner(2, "\"")); + let r = paste(&mut s, html(second, "F1")); + let copy = ids(&r)[0]; + assert_eq!(instance_main(&s, copy), main, "the copy shows the main pasted first"); + assert_eq!(components(&s), before, "no component came along"); + let doc = s.doc().unwrap(); + let nested: Vec = + doc.subtree(copy).into_iter().filter(|i| *i != copy && matches!(doc.node(*i).unwrap().kind, NodeKind::Instance { .. })).collect(); + assert_eq!(nested.len(), 1); + let in_main: Vec = doc.subtree(main).into_iter().filter(|i| matches!(doc.node(*i).unwrap().kind, NodeKind::Instance { .. })).collect(); + assert_eq!(in_main.len(), 1); + let inner = instance_main(&s, in_main[0]); + assert_eq!(instance_main(&s, nested[0]), inner, "the nested instance shows the inner main the first paste brought"); + assert!(doc.contains(inner)); +} + +#[test] +fn a_duplicated_main_does_not_take_later_pastes() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + // An instance, detached, then made a component: a copy of the main that FigCraft made. + let inst = ids(&s.execute("edit.duplicate", &json!({"ids": [main]})).unwrap())[0]; + s.execute("component.detach", &json!({"ids": [inst]})).unwrap(); + s.execute("component.create", &json!({"ids": [inst]})).unwrap(); + assert!(matches!(s.doc().unwrap().node(inst).unwrap().kind, NodeKind::Component { .. })); + let copy_data = &s.doc().unwrap().node(inst).unwrap().plugin_data; + assert!(copy_data.keys().all(|k| !matches!(k.as_str(), "fig.guid" | "fig.key" | "fig.file")), "{copy_data:?}"); + let r = paste(&mut s, html(payload_instance(20, Some("btn"), true), "F1")); + assert_eq!(instance_main(&s, ids(&r)[0]), main, "the original takes the paste"); + // Without the original, the copy is not the pasted main. + s.execute("edit.delete", &json!({"ids": [main]})).unwrap(); + let r = paste(&mut s, html(payload_instance(20, Some("btn"), true), "F1")); + assert_ne!(instance_main(&s, ids(&r)[0]), inst, "the copy never carried the main's identity"); +} + +#[test] +fn a_duplicated_variant_does_not_carry_the_identity() { + let mut s = Session::new(); + let mut first = page_nodes(); + first.extend(set_nodes(1, 20, 21, 23)); + paste(&mut s, html(first, "F1")); + let before = components(&s); + let guids = |s: &Session| s.doc().unwrap().nodes().filter(|n| n.plugin_data.contains_key("fig.guid")).count(); + let n = guids(&s); + s.execute("edit.duplicate", &json!({"ids": [before[0]]})).unwrap(); + assert_eq!(components(&s).len(), 3, "the copy is a new variant"); + assert_eq!(guids(&s), n, "the copy carries none of the identity"); +} + +/// A `.fig` file with a main (guid 20) and an instance of it, as File > Open reads it. +fn fig_file(main_name: &str) -> String { + let mut v = page_nodes(); + v.push(node(20, Some((1, "!")), "SYMBOL", main_name, vec![("size", xy(40.0, 20.0)), ("key", Kv::Str("lib".into()))])); + v.push(node(21, Some((20, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))])); + v.push(instance_of(30, 20, 1, "\"")); + let bytes = figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(v))])).expect("packs"); + B64.encode(bytes) +} + +#[test] +fn mains_from_opened_files_carry_no_figma_identity() { + let mut s = Session::empty(); + s.execute("file.open", &json!({"data": fig_file("Button"), "name": "A.fig"})).unwrap(); + let doc = s.doc().unwrap(); + assert!(doc.nodes().any(|n| matches!(n.kind, NodeKind::Component { .. }))); + assert!(doc.nodes().all(|n| n.plugin_data.keys().all(|k| !k.starts_with("fig.")))); +} + +#[test] +fn an_instance_copied_between_two_opened_files_stays_unlinked() { + let mut s = Session::empty(); + s.execute("file.open", &json!({"data": fig_file("Button"), "name": "A.fig"})).unwrap(); + let a_main = components(&s)[0]; + s.execute("file.open", &json!({"data": fig_file("Other"), "name": "B.fig"})).unwrap(); + let instance = s.doc().unwrap().nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap().id; + s.execute("edit.copy", &json!({"ids": [instance]})).unwrap(); + s.active = 0; + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("edit.paste", &json!({})).unwrap(); + assert_ne!(instance_main(&s, ids(&r)[0]), a_main, "the same guid in an unrelated file is not the same component"); +} + +#[test] +fn a_main_from_an_opened_file_is_not_matched_to_a_pasted_one() { + let mut s = Session::empty(); + s.execute("file.open", &json!({"data": fig_file("Other"), "name": "B.fig"})).unwrap(); + let instance = s.doc().unwrap().nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap().id; + s.execute("edit.copy", &json!({"ids": [instance]})).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + // The paste above replaced the clipboard: copy again from the opened file. + s.active = 0; + s.execute("edit.copy", &json!({"ids": [instance]})).unwrap(); + s.active = 1; + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("edit.paste", &json!({})).unwrap(); + assert_ne!(instance_main(&s, ids(&r)[0]), main); +} + /// The export schema, with the library `key` field the payloads of a library's components carry. fn schema() -> String { figcraft_format::fig::EXPORT_SCHEMA.replacen("message NodeChange ", "message NodeChange string key=9999, ", 1) diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 21c3ada49..07c5aa3b9 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -134,7 +134,18 @@ pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec), Forma import_with_image_limit(bytes, name, MAX_IMAGE_BYTES) } +/// [`try_import`] for layers pasted from the clipboard: each main also keeps the identity it had in +/// the design app (`fig.guid`, `fig.key`; instances keep `fig.main`) in its plugin data, so +/// instances pasted later can link to it (#2022). A file that is opened carries none. +pub fn try_import_pasted(bytes: &[u8], name: &str) -> Option), FormatError>> { + is_fig(bytes).then(|| import_inner(bytes, name, MAX_IMAGE_BYTES, true)) +} + fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result<(Document, Vec), FormatError> { + import_inner(bytes, name, image_limit, false) +} + +fn import_inner(bytes: &[u8], name: &str, image_limit: u64, identity: bool) -> Result<(Document, Vec), FormatError> { let mut archive = Archive::open(bytes)?; archive.image_budget.remaining.set(image_limit); // The budgets follow the compressed canvas, which the file itself bounds (its zip member may @@ -159,7 +170,11 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result canonical_image_refs(&mut json, &aliases); } let images = |r: &str| archive.image(r).or_else(|| embedded.get(r).map(|b| b.to_vec())); - let (mut doc, more) = crate::rest::import_with_networks(&json, &images, networks, max_nodes)?; + let (mut doc, more) = if identity { + crate::rest::import_with_identity(&json, &images, networks, max_nodes)? + } else { + crate::rest::import_with_networks(&json, &images, networks, max_nodes)? + }; let skipped = archive.image_budget.skipped.get(); if skipped > 0 { warnings.push(format!("{skipped} ZIP image(s) skipped by the total ZIP image byte budget ({image_limit} bytes)")); diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 3e9ac1994..9651a1025 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -754,8 +754,6 @@ fn canon(doc: &Document) -> Vec { .map(|id| { let mut n = doc.node(*id).unwrap().clone(); normalize(&mut n, &ix); - // The identity the import keeps of a file's components (#2022) is not written back. - n.plugin_data.retain(|k, _| !k.starts_with("fig.")); let mut v = serde_json::to_value(&n).unwrap(); // Written even when it's the identity: near-identity read back must compare. v["transform"] = serde_json::json!(n.transform.as_coeffs()); diff --git a/crates/format/src/fig/paste_relink_tests.rs b/crates/format/src/fig/paste_relink_tests.rs index 38ed48242..0702bcfa5 100644 --- a/crates/format/src/fig/paste_relink_tests.rs +++ b/crates/format/src/fig/paste_relink_tests.rs @@ -6,11 +6,11 @@ use figcraft_doc::{Document, Node, NodeKind}; use super::kiwi::Kv; use super::tests::{arr, canvas, g, node, o, s, schema, xy}; -use super::try_import; +use super::try_import_pasted; fn import(nodes: Vec>) -> Document { let bytes = canvas(&schema(), &o(vec![("nodeChanges", arr(nodes))])); - try_import(&bytes, "Pasted layers").expect("design data").expect("it imports").0 + try_import_pasted(&bytes, "Pasted layers").expect("design data").expect("it imports").0 } fn named<'a>(doc: &'a Document, name: &str) -> &'a Node { diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index ded2d27de..e6fd82791 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -165,7 +165,7 @@ pub fn import(v: &Value, images: ImageResolver) -> Result<(Document, Vec /// in the file JSON (a `meta` with `variableCollections`, or `variableCollections` and /// `variables` at the top level) are read too; the first definition of an id wins. pub fn import_with(v: &Value, variables: Option<&Value>, images: ImageResolver) -> Result<(Document, Vec), FormatError> { - import_parts(v, variables, images, Vec::new(), MAX_NODES, false) + import_parts(v, variables, images, Vec::new(), MAX_NODES, false, false) } /// Internal .fig JSON path: GUID provenance is not part of the public REST import contract. @@ -184,7 +184,19 @@ pub(crate) fn import_with_networks( networks: Vec>, max_nodes: usize, ) -> Result<(Document, Vec), FormatError> { - import_parts(v, None, images, networks, max_nodes, true) + import_parts(v, None, images, networks, max_nodes, true, false) +} + +/// [`import_with_networks`] that also records each main's Figma identity in its plugin data +/// (`fig.guid`, `fig.key`, `fig.main`; see `Ctx::record_identity`). Only a clipboard paste asks +/// for it: a file that is opened carries no identity. +pub(crate) fn import_with_identity( + v: &Value, + images: ImageResolver, + networks: Vec>, + max_nodes: usize, +) -> Result<(Document, Vec), FormatError> { + import_parts(v, None, images, networks, max_nodes, true, true) } /// [`import_with_networks`] for imports other than `.fig` (no `.fig` source identities): the @@ -195,7 +207,7 @@ pub(crate) fn import_with_networks_plain( networks: Vec>, max_nodes: usize, ) -> Result<(Document, Vec), FormatError> { - import_parts(v, None, images, networks, max_nodes, false) + import_parts(v, None, images, networks, max_nodes, false, false) } fn import_parts( @@ -205,6 +217,7 @@ fn import_parts( networks: Vec>, max_nodes: usize, fig_sources: bool, + identity: bool, ) -> Result<(Document, Vec), FormatError> { let entries: Vec<&Value> = if is_document(v) { vec![v] } else { nodes_entries(v).collect() }; if entries.is_empty() { @@ -213,6 +226,7 @@ fn import_parts( let name = text(v, "name").filter(|n| !n.trim().is_empty()).map_or("Imported file", clip_str); let mut cx = Ctx::new(Document::new(name), images); cx.fig_sources = fig_sources.then(|| fig_sources::Sources::new(max_nodes)); + cx.keep_identity = identity; let blank = cx.doc.first_page(); let mut loose: Option = None; for e in &entries { @@ -455,6 +469,8 @@ pub(crate) struct Ctx<'a> { max_nodes: usize, /// Mains the `.fig` file has but its layer cap kept out ([`FIG_CAPPED_MAINS_FIELD`]). capped_mains: BTreeSet, + /// Whether mains keep their Figma identity in plugin data (a clipboard paste). + keep_identity: bool, } impl<'a> Ctx<'a> { @@ -485,6 +501,7 @@ impl<'a> Ctx<'a> { networks: Vec::new(), max_nodes: MAX_NODES, capped_mains: BTreeSet::new(), + keep_identity: false, } } @@ -593,7 +610,7 @@ impl<'a> Ctx<'a> { if let Some(sources) = &mut self.fig_sources { sources.record(id, j, primary); } - if primary && self.fig_sources.is_some() { + if primary && self.keep_identity { self.record_identity(id, rid, ty, j); } } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index bc0017f71..8ed2bc65f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (pasting an instance copied from a design app links it to its main component when that main was pasted earlier, matched by the identity kept on the main (#2022); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-09 · **Change:** minor (pasting an instance copied from a design app links it to its main component when that main was pasted earlier, matched by the identity kept on pasted mains (#2022); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -39,8 +39,8 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only within the same file, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only within the same file, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; only a clipboard paste records it (a file opened or imported carries none), and a copy FigCraft makes of a main (duplicate, instance, detach, Create component) drops it; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only when both sides carry the same file key, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; only a clipboard paste records it (a file opened or imported carries none), and a copy FigCraft makes of a main (duplicate, instance, detach, Create component) drops it; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only when both sides carry the same file key, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | ## Export @@ -196,7 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| -| 2026-11-09 | minor | M6, #2022: instances copied from a design app link to mains pasted earlier. The importer records each main's layer guids (and its library key) as `fig.*` plugin data, the paste reads the file key from the clipboard metadata, and the paste matches the mains an instance uses with components already in the file by guid within the same file or by library key, linking the instance and its layers to them; before, the main came along as a library copy the paste dropped, so the instance showed "Main component deleted". No match keeps the old result with a note. `fig.*` plugin data is not named in the `.fig` export's plugin-data note. Mains pasted after their instances are not relinked yet. | +| 2026-11-09 | minor | M6, #2022: instances copied from a design app link to mains pasted earlier. The paste's import (not File > Open or Import) records each main's layer guids (and its library key) as `fig.*` plugin data and the paste reads the file key from the clipboard metadata, and the paste matches the mains an instance uses with components already in the file by guid within the same known file or by library key, linking the instance and its layers to them; before, the main came along as a library copy the paste dropped, so the instance showed "Main component deleted". No match keeps the old result with a note. Copies FigCraft makes of a main drop that identity. `fig.*` plugin data is not named in the `.fig` export's plugin-data note. Mains pasted after their instances are not relinked yet. | | 2026-11-08 | minor | M6, #2097 follow-up: per-point vector corner radii take the scale of the row supplying `vectorData`, including nested instance rows; override and derived rows are not scaled twice. Network caching distinguishes the instance scale even when resizing gives two vectors the same final box. Synthetic tests cover missing/unit factors, half/double scale, derived size alone, overridden and derived vector data, nested scale and equal-size cache separation. Layer-radius fallback remains the separate #2115 change. Numbers unchanged. | | 2026-11-08 | patch | #2097 / #2100: scaled-instance lengths reset to the unscaled main value survive export/import as explicit overrides. Dimensionless values and zero do not gain scale overrides. Exported factors stay within the importer's 0.001–1000 range; larger or smaller ratios use explicit values instead. Effect/grid payload rows above an inherited style link take precedence at their own scale, including nested instances and empty-list clears, without detaching styles. Synthetic regressions cover corners, dashes/shadows, layout/grids and bounds, typography and styled runs, linked text and nested styles. Numbers unchanged. | | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | From 555e69fd8796726080aa64000c05c08f44fbfc75 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Mon, 9 Nov 2026 15:29:52 -0500 Subject: [PATCH 03/21] M6: cover paste identity edge cases, file key handling and relink order (#2141 review) Tests for the clipboard file key (data plus fileKey, no file key, malformed, empty, oversized and over-long keys), the first-wins rule for duplicate library keys, a main pasted after its instance, fig.main kept on copies, no identity on layers an instance expands, export warnings for fig.* plugin data, and pack_canvas errors; two negative relink tests now assert the component set and the unlinked warning. Docs name the new test files, the fileKey parameter, the no-file-key rule and the unverified clipboard metadata shape; pack_canvas has a contract. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 triaged and briefed; Sonnet 5.5 verified and wrote at medium --- crates/engine/src/cmd/edit.rs | 2 +- .../engine/src/design_paste_relink_tests.rs | 105 +++++++++++++++++- crates/format/src/fig/export.rs | 7 +- crates/format/src/fig/paste_relink_tests.rs | 28 +++++ docs/file-format-parity.md | 4 +- 5 files changed, 140 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 6985fc5eb..bf682036b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { spec!( "edit.pasteDesignLayers", "Paste design layers", - "{html (the clipboard's HTML) | data (base64 of the clipboard's design data, at most 256 MB), parent?, x?, y?} layers copied from another design app (a .fig canvas in the clipboard's HTML), read like a .fig file (best effort, with `warnings`), pasted as edit.paste pastes; `missingImages`: the names of pasted layers whose image the clipboard didn't carry (they show the missing-image placeholder)", + "{html (the clipboard's HTML) | data (base64 of the clipboard's design data, at most 256 MB), fileKey? (the Figma file the copy came from, with `data`; `html` carries it in its metadata; without one only a library key links instances to mains pasted earlier), parent?, x?, y?} layers copied from another design app (a .fig canvas in the clipboard's HTML), read like a .fig file (best effort, with `warnings`), pasted as edit.paste pastes; `missingImages`: the names of pasted layers whose image the clipboard didn't carry (they show the missing-image placeholder)", true, paste_design_layers ), diff --git a/crates/engine/src/design_paste_relink_tests.rs b/crates/engine/src/design_paste_relink_tests.rs index 372529fde..3ece0ada3 100644 --- a/crates/engine/src/design_paste_relink_tests.rs +++ b/crates/engine/src/design_paste_relink_tests.rs @@ -137,6 +137,9 @@ fn a_main_from_another_figma_file_is_not_matched_by_guid_alone() { let r = paste(&mut s, html(payload_instance(20, None, true), "F2")); let copy = ids(&r)[0]; assert_ne!(instance_main(&s, copy), main, "the same guid in another file is another component"); + assert_eq!(components(&s), [main], "no component came along with the instance"); + assert!(!s.doc().unwrap().contains(instance_main(&s, copy)), "its main stayed behind"); + assert!(r["warnings"].to_string().contains("stay unlinked"), "{r}"); } #[test] @@ -146,6 +149,7 @@ fn the_same_library_key_links_whatever_the_guids() { let r = paste(&mut s, html(payload_instance(77, Some("btn"), true), "F2")); let copy = ids(&r)[0]; assert_eq!(instance_main(&s, copy), main); + assert_eq!(components(&s), [main], "the pasted main did not come along as a second component"); } #[test] @@ -336,5 +340,104 @@ fn a_main_from_an_opened_file_is_not_matched_to_a_pasted_one() { /// The export schema, with the library `key` field the payloads of a library's components carry. fn schema() -> String { - figcraft_format::fig::EXPORT_SCHEMA.replacen("message NodeChange ", "message NodeChange string key=9999, ", 1) + let schema = figcraft_format::fig::EXPORT_SCHEMA.replacen("message NodeChange ", "message NodeChange string key=9999, ", 1); + assert_ne!(schema, figcraft_format::fig::EXPORT_SCHEMA, "the key field was injected"); + schema +} + +fn data(nodes: Vec>) -> String { + B64.encode(figcraft_format::fig::pack_canvas(&schema(), &o(vec![("nodeChanges", Kv::Array(nodes))])).expect("packs")) +} + +fn paste_data(s: &mut Session, data: String, file: Option<&str>) -> serde_json::Value { + s.execute("select.set", &json!({"ids": []})).expect("clears"); + let mut p = json!({ "data": data }); + if let Some(f) = file { + p["fileKey"] = json!(f); + } + s.execute("edit.pasteDesignLayers", &p).expect("pastes") +} + +#[test] +fn data_with_a_file_key_links_by_guid_and_without_one_only_by_library_key() { + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, None), "F1")))[0]; + let r = paste_data(&mut s, data(payload_instance(20, None, true)), Some("F1")); + assert_eq!(instance_main(&s, ids(&r)[0]), main, "data + fileKey links by guid"); + // No file key: a guid alone never links, a library key does. + let mut s = Session::new(); + let main = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1"))).first().copied().unwrap(); + let r = paste_data(&mut s, data(payload_instance(20, None, true)), None); + assert_ne!(instance_main(&s, ids(&r)[0]), main, "guid alone does not link"); + assert_eq!(components(&s), [main], "no component came along with the instance"); + assert!(r["warnings"].to_string().contains("stay unlinked"), "{r}"); + let r = paste_data(&mut s, data(payload_instance(77, Some("btn"), true)), None); + assert_eq!(instance_main(&s, ids(&r)[0]), main, "the library key links without a file key"); +} + +#[test] +fn the_first_main_with_a_library_key_takes_the_paste() { + let mut s = Session::new(); + let first = ids(&paste(&mut s, html(payload_main(20, Some("btn")), "F1")))[0]; + let second = ids(&paste(&mut s, html(payload_main(30, Some("btn")), "F2")))[0]; + assert_ne!(first, second); + let r = paste(&mut s, html(payload_instance(77, Some("btn"), true), "F3")); + assert_eq!(instance_main(&s, ids(&r)[0]), first, "the older component wins, every time"); + assert_eq!(components(&s).len(), 2, "no third component came along"); +} + +#[test] +fn pasting_the_main_after_its_instance_does_not_relink_it() { + let mut s = Session::new(); + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + let gone = instance_main(&s, copy); + paste(&mut s, html(payload_main(20, None), "F1")); + assert_eq!(instance_main(&s, copy), gone, "the earlier instance keeps pointing at its missing main"); + assert!(!s.doc().unwrap().contains(gone)); +} + +#[test] +fn a_copy_of_a_pasted_instance_keeps_its_main_pointer_and_drops_the_guid() { + let mut s = Session::new(); + let copy = ids(&paste(&mut s, html(payload_instance(20, None, true), "F1")))[0]; + let data = |s: &Session, i: NodeId| s.doc().unwrap().node(i).unwrap().plugin_data.clone(); + assert_eq!(data(&s, copy).get("fig.main").map(String::as_str), Some("1:20")); + let dup = ids(&s.execute("edit.duplicate", &json!({"ids": [copy]})).unwrap())[0]; + let d = data(&s, dup); + assert_eq!(d.get("fig.main").map(String::as_str), Some("1:20"), "{d:?}"); + assert!(!d.contains_key("fig.guid") && !d.contains_key("fig.key") && !d.contains_key("fig.file"), "{d:?}"); +} + +#[test] +fn layers_an_instance_expands_carry_no_identity() { + let mut s = Session::new(); + let mut first = page_nodes(); + first.extend([ + node(20, Some((1, "!")), "SYMBOL", "Outer", vec![("size", xy(80.0, 40.0))]), + instance_of(25, 40, 20, "!"), + node(40, Some((1, "\"")), "SYMBOL", "Inner", vec![("size", xy(40.0, 20.0))]), + node(41, Some((40, "!")), "RECTANGLE", "Face", vec![("size", xy(40.0, 20.0))]), + ]); + paste(&mut s, html(first, "F1")); + let doc = s.doc().unwrap(); + let inside: Vec<_> = + doc.nodes().filter(|n| doc.ancestors(n.id).into_iter().any(|a| matches!(doc.node(a).unwrap().kind, NodeKind::Instance { .. }))).collect(); + assert!(!inside.is_empty(), "the instance has layers of its own"); + assert!(inside.iter().all(|n| !n.plugin_data.contains_key("fig.guid")), "{:?}", inside.iter().map(|n| &n.plugin_data).collect::>()); +} + +#[test] +fn a_file_key_is_read_from_the_clipboard_metadata_only_when_it_is_sound() { + use crate::cmd::edit::design_clipboard_file; + let meta = |json: &str| format!("(figmeta){}(/figmeta)", B64.encode(json)); + assert_eq!(design_clipboard_file(&meta(r#"{"fileKey":"F1"}"#)).as_deref(), Some("F1")); + assert_eq!(design_clipboard_file(&meta(r#"{"fileKey":""}"#)), None, "empty"); + assert_eq!(design_clipboard_file(&meta(&format!(r#"{{"fileKey":"{}"}}"#, "k".repeat(129)))), None, "over 128 characters"); + assert_eq!(design_clipboard_file(&meta(&format!(r#"{{"fileKey":"{}"}}"#, "k".repeat(128)))).map(|k| k.len()), Some(128)); + assert_eq!(design_clipboard_file(&meta(r#"{"fileKey":7}"#)), None, "not a string"); + assert_eq!(design_clipboard_file("(figmeta)!!not base64!!(/figmeta)"), None, "malformed"); + assert_eq!(design_clipboard_file(&format!("(figmeta){}(/figmeta)", B64.encode("not json"))), None, "not json"); + assert_eq!(design_clipboard_file("(figmeta)e30="), None, "unclosed"); + assert_eq!(design_clipboard_file(&format!("(figmeta){}(/figmeta)", "A".repeat(64 * 1024 + 1))), None, "oversized"); + assert_eq!(design_clipboard_file(""), None, "empty html"); } diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index 364fbd7bc..8d721a849 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -209,8 +209,11 @@ pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec< } /// A `canvas.fig` holding `message` (a `Message` of the kiwi schema `schema_source`, normally -/// [`SCHEMA`]), as the design apps put it on the clipboard. Lets synthetic payloads be built -/// outside this crate. +/// [`SCHEMA`], optionally extended with fields), as the design apps put it on the clipboard. +/// Returns the `canvas.fig` bytes (the schema, then the encoded message), or an error when the +/// schema does not parse, has no `Message`, or the message does not fit it. Public so tests in +/// other crates can build synthetic design-app payloads; the app itself only exports through +/// [`export`]. pub fn pack_canvas(schema_source: &str, message: &Kv) -> Result, FormatError> { let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); let schema = Schema::parse(schema_source).map_err(fail)?; diff --git a/crates/format/src/fig/paste_relink_tests.rs b/crates/format/src/fig/paste_relink_tests.rs index 0702bcfa5..1588d3e37 100644 --- a/crates/format/src/fig/paste_relink_tests.rs +++ b/crates/format/src/fig/paste_relink_tests.rs @@ -53,3 +53,31 @@ fn a_cached_main_in_the_internal_canvas_is_an_instance_main_in_the_store() { assert_eq!(main.plugin_data.get("fig.guid").map(String::as_str), Some("1:20")); assert_eq!(copy.plugin_data.get("fig.main").map(String::as_str), Some("1:20")); } + +fn exported_warnings(data: &[(&str, &str)]) -> Vec { + let mut doc = Document::new("x"); + let page = doc.first_page().expect("a page"); + let id = doc.alloc_id(); + let mut n = Node::new(id, NodeKind::Frame, "A", 10.0, 10.0); + for (k, v) in data { + n.plugin_data.insert((*k).into(), (*v).into()); + } + doc.insert(n, page, None).expect("inserts"); + super::export(&doc, None).expect("exports").1 +} + +#[test] +fn identity_keys_alone_do_not_warn_on_export_but_other_plugin_data_does() { + let has = |w: &[String]| w.iter().any(|m| m.contains("plugin data")); + assert!(!has(&exported_warnings(&[("fig.guid", "1:2"), ("fig.key", "k"), ("fig.file", "F"), ("fig.main", "1:3")]))); + assert!(has(&exported_warnings(&[("fig.guid", "1:2"), ("other", "x")]))); + assert!(has(&exported_warnings(&[("other", "x")]))); +} + +#[test] +fn pack_canvas_refuses_a_schema_that_does_not_parse_or_has_no_message() { + let msg = o(vec![("nodeChanges", arr(vec![]))]); + assert!(super::pack_canvas("not a schema", &msg).is_err()); + assert!(super::pack_canvas("enum A X=0", &msg).is_err(), "no Message"); + assert!(super::pack_canvas(super::EXPORT_SCHEMA, &msg).is_ok()); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8ed2bc65f..5cd06af72 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -39,8 +39,8 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; only a clipboard paste records it (a file opened or imported carries none), and a copy FigCraft makes of a main (duplicate, instance, detach, Create component) drops it; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only when both sides carry the same file key, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), never with a real clipboard from other software | with `.fig` | -| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata; only a clipboard paste records it (a file opened or imported carries none), and a copy FigCraft makes of a main (duplicate, instance, detach, Create component) drops it; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only when both sides carry the same file key, a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data, fileKey}`, refused over 256 MB before decoding); text copied later pastes as text again. An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata (the `(figmeta)` span of base64 JSON with a `fileKey`; its shape is unverified against a real clipboard, and `data` takes the key as `fileKey`); only a clipboard paste records it (a file opened or imported carries none), and a copy FigCraft makes of a main (duplicate, a paste of FigCraft layers, instance, detach, Create component) drops it; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only when both sides carry the same file key (with no file key only a library key can link), a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`), the identity and relinking with design data built in code (`design_paste_relink_tests`, `paste_relink_tests`), never with a real clipboard from other software | with `.fig` | +| Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data, fileKey}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). A pasted main keeps the identity it had in its file (layer guid, and library key when it has one) in its plugin data (`fig.*` keys), together with the file key from the clipboard's metadata (the `(figmeta)` span of base64 JSON with a `fileKey`; its shape is unverified against a real clipboard, and `data` takes the key as `fileKey`); only a clipboard paste records it (a file opened or imported carries none), and a copy FigCraft makes of a main (duplicate, a paste of FigCraft layers, instance, detach, Create component) drops it; an instance pasted later whose main is one of those components links to it (and its layers to the main's layers) instead of showing "Main component deleted": a guid matches only when both sides carry the same file key (with no file key only a library key can link), a library key matches across files; an instance whose main was never pasted stays as before (restorable) with a note in the paste result, and pasting the main after the instance does not relink it yet (#2022). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), the identity and relinking with design data built in code (`design_paste_relink_tests`, `paste_relink_tests`), never with a real clipboard from other software | with `.fig` | ## Export From 86794c4042e597ba192924cfcc524ea615599aaa Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 00:28:48 -0500 Subject: [PATCH 04/21] M7: a layer of a main matched by its library key across files is linked by GUID only within the same file (#2022) A fig.guid is unique within one file only, so a main found by its library key in another file shares no layer guids with the component found; its layers are no longer matched by guid unless both mains carry the same fig.file. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/engine/src/assets/library.rs | 6 ++++ crates/engine/src/assets/library/tests.rs | 37 +++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 82aa3f4ea..521ca2af8 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1340,6 +1340,12 @@ fn relink_by_identity( let layers: BTreeMap<&str, NodeId> = doc.subtree(mine).into_iter().filter_map(|i| Some((doc.node(i)?.plugin_data.get("fig.guid")?.as_str(), i))).collect(); remote.insert(m, mine); + // A guid is unique within one file only: a main matched by its library key across files + // shares no layer guids with the component found, so its layers are not matched by guid. + let same_file = theirs.plugin_data.get("fig.file").is_some_and(|f| doc.node(mine).is_some_and(|n| n.plugin_data.get("fig.file") == Some(f))); + if !same_file { + continue; + } for l in src.subtree(m) { if let Some(&target) = src.node(l).and_then(|n| n.plugin_data.get("fig.guid")).and_then(|g| layers.get(g.as_str())) { remote.entry(l).or_insert(target); diff --git a/crates/engine/src/assets/library/tests.rs b/crates/engine/src/assets/library/tests.rs index 4c329cb5f..ea6f3c007 100644 --- a/crates/engine/src/assets/library/tests.rs +++ b/crates/engine/src/assets/library/tests.rs @@ -695,3 +695,40 @@ fn library_links_follow_a_moved_folder() { link_found(&mut s, &lid); let _ = std::fs::remove_dir_all(&d); } + +/// A component with a layer, both carrying the identity a paste from a design app records. +fn identified(d: &mut Document, name: &str, file: &str, main: &str, layer: &str, key: Option<&str>) -> (NodeId, NodeId) { + let page = d.pages[0]; + let kind = || NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }; + let c = d.create(page, kind(), name, 0.0, 0.0, 40.0, 20.0).unwrap(); + let l = d.create(c, NodeKind::Frame, "Face", 0.0, 0.0, 40.0, 20.0).unwrap(); + for (id, guid) in [(c, main), (l, layer)] { + let n = d.get_mut(id).unwrap(); + n.plugin_data.insert("fig.guid".into(), guid.into()); + n.plugin_data.insert("fig.file".into(), file.into()); + } + if let Some(k) = key { + d.get_mut(c).unwrap().plugin_data.insert("fig.key".into(), k.into()); + } + (c, l) +} + +#[test] +fn a_main_matched_by_library_key_maps_layers_by_guid_only_within_one_file() { + let relink = |their_file: &str, their_main: &str| { + let mut doc = Document::new("mine"); + let (mine, _) = identified(&mut doc, "Button", "F1", "1:20", "1:21", Some("btn")); + let mut src = Document::new("theirs"); + // Their layer carries the guid of `mine`'s main: unrelated layers in another file. + let (theirs, their_face) = identified(&mut src, "Button", their_file, their_main, "1:20", Some("btn")); + let mut remote = BTreeMap::new(); + relink_by_identity(&doc, &src, &BTreeSet::from([theirs]), &BTreeMap::new(), &mut remote); + (remote, mine, theirs, their_face) + }; + let (remote, mine, theirs, their_face) = relink("F2", "1:19"); + assert_eq!(remote.get(&theirs), Some(&mine), "the library key still links the main"); + assert_eq!(remote.get(&their_face), None, "a guid of another file names an unrelated layer"); + let (remote, mine, theirs, their_face) = relink("F1", "1:19"); + assert_eq!(remote.get(&theirs), Some(&mine)); + assert_eq!(remote.get(&their_face), Some(&mine), "the same file: the guid is the layer"); +} From 7799bf2e03e988f9f6f75410436e3343da0c4444 Mon Sep 17 00:00:00 2001 From: Mochamad Aufa Date: Mon, 30 Nov 2026 18:57:24 +0700 Subject: [PATCH 05/21] feat(agent): a full-height Agent panel with one-click connections and canvas context - The Agent is its own left-sidebar tab, holding only the chat: messages, grouped tool steps, approval cards and a pinned composer. - Connections: subscriptions through the installed Claude Code, Codex or OpenCode CLI (tools served over a loopback MCP endpoint with a bearer token), or an API key that is checked by listing models and picks a default model; the rest sits under Advanced. - Canvas context: the selection shows as chips and goes with the message; "Ask agent..." and quick actions in the layer menu and Cmd+Shift+M. - Reference images from the clipboard, a drop, or a render of the selection. - Message controls: copy, edit the last request, try again, a queue while a turn runs, and a per-file chat history. --- Cargo.lock | 46 + Cargo.toml | 5 + apps/figcraft/src/services.rs | 4 + crates/agent/Cargo.toml | 21 + crates/agent/src/anthropic.rs | 260 +++ crates/agent/src/bridge.rs | 104 ++ crates/agent/src/cli.rs | 615 +++++++ crates/agent/src/config.rs | 511 ++++++ crates/agent/src/http.rs | 99 ++ crates/agent/src/lib.rs | 250 +++ crates/agent/src/mcp_http.rs | 389 +++++ crates/agent/src/neutral.rs | 183 +++ crates/agent/src/openai.rs | 277 ++++ crates/agent/src/session.rs | 647 ++++++++ crates/agent/src/sse.rs | 86 + crates/ui-egui/Cargo.toml | 3 + crates/ui-egui/locales/en.toml | 100 +- crates/ui-egui/src/app.rs | 16 + crates/ui-egui/src/chat.rs | 2371 +++++++++++++++++++++++++++ crates/ui-egui/src/chat_tests.rs | 149 ++ crates/ui-egui/src/control.rs | 20 +- crates/ui-egui/src/lib.rs | 7 + crates/ui-egui/src/menus.rs | 5 + crates/ui-egui/src/panels/layers.rs | 21 +- crates/ui-egui/src/services.rs | 5 + crates/ui-egui/src/state.rs | 2 + docs/architecture.md | 1 + docs/harness.md | 252 +++ xtask/src/layers.rs | 4 +- 29 files changed, 6449 insertions(+), 4 deletions(-) create mode 100644 crates/agent/Cargo.toml create mode 100644 crates/agent/src/anthropic.rs create mode 100644 crates/agent/src/bridge.rs create mode 100644 crates/agent/src/cli.rs create mode 100644 crates/agent/src/config.rs create mode 100644 crates/agent/src/http.rs create mode 100644 crates/agent/src/lib.rs create mode 100644 crates/agent/src/mcp_http.rs create mode 100644 crates/agent/src/neutral.rs create mode 100644 crates/agent/src/openai.rs create mode 100644 crates/agent/src/session.rs create mode 100644 crates/agent/src/sse.rs create mode 100644 crates/ui-egui/src/chat.rs create mode 100644 crates/ui-egui/src/chat_tests.rs create mode 100644 docs/harness.md diff --git a/Cargo.lock b/Cargo.lock index d780844ed..87d229a46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1062,12 +1062,41 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + [[package]] name = "cookie-factory" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -2807,6 +2836,19 @@ dependencies = [ "zbus", ] +[[package]] +name = "figcraft-agent" +version = "0.19.0" +dependencies = [ + "base64 0.22.1", + "figcraft-mcp", + "log", + "proptest", + "serde", + "serde_json", + "ureq", +] + [[package]] name = "figcraft-cli" version = "0.19.0" @@ -3130,6 +3172,7 @@ dependencies = [ "craft-window", "egui", "egui_extras", + "figcraft-agent", "figcraft-color", "figcraft-doc", "figcraft-engine", @@ -7449,12 +7492,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64 0.23.1", + "cookie_store", "flate2", "log", "percent-encoding", "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_json", "ureq-proto", "utf8-zero", "webpki-roots", diff --git a/Cargo.toml b/Cargo.toml index d8239ba64..5eb6d9ba7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ figcraft-ui-egui = { path = "crates/ui-egui" } figcraft-mcp = { path = "crates/mcp" } figcraft-collab-net = { path = "crates/collab-net" } figcraft-plugin = { path = "crates/plugin" } +figcraft-agent = { path = "crates/agent" } # Keep every craft-libs crate on one rev. # Which paths stored in a document may be followed (craft-libs). @@ -144,6 +145,10 @@ crc32fast = "1" wasmi = { version = "2", default-features = false, features = ["std", "stable", "validate", "portable-dispatch"] } wat = "1.261" +# The agent's HTTP client: blocking, rustls (the TLS provider collab-net already uses), pure Rust +# and forbidden from `unsafe`. Already in the lock through craft-update. +ureq = { version = "3.5", features = ["json"] } + # ui egui = "0.37" egui_extras = { version = "0.37", default-features = false } diff --git a/apps/figcraft/src/services.rs b/apps/figcraft/src/services.rs index e23294567..4d3d70b73 100644 --- a/apps/figcraft/src/services.rs +++ b/apps/figcraft/src/services.rs @@ -493,6 +493,10 @@ pub(crate) fn remembering(last: Arc>>, pick: DialogFuture, } impl Services for Desktop { + fn agent_config_path(&self) -> Option { + crate::services::config_dir().map(|d| d.join("agents.json")) + } + fn pick_open(&mut self, title: &str, exts: &[&str]) -> DialogFuture { let pick = picked(self.dialog_in_last_folder(title).add_filter("Supported files", exts).pick_file()); remembering(self.last_folder.clone(), pick, false) diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml new file mode 100644 index 000000000..1e3ee2821 --- /dev/null +++ b/crates/agent/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "figcraft-agent" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "FigCraft's in-app agent: provider adapters, the tool-call loop and the bridge to the open window" + +[lints] +workspace = true + +[dependencies] +figcraft-mcp = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +base64 = { workspace = true } +log = { workspace = true } +# Blocking HTTP with rustls (the same TLS provider collab-net uses), no async runtime. +ureq = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/agent/src/anthropic.rs b/crates/agent/src/anthropic.rs new file mode 100644 index 000000000..4c9bdd9ed --- /dev/null +++ b/crates/agent/src/anthropic.rs @@ -0,0 +1,260 @@ +//! The Anthropic Messages dialect. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::sse::Sse; +use crate::{Invocation, Step}; + +const ANTHROPIC_VERSION: &str = "2023-06-01"; + +pub fn payload(provider: &Provider, system: &str, messages: &[Message], tools: &[Value]) -> Value { + let mut body = json!({ + "model": provider.model, + "max_tokens": provider.max_tokens.max(1), + "system": system, + "messages": wire_messages(messages), + "stream": true, + }); + let tools = crate::neutral::anthropic_tools(tools); + if !tools.is_empty() { + body["tools"] = json!(tools); + } + body +} + +fn wire_messages(messages: &[Message]) -> Vec { + let mut out: Vec = Vec::new(); + for m in messages { + let role = match m.role { + Role::User => "user", + Role::Assistant => "assistant", + }; + let mut content = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => content.push(json!({"type": "text", "text": t})), + Block::Image(i) => content.push(json!({ + "type": "image", + "source": {"type": "base64", "media_type": i.mime, "data": i.data}, + })), + Block::ToolCall { id, name, args } => content.push(json!({ + "type": "tool_use", + "id": id, + "name": name, + "input": args, + })), + Block::ToolResult { id, ok, text, images, .. } => { + let mut blocks = vec![json!({"type": "text", "text": text})]; + for i in images { + blocks.push(json!({ + "type": "image", + "source": {"type": "base64", "media_type": i.mime, "data": i.data}, + })); + } + content.push(json!({ + "type": "tool_result", + "tool_use_id": id, + "content": blocks, + "is_error": !ok, + })); + } + } + } + if content.is_empty() { + continue; + } + // Anthropic wants alternating roles; two user messages in a row (text, then tool results) + // are merged into one. + if let Some(last) = out.last_mut() + && last["role"].as_str() == Some(role) + && let Some(parts) = last["content"].as_array_mut() + { + parts.extend(content); + continue; + } + out.push(json!({"role": role, "content": content})); + } + out +} + +fn headers(provider: &Provider, session: &str) -> Vec<(&'static str, String)> { + let mut h = vec![ + ("x-api-key", provider.api_key.trim().to_string()), + ("anthropic-version", ANTHROPIC_VERSION.to_string()), + ("accept", "text/event-stream".to_string()), + ]; + if provider.base_url.contains("opencode.ai") { + h.push(("x-opencode-session", session.to_string())); + } + h +} + +pub fn stream( + http: &Http, + provider: &Provider, + system: &str, + messages: &[Message], + tools: &[Value], + session: &str, + on_text: &mut dyn FnMut(&str), + cancel: &AtomicBool, +) -> Result { + let reply = http.post(&provider.endpoint(), &headers(provider, session), &payload(provider, system, messages, tools))?; + if reply.status >= 400 { + return Err(read_error(reply.status, reply.body)); + } + let mut sse = Sse::new(reply.body); + let mut step = Step::default(); + // Blocks being built, by index: (id, name, arguments JSON text). + let mut pending: BTreeMap = BTreeMap::new(); + while let Some(event) = sse.next_event()? { + if cancel.load(Ordering::Relaxed) { + return Err("stopped".to_string()); + } + if event.data.trim().is_empty() { + continue; + } + let v: Value = match serde_json::from_str(&event.data) { + Ok(v) => v, + Err(_) => continue, + }; + match event.name.as_str() { + "message_start" => { + if let Some(u) = v.get("message").and_then(|m| m.get("usage")) { + step.usage.input = u.get("input_tokens").and_then(Value::as_u64).unwrap_or(step.usage.input); + step.usage.output = u.get("output_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output); + } + } + "content_block_start" => { + let index = v.get("index").and_then(Value::as_u64).unwrap_or(0); + let block = &v["content_block"]; + match block.get("type").and_then(Value::as_str) { + Some("tool_use") => { + let id = block.get("id").and_then(Value::as_str).unwrap_or("").to_string(); + let name = block.get("name").and_then(Value::as_str).unwrap_or("").to_string(); + // A non-streamed endpoint may already have given the input. + let raw = block.get("input").filter(|i| !i.is_null()).map(|i| i.to_string()).unwrap_or_default(); + pending.insert(index, (id, name, raw)); + } + Some("text") => { + if let Some(t) = block.get("text").and_then(Value::as_str) + && !t.is_empty() + { + step.text.push_str(t); + on_text(t); + } + } + _ => {} + } + } + "content_block_delta" => { + let index = v.get("index").and_then(Value::as_u64).unwrap_or(0); + let delta = &v["delta"]; + match delta.get("type").and_then(Value::as_str) { + Some("text_delta") => { + if let Some(t) = delta.get("text").and_then(Value::as_str) { + step.text.push_str(t); + on_text(t); + } + } + Some("input_json_delta") => { + if let Some(partial) = delta.get("partial_json").and_then(Value::as_str) + && let Some(entry) = pending.get_mut(&index) + { + entry.2.push_str(partial); + } + } + _ => {} + } + } + "message_delta" => { + if let Some(reason) = v.get("delta").and_then(|d| d.get("stop_reason")).and_then(Value::as_str) { + step.stop = reason.to_string(); + } + if let Some(u) = v.get("usage") { + step.usage.output = u.get("output_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output); + } + } + "error" => { + let msg = + v.get("error").and_then(|e| e.get("message")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| event.data.clone()); + return Err(msg); + } + _ => {} + } + } + for (i, (id, name, raw)) in pending { + if name.is_empty() { + continue; + } + let id = if id.is_empty() { format!("toolu_{i}") } else { id }; + let args = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(Value::Null) }; + step.calls.push(Invocation { id, name, args, args_raw: raw }); + } + Ok(step) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ApiKind; + + fn provider() -> Provider { + let mut p = Provider::new("Anthropic", ApiKind::AnthropicMessages, "https://api.anthropic.com/v1"); + p.model = "claude-sonnet-5".into(); + p.api_key = "sk-ant".into(); + p.max_tokens = 4096; + p + } + + #[test] + fn the_system_prompt_is_top_level_and_max_tokens_is_sent() { + let messages = vec![Message::user_text("hi")]; + let body = payload(&provider(), "you design", &messages, &[]); + assert_eq!(body["system"], "you design"); + assert_eq!(body["max_tokens"], 4096); + assert_eq!(body["messages"][0]["content"][0]["text"], "hi"); + } + + #[test] + fn tool_results_are_user_blocks_with_images_inside() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "toolu_1".into(), + name: "screenshot".into(), + ok: true, + text: "the page".into(), + images: vec![crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() }], + }], + }]; + let body = payload(&provider(), "s", &messages, &[]); + let block = &body["messages"][0]["content"][0]; + assert_eq!(block["type"], "tool_result"); + assert_eq!(block["content"][1]["type"], "image"); + assert_eq!(block["content"][1]["source"]["data"], "AAAA"); + } + + #[test] + fn consecutive_user_messages_are_merged() { + let messages = vec![Message::user_text("look"), Message::user_text("again")]; + let body = payload(&provider(), "s", &messages, &[]); + let wire = body["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(wire.len(), 1, "Anthropic requires alternating roles"); + assert_eq!(wire[0]["content"].as_array().map(Vec::len), Some(2)); + } + + #[test] + fn headers_use_x_api_key_not_bearer() { + let h = headers(&provider(), "s"); + assert!(h.iter().any(|(k, v)| *k == "x-api-key" && v == "sk-ant")); + assert!(h.iter().any(|(k, _)| *k == "anthropic-version")); + assert!(!h.iter().any(|(k, _)| *k == "authorization")); + } +} diff --git a/crates/agent/src/bridge.rs b/crates/agent/src/bridge.rs new file mode 100644 index 000000000..13bb6d3dc --- /dev/null +++ b/crates/agent/src/bridge.rs @@ -0,0 +1,104 @@ +//! The bridge to the open window. +//! +//! The agent runs on its own thread and must not touch the session (it lives on the UI thread). +//! Every tool call becomes a [`Call`] the UI drains into its control queue, exactly like a request +//! from `figcraft-cli mcp --attach`; the reply comes back on the call's channel. Implementing +//! [`figcraft_mcp::Backend`] over that channel is what lets the agent reuse the MCP tool set +//! unchanged, with the same behaviour an external MCP client gets. + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use serde_json::{Value, json}; + +/// One control request from the agent thread to the UI thread. +pub struct Call { + pub method: String, + pub params: Value, + pub reply: Sender>, +} + +/// The UI side: the calls the agent thread is waiting for. +pub struct Bridge { + pub calls: Receiver, +} + +/// The agent side: sends calls and waits for their answers. +#[derive(Clone)] +pub struct Remote { + tx: Sender, + /// The name every command runs as, so the app shows the agent's avatar and signs its comments. + agent: String, + /// Wakes the window, which is idle between frames while the agent waits for an answer. + wake: Arc, +} + +/// A fresh pair: the UI keeps the bridge, the agent thread keeps the remote. +pub fn pair(agent: impl Into, wake: Arc) -> (Bridge, Remote) { + let (tx, rx) = channel(); + (Bridge { calls: rx }, Remote { tx, agent: agent.into(), wake }) +} + +impl Remote { + /// How long one tool call waits for the UI before giving up. + const WAIT: Duration = Duration::from_secs(600); + + /// Send one control method and wait for its answer. + pub fn request(&self, method: &str, params: Value) -> Result { + self.send(method, params) + } + + fn send(&self, method: &str, mut params: Value) -> Result { + if method == "engine.execute" { + // The app shows an AI agent's presence from this, and signs its comments. + params["agent"] = json!(self.agent); + } + let (reply, answer) = channel(); + self.tx.send(Call { method: method.to_string(), params, reply }).map_err(|_| "the window closed".to_string())?; + (self.wake)(); + match answer.recv_timeout(Self::WAIT) { + Ok(r) => r, + Err(_) => Err(format!("the window did not answer `{method}` in time")), + } + } +} + +impl figcraft_mcp::Backend for Remote { + fn call(&mut self, method: &str, params: Value) -> Result { + self.send(method, params) + } + + fn has_ui(&self) -> bool { + true + } + + fn describe(&self) -> String { + "the open window".to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_call_carries_the_agent_name_and_its_reply() { + let (bridge, mut remote) = pair("FigCraft Agent", Arc::new(|| {})); + let t = std::thread::spawn(move || figcraft_mcp::Backend::call(&mut remote, "engine.execute", json!({"command": "frame.create"}))); + let call = bridge.calls.recv().expect("a call"); + assert_eq!(call.method, "engine.execute"); + assert_eq!(call.params["agent"], "FigCraft Agent"); + call.reply.send(Ok(json!({"id": 7}))).expect("reply"); + assert_eq!(t.join().expect("thread"), Ok(json!({"id": 7}))); + } + + #[test] + fn a_closed_window_fails_the_call_instead_of_hanging() { + let (bridge, remote) = pair("Agent", Arc::new(|| {})); + drop(bridge); + let mut remote = remote; + let err = figcraft_mcp::Backend::call(&mut remote, "document.inspect", json!({})).unwrap_err(); + assert!(err.contains("window closed")); + } +} diff --git a/crates/agent/src/cli.rs b/crates/agent/src/cli.rs new file mode 100644 index 000000000..1aabb2670 --- /dev/null +++ b/crates/agent/src/cli.rs @@ -0,0 +1,615 @@ +//! Connections through an installed command-line agent: Claude Code, Codex or OpenCode. +//! +//! The person signs in to those programs with their own plan; FigCraft never sees that login. A +//! turn runs the program once, non-interactively, with FigCraft's tools attached over MCP +//! ([`crate::mcp_http`]) and its own built-in tools left out, and reads its JSON event stream. The +//! program keeps the conversation; the next turn resumes it by the session id it reported. + +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::channel; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::Usage; +use crate::config::ApiKind; + +/// Whether a command-line agent can be used. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Status { + /// Not found on this computer. + Missing, + /// Installed but not signed in. + SignedOut(PathBuf), + /// Installed and signed in (or the program could not tell; the first turn will). + Ready(PathBuf), +} + +/// Find the program: the `PATH` the app was started with, then the folders installers use (an app +/// opened from the Finder gets a short `PATH`). +pub fn locate(kind: ApiKind) -> Option { + let name = kind.program()?; + let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }; + let mut dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + if let Some(home) = home() { + for d in [".local/bin", ".opencode/bin", ".bun/bin", ".npm-global/bin", ".claude/local", ".cargo/bin", "bin"] { + dirs.push(home.join(d)); + } + } + for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"] { + dirs.push(PathBuf::from(d)); + } + dirs.into_iter().map(|d| d.join(&exe)).find(|p| p.is_file()) +} + +fn home() -> Option { + std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) +} + +/// Whether the program is there and signed in. Runs it briefly, so call it off the UI thread. +pub fn status(kind: ApiKind) -> Status { + let Some(path) = locate(kind) else { return Status::Missing }; + let signed_in = match kind { + ApiKind::ClaudeCode => output(&path, &["auth", "status"]).map(|o| { + serde_json::from_str::(&o).ok().and_then(|v| v.get("loggedIn").and_then(Value::as_bool)).unwrap_or(!o.contains("Not logged in")) + }), + ApiKind::Codex => output(&path, &["login", "status"]).map(|o| !o.to_ascii_lowercase().contains("not logged in")), + ApiKind::OpenCode => output(&path, &["auth", "list"]).map(|o| o.lines().any(|l| l.contains("stored") || l.contains("environment"))), + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => None, + }; + match signed_in { + Some(false) => Status::SignedOut(path), + _ => Status::Ready(path), + } +} + +/// The models the program offers, when it can list them (OpenCode); `None` keeps the preset's. +pub fn models(kind: ApiKind) -> Option> { + if kind != ApiKind::OpenCode { + return None; + } + let path = locate(kind)?; + let out = output(&path, &["models"])?; + let ids: Vec = out.lines().map(str::trim).filter(|l| l.contains('/') && !l.contains(' ')).map(str::to_string).collect(); + if ids.is_empty() { None } else { Some(ids) } +} + +/// Run `program args`, giving up after 20 seconds; its standard output, or `None`. +fn output(program: &Path, args: &[&str]) -> Option { + let mut child = Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().ok()?; + let mut stdout = child.stdout.take()?; + let mut stderr = child.stderr.take()?; + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut s = String::new(); + let _ = stdout.read_to_string(&mut s); + let mut e = String::new(); + let _ = stderr.read_to_string(&mut e); + let _ = tx.send(format!("{s}\n{e}")); + }); + match rx.recv_timeout(Duration::from_secs(20)) { + Ok(s) => { + let _ = child.wait(); + Some(s) + } + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + None + } + } +} + +/// Everything one turn needs to start the program. +pub struct Turn<'a> { + pub kind: ApiKind, + pub program: &'a Path, + pub model: &'a str, + /// The conversation to continue, from the last turn. + pub session: Option<&'a str>, + pub prompt: &'a str, + /// FigCraft's rules for the agent, added to the program's own. + pub system: &'a str, + pub mcp_url: &'a str, + pub mcp_token: &'a str, + /// The folder the program runs in (it keeps nothing of the person's there). + pub workdir: &'a Path, + /// Images the person attached to this request. + pub images: &'a [crate::neutral::Image], +} + +/// The token's environment variable for Codex, which reads a bearer token from one. +const TOKEN_ENV: &str = "FIGCRAFT_MCP_TOKEN"; + +/// The command for one turn. `files` are the attached images written to disk, for the programs +/// that take images as files (Codex, OpenCode); Claude Code reads them from its input instead +/// ([`stdin_message`]). +pub fn command(turn: &Turn<'_>, files: &[PathBuf]) -> Command { + let mut cmd = Command::new(turn.program); + let piped = turn.kind == ApiKind::ClaudeCode && !turn.images.is_empty(); + cmd.current_dir(turn.workdir).stdin(if piped { Stdio::piped() } else { Stdio::null() }).stdout(Stdio::piped()).stderr(Stdio::piped()); + match turn.kind { + ApiKind::ClaudeCode => { + let config = json!({"mcpServers": {"figcraft": { + "type": "http", + "url": turn.mcp_url, + "headers": {"Authorization": format!("Bearer {}", turn.mcp_token)}, + }}}); + cmd.args(["-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages"]); + // Only FigCraft's tools: no shell, no file edits, no other MCP servers. + cmd.args(["--strict-mcp-config", "--mcp-config"]).arg(config.to_string()); + cmd.args(["--tools", "", "--allowedTools", "mcp__figcraft", "--disable-slash-commands"]); + cmd.arg("--append-system-prompt").arg(turn.system); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.arg("--resume").arg(s); + } + if piped { + // The request, images included, arrives as one message on standard input. + cmd.args(["--input-format", "stream-json"]); + } else { + cmd.arg("--").arg(turn.prompt); + } + } + ApiKind::Codex => { + cmd.env(TOKEN_ENV, turn.mcp_token); + cmd.arg("exec"); + if let Some(s) = turn.session { + cmd.args(["resume", s]); + } + cmd.args(["--json", "--skip-git-repo-check", "--sandbox", "read-only"]); + cmd.arg("-c").arg(format!("mcp_servers.figcraft.url={}", toml_string(turn.mcp_url))); + cmd.arg("-c").arg(format!("mcp_servers.figcraft.bearer_token_env_var={}", toml_string(TOKEN_ENV))); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + for f in files { + cmd.arg("--image").arg(f); + } + // Codex has no flag for added instructions: the first turn carries them. + let prompt = if turn.session.is_none() { format!("{}\n\n---\n\n{}", turn.system, turn.prompt) } else { turn.prompt.to_string() }; + cmd.arg("--").arg(prompt); + } + ApiKind::OpenCode => { + let config = json!({ + "$schema": "https://opencode.ai/config.json", + "mcp": {"figcraft": { + "type": "remote", + "url": turn.mcp_url, + "enabled": true, + "headers": {"Authorization": format!("Bearer {}", turn.mcp_token)}, + }}, + "agent": {"figcraft": { + "description": "Designs in the open FigCraft window", + "mode": "primary", + "prompt": turn.system, + "tools": {"*": false, "figcraft_*": true}, + }}, + }); + cmd.env("OPENCODE_CONFIG_CONTENT", config.to_string()); + cmd.args(["run", "--format", "json", "--agent", "figcraft"]); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.arg("--session").arg(s); + } + for f in files { + cmd.arg("--file").arg(f); + } + cmd.arg("--").arg(turn.prompt); + } + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => {} + } + cmd +} + +/// Claude Code's input when the request carries images: one user message, text and images. +pub fn stdin_message(turn: &Turn<'_>) -> String { + let mut content = vec![json!({"type": "text", "text": turn.prompt})]; + for i in turn.images { + content.push(json!({"type": "image", "source": {"type": "base64", "media_type": i.mime, "data": i.data}})); + } + json!({"type": "user", "message": {"role": "user", "content": content}}).to_string() +} + +/// Write the attached images where the program can read them; their paths, in order. +fn write_images(turn: &Turn<'_>) -> Result, String> { + if turn.images.is_empty() || turn.kind == ApiKind::ClaudeCode { + return Ok(Vec::new()); + } + use base64::Engine as _; + let dir = turn.workdir.join("attachments"); + std::fs::create_dir_all(&dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0); + let mut out = Vec::new(); + for (n, i) in turn.images.iter().enumerate() { + let ext = match i.mime.as_str() { + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + _ => "png", + }; + let bytes = base64::engine::general_purpose::STANDARD.decode(i.data.as_bytes()).map_err(|e| format!("an attached image is damaged: {e}"))?; + let path = dir.join(format!("{stamp}-{n}.{ext}")); + std::fs::write(&path, bytes).map_err(|e| format!("can't write {}: {e}", path.display()))?; + out.push(path); + } + Ok(out) +} + +fn toml_string(s: &str) -> String { + format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) +} + +/// One thing read off the program's event stream. +#[derive(Clone, Debug, PartialEq)] +pub enum Parsed { + /// The conversation id to resume next time. + Session(String), + Text(String), + /// Tokens this event used (added to the turn's total). + Usage(Usage), + Error(String), +} + +/// Reads one program's JSON lines into [`Parsed`] events. +pub struct Parser { + kind: ApiKind, + /// Claude Code sends text twice (deltas, then the whole message); once deltas came, the whole + /// message is skipped. + deltas: bool, + /// Whether any text was given yet, so a later block starts a new paragraph. + wrote: bool, +} + +impl Parser { + pub fn new(kind: ApiKind) -> Self { + Self { kind, deltas: false, wrote: false } + } + + fn text(&mut self, out: &mut Vec, t: &str, new_block: bool) { + if t.is_empty() { + return; + } + if new_block && self.wrote { + out.push(Parsed::Text("\n\n".into())); + } + self.wrote = true; + out.push(Parsed::Text(t.to_string())); + } + + pub fn line(&mut self, line: &str) -> Vec { + let mut out = Vec::new(); + let Ok(v) = serde_json::from_str::(line.trim()) else { return out }; + let ty = v.get("type").and_then(Value::as_str).unwrap_or(""); + let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("").to_string(); + let n = |x: &Value, p: &str| x.pointer(p).and_then(Value::as_u64).unwrap_or(0); + match self.kind { + ApiKind::ClaudeCode => match ty { + "system" if s("/subtype") == "init" => out.push(Parsed::Session(s("/session_id"))), + "stream_event" => { + let e = &v["event"]; + match e.get("type").and_then(Value::as_str) { + Some("content_block_start") if e.pointer("/content_block/type").and_then(Value::as_str) == Some("text") => { + self.deltas = true; + let t = e.pointer("/content_block/text").and_then(Value::as_str).unwrap_or(""); + if self.wrote { + out.push(Parsed::Text("\n\n".into())); + } + self.wrote = true; + if !t.is_empty() { + out.push(Parsed::Text(t.to_string())); + } + } + Some("content_block_delta") if e.pointer("/delta/type").and_then(Value::as_str) == Some("text_delta") => { + self.deltas = true; + self.wrote = true; + let t = e.pointer("/delta/text").and_then(Value::as_str).unwrap_or(""); + if !t.is_empty() { + out.push(Parsed::Text(t.to_string())); + } + } + _ => {} + } + } + "assistant" if !self.deltas => { + for block in v.pointer("/message/content").and_then(Value::as_array).into_iter().flatten() { + if block.get("type").and_then(Value::as_str) == Some("text") { + let t = block.get("text").and_then(Value::as_str).unwrap_or("").to_string(); + self.text(&mut out, &t, true); + } + } + } + "result" => { + if !s("/session_id").is_empty() { + out.push(Parsed::Session(s("/session_id"))); + } + let u = &v["usage"]; + let input = n(u, "/input_tokens") + n(u, "/cache_creation_input_tokens") + n(u, "/cache_read_input_tokens"); + out.push(Parsed::Usage(Usage { input, output: n(u, "/output_tokens") })); + if v.get("is_error").and_then(Value::as_bool).unwrap_or(false) { + let why = if s("/result").is_empty() { s("/subtype") } else { s("/result") }; + out.push(Parsed::Error(why)); + } + } + _ => {} + }, + ApiKind::OpenCode => { + if let Some(id) = v.get("sessionID").and_then(Value::as_str) { + out.push(Parsed::Session(id.to_string())); + } + match ty { + "text" => { + let t = s("/part/text"); + self.text(&mut out, &t, true); + } + "step_finish" => { + let tk = &v["part"]["tokens"]; + let input = n(tk, "/input") + n(tk, "/cache/read") + n(tk, "/cache/write"); + out.push(Parsed::Usage(Usage { input, output: n(tk, "/output") + n(tk, "/reasoning") })); + } + "error" => { + let why = [s("/error/data/message"), s("/error/message"), s("/message")].into_iter().find(|m| !m.is_empty()); + out.push(Parsed::Error(why.unwrap_or_else(|| line.chars().take(300).collect()))); + } + _ => {} + } + } + ApiKind::Codex => match ty { + "thread.started" => out.push(Parsed::Session(s("/thread_id"))), + "item.completed" if s("/item/type") == "agent_message" => { + let t = s("/item/text"); + self.text(&mut out, &t, true); + } + "turn.completed" => { + let u = &v["usage"]; + out.push(Parsed::Usage(Usage { input: n(u, "/input_tokens"), output: n(u, "/output_tokens") })); + } + "turn.failed" => out.push(Parsed::Error(s("/error/message"))), + "error" => out.push(Parsed::Error(s("/message"))), + _ => {} + }, + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => {} + } + out + } +} + +/// What a finished run reports. +pub struct Outcome { + pub session: Option, + pub usage: Usage, + pub stopped: bool, + /// The error to show, when the run failed. + pub error: Option, +} + +/// Run one turn to the end, streaming text through `on_text`; Stop kills the program. +pub fn run(turn: &Turn<'_>, on_text: &mut dyn FnMut(&str), cancel: &Arc) -> Outcome { + let mut outcome = Outcome { session: turn.session.map(str::to_string), usage: Usage::default(), stopped: false, error: None }; + let _ = std::fs::create_dir_all(turn.workdir); + let name = turn.kind.label(); + let files = match write_images(turn) { + Ok(f) => f, + Err(e) => { + outcome.error = Some(e); + return outcome; + } + }; + let mut child = match command(turn, &files).spawn() { + Ok(c) => c, + Err(e) => { + outcome.error = Some(format!("can't start {name} ({}): {e}", turn.program.display())); + return outcome; + } + }; + if let Some(mut stdin) = child.stdin.take() { + use std::io::Write as _; + let message = stdin_message(turn); + // Closing standard input after the message ends the request. + std::thread::spawn(move || { + let _ = stdin.write_all(message.as_bytes()); + let _ = stdin.write_all(b"\n"); + }); + } + let (tx, rx) = channel::(); + if let Some(stdout) = child.stdout.take() { + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if tx.send(line).is_err() { + break; + } + } + }); + } + let (etx, erx) = channel::(); + if let Some(mut stderr) = child.stderr.take() { + std::thread::spawn(move || { + let mut s = String::new(); + let _ = stderr.read_to_string(&mut s); + let _ = etx.send(s); + }); + } + let mut parser = Parser::new(turn.kind); + let mut failed: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + outcome.stopped = true; + return outcome; + } + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(line) => { + for p in parser.line(&line) { + match p { + Parsed::Session(s) if !s.is_empty() => outcome.session = Some(s), + Parsed::Session(_) => {} + Parsed::Text(t) => on_text(&t), + Parsed::Usage(u) => { + outcome.usage.input = outcome.usage.input.saturating_add(u.input); + outcome.usage.output = outcome.usage.output.saturating_add(u.output); + } + Parsed::Error(e) if !e.is_empty() => failed.push(e), + Parsed::Error(_) => {} + } + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } + let status = child.wait(); + let stderr = erx.recv_timeout(Duration::from_secs(2)).unwrap_or_default(); + if !failed.is_empty() { + outcome.error = Some(format!("{name}: {}", failed.join("; "))); + } else if let Ok(s) = status + && !s.success() + { + let tail: String = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").chars().take(400).collect(); + outcome.error = Some(if tail.is_empty() { format!("{name} exited with {s}") } else { format!("{name}: {tail}") }); + } + outcome +} + +#[cfg(test)] +mod tests { + use super::*; + + fn texts(p: &[Parsed]) -> String { + p.iter() + .filter_map(|x| match x { + Parsed::Text(t) => Some(t.as_str()), + _ => None, + }) + .collect() + } + + #[test] + fn claude_code_text_arrives_once_and_blocks_are_paragraphs() { + let mut p = Parser::new(ApiKind::ClaudeCode); + let mut all = Vec::new(); + for line in [ + r#"{"type":"system","subtype":"init","session_id":"s-1"}"#, + r#"{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Making "}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a card."}}}"#, + r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Making a card."}]}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}}"#, + r#"{"type":"result","subtype":"success","is_error":false,"session_id":"s-1","usage":{"input_tokens":3,"cache_read_input_tokens":10,"output_tokens":5}}"#, + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "Making a card.\n\nDone."); + assert!(all.contains(&Parsed::Session("s-1".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Usage(u) if u.input > u.output))); + assert!(!all.iter().any(|x| matches!(x, Parsed::Error(_)))); + } + + #[test] + fn a_failed_claude_code_run_says_why() { + let mut p = Parser::new(ApiKind::ClaudeCode); + let out = p.line(r#"{"type":"result","subtype":"error","is_error":true,"result":"Not logged in · Please run /login","usage":{}}"#); + assert!(out.iter().any(|x| matches!(x, Parsed::Error(e) if e.contains("login")))); + } + + #[test] + fn opencode_parts_become_text_usage_and_a_session() { + let mut p = Parser::new(ApiKind::OpenCode); + let mut all = Vec::new(); + for line in [ + r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#, + r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"First."}}"#, + r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"Second."}}"#, + r#"{"type":"step_finish","sessionID":"ses_1","part":{"tokens":{"input":70,"output":3,"reasoning":2,"cache":{"read":5,"write":0}}}}"#, + "not json", + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "First.\n\nSecond."); + assert!(all.contains(&Parsed::Session("ses_1".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Usage(u) if u.input == 75 && u.output == 5))); + } + + #[test] + fn codex_messages_and_failures_are_read() { + let mut p = Parser::new(ApiKind::Codex); + let mut all = Vec::new(); + for line in [ + r#"{"type":"thread.started","thread_id":"th-9"}"#, + r#"{"type":"item.completed","item":{"id":"i0","type":"reasoning","text":"thinking"}}"#, + r#"{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"Built it."}}"#, + r#"{"type":"turn.completed","usage":{"input_tokens":20,"output_tokens":4}}"#, + r#"{"type":"turn.failed","error":{"message":"usage limit reached"}}"#, + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "Built it.", "reasoning is not the answer"); + assert!(all.contains(&Parsed::Session("th-9".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Error(e) if e.contains("limit")))); + } + + #[test] + fn claude_code_gets_only_figcraft_tools() { + let dir = std::env::temp_dir(); + let turn = Turn { + kind: ApiKind::ClaudeCode, + program: Path::new("claude"), + model: "", + session: Some("s-1"), + prompt: "--dangerous-looking prompt", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &[], + }; + let cmd = command(&turn, &[]); + let args: Vec = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = |flag: &str| args.iter().position(|a| a == flag).map(|i| args[i + 1].clone()); + assert_eq!(at("--tools").as_deref(), Some(""), "no built-in tools"); + assert_eq!(at("--allowedTools").as_deref(), Some("mcp__figcraft")); + assert!(args.contains(&"--strict-mcp-config".to_string()), "no other MCP servers"); + assert_eq!(at("--resume").as_deref(), Some("s-1")); + assert_eq!(at("--").as_deref(), Some("--dangerous-looking prompt"), "the prompt is never read as a flag"); + assert!(!args.iter().any(|a| a == "--model"), "the default model"); + } + + #[test] + fn attached_images_reach_each_program_its_own_way() { + let dir = std::env::temp_dir(); + let images = [crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() }]; + let mut turn = Turn { + kind: ApiKind::ClaudeCode, + program: Path::new("claude"), + model: "", + session: None, + prompt: "like this", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &images, + }; + let args = |c: &Command| c.get_args().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let claude = args(&command(&turn, &[])); + assert!(claude.windows(2).any(|w| w == ["--input-format", "stream-json"]), "Claude Code reads the request from its input"); + assert!(!claude.contains(&"like this".to_string()), "the prompt is in the message, not an argument"); + let message: Value = serde_json::from_str(&stdin_message(&turn)).expect("json"); + assert_eq!(message.pointer("/message/content/1/type").and_then(Value::as_str), Some("image")); + turn.kind = ApiKind::OpenCode; + let file = PathBuf::from("/tmp/a.png"); + assert!(args(&command(&turn, std::slice::from_ref(&file))).windows(2).any(|w| w == ["--file", "/tmp/a.png"])); + turn.kind = ApiKind::Codex; + assert!(args(&command(&turn, std::slice::from_ref(&file))).windows(2).any(|w| w == ["--image", "/tmp/a.png"])); + } +} diff --git a/crates/agent/src/config.rs b/crates/agent/src/config.rs new file mode 100644 index 000000000..83edec9fc --- /dev/null +++ b/crates/agent/src/config.rs @@ -0,0 +1,511 @@ +//! The agent's settings: connected providers, the chosen model and how much the agent may do on +//! its own. Stored in `agents.json` beside the app's preferences, readable only by the user (it +//! holds API keys). + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +/// Which wire dialect a provider speaks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ApiKind { + #[default] + OpenAiCompletions, + AnthropicMessages, + /// The person's own Claude Code install (`claude`), signed in with their Claude plan. + ClaudeCode, + /// The person's own Codex install (`codex`), signed in with their ChatGPT plan. + Codex, + /// The person's own OpenCode install (`opencode`), with the providers it is signed in to. + OpenCode, +} + +impl ApiKind { + pub fn label(self) -> &'static str { + match self { + ApiKind::OpenAiCompletions => "OpenAI Completions", + ApiKind::AnthropicMessages => "Anthropic Messages", + ApiKind::ClaudeCode => "Claude Code", + ApiKind::Codex => "Codex", + ApiKind::OpenCode => "OpenCode", + } + } + + /// Whether requests go through an installed command-line agent rather than an HTTP endpoint. + pub fn is_cli(self) -> bool { + matches!(self, ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode) + } + + /// The program a command-line connection runs. + pub fn program(self) -> Option<&'static str> { + match self { + ApiKind::ClaudeCode => Some("claude"), + ApiKind::Codex => Some("codex"), + ApiKind::OpenCode => Some("opencode"), + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => None, + } + } +} + +/// How much a reasoning model may think before answering (OpenAI-compatible endpoints; the +/// Anthropic adapter leaves its provider default alone). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Reasoning { + #[default] + Auto, + Low, + Medium, + High, +} + +impl Reasoning { + pub fn label(self) -> &'static str { + match self { + Reasoning::Auto => "Auto", + Reasoning::Low => "Low", + Reasoning::Medium => "Medium", + Reasoning::High => "High", + } + } + + /// The `reasoning_effort` value, `None` for Auto (the provider's own default). + pub fn effort(self) -> Option<&'static str> { + match self { + Reasoning::Auto => None, + Reasoning::Low => Some("low"), + Reasoning::Medium => Some("medium"), + Reasoning::High => Some("high"), + } + } + + pub const CHOICES: &'static [Reasoning] = &[Reasoning::Auto, Reasoning::Low, Reasoning::Medium, Reasoning::High]; +} + +/// How much the agent does without asking. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Permission { + /// Canvas edits run at once; anything that reads or writes a file, or reaches the network, + /// waits for the person's Allow. + #[default] + AskFiles, + /// Everything runs at once. The automation roots still confine file access. + Auto, +} + +/// One connected model endpoint. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Provider { + pub name: String, + #[serde(default)] + pub kind: ApiKind, + /// The API root, e.g. `https://opencode.ai/zen/go/v1`; the adapter adds `/chat/completions` + /// or `/messages`. + pub base_url: String, + #[serde(default)] + pub api_key: String, + #[serde(default)] + pub model: String, + /// Model ids seen from this endpoint (`/models`), for the picker. + #[serde(default)] + pub models: Vec, + /// The model's limits, in tokens. + #[serde(default = "default_context")] + pub context_window: u32, + #[serde(default = "default_max_tokens")] + pub max_tokens: u32, + /// Whether the model reads images (screenshots of the canvas). + #[serde(default = "default_true")] + pub vision: bool, + /// Reasoning effort, where the endpoint supports one. + #[serde(default)] + pub reasoning: Reasoning, + /// What the endpoint charges, in US dollars per million tokens; 0 leaves the estimate out. + #[serde(default)] + pub price_in: f64, + #[serde(default)] + pub price_out: f64, +} + +fn default_context() -> u32 { + 128_000 +} + +fn default_max_tokens() -> u32 { + 8_192 +} + +fn default_true() -> bool { + true +} + +impl Provider { + pub fn new(name: &str, kind: ApiKind, base_url: &str) -> Self { + Self { + name: name.to_string(), + kind, + base_url: base_url.trim_end_matches('/').to_string(), + api_key: String::new(), + model: String::new(), + models: Vec::new(), + context_window: default_context(), + max_tokens: default_max_tokens(), + vision: true, + reasoning: Reasoning::Auto, + price_in: 0.0, + price_out: 0.0, + } + } + + /// The endpoint a request goes to. + pub fn endpoint(&self) -> String { + let root = self.base_url.trim_end_matches('/'); + match self.kind { + ApiKind::OpenAiCompletions => format!("{root}/chat/completions"), + ApiKind::AnthropicMessages => format!("{root}/messages"), + ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode => String::new(), + } + } + + /// Whether enough is filled in to send a request. A command-line connection needs nothing: + /// an empty model means that program's own default. + pub fn ready(&self) -> bool { + self.kind.is_cli() || (!self.base_url.trim().is_empty() && !self.model.trim().is_empty()) + } + + /// The model as the panel shows it. + pub fn model_label(&self) -> &str { + if self.model.trim().is_empty() { "Default model" } else { self.model.as_str() } + } + + /// A connection to the preset, with its model filled in later by [`pick_model`]. + pub fn from_preset(preset: &Preset) -> Self { + Self::new(preset.name, preset.kind, preset.base_url) + } + + /// A connection to an installed command-line agent. + pub fn from_cli(cli: &CliPreset) -> Self { + let mut p = Self::new(cli.name, cli.kind, ""); + p.models = cli.models.iter().map(|m| m.to_string()).collect(); + p + } +} + +/// A provider the person connects with an API key (or nothing, for a local server); the model is +/// picked from the endpoint's list. +pub struct Preset { + pub name: &'static str, + pub kind: ApiKind, + pub base_url: &'static str, + /// One line under the name on the connection card. + pub blurb: &'static str, + /// Where the person gets a key; `None` for a local server, which needs none. + pub key_url: Option<&'static str>, + /// Model ids (or parts of them) to choose first, in order, after the list arrives. + pub prefer: &'static [&'static str], +} + +impl Preset { + pub fn needs_key(&self) -> bool { + self.key_url.is_some() + } +} + +pub const PRESETS: &[Preset] = &[ + Preset { + name: "Anthropic", + kind: ApiKind::AnthropicMessages, + base_url: "https://api.anthropic.com/v1", + blurb: "Claude models with an API key", + key_url: Some("https://console.anthropic.com/settings/keys"), + prefer: &["claude-sonnet", "claude-opus"], + }, + Preset { + name: "OpenAI", + kind: ApiKind::OpenAiCompletions, + base_url: "https://api.openai.com/v1", + blurb: "GPT models with an API key", + key_url: Some("https://platform.openai.com/api-keys"), + prefer: &["gpt-5", "gpt-4.1"], + }, + Preset { + name: "OpenCode Go", + kind: ApiKind::OpenAiCompletions, + base_url: "https://opencode.ai/zen/go/v1", + blurb: "Open models on the OpenCode Go plan", + key_url: Some("https://opencode.ai/auth"), + prefer: &["kimi-k3", "glm-5", "qwen", "deepseek"], + }, + Preset { + name: "OpenCode Zen", + kind: ApiKind::OpenAiCompletions, + base_url: "https://opencode.ai/zen/v1", + blurb: "Pay-as-you-go models from OpenCode", + key_url: Some("https://opencode.ai/auth"), + prefer: &["claude-sonnet", "gpt-5", "kimi"], + }, + Preset { + name: "OpenRouter", + kind: ApiKind::OpenAiCompletions, + base_url: "https://openrouter.ai/api/v1", + blurb: "Many providers behind one key", + key_url: Some("https://openrouter.ai/keys"), + prefer: &["anthropic/claude-sonnet", "openai/gpt-5"], + }, + Preset { + name: "DeepSeek", + kind: ApiKind::OpenAiCompletions, + base_url: "https://api.deepseek.com/v1", + blurb: "DeepSeek models with an API key", + key_url: Some("https://platform.deepseek.com/api_keys"), + prefer: &["deepseek-chat"], + }, + Preset { + name: "Ollama", + kind: ApiKind::OpenAiCompletions, + base_url: "http://localhost:11434/v1", + blurb: "Models running on this computer", + key_url: None, + prefer: &[], + }, + Preset { + name: "LM Studio", + kind: ApiKind::OpenAiCompletions, + base_url: "http://localhost:1234/v1", + blurb: "Models running on this computer", + key_url: None, + prefer: &[], + }, +]; + +/// An installed command-line agent the person signs in to with their own plan. +pub struct CliPreset { + pub name: &'static str, + pub kind: ApiKind, + pub blurb: &'static str, + /// How to install it, shown when it is missing. + pub install: &'static str, + /// How to sign in, shown when it is installed but signed out. + pub login: &'static str, + /// Models offered before the program is asked for its own list (empty: its default only). + pub models: &'static [&'static str], +} + +pub const SUBSCRIPTIONS: &[CliPreset] = &[ + CliPreset { + name: "Claude Code", + kind: ApiKind::ClaudeCode, + blurb: "Use your Claude Pro or Max plan", + install: "curl -fsSL https://claude.ai/install.sh | bash", + login: "claude auth login", + models: &["sonnet", "opus", "haiku"], + }, + CliPreset { + name: "Codex", + kind: ApiKind::Codex, + blurb: "Use your ChatGPT plan", + install: "brew install codex", + login: "codex login", + models: &[], + }, + CliPreset { + name: "OpenCode", + kind: ApiKind::OpenCode, + blurb: "Use the providers OpenCode is signed in to", + install: "curl -fsSL https://opencode.ai/install | bash", + login: "opencode auth login", + models: &[], + }, +]; + +/// The model to start with once an endpoint listed its models: the first id that matches one of +/// `prefer` (newest first, skipping small and non-chat models), else the first chat model. +pub fn pick_model(prefer: &[&str], models: &[String]) -> Option { + const NOT_CHAT: &[&str] = &["embed", "audio", "realtime", "tts", "transcribe", "moderation", "image", "search", "whisper", "dall-e"]; + const SMALL: &[&str] = &["nano", "mini", "haiku", "flash", "lite"]; + let chat: Vec<&String> = models.iter().filter(|m| !NOT_CHAT.iter().any(|n| m.to_ascii_lowercase().contains(n))).collect(); + for want in prefer { + let mut hits: Vec<&&String> = chat.iter().filter(|m| m.contains(want)).collect(); + hits.sort_by(|a, b| b.cmp(a)); + if let Some(m) = hits.iter().find(|m| !SMALL.iter().any(|s| m.contains(s))).or(hits.first()) { + return Some((**m).to_string()); + } + } + chat.iter().find(|m| !SMALL.iter().any(|s| m.contains(s))).or(chat.first()).map(|m| m.to_string()) +} + +/// Everything `agents.json` holds. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentsFile { + #[serde(default)] + pub providers: Vec, + /// Index into `providers`; out of range means the first. + #[serde(default)] + pub active: usize, + #[serde(default)] + pub permission: Permission, + /// Whether the app opens on the Agent tab (the rail's Agent button was the last one used). + #[serde(default)] + pub panel: bool, + /// Whether the agent looks at the canvas after a turn that changed it and fixes what it sees + /// (models that read images only). + #[serde(default = "default_true")] + pub review: bool, + /// How many versions one request builds (1: just the design, up to 3 side by side). + #[serde(default = "one")] + pub variants: u8, +} + +fn one() -> u8 { + 1 +} + +impl AgentsFile { + /// The provider requests go to. + pub fn active(&self) -> Option<&Provider> { + self.providers.get(self.active).or_else(|| self.providers.first()) + } + + pub fn active_mut(&mut self) -> Option<&mut Provider> { + let i = if self.active < self.providers.len() { self.active } else { 0 }; + self.providers.get_mut(i) + } + + /// Read the file; a missing one is an empty setup, a damaged one is an empty setup with the + /// reason kept for the panel. + pub fn load(path: Option<&Path>) -> (Self, Option) { + let Some(path) = path else { return (Self::default(), None) }; + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::default(), None), + Err(e) => return (Self::default(), Some(format!("can't read {}: {e}", path.display()))), + }; + match serde_json::from_slice::(&bytes) { + Ok(mut f) => { + if f.active >= f.providers.len() { + f.active = 0; + } + (f, None) + } + Err(e) => (Self::default(), Some(format!("{} is damaged: {e}", path.display()))), + } + } + + /// Write the file, readable only by the user: it holds API keys. + pub fn save(&self, path: Option<&Path>) -> Result<(), String> { + let Some(path) = path else { return Err("this build has no settings folder to keep providers in".into()) }; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + } + let bytes = serde_json::to_vec_pretty(self).map_err(|e| format!("can't encode the agent settings: {e}"))?; + write_private(path, &bytes) + } +} + +/// Write `bytes` to `path` through a temporary file, keeping the file owner-only where the +/// platform has permissions. +pub fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + } + let mut tmp = path.to_path_buf(); + tmp.set_extension("json.tmp"); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + opts.mode(0o600); + } + let mut file = opts.open(&tmp).map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + use std::io::Write as _; + file.write_all(bytes).map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + file.flush().map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + } + std::fs::rename(&tmp, path).map_err(|e| format!("can't replace {}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_follow_the_dialect() { + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://opencode.ai/zen/go/v1/"); + assert_eq!(p.endpoint(), "https://opencode.ai/zen/go/v1/chat/completions"); + p.kind = ApiKind::AnthropicMessages; + assert_eq!(p.endpoint(), "https://opencode.ai/zen/go/v1/messages"); + assert!(!p.ready(), "no model chosen"); + p.model = "claude-haiku-5-5".into(); + assert!(p.ready()); + } + + #[test] + fn the_first_model_is_a_capable_chat_model() { + let ids = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let anthropic = ids(&["claude-haiku-5-5", "claude-opus-4-1", "claude-sonnet-4-5", "claude-sonnet-5-5"]); + assert_eq!(pick_model(&["claude-sonnet"], &anthropic).as_deref(), Some("claude-sonnet-5-5"), "the newest preferred"); + let openai = ids(&["gpt-5-nano", "gpt-5.5", "text-embedding-3", "gpt-5-mini"]); + assert_eq!(pick_model(&["gpt-5"], &openai).as_deref(), Some("gpt-5.5"), "not a small model"); + let local = ids(&["nomic-embed", "llama4"]); + assert_eq!(pick_model(&[], &local).as_deref(), Some("llama4"), "not an embedding model"); + assert_eq!(pick_model(&["x"], &[]), None); + } + + #[test] + fn a_command_line_connection_needs_no_model() { + let p = Provider::from_cli(&SUBSCRIPTIONS[0]); + assert!(p.ready()); + assert!(p.kind.is_cli()); + assert!(!p.models.is_empty()); + } + + #[test] + fn settings_round_trip_through_a_private_file() { + let dir = std::env::temp_dir().join(format!("figcraft-agent-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("agents.json"); + let mut f = AgentsFile::default(); + f.providers.push(Provider::new("Go", ApiKind::OpenAiCompletions, "https://example.test/v1")); + f.providers[0].api_key = "sk-secret".into(); + f.providers[0].model = "deepseek-v4.1-flash".into(); + f.providers[0].reasoning = Reasoning::Medium; + f.providers[0].price_in = 1.5; + f.providers[0].price_out = 6.0; + f.active = 0; + f.permission = Permission::Auto; + f.variants = 3; + f.save(Some(&path)).expect("saved"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mode = std::fs::metadata(&path).map(|m| m.permissions().mode()).unwrap_or(0); + assert_eq!(mode & 0o777, 0o600, "the key file is owner-only"); + } + let (back, err) = AgentsFile::load(Some(&path)); + assert!(err.is_none()); + assert_eq!(back.providers[0].api_key, "sk-secret"); + assert_eq!(back.permission, Permission::Auto); + assert_eq!(back.providers[0].reasoning, Reasoning::Medium); + assert_eq!(back.providers[0].price_out, 6.0); + assert_eq!(back.variants, 3); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_damaged_file_is_reported_not_fatal() { + let dir = std::env::temp_dir().join(format!("figcraft-agent-bad-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("agents.json"); + std::fs::write(&path, b"{not json").expect("write"); + let (f, err) = AgentsFile::load(Some(&path)); + assert!(f.providers.is_empty()); + assert!(err.is_some()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/agent/src/http.rs b/crates/agent/src/http.rs new file mode 100644 index 000000000..a3c9bb595 --- /dev/null +++ b/crates/agent/src/http.rs @@ -0,0 +1,99 @@ +//! Blocking HTTP for the provider adapters: rustls, no async runtime (the shape `figcraft-mcp` +//! and `collab-net` already use). + +use std::io::{BufRead, BufReader}; +use std::time::Duration; + +use serde_json::Value; + +pub struct Http { + agent: ureq::Agent, +} + +/// A response whose body is still being read (the SSE stream of a model answer). +pub struct Reply { + pub status: u16, + pub body: Box, +} + +impl Http { + pub fn new() -> Self { + let config = ureq::Agent::config_builder() + // A streamed answer can run for minutes: no whole-request deadline, but a stuck + // connection is caught by the per-read limit. + .timeout_global(None) + .timeout_connect(Some(Duration::from_secs(20))) + .timeout_recv_response(Some(Duration::from_secs(120))) + .timeout_per_read(Some(Duration::from_secs(300))) + // A 4xx carries the provider's message: read it, don't turn it into a bare error. + .http_status_as_error(false) + .build(); + Self { agent: config.new_agent() } + } + + fn send(&self, request: ureq::RequestBuilder, headers: &[(&str, String)], body: &Value) -> Result { + let mut request = request; + for (name, value) in headers { + request = request.header(*name, value.clone()); + } + let response = request.send_json(body).map_err(network)?; + let status = response.status().as_u16(); + let body = Box::new(BufReader::new(response.into_body().into_reader())); + Ok(Reply { status, body }) + } + + /// POST JSON and stream the answer back. + pub fn post(&self, url: &str, headers: &[(&str, String)], body: &Value) -> Result { + self.send(self.agent.post(url), headers, body) + } + + /// GET JSON (model lists), with the response body read whole. + pub fn get_json(&self, url: &str, headers: &[(&str, String)]) -> Result { + let mut request = self.agent.get(url); + for (name, value) in headers { + request = request.header(*name, value.clone()); + } + let response = request.call().map_err(network)?; + let status = response.status().as_u16(); + let mut body = response.into_body(); + let text = body.read_to_string().map_err(|e| format!("reading the answer failed: {e}"))?; + if status >= 400 { + return Err(status_message(status, &text)); + } + serde_json::from_str(&text).map_err(|e| format!("the endpoint sent something that is not JSON: {e}")) + } +} + +impl Default for Http { + fn default() -> Self { + Self::new() + } +} + +fn network(e: ureq::Error) -> String { + match e { + ureq::Error::Timeout(t) => format!("the endpoint did not answer in time ({t})"), + ureq::Error::StatusCode(code) => format!("the endpoint answered {code}"), + ureq::Error::Io(e) => format!("network error: {e}"), + other => format!("request failed: {other}"), + } +} + +/// The provider's own error message when it sent one, else the status and the start of the body. +pub fn status_message(status: u16, body: &str) -> String { + if let Ok(v) = serde_json::from_str::(body) + && let Some(m) = v.get("error").and_then(|e| e.get("message")).and_then(Value::as_str) + { + return format!("{status}: {m}"); + } + let head: String = body.chars().take(400).collect(); + format!("{status}: {}", head.trim()) +} + +/// The whole body of a failed reply, for its message. +pub fn read_error(status: u16, body: Box) -> String { + use std::io::Read as _; + let mut text = String::new(); + let _ = body.take(64 * 1024).read_to_string(&mut text); + status_message(status, &text) +} diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs new file mode 100644 index 000000000..e5605d3de --- /dev/null +++ b/crates/agent/src/lib.rs @@ -0,0 +1,250 @@ +//! FigCraft's in-app agent. +//! +//! Two provider dialects (OpenAI Chat Completions and Anthropic Messages), the tool-call loop on +//! top of [`figcraft_mcp`]'s tool set, and the bridge that lets the loop run on its own thread +//! while the session stays on the UI thread. +//! +//! The app shows a chat panel; the panel owns a [`Worker`], which owns an [`Agent`]. Every tool +//! call goes through [`figcraft_mcp::Backend`], so the in-app agent and an external MCP client +//! behave the same. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod anthropic; +pub mod bridge; +pub mod cli; +pub mod config; +pub mod http; +pub mod mcp_http; +pub mod neutral; +pub mod openai; +pub mod session; +pub mod sse; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use serde_json::Value; + +pub use config::{AgentsFile, ApiKind, CliPreset, PRESETS, Permission, Preset, Provider, SUBSCRIPTIONS, pick_model}; +pub use session::{AGENT_NAME, Agent, ChatEvent, approval, system_prompt}; + +/// Token counts one request used. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Usage { + pub input: u64, + pub output: u64, +} + +/// One tool call the model asked for. +#[derive(Clone, Debug, PartialEq)] +pub struct Invocation { + pub id: String, + pub name: String, + /// The arguments; `Value::Null` when the model sent text that is not JSON. + pub args: Value, + pub args_raw: String, +} + +/// One streamed model step: its text, its tool calls and what it used. +#[derive(Clone, Debug, Default)] +pub struct Step { + pub text: String, + pub calls: Vec, + pub stop: String, + pub usage: Usage, +} + +/// What the panel tells the worker to do. +pub enum Command { + Turn { + text: String, + context: Option, + /// Images the person attached (references, a render of the selection). + images: Vec, + }, + /// Switch the model (or endpoint) without losing the conversation. + SetProvider(Provider), + /// Move the conversation to another file (the next document's chat): the current one is + /// saved first, then the new one is read if it exists. + SetHistory(Option), + Clear, + Shutdown, +} + +/// The agent thread the panel talks to. It lives as long as the conversation does, keeping the +/// messages (and the provider's prompt cache) between turns. +pub struct Worker { + commands: Sender, + /// Events of the running (or last) turn, drained by the panel every frame. + pub events: Receiver, + /// Set to stop the running turn; the worker clears it when the next one starts. + pub cancel: Arc, + /// 0: ask before file and network tools, 1: auto. + pub permission: Arc, + /// Whether a turn that changes the canvas ends with a look at it. + pub review: Arc, + /// False once the thread ended (a panic included), so the panel can say so. + alive: Arc, + handle: Option>, +} + +/// Clears the worker's `alive` flag however the thread ends, a panic included. +struct Alive(Arc); + +impl Drop for Alive { + fn drop(&mut self) { + self.0.store(false, Ordering::Relaxed); + } +} + +impl Worker { + /// Start an agent thread for `provider`, whose tool calls go through `backend`. + pub fn spawn(provider: Provider, backend: bridge::Remote, wake: Arc) -> Self { + let (commands, inbox) = channel::(); + let (out, events) = channel::(); + let cancel = Arc::new(AtomicBool::new(false)); + let permission = Arc::new(AtomicU8::new(0)); + let review = Arc::new(AtomicBool::new(true)); + let alive = Arc::new(AtomicBool::new(true)); + let thread_cancel = cancel.clone(); + let thread_permission = permission.clone(); + let thread_review = review.clone(); + let thread_alive = alive.clone(); + let handle = std::thread::Builder::new().name("figcraft-agent".into()).spawn(move || { + let _alive = Alive(thread_alive); + let mut agent = Agent::new(provider, backend); + agent.permission = thread_permission; + agent.review = thread_review; + let mut history: Option = None; + // Every event wakes the window: it is idle between frames and would otherwise show + // the answer only on the next mouse move. + let shared: Arc = Arc::new(move |event: ChatEvent| { + let _ = out.send(event); + wake(); + }); + agent.sink = Some(shared.clone()); + let sink = |event: ChatEvent| shared(event); + while let Ok(command) = inbox.recv() { + match command { + Command::Turn { text, context, images } => { + thread_cancel.store(false, Ordering::Relaxed); + match agent.run_turn_with(&text, context, images, &sink, &thread_cancel) { + Ok(()) => {} + Err(e) => { + sink(ChatEvent::Error(e)); + sink(ChatEvent::Done { stopped: false }); + } + } + if let Some(path) = &history { + let _ = agent.save_history(path); + } + } + Command::Clear => { + agent.clear(); + if let Some(path) = &history { + let _ = agent.save_history(path); + } + } + Command::SetProvider(p) => agent.set_provider(p), + Command::SetHistory(path) => { + if let Some(old) = history.as_ref() { + let _ = agent.save_history(old); + } + history = path; + // The next conversation starts empty unless its own file holds one: the + // last one's messages must not carry over. + agent.clear(); + // A command-line agent runs beside the saved chats, never in a project. + if let Some(dir) = history.as_deref().and_then(std::path::Path::parent) { + agent.workdir = Some(dir.join("cli")); + } + if let Some(new) = history.as_ref() { + let _ = agent.load_history(new); + } + } + Command::Shutdown => break, + } + } + }); + Self { commands, events, cancel, permission, review, alive, handle: handle.ok() } + } + + pub fn send_turn(&self, text: String, context: Option) -> Result<(), String> { + self.send_turn_with(text, context, Vec::new()) + } + + /// [`send_turn`](Self::send_turn) with images attached to the request. + pub fn send_turn_with(&self, text: String, context: Option, images: Vec) -> Result<(), String> { + self.commands.send(Command::Turn { text, context, images }).map_err(|_| "the agent thread stopped".to_string()) + } + + pub fn clear(&self) -> Result<(), String> { + self.commands.send(Command::Clear).map_err(|_| "the agent thread stopped".to_string()) + } + + pub fn set_provider(&self, provider: Provider) -> Result<(), String> { + self.commands.send(Command::SetProvider(provider)).map_err(|_| "the agent thread stopped".to_string()) + } + + /// Ask the running turn to stop; the layer edits it already made stay. + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + + pub fn set_auto(&self, auto: bool) { + self.permission.store(u8::from(auto), Ordering::Relaxed); + } + + pub fn set_review(&self, on: bool) { + self.review.store(on, Ordering::Relaxed); + } + + /// False once the agent thread ended (a panic included). + pub fn alive(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } + + /// Move the conversation to another file (the next document's chat). + pub fn set_history(&self, path: Option) -> Result<(), String> { + self.commands.send(Command::SetHistory(path)).map_err(|_| "the agent thread stopped".to_string()) + } +} + +impl Drop for Worker { + fn drop(&mut self) { + let _ = self.commands.send(Command::Shutdown); + // The thread may be waiting on the network; it ends after that answer. Dropping the + // handle detaches it rather than blocking the UI thread here. + self.handle.take(); + } +} + +/// The model ids an endpoint lists (`GET {base}/models`). +pub fn list_models(provider: &Provider) -> Result, String> { + let http = http::Http::new(); + let url = format!("{}/models", provider.base_url.trim_end_matches('/')); + if provider.kind.is_cli() { + return cli::models(provider.kind).ok_or_else(|| format!("{} keeps its own model list", provider.kind.label())); + } + let mut headers: Vec<(&str, String)> = match provider.kind { + ApiKind::AnthropicMessages => vec![("x-api-key", provider.api_key.trim().to_string()), ("anthropic-version", "2023-06-01".to_string())], + _ => vec![("authorization", format!("Bearer {}", provider.api_key.trim()))], + }; + if provider.api_key.trim().is_empty() { + headers.retain(|(k, _)| *k == "anthropic-version"); + } + let v = http.get_json(&url, &headers)?; + let mut ids: Vec = v + .get("data") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|m| m.get("id").and_then(Value::as_str).map(str::to_string)).collect()) + .unwrap_or_default(); + ids.sort(); + ids.dedup(); + if ids.is_empty() { + return Err("the endpoint listed no models; type the model id instead".into()); + } + Ok(ids) +} diff --git a/crates/agent/src/mcp_http.rs b/crates/agent/src/mcp_http.rs new file mode 100644 index 000000000..683e04861 --- /dev/null +++ b/crates/agent/src/mcp_http.rs @@ -0,0 +1,389 @@ +//! FigCraft's tools for a command-line agent (Claude Code, Codex, OpenCode). +//! +//! Those programs run their own loop and reach tools over MCP. This serves the same tool set the +//! in-app loop uses ([`figcraft_mcp::Server`] over the [`Remote`](crate::bridge::Remote) bridge) on +//! a loopback HTTP endpoint for the length of the conversation: one JSON-RPC message per `POST`, +//! answered as `application/json` (MCP's Streamable HTTP transport without server-sent events). +//! +//! Only this app's child processes are meant to call it: it listens on 127.0.0.1 only, refuses a +//! request without the bearer token handed to the child, and refuses browser requests (an `Origin` +//! header, or a `Host` that is not loopback). Tool calls pass the same Ask/Auto gate as the in-app +//! loop, and report to the panel the same way. + +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hasher}; +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::bridge::Remote; +use crate::session::ChatEvent; + +/// The largest request body accepted (tool arguments are small; an image goes the other way). +const MAX_BODY: usize = 16 * 1024 * 1024; +/// The largest header block accepted. +const MAX_HEADERS: usize = 64 * 1024; + +/// Where a tool call reports to the panel, and how much it may do without asking. +#[derive(Clone)] +pub struct Gate { + /// 0: ask before file and network tools, 1: auto (shared with the panel's toggle). + pub permission: Arc, + /// The panel's event stream. + pub sink: Arc, + /// Set by Stop: calls still arriving are refused. + pub cancel: Arc, +} + +/// A running endpoint; dropping it stops the listener. +pub struct Endpoint { + pub url: String, + pub token: String, + stop: Arc, + port: u16, +} + +impl Drop for Endpoint { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // Wake the blocking accept so the thread sees the flag. + let _ = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(200)); + } +} + +/// One JSON-RPC message on its way to the server thread, and where its answer goes. +type Job = (Value, Sender>); + +/// Start serving FigCraft's tools on a free loopback port. +pub fn start(remote: Remote, gate: Gate) -> std::io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0))?; + let port = listener.local_addr()?.port(); + let token = new_token(); + let stop = Arc::new(AtomicBool::new(false)); + + // The MCP server is not `Send` (its backend is a trait object), so it lives on one thread and + // the connections hand it messages. + let (jobs, inbox) = channel::(); + std::thread::Builder::new().name("figcraft-agent-mcp".into()).spawn(move || serve_jobs(remote, gate, inbox))?; + + let accept_stop = stop.clone(); + let accept_token = token.clone(); + std::thread::Builder::new().name("figcraft-agent-mcp-accept".into()).spawn(move || { + for stream in listener.incoming() { + if accept_stop.load(Ordering::Relaxed) { + break; + } + let Ok(stream) = stream else { continue }; + let jobs = jobs.clone(); + let token = accept_token.clone(); + let _ = std::thread::Builder::new().name("figcraft-agent-mcp-conn".into()).spawn(move || connection(stream, &token, &jobs)); + } + })?; + Ok(Endpoint { url: format!("http://127.0.0.1:{port}/mcp"), token, stop, port }) +} + +fn serve_jobs(remote: Remote, gate: Gate, inbox: Receiver) { + let mut server = figcraft_mcp::Server::new(Box::new(remote)); + while let Ok((msg, reply)) = inbox.recv() { + let answer = handle_gated(&mut server, &gate, msg); + let _ = reply.send(answer); + } +} + +/// Run one message, with `tools/call` going through the Ask/Auto gate and reported to the panel. +fn handle_gated(server: &mut figcraft_mcp::Server, gate: &Gate, msg: Value) -> Option { + if msg.get("method").and_then(Value::as_str) != Some("tools/call") { + return server.handle(msg); + } + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let params = msg.get("params").cloned().unwrap_or(Value::Null); + let name = params.get("name").and_then(Value::as_str).unwrap_or("").to_string(); + let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); + let call_id = id.to_string(); + let refuse = |text: String| Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": true}})); + + (gate.sink)(ChatEvent::ToolStart { id: call_id.clone(), name: name.clone(), args: args.clone() }); + if gate.cancel.load(Ordering::Relaxed) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Stopped by the user".into() }); + return refuse("Not run: the user stopped the agent".into()); + } + if let Some(reason) = crate::session::approval(&name, &args) + && gate.permission.load(Ordering::Relaxed) == 0 + { + let (tx, rx) = channel(); + (gate.sink)(ChatEvent::Permission { id: call_id.clone(), name: name.clone(), args: args.clone(), reason: reason.clone(), reply: tx }); + if !rx.recv_timeout(Duration::from_secs(600)).unwrap_or(false) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Denied by the user".into() }); + return refuse(format!("Not run: the user denied this action ({reason})")); + } + } + let answer = server.handle(msg); + let result = answer.as_ref().and_then(|a| a.get("result")); + let ok = result.is_some_and(|r| !r.get("isError").and_then(Value::as_bool).unwrap_or(false)); + let text = result + .and_then(|r| r.get("content")) + .and_then(Value::as_array) + .and_then(|c| c.iter().find_map(|b| b.get("text").and_then(Value::as_str))) + .map(str::to_string) + .or_else(|| answer.as_ref().and_then(|a| a.pointer("/error/message")).and_then(Value::as_str).map(str::to_string)) + .unwrap_or_default(); + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + answer +} + +/// Serve one keep-alive connection until it closes or sends something unreadable. +fn connection(stream: TcpStream, token: &str, jobs: &Sender) { + let _ = stream.set_read_timeout(Some(Duration::from_secs(900))); + let Ok(mut out) = stream.try_clone() else { return }; + let mut reader = BufReader::new(stream); + loop { + let request = match read_request(&mut reader) { + Ok(Some(r)) => r, + Ok(None) => return, + Err(status) => { + let _ = write_response(&mut out, &Response::status(status)); + return; + } + }; + let close = request.header("connection").is_some_and(|v| v.eq_ignore_ascii_case("close")); + let response = respond(&request, token, &mut |msg| { + let (tx, rx) = channel(); + if jobs.send((msg, tx)).is_err() { + return None; + } + rx.recv().ok().flatten() + }); + if write_response(&mut out, &response).is_err() || close { + return; + } + } +} + +/// One HTTP request as read off the socket. +pub struct Request { + pub method: String, + pub path: String, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } +} + +pub struct Response { + pub status: u16, + pub body: Vec, +} + +impl Response { + fn status(status: u16) -> Self { + Self { status, body: Vec::new() } + } +} + +/// Answer one request: the checks, then the JSON-RPC message (or batch) through `forward`. +pub fn respond(req: &Request, token: &str, forward: &mut dyn FnMut(Value) -> Option) -> Response { + if req.header("origin").is_some() { + return Response::status(403); + } + let host = req.header("host").unwrap_or(""); + let host_name = host.rsplit_once(':').map_or(host, |(h, _)| h); + if !matches!(host_name, "127.0.0.1" | "localhost" | "[::1]") { + return Response::status(403); + } + let authorized = req.header("authorization").and_then(|v| v.strip_prefix("Bearer ")).is_some_and(|t| same(t.trim(), token)); + if !authorized { + return Response::status(401); + } + if req.path.split('?').next() != Some("/mcp") { + return Response::status(404); + } + match req.method.as_str() { + "POST" => {} + // No server-initiated stream and no sessions to end. + _ => return Response::status(405), + } + let Ok(msg) = serde_json::from_slice::(&req.body) else { + let body = json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "parse error"}}); + return Response { status: 400, body: body.to_string().into_bytes() }; + }; + let answer = match msg { + Value::Array(batch) => { + let answers: Vec = batch.into_iter().filter_map(&mut *forward).collect(); + if answers.is_empty() { None } else { Some(Value::Array(answers)) } + } + one => forward(one), + }; + match answer { + Some(a) => Response { status: 200, body: a.to_string().into_bytes() }, + // A notification or a client's response: accepted, nothing to say. + None => Response::status(202), + } +} + +/// Compare without stopping at the first different byte. +fn same(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// Read one request; `Ok(None)` when the peer closed the connection between requests, `Err` with +/// the status to answer for a request this server will not read. +fn read_request(reader: &mut impl BufRead) -> Result, u16> { + let mut line = String::new(); + match reader.read_line(&mut line) { + Ok(0) => return Ok(None), + Ok(_) => {} + Err(_) => return Ok(None), + } + let mut parts = line.split_whitespace(); + let (Some(method), Some(path)) = (parts.next(), parts.next()) else { return Err(400) }; + let (method, path) = (method.to_string(), path.to_string()); + let mut headers = Vec::new(); + let mut size = line.len(); + loop { + let mut h = String::new(); + if reader.read_line(&mut h).map_err(|_| 400u16)? == 0 { + return Err(400); + } + size += h.len(); + if size > MAX_HEADERS { + return Err(431); + } + let h = h.trim_end_matches(['\r', '\n']); + if h.is_empty() { + break; + } + if let Some((k, v)) = h.split_once(':') { + headers.push((k.trim().to_string(), v.trim().to_string())); + } + } + let req = Request { method, path, headers, body: Vec::new() }; + if req.header("transfer-encoding").is_some() { + return Err(411); + } + let length = match req.header("content-length") { + Some(v) => v.parse::().map_err(|_| 400u16)?, + None => 0, + }; + if length > MAX_BODY { + return Err(413); + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).map_err(|_| 400u16)?; + Ok(Some(Request { body, ..req })) +} + +fn write_response(out: &mut impl Write, r: &Response) -> std::io::Result<()> { + let reason = match r.status { + 200 => "OK", + 202 => "Accepted", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 411 => "Length Required", + 413 => "Payload Too Large", + _ => "Error", + }; + let mut head = format!("HTTP/1.1 {} {reason}\r\nContent-Length: {}\r\n", r.status, r.body.len()); + if !r.body.is_empty() { + head.push_str("Content-Type: application/json\r\n"); + } + if r.status == 405 { + head.push_str("Allow: POST\r\n"); + } + head.push_str("\r\n"); + out.write_all(head.as_bytes())?; + out.write_all(&r.body)?; + out.flush() +} + +/// 128 random bits as hex, from the standard library's per-process random hash keys. +fn new_token() -> String { + let mut out = String::new(); + for i in 0..2u64 { + let mut h = RandomState::new().build_hasher(); + h.write_u64(i); + h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); + out.push_str(&format!("{:016x}", h.finish())); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(headers: &[(&str, &str)], body: &str) -> Request { + Request { + method: "POST".into(), + path: "/mcp".into(), + headers: headers.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + body: body.as_bytes().to_vec(), + } + } + + fn echo(msg: Value) -> Option { + msg.get("id").map(|id| json!({"jsonrpc": "2.0", "id": id, "result": {}})) + } + + #[test] + fn only_the_child_with_the_token_reaches_the_tools() { + let body = r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#; + let ok = respond(&request(&[("Host", "127.0.0.1:5"), ("Authorization", "Bearer secret")], body), "secret", &mut echo); + assert_eq!(ok.status, 200); + let none = respond(&request(&[("Host", "127.0.0.1:5")], body), "secret", &mut echo); + assert_eq!(none.status, 401); + let wrong = respond(&request(&[("Host", "127.0.0.1:5"), ("Authorization", "Bearer secreT")], body), "secret", &mut echo); + assert_eq!(wrong.status, 401); + let browser = respond( + &request(&[("Host", "127.0.0.1:5"), ("Origin", "https://x.test"), ("Authorization", "Bearer secret")], body), + "secret", + &mut echo, + ); + assert_eq!(browser.status, 403, "a page in a browser is refused even with the token"); + let rebound = respond(&request(&[("Host", "evil.test:5"), ("Authorization", "Bearer secret")], body), "secret", &mut echo); + assert_eq!(rebound.status, 403, "a rebound host name is refused"); + } + + #[test] + fn a_notification_is_accepted_without_a_body() { + let r = respond( + &request(&[("Host", "localhost:1"), ("Authorization", "Bearer t")], r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#), + "t", + &mut echo, + ); + assert_eq!(r.status, 202); + assert!(r.body.is_empty()); + } + + #[test] + fn a_request_is_read_with_its_body_and_the_next_one_waits() { + let raw = "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 2\r\n\r\n{}POST"; + let mut reader = BufReader::new(raw.as_bytes()); + let r = read_request(&mut reader).ok().flatten().expect("a request"); + assert_eq!(r.body, b"{}"); + assert!(read_request(&mut reader).is_err(), "a cut-off request is refused, not waited on forever"); + } + + #[test] + fn tokens_differ() { + assert_ne!(new_token(), new_token()); + assert_eq!(new_token().len(), 32); + } +} diff --git a/crates/agent/src/neutral.rs b/crates/agent/src/neutral.rs new file mode 100644 index 000000000..a9d3d46ed --- /dev/null +++ b/crates/agent/src/neutral.rs @@ -0,0 +1,183 @@ +//! The conversation in a provider-neutral shape: messages made of text, image, tool-call and +//! tool-result blocks. Each adapter translates these to its wire format, so switching provider +//! keeps the history. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// One image travelling with a message: base64 data and its media type. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Image { + pub mime: String, + pub data: String, +} + +/// A piece of a message. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum Block { + Text(String), + Image(Image), + /// The model asked for a tool. + ToolCall { + id: String, + name: String, + args: Value, + }, + /// What the tool returned, for the model to read on the next step. + ToolResult { + id: String, + name: String, + ok: bool, + text: String, + images: Vec, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Role { + User, + Assistant, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Message { + pub role: Role, + pub blocks: Vec, +} + +impl Message { + pub fn user_text(text: impl Into) -> Self { + Self { role: Role::User, blocks: vec![Block::Text(text.into())] } + } + + /// The message as plain text (`None` when it holds anything but text). + pub fn as_text(&self) -> Option { + let mut out = String::new(); + for block in &self.blocks { + match block { + Block::Text(t) => out.push_str(t), + _ => return None, + } + } + Some(out) + } +} + +/// The MCP tool definitions as OpenAI Chat Completions tools. +pub fn openai_tools(defs: &[Value]) -> Vec { + defs.iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?; + Some(json!({ + "type": "function", + "function": { + "name": name, + "description": d.get("description").and_then(Value::as_str).unwrap_or(""), + "parameters": d.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}})), + } + })) + }) + .collect() +} + +/// The MCP tool definitions as Anthropic Messages tools. +pub fn anthropic_tools(defs: &[Value]) -> Vec { + defs.iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?; + Some(json!({ + "name": name, + "description": d.get("description").and_then(Value::as_str).unwrap_or(""), + "input_schema": d.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}})), + })) + }) + .collect() +} + +/// One tool result from an MCP [`figcraft_mcp::ToolResult`]: its text and any images. +pub fn tool_output(result: &figcraft_mcp::ToolResult) -> (String, Vec) { + let mut text = String::new(); + let mut images = Vec::new(); + for c in &result.content { + match c.get("type").and_then(Value::as_str) { + Some("text") => { + let t = c.get("text").and_then(Value::as_str).unwrap_or(""); + if !text.is_empty() && !t.is_empty() { + text.push('\n'); + } + text.push_str(t); + } + Some("image") => { + let mime = c.get("mimeType").and_then(Value::as_str).unwrap_or("image/png"); + if let Some(data) = c.get("data").and_then(Value::as_str) { + images.push(Image { mime: mime.to_string(), data: data.to_string() }); + } + } + _ => {} + } + } + (text, images) +} + +/// Cut a tool's text to a size a model can take, keeping both ends: the start names what ran and +/// the end holds the error or the summary. +pub fn clip(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_string(); + } + let keep = max.saturating_div(2); + let mut start = keep; + while start > 0 && !text.is_char_boundary(start) { + start -= 1; + } + let mut end = text.len() - keep; + while end < text.len() && !text.is_char_boundary(end) { + end += 1; + } + format!("{}\n…[{} bytes left out]…\n{}", &text[..start], end - start, &text[end..]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tools_keep_their_schema_in_both_dialects() { + let defs = vec![json!({ + "name": "create_node", + "description": "Create a layer", + "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}}} + })]; + let o = openai_tools(&defs); + assert_eq!(o[0]["function"]["name"], "create_node"); + assert_eq!(o[0]["function"]["parameters"]["properties"]["type"]["type"], "string"); + let a = anthropic_tools(&defs); + assert_eq!(a[0]["name"], "create_node"); + assert_eq!(a[0]["input_schema"]["type"], "object"); + } + + #[test] + fn tool_output_separates_text_and_images() { + let r = figcraft_mcp::ToolResult { + content: vec![ + json!({"type": "text", "text": "hello"}), + json!({"type": "image", "mimeType": "image/png", "data": "AAAA"}), + json!({"type": "text", "text": "world"}), + ], + is_error: false, + }; + let (text, images) = tool_output(&r); + assert_eq!(text, "hello\nworld"); + assert_eq!(images.len(), 1); + assert_eq!(images[0].mime, "image/png"); + } + + #[test] + fn clipping_keeps_both_ends_and_stays_on_char_boundaries() { + let s = format!("start{}end", "é".repeat(100)); + let out = clip(&s, 40); + assert!(out.starts_with("start")); + assert!(out.ends_with("end")); + assert!(out.len() < s.len()); + } +} diff --git a/crates/agent/src/openai.rs b/crates/agent/src/openai.rs new file mode 100644 index 000000000..ab5d2933c --- /dev/null +++ b/crates/agent/src/openai.rs @@ -0,0 +1,277 @@ +//! The OpenAI Chat Completions dialect: most gateways speak it (OpenAI, OpenCode Zen/Go, +//! OpenRouter, DeepSeek, Ollama, LM Studio and custom endpoints). + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::sse::Sse; +use crate::{Invocation, Step, Usage}; + +/// The request body for one step of the conversation. +pub fn payload(provider: &Provider, system: &str, messages: &[Message], tools: &[Value]) -> Value { + let mut body = json!({ + "model": provider.model, + "messages": wire_messages(system, messages), + "stream": true, + "stream_options": {"include_usage": true}, + }); + if let Some(effort) = provider.reasoning.effort() { + body["reasoning_effort"] = json!(effort); + } + let tools = crate::neutral::openai_tools(tools); + if !tools.is_empty() { + body["tools"] = json!(tools); + body["tool_choice"] = json!("auto"); + } + body +} + +fn wire_messages(system: &str, messages: &[Message]) -> Vec { + let mut out = vec![json!({"role": "system", "content": system})]; + for m in messages { + match m.role { + Role::Assistant => { + let mut text = String::new(); + let mut calls = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => text.push_str(t), + Block::ToolCall { id, name, args } => calls.push(json!({ + "id": id, + "type": "function", + "function": {"name": name, "arguments": serde_json::to_string(args).unwrap_or_else(|_| "{}".into())}, + })), + _ => {} + } + } + let mut msg = json!({"role": "assistant", "content": if text.is_empty() { Value::Null } else { json!(text) }}); + if !calls.is_empty() { + msg["tool_calls"] = json!(calls); + } + out.push(msg); + } + Role::User => { + let mut content = Vec::new(); + // Images from tool results cannot ride in the `tool` role's text, so they follow + // in a user message (every compatible endpoint accepts that). + let mut tool_images = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => content.push(json!({"type": "text", "text": t})), + Block::Image(i) => content.push(json!({"type": "image_url", "image_url": {"url": data_url(i)}})), + Block::ToolResult { id, text, images, .. } => { + out.push(json!({"role": "tool", "tool_call_id": id, "content": text})); + tool_images.extend(images.iter().map(data_url)); + } + Block::ToolCall { .. } => {} + } + } + if !content.is_empty() { + out.push(json!({"role": "user", "content": content})); + } + if !tool_images.is_empty() { + let mut parts = vec![json!({"type": "text", "text": "Images from the tool results above:"})]; + for url in tool_images { + parts.push(json!({"type": "image_url", "image_url": {"url": url}})); + } + out.push(json!({"role": "user", "content": parts})); + } + } + } + } + out +} + +fn data_url(image: &crate::neutral::Image) -> String { + format!("data:{};base64,{}", image.mime, image.data) +} + +fn headers(provider: &Provider, session: &str) -> Vec<(&'static str, String)> { + let mut h = vec![("authorization", format!("Bearer {}", provider.api_key.trim())), ("accept", "text/event-stream".to_string())]; + // OpenCode Zen/Go asks for one stable id per conversation, to route it to the same upstream + // and keep its prompt cache warm. + if provider.base_url.contains("opencode.ai") { + h.push(("x-opencode-session", session.to_string())); + } + h +} + +/// Send the conversation and read the streamed answer into a [`Step`]. +pub fn stream( + http: &Http, + provider: &Provider, + system: &str, + messages: &[Message], + tools: &[Value], + session: &str, + on_text: &mut dyn FnMut(&str), + cancel: &AtomicBool, +) -> Result { + let reply = http.post(&provider.endpoint(), &headers(provider, session), &payload(provider, system, messages, tools))?; + if reply.status >= 400 { + return Err(read_error(reply.status, reply.body)); + } + let mut sse = Sse::new(reply.body); + let mut step = Step::default(); + // Tool calls arrive split across chunks: keyed by their `index`, their name once, their + // arguments as JSON text joined together. + let mut calls: BTreeMap = BTreeMap::new(); + while let Some(event) = sse.next_event()? { + if cancel.load(Ordering::Relaxed) { + return Err("stopped".to_string()); + } + let data = event.data.trim(); + if data.is_empty() { + continue; + } + if data == "[DONE]" { + break; + } + let v: Value = match serde_json::from_str(data) { + Ok(v) => v, + // An endpoint may send a keep-alive payload that is not JSON. + Err(_) => continue, + }; + if let Some(err) = v.get("error").filter(|e| !e.is_null()) { + let msg = err.get("message").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| err.to_string()); + return Err(msg); + } + if let Some(u) = v.get("usage").filter(|u| !u.is_null()) { + step.usage = Usage { + input: u.get("prompt_tokens").and_then(Value::as_u64).unwrap_or(step.usage.input), + output: u.get("completion_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output), + }; + } + let Some(choice) = v.get("choices").and_then(|c| c.get(0)) else { continue }; + if let Some(delta) = choice.get("delta") { + match delta.get("content") { + Some(Value::String(t)) => { + step.text.push_str(t); + on_text(t); + } + Some(Value::Array(parts)) => { + for part in parts { + if part.get("type").and_then(Value::as_str) == Some("text") + && let Some(t) = part.get("text").and_then(Value::as_str) + { + step.text.push_str(t); + on_text(t); + } + } + } + _ => {} + } + if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) { + for tc in list { + let index = tc.get("index").and_then(Value::as_u64).unwrap_or(0); + let entry = calls.entry(index).or_default(); + if let Some(id) = tc.get("id").and_then(Value::as_str) { + entry.0 = id.to_string(); + } + if let Some(name) = tc.get("function").and_then(|f| f.get("name")).and_then(Value::as_str) { + entry.1.push_str(name); + } + if let Some(args) = tc.get("function").and_then(|f| f.get("arguments")).and_then(Value::as_str) { + entry.2.push_str(args); + } + } + } + } + if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) { + step.stop = reason.to_string(); + } + } + for (i, (id, name, raw)) in calls { + if name.is_empty() { + continue; + } + let id = if id.is_empty() { format!("call_{i}") } else { id }; + step.calls.push(Invocation { id, name, args: parse_args(&raw), args_raw: raw }); + } + Ok(step) +} + +fn parse_args(raw: &str) -> Value { + if raw.trim().is_empty() { + return json!({}); + } + serde_json::from_str(raw).unwrap_or(Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ApiKind; + + fn provider() -> Provider { + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://opencode.ai/zen/go/v1"); + p.model = "deepseek-v4.1-flash".into(); + p.api_key = "sk-test".into(); + p + } + + #[test] + fn tool_calls_and_tool_results_use_the_compatible_shape() { + let mut messages = vec![Message::user_text("hi")]; + messages.push(Message { + role: Role::Assistant, + blocks: vec![ + Block::Text("looking".into()), + Block::ToolCall { id: "call_1".into(), name: "run_command".into(), args: json!({"command": "frame.create"}) }, + ], + }); + messages.push(Message { + role: Role::User, + blocks: vec![Block::ToolResult { id: "call_1".into(), name: "run_command".into(), ok: true, text: "{\"id\":3}".into(), images: vec![] }], + }); + let body = payload(&provider(), "system", &messages, &[]); + let wire = body["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(wire[0]["role"], "system"); + assert_eq!(wire[1]["content"][0]["text"], "hi"); + assert_eq!(wire[2]["tool_calls"][0]["function"]["name"], "run_command"); + assert_eq!(wire[3]["role"], "tool"); + assert_eq!(wire[3]["tool_call_id"], "call_1"); + } + + #[test] + fn an_image_comes_back_as_a_data_url_on_the_user_message() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::Text("what is this".into()), Block::Image(crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() })], + }]; + let body = payload(&provider(), "s", &messages, &[]); + let parts = body["messages"][1]["content"].as_array().cloned().unwrap_or_default(); + assert_eq!(parts[0]["type"], "text"); + assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAAA"); + } + + #[test] + fn reasoning_effort_is_sent_only_when_chosen() { + use crate::config::Reasoning; + let mut p = provider(); + let messages = vec![Message::user_text("hi")]; + assert!(payload(&p, "s", &messages, &[]).get("reasoning_effort").is_none(), "Auto leaves it to the endpoint"); + p.reasoning = Reasoning::High; + assert_eq!(payload(&p, "s", &messages, &[])["reasoning_effort"], "high"); + } + + #[test] + fn opencode_gets_a_stable_session_header() { + let h = headers(&provider(), "abc"); + assert!(h.iter().any(|(k, v)| *k == "x-opencode-session" && v == "abc")); + assert!(h.iter().any(|(k, v)| *k == "authorization" && v == "Bearer sk-test")); + } + + #[test] + fn arguments_that_do_not_parse_stay_null_for_the_loop_to_report() { + let mut calls: BTreeMap = BTreeMap::new(); + calls.insert(0, ("id".into(), "run_command".into(), "{broken".into())); + let (_, _, raw) = calls.remove(&0).unwrap_or_default(); + assert!(parse_args(&raw).is_null()); + } +} diff --git a/crates/agent/src/session.rs b/crates/agent/src/session.rs new file mode 100644 index 000000000..e02e218db --- /dev/null +++ b/crates/agent/src/session.rs @@ -0,0 +1,647 @@ +//! The agent loop: send the conversation, stream the answer, run the tools the model asks for on +//! the open window, feed the results back, and repeat until it stops asking for tools. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::Sender; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::config::{ApiKind, Permission, Provider}; +use crate::http::Http; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step, Usage}; + +/// How many model steps one request may take before the loop stops (each step may run tools). +const MAX_STEPS: usize = 60; +/// Characters of conversation kept before the oldest tool output is shortened, per the model's +/// context window (about three characters a token, with room for the answer). +const CHARS_PER_TOKEN: usize = 3; +/// Tool output longer than this is clipped before the model sees it. +const TOOL_TEXT_MAX: usize = 60_000; +/// The name every command runs as in the app (its avatar, its comment signature). +pub const AGENT_NAME: &str = "FigCraft Agent"; +/// What the agent is told when it is handed the canvas to check its own work. +const REVIEW_PROMPT: &str = "Automatic self-review: the canvas after your changes is attached. \ +Compare it with what the user asked for. Fix anything wrong with the tools (overlap, clipping, \ +spacing, hierarchy, contrast, text that does not fit). If it looks right, reply to the user in one \ +or two sentences; do not take another screenshot for review. +"; + +/// What the worker tells the panel while a request runs. +pub enum ChatEvent { + /// Streamed answer text. + Text(String), + /// A tool call started. + ToolStart { id: String, name: String, args: Value }, + /// A tool call finished (`text` is a short summary for the card). + ToolEnd { id: String, name: String, ok: bool, title: String, text: String }, + /// The agent wants to do something outside the canvas; `reply` takes the person's answer. + Permission { id: String, name: String, args: Value, reason: String, reply: Sender }, + /// Tokens used so far. + Usage(Usage), + /// The request failed (network, provider, a bad answer). + Error(String), + /// The request is over. `stopped`: the person pressed Stop. + Done { stopped: bool }, +} + +/// An agent bound to one window, with the conversation it has had so far. +pub struct Agent { + pub provider: Provider, + pub messages: Vec, + http: Http, + backend: crate::bridge::Remote, + system: String, + tools: Vec, + session: String, + usage: Usage, + /// 0: ask before file and network tools, 1: auto. Shared with the panel's toggle, so changing + /// it mid-request applies to the next tool call. + pub permission: Arc, + /// Whether a turn that changed the canvas ends with the agent looking at it once. + pub review: Arc, + did_edit: bool, + reviewed: bool, + /// The panel's event stream, for tool calls a command-line agent makes over MCP (they arrive + /// on another thread, outside [`run_turn`](Self::run_turn)'s `out`). + pub sink: Option>, + /// Where a command-line agent runs (beside the saved chats); a temporary folder without one. + pub workdir: Option, + /// The command-line agent's conversation to resume, and which program it belongs to. + cli_session: Option<(ApiKind, String)>, + /// FigCraft's tools served to a command-line agent, started on its first turn. + endpoint: Option, +} + +impl Agent { + pub fn new(provider: Provider, backend: crate::bridge::Remote) -> Self { + let tools = figcraft_mcp::tool_definitions(); + let session = format!("figcraft-{}", now_id()); + Self { + provider, + messages: Vec::new(), + http: Http::new(), + backend, + system: system_prompt(), + tools, + session, + usage: Usage::default(), + permission: Arc::new(AtomicU8::new(0)), + review: Arc::new(AtomicBool::new(true)), + did_edit: false, + reviewed: false, + sink: None, + workdir: None, + cli_session: None, + endpoint: None, + } + } + + /// Switch the model or the connection. A command-line agent's conversation lives in that + /// program, so moving to another one starts a new conversation there. + pub fn set_provider(&mut self, provider: Provider) { + if self.cli_session.as_ref().is_some_and(|(kind, _)| *kind != provider.kind) { + self.cli_session = None; + } + self.provider = provider; + } + + /// The permission the panel's toggle holds now. + fn permission(&self) -> Permission { + if self.permission.load(Ordering::Relaxed) == 1 { Permission::Auto } else { Permission::AskFiles } + } + + pub fn usage(&self) -> Usage { + self.usage + } + + /// Forget the conversation (a new chat), keeping the provider and tools. + pub fn clear(&mut self) { + self.messages.clear(); + self.usage = Usage::default(); + self.cli_session = None; + } + + /// Run one request to completion. Reports everything through `out`; returns the error the + /// panel shows as a failed turn (the loop's own stops are not errors). + pub fn run_turn(&mut self, text: &str, context: Option, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result<(), String> { + self.run_turn_with(text, context, Vec::new(), out, cancel) + } + + /// [`run_turn`](Self::run_turn) with images the person attached. + pub fn run_turn_with( + &mut self, + text: &str, + context: Option, + images: Vec, + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result<(), String> { + let mut prompt = String::new(); + if let Some(c) = context.filter(|c| !c.trim().is_empty()) { + prompt.push_str(&c); + prompt.push_str("\n\n"); + } + prompt.push_str(text); + if self.provider.kind.is_cli() { + return self.run_cli_turn(&prompt, &images, out, cancel); + } + let mut message = Message::user_text(prompt); + // A model that reads no images is told what was left out rather than failing the request. + if self.provider.vision { + message.blocks.extend(images.into_iter().map(Block::Image)); + } else if !images.is_empty() { + message.blocks.push(Block::Text(format!("[{} attached image(s) left out: this model does not read images]", images.len()))); + } + self.messages.push(message); + self.did_edit = false; + self.reviewed = false; + self.trim(); + + for _step in 0..MAX_STEPS { + if cancel.load(Ordering::Relaxed) { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + let step = match self.stream(out, cancel) { + Ok(step) => step, + Err(e) if e == "stopped" => { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + Err(e) => return Err(e), + }; + if !step.text.trim().is_empty() { + // The panel already has the streamed text; nothing more to add here. + } + let mut blocks = Vec::new(); + if !step.text.is_empty() { + blocks.push(Block::Text(step.text.clone())); + } + for call in &step.calls { + blocks.push(Block::ToolCall { id: call.id.clone(), name: call.name.clone(), args: call.args.clone() }); + } + if !blocks.is_empty() { + self.messages.push(Message { role: Role::Assistant, blocks }); + } + if step.calls.is_empty() { + // One look at the canvas after a turn that changed it, when the model can see. + if self.review.load(Ordering::Relaxed) && self.provider.vision && self.did_edit && !self.reviewed { + self.reviewed = true; + if self.review_once(out, cancel) { + continue; + } + } + out(ChatEvent::Usage(self.usage)); + out(ChatEvent::Done { stopped: false }); + return Ok(()); + } + let mut results = Vec::new(); + for call in step.calls { + if cancel.load(Ordering::Relaxed) { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + let outcome = self.run_tool(call, out, cancel); + results.push(outcome); + } + self.messages.push(Message { role: Role::User, blocks: results }); + self.trim(); + } + out(ChatEvent::Done { stopped: false }); + Err(format!("the agent stopped after {MAX_STEPS} steps without finishing; ask it to continue")) + } + + /// One turn through an installed command-line agent: it runs its own loop and calls + /// FigCraft's tools over MCP; the tool cards reach the panel from the MCP side. + fn run_cli_turn( + &mut self, + prompt: &str, + images: &[crate::neutral::Image], + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result<(), String> { + let kind = self.provider.kind; + let program = crate::cli::locate(kind) + .ok_or_else(|| format!("{} is not installed on this computer; install it or pick another connection", kind.label()))?; + if self.endpoint.is_none() { + let sink = self.sink.clone().ok_or_else(|| "the agent has no panel to report to".to_string())?; + let gate = crate::mcp_http::Gate { permission: self.permission.clone(), sink, cancel: cancel.clone() }; + let endpoint = crate::mcp_http::start(self.backend.clone(), gate).map_err(|e| format!("can't serve FigCraft's tools: {e}"))?; + self.endpoint = Some(endpoint); + } + let endpoint = self.endpoint.as_ref().ok_or_else(|| "can't serve FigCraft's tools".to_string())?; + let workdir = self.workdir.clone().unwrap_or_else(|| std::env::temp_dir().join("figcraft-agent")); + let session = self.cli_session.as_ref().filter(|(k, _)| *k == kind).map(|(_, s)| s.clone()); + let system = app_rules(); + let turn = crate::cli::Turn { + kind, + program: &program, + model: &self.provider.model, + session: session.as_deref(), + prompt, + system: &system, + mcp_url: &endpoint.url, + mcp_token: &endpoint.token, + workdir: &workdir, + images, + }; + let mut on_text = |t: &str| out(ChatEvent::Text(t.to_string())); + let outcome = crate::cli::run(&turn, &mut on_text, cancel); + if let Some(s) = outcome.session { + self.cli_session = Some((kind, s)); + } + self.usage.input = self.usage.input.saturating_add(outcome.usage.input); + self.usage.output = self.usage.output.saturating_add(outcome.usage.output); + out(ChatEvent::Usage(self.usage)); + if outcome.stopped { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + if let Some(e) = outcome.error { + return Err(e); + } + out(ChatEvent::Done { stopped: false }); + Ok(()) + } + + fn stream(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result { + let mut on_text = |t: &str| { + out(ChatEvent::Text(t.to_string())); + }; + let result = match self.provider.kind { + ApiKind::OpenAiCompletions => { + crate::openai::stream(&self.http, &self.provider, &self.system, &self.messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::AnthropicMessages => { + crate::anthropic::stream(&self.http, &self.provider, &self.system, &self.messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode => Err("a command-line agent runs its own loop".to_string()), + }; + if let Ok(step) = &result { + self.usage.input = self.usage.input.saturating_add(step.usage.input); + self.usage.output = self.usage.output.saturating_add(step.usage.output); + out(ChatEvent::Usage(self.usage)); + } + result + } + + fn run_tool(&mut self, call: Invocation, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Block { + out(ChatEvent::ToolStart { id: call.id.clone(), name: call.name.clone(), args: call.args.clone() }); + let denied = |reason: String| Block::ToolResult { + id: call.id.clone(), + name: call.name.clone(), + ok: false, + text: format!("Not run: {reason}"), + images: vec![], + }; + if call.args.is_null() { + return denied("the model sent arguments that are not valid JSON; try again".into()); + } + if let Some(reason) = approval(&call.name, &call.args) + && self.permission() == Permission::AskFiles + { + let (tx, rx) = std::sync::mpsc::channel(); + out(ChatEvent::Permission { id: call.id.clone(), name: call.name.clone(), args: call.args.clone(), reason: reason.clone(), reply: tx }); + let allowed = rx.recv_timeout(std::time::Duration::from_secs(600)).unwrap_or(false); + if !allowed { + let result = denied(format!("the user denied this action ({reason})")); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok: false, + title: call.name.clone(), + text: "Denied by the user".into(), + }); + return result; + } + } + if cancel.load(Ordering::Relaxed) { + return denied("the user stopped the agent".into()); + } + let result = figcraft_mcp::call_tool(&mut self.backend, &call.name, &call.args); + if !result.is_error && mutating(&call.name, &call.args) { + self.did_edit = true; + } + let (text, mut images) = crate::neutral::tool_output(&result); + // A model that does not read images gets the text alone: sending one would fail the + // whole request (some endpoints reject it). + if !self.provider.vision { + images.clear(); + } + let text = crate::neutral::clip(&text, TOOL_TEXT_MAX); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok: !result.is_error, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + Block::ToolResult { id: call.id, name: call.name, ok: !result.is_error, text, images } + } + + /// Capture the page and hand it back to the model for one review pass. `true` when the image + /// is now in the conversation (the loop continues); `false` when there is nothing to see. + fn review_once(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> bool { + if cancel.load(Ordering::Relaxed) { + return false; + } + let id = "self-review".to_string(); + out(ChatEvent::ToolStart { id: id.clone(), name: "screenshot".into(), args: json!({}) }); + let result = figcraft_mcp::call_tool(&mut self.backend, "screenshot", &json!({})); + let (text, images) = crate::neutral::tool_output(&result); + let image = images.into_iter().next(); + out(ChatEvent::ToolEnd { + id, + name: "screenshot".into(), + ok: image.is_some() && !result.is_error, + title: "screenshot".into(), + text: if image.is_some() { "Looking at the canvas".into() } else { crate::neutral::clip(&text, 200) }, + }); + match image { + Some(image) => { + self.messages.push(Message { role: Role::User, blocks: vec![Block::Text(REVIEW_PROMPT.into()), Block::Image(image)] }); + true + } + None => false, + } + } + + /// Save the model's conversation beside the document's chat. + pub fn save_history(&self, path: &Path) -> Result<(), String> { + let (cli_kind, cli_session) = match &self.cli_session { + Some((k, s)) => (Some(*k), Some(s.clone())), + None => (None, None), + }; + let file = ContextFile { version: 1, messages: self.messages.clone(), usage: self.usage, cli_kind, cli_session }; + let bytes = serde_json::to_vec(&file).map_err(|e| format!("can't encode the conversation: {e}"))?; + crate::config::write_private(path, &bytes) + } + + /// Read back a conversation saved by [`save_history`](Self::save_history). + pub fn load_history(&mut self, path: &Path) -> Result<(), String> { + let bytes = std::fs::read(path).map_err(|e| format!("can't read {}: {e}", path.display()))?; + let file: ContextFile = serde_json::from_slice(&bytes).map_err(|e| format!("{} is damaged: {e}", path.display()))?; + if file.version != 1 { + return Err(format!("{} was saved by another version", path.display())); + } + self.messages = file.messages; + self.usage = file.usage; + self.cli_session = file.cli_kind.zip(file.cli_session); + self.trim(); + Ok(()) + } + + /// Shorten the oldest tool output when the conversation grows past what the model's context + /// window takes, so a long session keeps its shape without resending megabytes. + fn trim(&mut self) { + let budget = (self.provider.context_window as usize).saturating_mul(CHARS_PER_TOKEN).saturating_sub(24_000).clamp(60_000, 800_000); + trim_messages(&mut self.messages, budget); + } +} + +/// Shorten the oldest tool output until the conversation fits `budget`, keeping the last eight +/// messages whole: the recent steps are what the model is working from. +fn trim_messages(messages: &mut [Message], budget: usize) { + let mut total: usize = messages.iter().map(message_chars).sum(); + let mut i = 0; + while total > budget && i + 8 < messages.len() { + let before = message_chars(&messages[i]); + for block in &mut messages[i].blocks { + if let Block::ToolResult { text, images, .. } = block + && text.len() > 200 + { + *text = "[older tool output left out]".to_string(); + images.clear(); + } + } + let after = message_chars(&messages[i]); + total = total.saturating_sub(before.saturating_sub(after)); + i += 1; + } +} + +#[derive(Serialize, Deserialize)] +struct ContextFile { + version: u32, + messages: Vec, + usage: Usage, + /// A command-line agent's conversation id, resumed on the next turn. + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_session: Option, +} + +/// Whether a tool call can change what the canvas looks like (so a look at it is worth a review). +fn mutating(name: &str, args: &Value) -> bool { + match name { + "create_node" | "set_properties" | "batch" | "undo" | "redo" => true, + "run_command" => { + let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); + !(cmd.starts_with("inspect.") + || cmd.starts_with("variable.list") + || cmd.starts_with("style.list") + || cmd == "design.audit" + || cmd == "design.assert" + || cmd == "design.rules" + || cmd == "node.find" + || cmd == "comment.list" + || cmd == "text.fonts" + || cmd == "text.missingFonts" + || cmd == "image.presets" + || cmd == "list_commands") + } + _ => false, + } +} + +fn message_chars(m: &Message) -> usize { + m.blocks + .iter() + .map(|b| match b { + Block::Text(t) => t.len(), + Block::Image(i) => i.data.len(), + Block::ToolCall { name, args, .. } => name.len() + args.to_string().len(), + Block::ToolResult { text, images, .. } => text.len() + images.iter().map(|i| i.data.len()).sum::(), + }) + .sum() +} + +pub(crate) fn summarize(text: &str) -> String { + let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim(); + let mut s: String = first.chars().take(160).collect(); + if first.chars().count() > 160 { + s.push('…'); + } + s +} + +/// The card's title: the tool's own name plus what it acted on. +pub(crate) fn tool_title(name: &str, args: &Value) -> String { + if name == "run_command" + && let Some(cmd) = args.get("command").and_then(Value::as_str) + { + return cmd.to_string(); + } + name.to_string() +} + +/// Why a tool needs the person's Allow, or `None` when it only changes the canvas. +/// +/// Canvas edits (layers, styles, variables, components, layout, selection, undo) run at once; a +/// tool that reads or writes a file, joins a server, installs a plugin or downloads a font asks. +pub fn approval(tool: &str, args: &Value) -> Option { + match tool { + "open_file" => Some("reads a file".into()), + "save_file" => Some("writes the document to a file".into()), + "export" => Some("writes an export to a file".into()), + "export_assets" => Some("writes assets into a project folder".into()), + "sync_mappings" => Some("reads or writes figcraft.connect.json".into()), + "compare_design" => Some("reads a capture from disk".into()), + "component_mappings" => Some("reads a code project".into()), + "run_command" => { + let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); + command_reason(cmd) + } + _ => None, + } +} + +fn command_reason(cmd: &str) -> Option { + let file = [ + "file.open", + "file.save", + "file.saveAs", + "file.export", + "file.import", + "file.revert", + "file.recover", + "file.placeImage", + "file.exportSvg", + "file.exportLayers", + "file.exportFramesPdf", + "file.openRecent", + ]; + if file.iter().any(|p| cmd.starts_with(p)) { + return Some("reads or writes a file".into()); + } + if cmd.starts_with("collab.") { + return Some("reaches a collaboration server".into()); + } + if cmd.starts_with("plugin.") || cmd.starts_with("library.") { + return Some("installs or reaches a plugin or library server".into()); + } + if cmd.starts_with("font.download") { + return Some("downloads a font".into()); + } + if cmd.starts_with("variable.import") || cmd.starts_with("variable.export") || cmd.starts_with("codeConnect.") { + return Some("reads or writes a file".into()); + } + if cmd == "image.place" || cmd == "image.replace" { + return Some("reads an image file".into()); + } + None +} + +/// The instructions an in-app agent gets: the MCP conventions the external clients get, plus how +/// this one is expected to behave in front of the person. +pub fn system_prompt() -> String { + format!("{}\n\n---\n{}", figcraft_mcp::INSTRUCTIONS, app_rules()) +} + +/// How the in-app agent behaves in front of the person. A command-line agent gets these alone: +/// FigCraft's tool conventions reach it through the MCP server's own instructions. +pub fn app_rules() -> String { + "You are the FigCraft agent, running inside the window the user has open. \ +They see every change on the canvas as you make it.\n\ +- Work in small steps and verify with `screenshot` (or `design_context`) before claiming a screen is done.\n\ +- The user's current selection is given with each request; change that unless they name something else.\n\ +- Prefer auto layout, components and variables over absolutely placed copies.\n\ +- Keep the reply short: say what you changed and which frames it touched. Do not describe the tool calls one by one.\n\ +- If a tool is denied or fails, say so plainly and continue with what you can do." + .to_string() +} + +fn now_id() -> u128 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn canvas_edits_need_no_approval_but_files_do() { + assert!(approval("create_node", &json!({})).is_none()); + assert!(approval("set_properties", &json!({})).is_none()); + assert!(approval("run_command", &json!({"command": "node.set"})).is_none()); + assert!(approval("run_command", &json!({"command": "file.save"})).is_some()); + assert!(approval("run_command", &json!({"command": "collab.host"})).is_some()); + assert!(approval("save_file", &json!({})).is_some()); + assert!(approval("screenshot", &json!({})).is_none()); + } + + #[test] + fn trimming_shortens_the_oldest_output_and_keeps_the_last_steps_whole() { + let mut messages: Vec = (0..40) + .map(|_| Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "t".into(), + name: "inspect_document".into(), + ok: true, + text: "x".repeat(5_000), + images: vec![], + }], + }) + .collect(); + let before: usize = messages.iter().map(message_chars).sum(); + let budget = 60_000; + assert!(before > budget); + trim_messages(&mut messages, budget); + let after: usize = messages.iter().map(message_chars).sum(); + assert!(after <= budget, "fits the budget"); + assert_eq!(messages.len(), 40, "messages stay, their bulk goes"); + match &messages[0].blocks[0] { + Block::ToolResult { text, .. } => assert_eq!(text, "[older tool output left out]"), + _ => panic!("a tool result"), + } + match &messages[39].blocks[0] { + Block::ToolResult { text, .. } => assert_eq!(text.len(), 5_000, "the newest step is untouched"), + _ => panic!("a tool result"), + } + } + + #[test] + fn the_conversation_round_trips_through_its_file() { + let dir = std::env::temp_dir().join(format!("figcraft-conv-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("dir"); + let path = dir.join("chat.context.json"); + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://example.test/v1"); + p.model = "m".into(); + let (bridge, remote) = crate::bridge::pair("Test", Arc::new(|| {})); + drop(bridge); + let mut agent = Agent::new(p.clone(), remote); + agent.messages.push(Message::user_text("hello")); + agent.usage.input = 12; + agent.save_history(&path).expect("saved"); + let (bridge, remote) = crate::bridge::pair("Test", Arc::new(|| {})); + drop(bridge); + let mut back = Agent::new(p, remote); + back.load_history(&path).expect("loaded"); + assert_eq!(back.messages.len(), 1); + assert_eq!(back.usage.input, 12); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_card_title_names_the_command() { + assert_eq!(tool_title("run_command", &json!({"command": "frame.create"})), "frame.create"); + assert_eq!(tool_title("screenshot", &json!({})), "screenshot"); + } +} diff --git a/crates/agent/src/sse.rs b/crates/agent/src/sse.rs new file mode 100644 index 000000000..0f76b5d8c --- /dev/null +++ b/crates/agent/src/sse.rs @@ -0,0 +1,86 @@ +//! A Server-Sent Events reader: the provider streams one JSON object per `data:` line, ended by a +//! blank line. Hand-written because the crate has no async runtime. + +use std::io::BufRead; + +/// One event: its `event:` name when the stream set one, and its joined `data:` lines. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Event { + pub name: String, + pub data: String, +} + +pub struct Sse { + reader: R, +} + +impl Sse { + pub fn new(reader: R) -> Self { + Self { reader } + } + + /// The next event, `None` at the end of the stream. + pub fn next_event(&mut self) -> Result, String> { + let mut name = String::new(); + let mut data: Vec = Vec::new(); + loop { + let mut line = String::new(); + let read = self.reader.read_line(&mut line).map_err(|e| format!("reading the stream failed: {e}"))?; + if read == 0 { + return Ok(if data.is_empty() && name.is_empty() { None } else { Some(Event { name, data: data.join("\n") }) }); + } + let line = line.trim_end_matches(['\n', '\r']); + if line.is_empty() { + if data.is_empty() && name.is_empty() { + continue; + } + return Ok(Some(Event { name, data: data.join("\n") })); + } + if let Some(rest) = line.strip_prefix(':') { + let _ = rest; + continue; + } + if let Some(rest) = line.strip_prefix("event:") { + name = rest.trim().to_string(); + } else if let Some(rest) = line.strip_prefix("data:") { + data.push(rest.strip_prefix(' ').unwrap_or(rest).to_string()); + } + // Other fields (`id:`, `retry:`) are not used by either dialect. + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn events_join_data_lines_and_keep_their_name() { + let stream = "event: text\ndata: {\"a\":1}\ndata: {\"b\":2}\n\ndata: [DONE]\n\n"; + let mut sse = Sse::new(Cursor::new(stream.as_bytes())); + let first = sse.next_event().expect("read").expect("one event"); + assert_eq!(first.name, "text"); + assert_eq!(first.data, "{\"a\":1}\n{\"b\":2}"); + let second = sse.next_event().expect("read").expect("another"); + assert_eq!(second.name, ""); + assert_eq!(second.data, "[DONE]"); + assert!(sse.next_event().expect("read").is_none()); + } + + #[test] + fn comments_and_windows_newlines_are_tolerated() { + let stream = ": keep-alive\r\n\r\ndata: hi\r\n\r\n"; + let mut sse = Sse::new(Cursor::new(stream.as_bytes())); + let e = sse.next_event().expect("read").expect("one event"); + assert_eq!(e.data, "hi"); + } + + #[test] + fn an_unterminated_last_event_is_still_delivered() { + let mut sse = Sse::new(Cursor::new(b"data: last".as_slice())); + let e = sse.next_event().expect("read").expect("one event"); + assert_eq!(e.data, "last"); + assert!(sse.next_event().expect("read").is_none()); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 2123edaec..6ad904808 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -52,3 +52,6 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-update = { workspace = true } +# The in-app agent: HTTP providers and a worker thread, so desktop only (the browser build shows +# the panel's setup card through the stub in `panels/layers.rs`). +figcraft-agent = { workspace = true } diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 38998ba1f..8931d2ea2 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -12,7 +12,9 @@ name = "English" "(no longer published)" = "(no longer published)" "({n} warnings: some entries were skipped)" = { one = "({n} warning: some entries were skipped)", other = "({n} warnings: some entries were skipped)" } "+ Create variable" = "+ Create variable" +"+{count} more" = "+{count} more" ".fig (experimental)" = ".fig (experimental)" +"1 step" = "1 step" "1 year" = "1 year" "1…9, 0" = "1…9, 0" "30 days" = "30 days" @@ -78,8 +80,97 @@ name = "English" "Add stroke" = "Add stroke" "Add variant" = "Add variant" "Add variant with a new value" = "Add variant with a new value" +"Agent quick actions" = "Agent quick actions" +"Allow" = "Allow" +"API key" = "API key" +"Ask" = "Ask" +"Ask agent…" = "Ask agent…" +"At most {count} images go with one request." = "At most {count} images go with one request." +"Attach" = "Attach" +"Attach an image or the selection. You can also drop an image on this panel." = "Attach an image or the selection. You can also drop an image on this panel." +"Attach the selection as an image" = "Attach the selection as an image" +"Attached image {name}" = "Attached image {name}" +"Can't attach {name}: {error}" = "Can't attach {name}: {error}" +"Can't reach the provider. Check the internet connection and try again." = "Can't reach the provider. Check the internet connection and try again." +"Can't read {name}: {error}" = "Can't read {name}: {error}" +"Can't render the selection: {error}" = "Can't render the selection: {error}" +"Chat history" = "Chat history" +"Check again" = "Check again" +"Check contrast and accessibility, then fix what fails" = "Check contrast and accessibility, then fix what fails" +"Check the connection" = "Check the connection" +"Check the selection for spacing and contrast problems" = "Check the selection for spacing and contrast problems" +"Checking…" = "Checking…" +"Choose a model first." = "Choose a model first." +"Choose how the agent reaches an AI model. It takes one step." = "Choose how the agent reaches an AI model. It takes one step." +"Connect" = "Connect" +"Connect a model" = "Connect a model" +"Connect a model first." = "Connect a model first." +"Connect a model to start" = "Connect a model to start" +"Connected, but the provider listed no chat model. Pick one under Advanced." = "Connected, but the provider listed no chat model. Pick one under Advanced." +"Connections" = "Connections" +"Copy this answer" = "Copy this answer" +"Default model" = "Default model" +"Delete this chat" = "Delete this chat" +"Deny" = "Deny" +"Describe what to design…" = "Describe what to design…" +"Design a sign-in screen for a mobile app" = "Design a sign-in screen for a mobile app" +"Dropped image" = "Dropped image" "Edit property" = "Edit property" +"Endpoint" = "Endpoint" +"Everything runs without asking" = "Everything runs without asking" +"Files and network ask first" = "Files and network ask first" +"Get a key" = "Get a key" +"How many versions of the design to build" = "How many versions of the design to build" +"In $/1M" = "In $/1M" +"In use" = "In use" +"Installed, not signed in. Sign in with:" = "Installed, not signed in. Sign in with:" +"Layer {name}: select it" = "Layer {name}: select it" +"Leave {name} out of the request" = "Leave {name} out of the request" +"Look at the canvas after each change" = "Look at the canvas after each change" +"Make a pricing section with three plans" = "Make a pricing section with three plans" +"Make three variations of this" = "Make three variations of this" +"Manage connections…" = "Manage connections…" +"Model: {model}" = "Model: {model}" +"New chat" = "New chat" +"No earlier chats for this file" = "No earlier chats for this file" +"Not installed. Install it with:" = "Not installed. Install it with:" +"Nothing answered at this address. Is the local model server running?" = "Nothing answered at this address. Is the local model server running?" +"Out $/1M" = "Out $/1M" +"Paste a key and FigCraft picks a model for you. Keys stay in this app's settings, readable only by you." = "Paste a key and FigCraft picks a model for you. Keys stay in this app's settings, readable only by you." +"Paste image from clipboard" = "Paste image from clipboard" +"Paste your API key first." = "Paste your API key first." +"Pasted image {n}" = "Pasted image {n}" "Preferred components" = "Preferred components" +"Price per million tokens (for the cost estimate)" = "Price per million tokens (for the cost estimate)" +"Put this request back in the box to change it" = "Put this request back in the box to change it" +"Queued" = "Queued" +"Reasoning" = "Reasoning" +"Refresh the model list" = "Refresh the model list" +"Remove image {name}" = "Remove image {name}" +"Remove queued request: {text}" = "Remove queued request: {text}" +"Remove {name}" = "Remove {name}" +"Run everything without asking" = "Run everything without asking" +"Running {tool}" = "Running {tool}" +"Select this layer on the canvas" = "Select this layer on the canvas" +"Send" = "Send" +"Sign in once in the program itself; FigCraft uses that sign-in and never sees it." = "Sign in once in the program itself; FigCraft uses that sign-in and never sees it." +"Something went wrong" = "Something went wrong" +"Stopped." = "Stopped." +"The agent is working on the canvas" = "The agent is working on the canvas" +"The agent stopped unexpectedly." = "The agent stopped unexpectedly." +"The agent wants to: {reason}" = "The agent wants to: {reason}" +"The agent works on this canvas: describe a screen, or select layers and ask for a change." = "The agent works on this canvas: describe a screen, or select layers and ask for a change." +"The clipboard holds no image." = "The clipboard holds no image." +"The model reads images" = "The model reads images" +"The provider refused this key. Check that it is copied whole and still active." = "The provider refused this key. Check that it is copied whole and still active." +"Tidy up the spacing and alignment" = "Tidy up the spacing and alignment" +"Turn the selection into a component with variants" = "Turn the selection into a component with variants" +"Turn this into a component with variants" = "Turn this into a component with variants" +"Undid this turn's changes." = "Undid this turn's changes." +"Undo every change the agent made in its last answer" = "Undo every change the agent made in its last answer" +"Undo this turn" = "Undo this turn" +"Use a subscription" = "Use a subscription" +"Use an API key" = "Use an API key" "Values" = "Values" "Added" = "Added" "Added the library \"{name}\"" = "Added the library \"{name}\"" @@ -414,6 +505,14 @@ name = "English" "In code" = "In code" "Source file" = "Source file" "Variant value" = "Variant value" +"Versions: {count}" = "Versions: {count}" +"What should we design?" = "What should we design?" +"Working…" = "Working…" +"{count} steps" = "{count} steps" +"{count} steps, {failed} failed" = "{count} steps, {failed} failed" +"{input} in · {output} out" = "{input} in · {output} out" +"{name} is not an image this app reads: {error}" = "{name} is not an image this app reads: {error}" +"≈ ${cost} at API rates" = "≈ ${cost} at API rates" "⌘ click a padding field" = "⌘ click a padding field" "Ctrl+scroll" = "Ctrl+scroll" "Current name" = "Current name" @@ -2102,7 +2201,6 @@ name = "English" "Space" = "Space" "Nothing to pick: the page is empty" = "Nothing to pick: the page is empty" "Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" - "Retry with higher import limits?" = "Retry with higher import limits?" "Some layers were left out. Retrying opens a new tab and keeps the partial copy." = "Some layers were left out. Retrying opens a new tab and keeps the partial copy." "This file reached the import limit before it could open." = "This file reached the import limit before it could open." diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d6c9d490a..f26a1828d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -41,6 +41,8 @@ impl FigApp { field_focus: false, panels_unsaved: false, control_queue: Vec::new(), + #[cfg(not(target_arch = "wasm32"))] + chat: crate::chat::Chat::default(), control_waits: Default::default(), control_input: Vec::new(), frame_stats: frame_stats::FrameStats::default(), @@ -214,6 +216,19 @@ impl FigApp { // target/caret. Outgoing IME receipts run after mutation and cannot authorize it. let ime_input = shortcuts::ImeInputBaseline::capture(self); let t = theme::Tokens::get(&ctx); + // The agent's settings are read once, before the first frame lays out the panels: a + // window last left on the Agent tab opens on it. + #[cfg(not(target_arch = "wasm32"))] + if !self.chat.is_loaded() { + let path = self.services.agent_config_path(); + self.chat.ensure_loaded(path); + if self.chat.agents.panel { + self.ui.left_tab = LeftTab::Agent; + self.ui.left_collapsed = false; + } + } + #[cfg(not(target_arch = "wasm32"))] + crate::chat::shortcut(self, &ctx); // A field that had the keyboard when the frame began keeps its keys from the shortcuts // even if it lets go during the frame (Enter commits it), or as it began (egui drops the // focus on Escape before the frame, which cancels the field's edit and nothing else). @@ -345,6 +360,7 @@ impl FigApp { _ if self.ui.versions.open => i18n::tr("Version history"), LeftTab::File => i18n::tr("Layers"), LeftTab::Assets => i18n::tr("Assets"), + LeftTab::Agent => i18n::tr("Agent"), }; a11y::region(&mut self.ui.nav, ui, a11y::Region::Layers, egui::accesskit::Role::Pane, label); layers::left_panel(self, ui) diff --git a/crates/ui-egui/src/chat.rs b/crates/ui-egui/src/chat.rs new file mode 100644 index 000000000..057ca5590 --- /dev/null +++ b/crates/ui-egui/src/chat.rs @@ -0,0 +1,2371 @@ +//! The Agent tab: the conversation with the agent, filling the left panel. +//! +//! The panel owns the worker thread ([`figcraft_agent::Worker`]); every tool call the model asks +//! for goes to the UI thread through the bridge ([`Chat::take_bridge_calls`]) and runs like a +//! control request, so the agent and an external MCP client behave the same. +//! +//! Connecting is one step: pick a subscription the person already signed in to in its own tool +//! (Claude Code, Codex, OpenCode), or paste an API key; the model list and a sensible model come +//! from the provider. Endpoints, limits and prices stay under Advanced. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; + +use egui::{Align, CornerRadius, Layout, Margin, RichText, Sense, Stroke, Ui, pos2, vec2}; +use figcraft_agent::bridge::{self, Bridge}; +use figcraft_agent::cli::Status as CliStatus; +use figcraft_agent::config::Reasoning; +use figcraft_agent::{AGENT_NAME, AgentsFile, ApiKind, ChatEvent, PRESETS, Provider, SUBSCRIPTIONS, Usage, Worker}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::control::{ControlReply, ControlRequest, RequestGate}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, regular, semibold}; +use crate::widgets::{self, PAD}; +use crate::{FigApp, a11y, icons}; + +/// One line of the conversation. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum Entry { + User(String), + Assistant(String), + Tool { + title: String, + summary: String, + state: ToolState, + }, + Note(String), + /// A turn that failed (network, provider, sign-in), shown with a way to fix the connection. + Error(String), + /// What the person attached to the request after it: layers (clickable, to select them again) + /// and the names of images. + Refs { + layers: Vec, + images: Vec, + }, +} + +/// A layer attached to a request. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LayerRef { + pub id: u64, + pub name: String, +} + +/// An image attached to the next request. +pub struct Attachment { + pub name: String, + pub image: figcraft_agent::neutral::Image, + thumb: Option, +} + +/// Another conversation kept for this document. +pub struct PastChat { + pub key: String, + pub title: String, + pub current: bool, +} + +/// At most this many images go with one request. +const MAX_IMAGES: usize = 6; +/// The longest side an attached image is scaled down to (what vision models read at full detail). +const IMAGE_SIDE: u32 = 1568; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ToolState { + Running, + Ok, + Failed, +} + +/// Something the panel asks the app to do after drawing (it needs the whole `FigApp`). +pub enum Action { + Send, + /// Send this text (a suggestion) as the request. + SendText(String), + Stop, + Undo, + NewChat, + OpenSettings, + CloseSettings, + FetchModels, + ToggleAuto, + CycleVariants, + Allow(usize), + Deny(usize), + /// Connect a subscription (an installed command-line agent). + ConnectCli(ApiKind), + /// Check the installed programs again. + RefreshCli, + /// Connect the API-key preset with this index, using the key typed on its card. + ConnectKey(usize), + /// Make the provider with this index the one requests go to. + Use(usize), + /// Choose this model on the active provider. + UseModel(String), + Remove(usize), + /// Select this layer on the canvas (a chip was clicked). + SelectLayer(u64), + /// Leave this selected layer out of the next request. + Exclude(u64), + RemoveImage(usize), + PasteImage, + AttachRender, + CopyText(String), + /// Put the last request back in the composer. + EditLast, + /// Send the last request again. + Retry, + Unqueue(usize), + OpenChat(String), + DeleteChat(String), +} + +struct Approval { + reason: String, + name: String, + args: Value, + reply: Sender, +} + +/// A tool call's answer on its way back to the agent thread. +type ReplyForward = (Receiver, Sender>); + +/// A model list being fetched: the provider it belongs to and the thread's answer. +type ModelFetch = (usize, Receiver, String>>); + +/// An API-key connection being tried: the preset, and the provider with its model list once the +/// endpoint answered. +type KeyTrial = (usize, Receiver>); + +/// The installed command-line agents, as last checked. +type CliCheck = Receiver>; + +/// The prompts offered on an empty conversation. +const SUGGESTIONS: &[&str] = &[ + crate::i18n::tr_noop("Design a sign-in screen for a mobile app"), + crate::i18n::tr_noop("Make a pricing section with three plans"), + crate::i18n::tr_noop("Turn the selection into a component with variants"), + crate::i18n::tr_noop("Check the selection for spacing and contrast problems"), +]; + +/// The chat panel's state, kept on the window. +#[derive(Default)] +pub struct Chat { + /// `agents.json`'s contents and where it lives. + pub agents: AgentsFile, + path: Option, + loaded: bool, + /// The Connections screen is showing instead of the conversation. + pub settings_open: bool, + pub error: Option, + pub draft: String, + pub entries: Vec, + pub running: bool, + pub auto: bool, + pub usage: Usage, + /// Canvas changes made in this turn, for "Undo turn". + turn_steps: usize, + /// The undo depth the turn started at. + turn_mark: Option, + /// The window and document the conversation works in, pinned when a request is sent: a turn + /// must not follow the person to another tab or window halfway through. + window: Option, + document: Option, + /// The conversation on screen belongs to this file (a slug of its path or name). + pub(crate) doc_key: Option, + /// Where the per-document chats are kept (`agent-chats/` beside `agents.json`). + pub(crate) chats_dir: Option, + worker: Option, + pub(crate) bridge: Option, + /// Calls waiting for their answer, to hand it back to the agent thread. + pending: Vec, + approvals: Vec, + /// Model lists being fetched, and the provider they belong to. + fetching: Option, + /// The API-key card that is open, and what is typed in it. + key_card: Option, + key_draft: String, + trial: Option, + /// The installed command-line agents, and a check on its way. + cli: Vec<(ApiKind, CliStatus)>, + cli_check: Option, + /// The Advanced settings of the active connection are open. + advanced: bool, + /// Give the composer the keyboard on the next frame (the tab was just opened). + focus_composer: bool, + /// Whether the composer had the keyboard on the last frame (a paste there may be an image). + composer_focused: bool, + /// The canvas selection as the composer's chips, with each layer's icon. + selection: Vec<(LayerRef, icons::Icon)>, + /// Selected layers the person took off the next request; forgotten when the selection changes. + excluded: Vec, + /// Images going with the next request. + pub images: Vec, + /// Requests typed while the agent was working, sent in turn when it finishes. + pub queue: Vec, + /// The conversation on screen, when it is not the document's first one (`-