mirror of
https://github.com/storytold/figcraft.git
synced 2026-12-02 15:01:23 -05:00
Merge pull request #2828 from mad-af/feat/agent-panel
feat(agent): a built-in Agent tab that designs on the open canvas (part of #1379)
This commit is contained in:
Generated
+49
@@ -1056,12 +1056,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"
|
||||
@@ -2826,6 +2855,22 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-agent"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"figcraft-color",
|
||||
"figcraft-engine",
|
||||
"figcraft-mcp",
|
||||
"getrandom 0.4.3",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ureq",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "figcraft-cli"
|
||||
version = "0.19.0"
|
||||
@@ -3155,6 +3200,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"egui",
|
||||
"egui_extras",
|
||||
"figcraft-agent",
|
||||
"figcraft-color",
|
||||
"figcraft-doc",
|
||||
"figcraft-engine",
|
||||
@@ -7484,12 +7530,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",
|
||||
|
||||
@@ -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).
|
||||
@@ -151,6 +152,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 }
|
||||
|
||||
@@ -493,6 +493,10 @@ pub(crate) fn remembering(last: Arc<Mutex<Option<PathBuf>>>, pick: DialogFuture,
|
||||
}
|
||||
|
||||
impl Services for Desktop {
|
||||
fn agent_config_path(&self) -> Option<std::path::PathBuf> {
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
[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 }
|
||||
figcraft-color = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
# The MCP endpoint's bearer token (the OS random source collab-net's session secrets use).
|
||||
getrandom = "0.4"
|
||||
log = { workspace = true }
|
||||
# Blocking HTTP with rustls (the same TLS provider collab-net uses), no async runtime.
|
||||
ureq = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
figcraft-engine = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
@@ -0,0 +1,295 @@
|
||||
//! The Anthropic Messages dialect.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::config::Provider;
|
||||
use crate::http::{Http, read_error};
|
||||
use crate::neutral::{Block, Message, Role};
|
||||
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<Value> {
|
||||
let mut out: Vec<Value> = 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<Step, String> {
|
||||
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 events = crate::sse::spawn_events(reply.body);
|
||||
let mut step = Step::default();
|
||||
let mut pending: BTreeMap<u64, Pending> = BTreeMap::new();
|
||||
// `message_stop` ends a whole answer; a stream that ends before it was cut off.
|
||||
let mut stopped = false;
|
||||
while let Some(event) = crate::sse::next(&events, cancel)? {
|
||||
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_stop" => {
|
||||
stopped = true;
|
||||
break;
|
||||
}
|
||||
"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();
|
||||
// The start carries `input: {}` as a placeholder before the streamed
|
||||
// fragments; it is the input only when no fragment follows.
|
||||
let initial = block.get("input").filter(|i| !i.is_null()).map(|i| i.to_string()).unwrap_or_default();
|
||||
pending.insert(index, Pending { id, name, initial, streamed: String::new() });
|
||||
}
|
||||
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.streamed.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);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !stopped {
|
||||
return Err(crate::openai::INTERRUPTED.to_string());
|
||||
}
|
||||
for (i, p) in pending {
|
||||
if let Some(call) = p.into_call(i) {
|
||||
step.calls.push(call);
|
||||
}
|
||||
}
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// A tool call being built: the input its start gave, and the fragments streamed after it.
|
||||
struct Pending {
|
||||
id: String,
|
||||
name: String,
|
||||
initial: String,
|
||||
streamed: String,
|
||||
}
|
||||
|
||||
impl Pending {
|
||||
fn into_call(self, index: u64) -> Option<Invocation> {
|
||||
if self.name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let id = if self.id.is_empty() { format!("toolu_{index}") } else { self.id };
|
||||
let raw = if self.streamed.trim().is_empty() { self.initial } else { self.streamed };
|
||||
let args = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(Value::Null) };
|
||||
Some(Invocation { id, name: self.name, args, args_raw: raw })
|
||||
}
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
|
||||
fn call(initial: &str, fragments: &[&str]) -> Option<Invocation> {
|
||||
let streamed = fragments.concat();
|
||||
Pending { id: "toolu_1".into(), name: "load_skill".into(), initial: initial.into(), streamed }.into_call(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_arguments_replace_the_placeholder_input() {
|
||||
let c = call("{}", &["{\"name\":", "\"Design review\"}"]).expect("a call");
|
||||
assert_eq!(c.args["name"], "Design review");
|
||||
let none = call("{}", &[]).expect("a call");
|
||||
assert_eq!(none.args, json!({}), "no fragments: the start's input is the input");
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
@@ -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<Result<Value, String>>,
|
||||
}
|
||||
|
||||
/// The UI side: the calls the agent thread is waiting for.
|
||||
pub struct Bridge {
|
||||
pub calls: Receiver<Call>,
|
||||
}
|
||||
|
||||
/// The agent side: sends calls and waits for their answers.
|
||||
#[derive(Clone)]
|
||||
pub struct Remote {
|
||||
tx: Sender<Call>,
|
||||
/// 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<dyn Fn() + Send + Sync>,
|
||||
}
|
||||
|
||||
/// A fresh pair: the UI keeps the bridge, the agent thread keeps the remote.
|
||||
pub fn pair(agent: impl Into<String>, wake: Arc<dyn Fn() + Send + Sync>) -> (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<Value, String> {
|
||||
self.send(method, params)
|
||||
}
|
||||
|
||||
fn send(&self, method: &str, mut params: Value) -> Result<Value, String> {
|
||||
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<Value, String> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,898 @@
|
||||
//! The file's design system and the page it lives on, `00 · Design System`: the choices behind
|
||||
//! it (product, colour, type, shape, icons, voice) become variables, styles, review settings and
|
||||
//! a guidelines text on that page, in one step the agent takes with the `design_system` tool.
|
||||
//!
|
||||
//! The foundations follow what public design-system guides cover (Material 3, IBM Carbon, Apple's
|
||||
//! Human Interface Guidelines, Atlassian, Shopify Polaris, and the W3C Design Tokens format
|
||||
//! 2025.10): colour roles with light and dark modes, a type scale, a 4 or 8 spacing step, radius,
|
||||
//! elevation, an icon set and style, voice, and contrast targets. The idea of starting a file from
|
||||
//! a design library with variables and themes comes from pen.dev's public documentation
|
||||
//! (docs.pencil.dev: design systems, variables, AI agents). Ideas only; nothing here is copied.
|
||||
//!
|
||||
//! [`Brief::steps`] builds the commands for the engine's `command.batch`, so making (or updating)
|
||||
//! the system is one undo step and works the same from the panel, the CLI or MCP.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_color::{Color, Oklch};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The collections and their modes the steps make.
|
||||
pub const PRIMITIVES: &str = "Primitives";
|
||||
pub const THEME: &str = "Theme";
|
||||
pub const SIZES: &str = "Sizes";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Platform {
|
||||
Mobile,
|
||||
#[default]
|
||||
Web,
|
||||
Both,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Neutral {
|
||||
Cool,
|
||||
#[default]
|
||||
Neutral,
|
||||
Warm,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Modes {
|
||||
Light,
|
||||
Dark,
|
||||
#[default]
|
||||
Both,
|
||||
}
|
||||
|
||||
impl Modes {
|
||||
pub fn names(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Modes::Light => &["Light"],
|
||||
Modes::Dark => &["Dark"],
|
||||
Modes::Both => &["Light", "Dark"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TypeScale {
|
||||
/// 14 px body, sizes 1.2 apart.
|
||||
Compact,
|
||||
/// 16 px body, 1.25 apart.
|
||||
#[default]
|
||||
Default,
|
||||
/// 18 px body, 1.25 apart.
|
||||
Large,
|
||||
}
|
||||
|
||||
impl TypeScale {
|
||||
fn base_ratio(self) -> (f64, f64) {
|
||||
match self {
|
||||
TypeScale::Compact => (14.0, 1.2),
|
||||
TypeScale::Default => (16.0, 1.25),
|
||||
TypeScale::Large => (18.0, 1.25),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Radius {
|
||||
Sharp,
|
||||
#[default]
|
||||
Soft,
|
||||
Round,
|
||||
Pill,
|
||||
}
|
||||
|
||||
impl Radius {
|
||||
/// Small, medium, large.
|
||||
fn values(self) -> [f64; 3] {
|
||||
match self {
|
||||
Radius::Sharp => [2.0, 4.0, 6.0],
|
||||
Radius::Soft => [4.0, 8.0, 12.0],
|
||||
Radius::Round => [8.0, 16.0, 24.0],
|
||||
Radius::Pill => [12.0, 20.0, 28.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Elevation {
|
||||
Flat,
|
||||
#[default]
|
||||
Subtle,
|
||||
Raised,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum IconStyle {
|
||||
#[default]
|
||||
Outline,
|
||||
Filled,
|
||||
Duotone,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Contrast {
|
||||
#[default]
|
||||
Aa,
|
||||
Aaa,
|
||||
}
|
||||
|
||||
/// Open-source icon sets a brief can name: (name, licence, what it looks like). Nothing is
|
||||
/// downloaded; the agent draws icons in the set's manner, or the person imports them.
|
||||
pub const ICON_SETS: &[(&str, &str, &str)] = &[
|
||||
("Lucide", "ISC", "Clean outline icons on a 24 grid, 2 px strokes, round caps; a wide everyday set."),
|
||||
("Heroicons", "MIT", "Outline (1.5 px) and solid versions at 24, with smaller solid sizes; plain and friendly."),
|
||||
("Tabler Icons", "MIT", "A very large outline set on a 24 grid with 2 px strokes; consistent and neutral."),
|
||||
("Phosphor", "MIT", "One set in six weights from thin to fill plus duotone; soft, rounded shapes."),
|
||||
("Feather", "MIT", "A small, light outline set on a 24 grid with 2 px strokes; minimal."),
|
||||
("Material Symbols", "Apache-2.0", "Google's set with fill, weight and size variations; geometric and familiar on Android."),
|
||||
];
|
||||
|
||||
/// What the file's design system should be. Every field has a default, so an older or partial
|
||||
/// brief reads back.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Brief {
|
||||
pub version: u32,
|
||||
// The product.
|
||||
pub product: String,
|
||||
pub description: String,
|
||||
pub audience: String,
|
||||
pub platform: Platform,
|
||||
/// The language the copy is written in.
|
||||
pub language: String,
|
||||
// Colour (hex).
|
||||
pub primary: String,
|
||||
pub secondary: String,
|
||||
pub accent: String,
|
||||
pub neutral: Neutral,
|
||||
pub success: String,
|
||||
pub warning: String,
|
||||
pub danger: String,
|
||||
pub info: String,
|
||||
pub modes: Modes,
|
||||
// Type.
|
||||
pub heading_font: String,
|
||||
pub body_font: String,
|
||||
pub mono_font: String,
|
||||
pub scale: TypeScale,
|
||||
// Shape.
|
||||
/// 4 or 8.
|
||||
pub spacing: u8,
|
||||
pub radius: Radius,
|
||||
pub elevation: Elevation,
|
||||
pub border: f64,
|
||||
// Icons.
|
||||
/// A name from [`ICON_SETS`], or anything the person typed.
|
||||
pub icon_set: String,
|
||||
pub icon_style: IconStyle,
|
||||
pub icon_stroke: f64,
|
||||
pub icon_size: u8,
|
||||
// Voice and rules.
|
||||
pub tone: String,
|
||||
pub imagery: String,
|
||||
pub contrast: Contrast,
|
||||
pub notes: String,
|
||||
}
|
||||
|
||||
impl Default for Brief {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
product: String::new(),
|
||||
description: String::new(),
|
||||
audience: String::new(),
|
||||
platform: Platform::Web,
|
||||
language: String::new(),
|
||||
primary: "#2563EB".into(),
|
||||
secondary: String::new(),
|
||||
accent: String::new(),
|
||||
neutral: Neutral::Neutral,
|
||||
success: "#16A34A".into(),
|
||||
warning: "#D97706".into(),
|
||||
danger: "#DC2626".into(),
|
||||
info: "#0284C7".into(),
|
||||
modes: Modes::Both,
|
||||
heading_font: "Inter".into(),
|
||||
body_font: "Inter".into(),
|
||||
mono_font: "JetBrains Mono".into(),
|
||||
scale: TypeScale::Default,
|
||||
spacing: 4,
|
||||
radius: Radius::Soft,
|
||||
elevation: Elevation::Subtle,
|
||||
border: 1.0,
|
||||
icon_set: "Lucide".into(),
|
||||
icon_style: IconStyle::Outline,
|
||||
icon_stroke: 2.0,
|
||||
icon_size: 24,
|
||||
tone: String::new(),
|
||||
imagery: String::new(),
|
||||
contrast: Contrast::Aa,
|
||||
notes: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ramp steps every colour gets.
|
||||
pub const STEPS: [u16; 10] = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
|
||||
/// OKLCH lightness per step, light to dark.
|
||||
const RAMP_L: [f32; 10] = [0.97, 0.93, 0.87, 0.79, 0.70, 0.61, 0.52, 0.44, 0.36, 0.28];
|
||||
/// Share of the colour's own chroma per step (pale and deep ends are calmer).
|
||||
const RAMP_C: [f32; 10] = [0.15, 0.3, 0.5, 0.75, 0.92, 1.0, 0.95, 0.85, 0.72, 0.6];
|
||||
|
||||
/// Ten shades of `hex` from 50 (palest) to 900 (deepest), keeping its hue; `None` if it is not a
|
||||
/// colour.
|
||||
pub fn ramp(hex: &str) -> Option<Vec<String>> {
|
||||
let base = Oklch::from_color(Color::from_hex(hex)?);
|
||||
Some(ramp_of(base.c, base.h))
|
||||
}
|
||||
|
||||
fn ramp_of(chroma: f32, hue: f32) -> Vec<String> {
|
||||
(0..STEPS.len()).map(|i| Oklch { l: RAMP_L[i], c: chroma * RAMP_C[i], h: hue }.to_color().to_css_hex()).collect()
|
||||
}
|
||||
|
||||
/// A grey ramp, tinted cool (blue), warm (sand) or not at all.
|
||||
fn neutral_ramp(tone: Neutral) -> Vec<String> {
|
||||
match tone {
|
||||
Neutral::Cool => ramp_of(0.02, 255.0),
|
||||
Neutral::Neutral => ramp_of(0.0, 0.0),
|
||||
Neutral::Warm => ramp_of(0.018, 70.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// `hex` made lighter, for the dark mode of a status colour.
|
||||
fn lighter(hex: &str) -> String {
|
||||
match Color::from_hex(hex) {
|
||||
Some(c) => {
|
||||
let o = Oklch::from_color(c);
|
||||
Oklch { l: (o.l + 0.12).min(0.85), ..o }.to_color().to_css_hex()
|
||||
}
|
||||
None => hex.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a file already has, so running the steps again updates rather than duplicates.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Existing {
|
||||
/// Collection name → its mode names.
|
||||
pub collections: BTreeMap<String, Vec<String>>,
|
||||
/// (collection name, variable name) → the variable's id, so an update names that one variable
|
||||
/// even when another collection has one of the same name.
|
||||
pub variables: BTreeMap<(String, String), String>,
|
||||
pub styles: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Existing {
|
||||
/// Read `variable.list` and `style.list` results.
|
||||
pub fn from_lists(variables: &Value, styles: &Value) -> Self {
|
||||
let mut e = Existing::default();
|
||||
let mut by_id = BTreeMap::new();
|
||||
for c in variables.get("collections").and_then(Value::as_array).into_iter().flatten() {
|
||||
let (Some(id), Some(name)) = (c.get("id").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) else { continue };
|
||||
let modes = c
|
||||
.get("modes")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|m| m.get("name").and_then(Value::as_str))
|
||||
.map(str::to_string);
|
||||
e.collections.insert(name.to_string(), modes.collect());
|
||||
by_id.insert(id.to_string(), name.to_string());
|
||||
}
|
||||
for v in variables.get("variables").and_then(Value::as_array).into_iter().flatten() {
|
||||
let (Some(c), Some(name)) = (v.get("collection").and_then(Value::as_str), v.get("name").and_then(Value::as_str)) else { continue };
|
||||
if let Some(cname) = by_id.get(c) {
|
||||
let id = v.get("id").and_then(Value::as_str).unwrap_or(name);
|
||||
e.variables.insert((cname.clone(), name.to_string()), id.to_string());
|
||||
}
|
||||
}
|
||||
for s in styles.as_array().into_iter().flatten() {
|
||||
if let Some(name) = s.get("name").and_then(Value::as_str) {
|
||||
e.styles.insert(name.to_string());
|
||||
}
|
||||
}
|
||||
e
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable's value per mode: a colour, a number, or an alias to another variable.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Val {
|
||||
Lit(Value),
|
||||
Alias(String),
|
||||
}
|
||||
|
||||
impl Val {
|
||||
fn json(&self) -> Value {
|
||||
match self {
|
||||
Val::Lit(v) => v.clone(),
|
||||
Val::Alias(name) => json!({"alias": name}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Brief {
|
||||
/// Read a brief kept as page data; a damaged one gives the defaults back.
|
||||
pub fn from_json(text: &str) -> Option<Self> {
|
||||
serde_json::from_str(text).ok()
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> String {
|
||||
serde_json::to_string(self).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn hex_or<'a>(value: &'a str, fallback: &'a str) -> &'a str {
|
||||
if Color::from_hex(value).is_some() { value } else { fallback }
|
||||
}
|
||||
|
||||
/// The colour ramps of the Primitives collection: (group name, ten shades).
|
||||
fn ramps(&self) -> Vec<(&'static str, Vec<String>)> {
|
||||
let mut out = vec![("Primary", ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default())];
|
||||
for (name, hex) in [("Secondary", &self.secondary), ("Accent", &self.accent)] {
|
||||
if let Some(r) = ramp(hex) {
|
||||
out.push((name, r));
|
||||
}
|
||||
}
|
||||
out.push(("Neutral", neutral_ramp(self.neutral)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The Theme roles: (name, Light value, Dark value).
|
||||
fn roles(&self) -> Vec<(String, Val, Val)> {
|
||||
let a = |s: &str| Val::Alias(s.to_string());
|
||||
let lit = |s: &str| Val::Lit(json!(s));
|
||||
// Text on the primary colour: white or near-black, whichever reads better on Primary/600.
|
||||
let primary = ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default();
|
||||
let on_primary = primary
|
||||
.get(6)
|
||||
.and_then(|p| Color::from_hex(p))
|
||||
.map(|p| {
|
||||
let (white, ink) = (Color::new(1.0, 1.0, 1.0, 1.0), Color::from_hex("#111111").unwrap_or(Color::new(0.07, 0.07, 0.07, 1.0)));
|
||||
if p.contrast(white) >= p.contrast(ink) { "#FFFFFF" } else { "#111111" }
|
||||
})
|
||||
.unwrap_or("#FFFFFF");
|
||||
let mut roles = vec![
|
||||
("Background".to_string(), lit("#FFFFFF"), a("Neutral/900")),
|
||||
("Surface".into(), a("Neutral/50"), a("Neutral/800")),
|
||||
("Surface raised".into(), lit("#FFFFFF"), a("Neutral/700")),
|
||||
("Text".into(), a("Neutral/900"), a("Neutral/50")),
|
||||
("Text muted".into(), a("Neutral/600"), a("Neutral/300")),
|
||||
("Border".into(), a("Neutral/200"), a("Neutral/700")),
|
||||
("Primary".into(), a("Primary/600"), a("Primary/400")),
|
||||
("Primary hover".into(), a("Primary/700"), a("Primary/300")),
|
||||
("On primary".into(), lit(on_primary), a("Neutral/900")),
|
||||
("Focus".into(), a("Primary/500"), a("Primary/400")),
|
||||
];
|
||||
for (name, hex) in [("Secondary", &self.secondary), ("Accent", &self.accent)] {
|
||||
if Color::from_hex(hex).is_some() {
|
||||
roles.push((name.into(), a(&format!("{name}/600")), a(&format!("{name}/400"))));
|
||||
}
|
||||
}
|
||||
for (name, hex, fallback) in [
|
||||
("Success", &self.success, "#16A34A"),
|
||||
("Warning", &self.warning, "#D97706"),
|
||||
("Danger", &self.danger, "#DC2626"),
|
||||
("Info", &self.info, "#0284C7"),
|
||||
] {
|
||||
let hex = Self::hex_or(hex, fallback);
|
||||
roles.push((name.into(), lit(hex), Val::Lit(json!(lighter(hex)))));
|
||||
}
|
||||
roles
|
||||
}
|
||||
|
||||
/// The Sizes collection: (name, value).
|
||||
fn sizes(&self) -> Vec<(String, f64)> {
|
||||
let base = if self.spacing == 8 { 8.0 } else { 4.0 };
|
||||
let mut out: Vec<(String, f64)> = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0]
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let v = base * m;
|
||||
(format!("Space/{v}"), v)
|
||||
})
|
||||
.collect();
|
||||
let [s, m, l] = self.radius.values();
|
||||
out.extend([("Radius/S".to_string(), s), ("Radius/M".into(), m), ("Radius/L".into(), l), ("Radius/Full".into(), 9999.0)]);
|
||||
out.extend([
|
||||
("Border/Default".to_string(), self.border.clamp(0.5, 4.0)),
|
||||
("Border/Focus".into(), 2.0),
|
||||
("Icon/Size".into(), f64::from(self.icon_size.clamp(12, 48))),
|
||||
("Icon/Stroke".into(), self.icon_stroke.clamp(0.5, 4.0)),
|
||||
]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Text styles: (name, size, weight, line height, family).
|
||||
fn type_styles(&self) -> Vec<(&'static str, f64, u16, f64, String)> {
|
||||
let (b, r) = self.scale.base_ratio();
|
||||
let size = |step: i32| (b * r.powi(step)).round();
|
||||
let font = |f: &str, fallback: &str| if f.trim().is_empty() { fallback.to_string() } else { f.trim().to_string() };
|
||||
let (head, body, mono) = (font(&self.heading_font, "Inter"), font(&self.body_font, "Inter"), font(&self.mono_font, "JetBrains Mono"));
|
||||
let tight = |s: f64| (s * 1.2 / 2.0).round() * 2.0;
|
||||
let loose = |s: f64| (s * 1.5 / 2.0).round() * 2.0;
|
||||
let list: [(&str, i32, u16, bool, &str); 10] = [
|
||||
("Display", 5, 700, true, "h"),
|
||||
("Heading 1", 4, 700, true, "h"),
|
||||
("Heading 2", 3, 600, true, "h"),
|
||||
("Heading 3", 2, 600, true, "h"),
|
||||
("Body large", 1, 400, false, "b"),
|
||||
("Body", 0, 400, false, "b"),
|
||||
("Body small", -1, 400, false, "b"),
|
||||
("Caption", -2, 400, false, "b"),
|
||||
("Label", -1, 500, false, "b"),
|
||||
("Code", -1, 400, false, "m"),
|
||||
];
|
||||
list.iter()
|
||||
.map(|(name, step, weight, heading, fam)| {
|
||||
let s = size(*step);
|
||||
let family = match *fam {
|
||||
"h" => head.clone(),
|
||||
"m" => mono.clone(),
|
||||
_ => body.clone(),
|
||||
};
|
||||
(*name, s, *weight, if *heading { tight(s) } else { loose(s) }, family)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Shadow styles: (name, y offset, blur, spread, opacity).
|
||||
fn shadows(&self) -> [(&'static str, f64, f64, f64, f64); 3] {
|
||||
let k = match self.elevation {
|
||||
Elevation::Flat => 0.5,
|
||||
Elevation::Subtle => 1.0,
|
||||
Elevation::Raised => 1.6,
|
||||
};
|
||||
[("Shadow/S", 1.0, 2.0, 0.0, 0.06 * k), ("Shadow/M", 4.0, 10.0, -2.0, 0.08 * k), ("Shadow/L", 12.0, 28.0, -6.0, 0.11 * k)]
|
||||
}
|
||||
|
||||
/// The file's design review settings (`design.configure`) from the brief: its spacing step as
|
||||
/// the grid, its corners as the radii, its colours as the brand, and the contrast target.
|
||||
pub fn review_settings(&self) -> Value {
|
||||
let preset = match self.contrast {
|
||||
Contrast::Aa => "recommended",
|
||||
Contrast::Aaa => "accessibility",
|
||||
};
|
||||
let brand: Vec<String> = [&self.primary, &self.secondary, &self.accent]
|
||||
.into_iter()
|
||||
.filter_map(|h| Color::from_hex(h).map(|c| c.to_css_hex()))
|
||||
.chain(ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default().into_iter().skip(4).take(4))
|
||||
.collect();
|
||||
json!({
|
||||
"preset": preset,
|
||||
"grid": if self.spacing == 8 { 8 } else { 4 },
|
||||
"radii": self.radius.values(),
|
||||
"brand": brand,
|
||||
})
|
||||
}
|
||||
|
||||
/// The commands that make (or bring up to date) the file's variables and styles, for
|
||||
/// `command.batch`: `[{command, params}]`.
|
||||
pub fn steps(&self, existing: &Existing) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
// Primitives: one mode, the colour ramps.
|
||||
let mut prim: Vec<(String, Vec<Val>)> = Vec::new();
|
||||
for (group, shades) in self.ramps() {
|
||||
for (step, hex) in STEPS.iter().zip(shades) {
|
||||
prim.push((format!("{group}/{step}"), vec![Val::Lit(json!(hex))]));
|
||||
}
|
||||
}
|
||||
collection(&mut out, existing, PRIMITIVES, &["Default"], "color", prim);
|
||||
// Theme: the roles, per mode.
|
||||
let modes = self.modes.names();
|
||||
let theme = self
|
||||
.roles()
|
||||
.into_iter()
|
||||
.map(|(name, light, dark)| {
|
||||
let values = modes.iter().map(|m| if *m == "Dark" { dark.clone() } else { light.clone() }).collect();
|
||||
(name, values)
|
||||
})
|
||||
.collect();
|
||||
collection(&mut out, existing, THEME, modes, "color", theme);
|
||||
// Sizes.
|
||||
let sizes = self.sizes().into_iter().map(|(n, v)| (n, vec![Val::Lit(json!(v))])).collect();
|
||||
collection(&mut out, existing, SIZES, &["Default"], "number", sizes);
|
||||
// Text styles.
|
||||
for (name, size, weight, line, family) in self.type_styles() {
|
||||
let value = json!({"fontFamily": family, "fontSize": size, "fontWeight": weight, "lineHeight": line});
|
||||
out.push(if existing.styles.contains(name) {
|
||||
json!({"command": "style.update", "params": {"style": name, "value": value}})
|
||||
} else {
|
||||
json!({"command": "style.create", "params": {"type": "text", "name": name, "value": value}})
|
||||
});
|
||||
}
|
||||
// FigCraft's design review checks against the same choices.
|
||||
out.push(json!({"command": "design.configure", "params": self.review_settings()}));
|
||||
// Shadows.
|
||||
for (name, y, blur, spread, alpha) in self.shadows() {
|
||||
let a = (alpha.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
let value = json!([{"type": "dropShadow", "color": format!("#0F172A{a:02X}"), "offset": [0.0, y], "radius": blur, "spread": spread}]);
|
||||
out.push(if existing.styles.contains(name) {
|
||||
json!({"command": "style.update", "params": {"style": name, "value": value}})
|
||||
} else {
|
||||
json!({"command": "style.create", "params": {"type": "effect", "name": name, "value": value}})
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The design guidelines as written on the design system page.
|
||||
pub fn guidelines(&self) -> String {
|
||||
let mut lines = vec![GUIDELINES.to_string()];
|
||||
let opt = |label: &str, v: &str| if v.trim().is_empty() { None } else { Some(format!("{label}: {}", v.trim())) };
|
||||
lines.extend(opt("Product", &self.product));
|
||||
lines.extend(opt("What it does", &self.description));
|
||||
lines.extend(opt("For", &self.audience));
|
||||
lines.push(format!(
|
||||
"Platform: {}",
|
||||
match self.platform {
|
||||
Platform::Mobile => "mobile app (390 x 844 frames)",
|
||||
Platform::Web => "web (1440 wide desktop frames, plus 390 mobile when asked)",
|
||||
Platform::Both => "mobile app and web",
|
||||
}
|
||||
));
|
||||
lines.extend(opt("Write the copy in", &self.language));
|
||||
lines.push(format!(
|
||||
"Colour: primary {}{}{}; status colours success {}, warning {}, danger {}, info {}; modes {}. Use the Theme variables (Background, Surface, Text, Text muted, Border, Primary, On primary…) for every colour once they exist.",
|
||||
self.primary,
|
||||
if self.secondary.trim().is_empty() { String::new() } else { format!(", secondary {}", self.secondary.trim()) },
|
||||
if self.accent.trim().is_empty() { String::new() } else { format!(", accent {}", self.accent.trim()) },
|
||||
self.success,
|
||||
self.warning,
|
||||
self.danger,
|
||||
self.info,
|
||||
self.modes.names().join(" and "),
|
||||
));
|
||||
let (base, ratio) = self.scale.base_ratio();
|
||||
lines.push(format!(
|
||||
"Type: headings in {}, body in {}, code in {}; body {base} px, sizes {ratio} apart. Use the text styles (Display, Heading 1-3, Body, Body small, Caption, Label, Code).",
|
||||
self.heading_font, self.body_font, self.mono_font
|
||||
));
|
||||
lines.push(format!(
|
||||
"Shape: spacing in steps of {} (Sizes/Space variables), corners {:?} (Radius variables), elevation {:?} (Shadow styles), borders {} px.",
|
||||
if self.spacing == 8 { 8 } else { 4 },
|
||||
self.radius,
|
||||
self.elevation,
|
||||
self.border
|
||||
));
|
||||
let set = ICON_SETS.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(self.icon_set.trim()));
|
||||
lines.push(format!(
|
||||
"Icons: {} ({:?}, {} px stroke, {} px){}. Draw each icon as vector paths in that set's manner on a {} grid, or use an icon the user imported; never emoji.",
|
||||
if self.icon_set.trim().is_empty() { "a line icon set" } else { self.icon_set.trim() },
|
||||
self.icon_style,
|
||||
self.icon_stroke,
|
||||
self.icon_size,
|
||||
set.map(|(_, _, d)| format!(": {d}")).unwrap_or_default(),
|
||||
self.icon_size
|
||||
));
|
||||
lines.extend(opt("Voice", &self.tone));
|
||||
lines.extend(opt("Imagery", &self.imagery));
|
||||
lines.push(match self.contrast {
|
||||
Contrast::Aa => "Accessibility: WCAG AA (text 4.5:1, large text and controls 3:1), touch targets at least 44.".to_string(),
|
||||
Contrast::Aaa => "Accessibility: WCAG AAA (text 7:1, large text 4.5:1), touch targets at least 44.".to_string(),
|
||||
});
|
||||
lines.extend(opt("Also", &self.notes));
|
||||
lines.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Steps for one collection: create it (or add missing modes), then create or set each variable.
|
||||
fn collection(out: &mut Vec<Value>, existing: &Existing, name: &str, modes: &[&str], kind: &str, vars: Vec<(String, Vec<Val>)>) {
|
||||
match existing.collections.get(name) {
|
||||
None => out.push(json!({"command": "variable.createCollection", "params": {"name": name, "modes": modes}})),
|
||||
Some(have) => {
|
||||
for m in modes {
|
||||
if !have.iter().any(|h| h == m) {
|
||||
out.push(json!({"command": "variable.addMode", "params": {"collection": name, "name": m}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var, values) in vars {
|
||||
if let Some(id) = existing.variables.get(&(name.to_string(), var.clone())) {
|
||||
for (m, v) in modes.iter().zip(&values) {
|
||||
out.push(json!({"command": "variable.set", "params": {"variable": id, "mode": m, "value": v.json()}}));
|
||||
}
|
||||
} else {
|
||||
let values: serde_json::Map<String, Value> = modes.iter().map(ToString::to_string).zip(values.iter().map(Val::json)).collect();
|
||||
out.push(json!({"command": "variable.create", "params": {"collection": name, "name": var, "type": kind, "values": values}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool the model reads and makes the design system page with.
|
||||
pub const TOOL_NAME: &str = "design_system";
|
||||
|
||||
/// The page every file's design system lives on, first in the file.
|
||||
pub const PAGE: &str = "00 · Design System";
|
||||
|
||||
/// The text layer on that page holding the choices tokens can't hold (icons, voice, rules).
|
||||
pub const GUIDELINES: &str = "Design guidelines";
|
||||
|
||||
/// The `design_system` tool, as the tool list has it.
|
||||
pub fn tool_definition() -> Value {
|
||||
json!({
|
||||
"name": TOOL_NAME,
|
||||
"description": "The file's design system, which lives on the page '00 · Design System'. With no arguments: whether that page exists, its frames, its design guidelines and the variable collections. With `spec`: make or update it in one undo step: the page (first in the file), the variables (colour ramps, Theme roles with Light/Dark, Sizes), text and shadow styles, the review settings design.audit uses, and a 'Design guidelines' text on the page with the choices tokens can't hold. Spec fields (all optional): product, description, audience, platform (mobile|web|both), language, primary, secondary, accent (hex), neutral (cool|neutral|warm), success, warning, danger, info (hex), modes (light|dark|both), headingFont, bodyFont, monoFont, scale (compact|default|large), spacing (4|8), radius (sharp|soft|round|pill), elevation (flat|subtle|raised), border, iconSet (e.g. Lucide, Heroicons, Tabler Icons, Phosphor, Feather, Material Symbols), iconStyle (outline|filled|duotone), iconStroke, iconSize, tone, imagery, contrast (aa|aaa), notes.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"spec": {"type": "object", "description": "Design system choices to make (others take defaults)"}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Run a command on the file the operation started in (`document`, from `doc.list`), so a tab the
|
||||
/// person switches to meanwhile is never written to; a file closed meanwhile fails the call.
|
||||
fn exec(b: &mut dyn figcraft_mcp::Backend, document: Option<u64>, cmd: &str, params: Value) -> Result<Value, String> {
|
||||
let mut request = json!({"command": cmd, "params": params});
|
||||
if let Some(d) = document {
|
||||
request["document"] = json!(d);
|
||||
}
|
||||
b.call("engine.execute", request)
|
||||
}
|
||||
|
||||
/// The id of the file in front, which the whole operation then works in.
|
||||
fn front_document(b: &mut dyn figcraft_mcp::Backend) -> Option<u64> {
|
||||
let list = exec(b, None, "doc.list", json!({})).ok()?;
|
||||
list.as_array()?.iter().find(|d| d.get("active").and_then(Value::as_bool) == Some(true))?.get("id")?.as_u64()
|
||||
}
|
||||
|
||||
/// Whether a page name is the design system page (its number and words, however typed).
|
||||
pub fn is_page(name: &str) -> bool {
|
||||
let spaced: String = name.to_lowercase().chars().map(|c| if c.is_alphanumeric() { c } else { ' ' }).collect();
|
||||
spaced.split_whitespace().collect::<Vec<_>>().join(" ") == "00 design system"
|
||||
}
|
||||
|
||||
/// The design system page (id) and the guidelines text layer on it (id, text), if there.
|
||||
/// The design system page's id, and its guidelines text layer (id, text), each if there.
|
||||
type Found = (Option<u64>, Option<(u64, String)>);
|
||||
|
||||
fn find(b: &mut dyn figcraft_mcp::Backend, doc: Option<u64>) -> Result<Found, String> {
|
||||
let pages = exec(b, doc, "page.list", json!({}))?;
|
||||
let Some(page) = pages
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|p| p.get("name").and_then(Value::as_str).is_some_and(is_page))
|
||||
.and_then(|p| p.get("id").and_then(Value::as_u64))
|
||||
else {
|
||||
return Ok((None, None));
|
||||
};
|
||||
let found = exec(b, doc, "node.find", json!({"name": GUIDELINES, "root": page, "type": "text"}))?;
|
||||
let ids: Vec<u64> = found.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect();
|
||||
for id in ids {
|
||||
let node = exec(b, doc, "node.get", json!({"id": id}))?;
|
||||
if let Some(text) = node.get("characters").or_else(|| node.get("text")).and_then(Value::as_str) {
|
||||
return Ok((Some(page), Some((id, text.to_string()))));
|
||||
}
|
||||
}
|
||||
Ok((Some(page), None))
|
||||
}
|
||||
|
||||
/// Answer a `design_system` call through the window (or file) the agent works in: the text for
|
||||
/// the model, and whether it worked.
|
||||
pub fn call(b: &mut dyn figcraft_mcp::Backend, args: &Value) -> (String, bool) {
|
||||
match run(b, args) {
|
||||
Ok(text) => (text, true),
|
||||
Err(e) => (format!("design_system failed: {e}"), false),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(b: &mut dyn figcraft_mcp::Backend, args: &Value) -> Result<String, String> {
|
||||
let doc = front_document(b);
|
||||
let (page, guidelines) = find(b, doc)?;
|
||||
let vars = exec(b, doc, "variable.list", json!({}))?;
|
||||
let styles = exec(b, doc, "style.list", json!({}))?;
|
||||
let existing = Existing::from_lists(&vars, &styles);
|
||||
let collections: Vec<&String> = existing.collections.keys().collect();
|
||||
let Some(fields) = args.get("spec").or_else(|| args.get("brief")).and_then(Value::as_object) else {
|
||||
return Ok(match page {
|
||||
None => format!(
|
||||
"This file has no '{PAGE}' page yet. Variable collections: {}.",
|
||||
if collections.is_empty() { "none".to_string() } else { format!("{collections:?}") }
|
||||
),
|
||||
Some(id) => format!(
|
||||
"'{PAGE}' is page {id}; read its frames with design_context. Variable collections: {collections:?}.\n{}",
|
||||
guidelines.map(|(_, t)| t).unwrap_or_else(|| "It has no 'Design guidelines' text yet.".into())
|
||||
),
|
||||
});
|
||||
};
|
||||
let mut merged = serde_json::to_value(Brief::default()).map_err(|e| e.to_string())?;
|
||||
if let Some(obj) = merged.as_object_mut() {
|
||||
for (k, v) in fields {
|
||||
let v = match v {
|
||||
Value::String(s)
|
||||
if matches!(k.as_str(), "platform" | "neutral" | "modes" | "scale" | "radius" | "elevation" | "iconStyle" | "contrast") =>
|
||||
{
|
||||
Value::String(s.to_lowercase())
|
||||
}
|
||||
other => other.clone(),
|
||||
};
|
||||
obj.insert(k.clone(), v);
|
||||
}
|
||||
}
|
||||
let spec: Brief = serde_json::from_value(merged).map_err(|e| format!("the spec has a field with a wrong value: {e}"))?;
|
||||
// The page (first in the file), the tokens, styles and review settings, and the guidelines
|
||||
// text, in one batch: one undo step, and nothing changed when any part fails.
|
||||
let text = spec.guidelines();
|
||||
let tokens = spec.steps(&existing);
|
||||
let made = tokens.iter().filter(|s| matches!(s["command"].as_str(), Some("variable.create" | "style.create"))).count();
|
||||
let mut steps = Vec::with_capacity(tokens.len() + 3);
|
||||
let page_ref = match page {
|
||||
Some(id) => json!(id),
|
||||
None => {
|
||||
steps.push(json!({"command": "page.add", "params": {"name": PAGE}, "as": "dsPage"}));
|
||||
json!({"$ref": "dsPage"})
|
||||
}
|
||||
};
|
||||
steps.push(json!({"command": "page.move", "params": {"id": page_ref, "index": 0}}));
|
||||
steps.extend(tokens);
|
||||
steps.push(match guidelines {
|
||||
Some((id, _)) => json!({"command": "node.set", "params": {"ids": [id], "props": {"characters": text}}}),
|
||||
None => json!({"command": "node.create", "params": {
|
||||
"type": "text", "parent": page_ref, "name": GUIDELINES, "x": -560, "y": 0, "characters": text, "select": false,
|
||||
"props": {"width": 480, "textAutoResize": "height", "fontSize": 14, "lineHeight": 22}}}),
|
||||
});
|
||||
exec(b, doc, "command.batch", json!({"label": "Design system", "commands": steps}))?;
|
||||
let (page, _) = find(b, doc)?;
|
||||
let page = page.ok_or("the design system page is missing after it was made")?;
|
||||
Ok(format!(
|
||||
"'{PAGE}' is page {page} (first in the file), with {made} new variables and styles: {PRIMITIVES} (colour ramps 50-900), {THEME} (roles, modes {}), {SIZES} (Space/…, Radius/S|M|L|Full, Border/…, Icon/…); text styles Display, Heading 1-3, Body large, Body, Body small, Caption, Label, Code; shadow styles Shadow/S, M, L; design.audit settings from the spec; and a 'Design guidelines' text. Lay out the foundations and base components on that page next (the 'Design system setup' skill).\n{text}",
|
||||
spec.modes.names().join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_brief_reads_back_and_an_old_one_takes_the_defaults() {
|
||||
let b = Brief { product: "Klinik".into(), icon_set: "Phosphor".into(), ..Brief::default() };
|
||||
assert_eq!(Brief::from_json(&b.to_json()), Some(b));
|
||||
let old = Brief::from_json(r#"{"product": "X"}"#).expect("a partial brief");
|
||||
assert_eq!(old.product, "X");
|
||||
assert_eq!(old.spacing, Brief::default().spacing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ramp_goes_from_pale_to_deep_in_the_colours_hue() {
|
||||
let r = ramp("#2563EB").expect("a colour");
|
||||
assert_eq!(r.len(), STEPS.len());
|
||||
let lum: Vec<f32> = r.iter().filter_map(|h| Color::from_hex(h)).map(Color::luminance).collect();
|
||||
assert!(lum.windows(2).all(|w| w[0] > w[1]), "each step darker: {r:?}");
|
||||
assert!(ramp("not a colour").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_again_updates_instead_of_making_copies() {
|
||||
let b = Brief::default();
|
||||
let fresh = b.steps(&Existing::default());
|
||||
let creates = |steps: &[Value], cmd: &str| steps.iter().filter(|s| s["command"] == cmd).count();
|
||||
assert!(creates(&fresh, "variable.createCollection") == 3);
|
||||
assert!(creates(&fresh, "variable.create") > 40);
|
||||
assert!(creates(&fresh, "style.create") >= 13);
|
||||
|
||||
let mut existing = Existing::default();
|
||||
for s in &fresh {
|
||||
let p = &s["params"];
|
||||
match s["command"].as_str() {
|
||||
Some("variable.createCollection") => {
|
||||
let modes = p["modes"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
|
||||
existing.collections.insert(p["name"].as_str().unwrap_or_default().to_string(), modes);
|
||||
}
|
||||
Some("variable.create") => {
|
||||
let name: String = p["name"].as_str().unwrap_or_default().into();
|
||||
existing.variables.insert((p["collection"].as_str().unwrap_or_default().into(), name.clone()), name);
|
||||
}
|
||||
Some("style.create") => {
|
||||
existing.styles.insert(p["name"].as_str().unwrap_or_default().into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let again = b.steps(&existing);
|
||||
assert_eq!(creates(&again, "variable.createCollection") + creates(&again, "variable.create") + creates(&again, "style.create"), 0);
|
||||
assert!(creates(&again, "variable.set") > 0 && creates(&again, "style.update") > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_names_the_icon_set_and_its_style() {
|
||||
let b = Brief { icon_set: "Phosphor".into(), icon_style: IconStyle::Duotone, ..Brief::default() };
|
||||
let p = b.guidelines();
|
||||
assert!(p.contains("Phosphor") && p.contains("Duotone"));
|
||||
assert!(p.contains("never emoji"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_design_system_page_itself_counts() {
|
||||
assert!(is_page("00 · Design System") && is_page("00 - design system") && is_page("00_Design_System"));
|
||||
assert!(!is_page("00 · Design System exploration"));
|
||||
assert!(!is_page("Design System"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_names_the_variable_of_its_own_collection() {
|
||||
let vars = json!({
|
||||
"collections": [{"id": "c1", "name": "Other", "modes": [{"name": "Default"}]}, {"id": "c2", "name": SIZES, "modes": [{"name": "Default"}]}],
|
||||
"variables": [{"id": "v1", "collection": "c1", "name": "Radius/S"}, {"id": "v2", "collection": "c2", "name": "Radius/S"}],
|
||||
});
|
||||
let existing = Existing::from_lists(&vars, &json!([]));
|
||||
let steps = Brief::default().steps(&existing);
|
||||
let set = steps.iter().find(|s| s["command"] == "variable.set" && s["params"]["variable"].as_str().is_some_and(|v| v.starts_with('v')));
|
||||
assert_eq!(set.map(|s| s["params"]["variable"].clone()), Some(json!("v2")));
|
||||
}
|
||||
|
||||
/// The engine as the agent's tools see it, without a window.
|
||||
struct Engine(figcraft_engine::Session);
|
||||
|
||||
impl figcraft_mcp::Backend for Engine {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match method {
|
||||
"engine.execute" => {
|
||||
let cmd = params["command"].as_str().unwrap_or_default().to_string();
|
||||
self.0.execute(&cmd, ¶ms["params"]).map_err(|e| e.to_string())
|
||||
}
|
||||
other => Err(format!("not here: {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"test".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_makes_the_design_system_page_with_one_call_and_reads_it_back() {
|
||||
let mut engine = Engine(figcraft_engine::Session::new());
|
||||
let (text, ok) = call(&mut engine, &json!({}));
|
||||
assert!(ok && text.contains("no '00 · Design System' page"), "{text}");
|
||||
|
||||
let spec = json!({"spec": {"product": "Klinik", "primary": "#0F766E", "radius": "Round", "iconSet": "Phosphor", "spacing": 8}});
|
||||
let (text, ok) = call(&mut engine, &spec);
|
||||
assert!(ok, "{text}");
|
||||
let pages = engine.0.execute("page.list", &json!({})).expect("pages");
|
||||
assert_eq!(pages[0]["name"], PAGE, "first in the file: {pages}");
|
||||
|
||||
// A later conversation finds the page and the guidelines on it.
|
||||
let (text, ok) = call(&mut engine, &json!({}));
|
||||
assert!(ok && text.contains("Phosphor") && text.contains("Klinik"), "{text}");
|
||||
let vars = engine.0.execute("variable.list", &json!({})).expect("variables");
|
||||
assert!(vars["collections"].as_array().into_iter().flatten().any(|c| c["name"] == THEME));
|
||||
let audit = engine.0.execute("design.audit", &json!({"scope": "page"})).expect("an audit");
|
||||
assert_eq!(audit["grid"], json!(8.0), "the spacing step is the review grid");
|
||||
|
||||
// One call is one undo step.
|
||||
let undo_to = engine.0.undo_depth().0;
|
||||
let (_, ok) = call(&mut engine, &json!({"spec": {"iconSet": "Feather"}}));
|
||||
assert!(ok);
|
||||
assert_eq!(engine.0.undo_depth().0, undo_to + 1, "one undo step");
|
||||
|
||||
// Again: the same page and guidelines, updated, not copied.
|
||||
let (_, ok) = call(&mut engine, &json!({"spec": {"iconSet": "Lucide"}}));
|
||||
assert!(ok);
|
||||
let pages = engine.0.execute("page.list", &json!({})).expect("pages");
|
||||
assert_eq!(pages.as_array().into_iter().flatten().filter(|p| p["name"] == PAGE).count(), 1);
|
||||
let (text, _) = call(&mut engine, &json!({}));
|
||||
assert!(text.contains("Lucide"));
|
||||
let found = engine.0.execute("node.find", &json!({"name": GUIDELINES, "root": pages[0]["id"]})).expect("find");
|
||||
assert_eq!(found["total"], json!(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
//! 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<PathBuf> {
|
||||
let name = kind.program()?;
|
||||
let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() };
|
||||
let mut dirs: Vec<PathBuf> = 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<PathBuf> {
|
||||
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::<Value>(&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<Vec<String>> {
|
||||
if kind != ApiKind::OpenCode {
|
||||
return None;
|
||||
}
|
||||
let path = locate(kind)?;
|
||||
let out = output(&path, &["models"])?;
|
||||
let ids: Vec<String> = 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<String> {
|
||||
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);
|
||||
// `exec`'s own options come before `resume`: that subcommand doesn't take them, and a
|
||||
// resumed turn must keep the read-only sandbox.
|
||||
cmd.arg("exec");
|
||||
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());
|
||||
}
|
||||
if let Some(s) = turn.session {
|
||||
cmd.args(["resume", s]);
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
||||
/// A folder of copies made for one run, removed when it is dropped (after the program has exited).
|
||||
struct Staged(Option<PathBuf>);
|
||||
|
||||
impl Drop for Staged {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dir) = self.0.take() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the attached images where the program can read them, in a folder of this run's own that
|
||||
/// goes away with `staged`; their paths, in order.
|
||||
fn write_images(turn: &Turn<'_>, staged: &mut Staged) -> Result<Vec<PathBuf>, String> {
|
||||
if turn.images.is_empty() || turn.kind == ApiKind::ClaudeCode {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
use base64::Engine as _;
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let dir = turn.workdir.join("attachments").join(format!("{stamp}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?;
|
||||
staged.0 = Some(dir.clone());
|
||||
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!("{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<Parsed>, 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<Parsed> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(v) = serde_json::from_str::<Value>(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<String>,
|
||||
pub usage: Usage,
|
||||
pub stopped: bool,
|
||||
/// The error to show, when the run failed.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<AtomicBool>) -> 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();
|
||||
// Declared before the child, so the copies outlive it: removed after it has exited.
|
||||
let mut staged = Staged(None);
|
||||
let files = match write_images(turn, &mut staged) {
|
||||
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::<String>();
|
||||
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::<String>();
|
||||
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<String> = 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,
|
||||
}
|
||||
}
|
||||
// The program closed its output but may still be running: Stop keeps working until it exits.
|
||||
let status = loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
outcome.stopped = true;
|
||||
return outcome;
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(s)) => break Ok(s),
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
|
||||
Err(e) => break Err(e),
|
||||
}
|
||||
};
|
||||
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<String> = 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 a_resumed_codex_turn_keeps_the_read_only_sandbox() {
|
||||
let dir = std::env::temp_dir();
|
||||
let turn = Turn {
|
||||
kind: ApiKind::Codex,
|
||||
program: Path::new("codex"),
|
||||
model: "",
|
||||
session: Some("th-1"),
|
||||
prompt: "again",
|
||||
system: "rules",
|
||||
mcp_url: "http://127.0.0.1:1/mcp",
|
||||
mcp_token: "t",
|
||||
workdir: &dir,
|
||||
images: &[],
|
||||
};
|
||||
let args: Vec<String> = command(&turn, &[]).get_args().map(|a| a.to_string_lossy().into_owned()).collect();
|
||||
let at = |a: &str| args.iter().position(|x| x == a);
|
||||
let resume = at("resume").expect("resumes");
|
||||
assert!(at("--sandbox").is_some_and(|i| i < resume && args[i + 1] == "read-only"), "{args:?}");
|
||||
assert!(at("--json").is_some_and(|i| i < resume));
|
||||
}
|
||||
|
||||
#[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::<Vec<_>>();
|
||||
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"]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
//! 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. File access is confined only when the app was started with
|
||||
/// automation roots; a window opened normally has none.
|
||||
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<String>,
|
||||
/// 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<String> {
|
||||
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<Provider>,
|
||||
/// 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<String>) {
|
||||
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::<Self>(&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::<Vec<_>>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<dyn BufRead + Send>,
|
||||
}
|
||||
|
||||
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<ureq::typestate::WithBody>, headers: &[(&str, String)], body: &Value) -> Result<Reply, String> {
|
||||
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<Reply, String> {
|
||||
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<Value, String> {
|
||||
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::<Value>(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<dyn BufRead + Send>) -> 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)
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! 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 brief;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod http;
|
||||
pub mod mcp_http;
|
||||
pub mod neutral;
|
||||
pub mod openai;
|
||||
pub mod session;
|
||||
pub mod skills;
|
||||
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<Invocation>,
|
||||
pub stop: String,
|
||||
pub usage: Usage,
|
||||
}
|
||||
|
||||
/// What the panel tells the worker to do.
|
||||
pub enum Command {
|
||||
Turn {
|
||||
text: String,
|
||||
context: Option<String>,
|
||||
/// Images the person attached (references, a render of the selection).
|
||||
images: Vec<neutral::Image>,
|
||||
},
|
||||
/// 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<std::path::PathBuf>),
|
||||
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<Command>,
|
||||
/// Events of the running (or last) turn, drained by the panel every frame.
|
||||
pub events: Receiver<ChatEvent>,
|
||||
/// Set to stop the running turn; the worker clears it when the next one starts.
|
||||
pub cancel: Arc<AtomicBool>,
|
||||
/// 0: ask before file and network tools, 1: auto.
|
||||
pub permission: Arc<AtomicU8>,
|
||||
/// Whether a turn that changes the canvas ends with a look at it.
|
||||
pub review: Arc<AtomicBool>,
|
||||
/// The skills the model can load; the panel keeps it current.
|
||||
pub skills: skills::SkillBook,
|
||||
/// False once the thread ended (a panic included), so the panel can say so.
|
||||
alive: Arc<AtomicBool>,
|
||||
handle: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
/// Clears the worker's `alive` flag however the thread ends, a panic included.
|
||||
struct Alive(Arc<AtomicBool>);
|
||||
|
||||
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<dyn Fn() + Send + Sync>) -> Self {
|
||||
let (commands, inbox) = channel::<Command>();
|
||||
let (out, events) = channel::<ChatEvent>();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let permission = Arc::new(AtomicU8::new(0));
|
||||
let review = Arc::new(AtomicBool::new(true));
|
||||
let skills: skills::SkillBook = Arc::new(std::sync::RwLock::new(skills::builtins()));
|
||||
let thread_skills = skills.clone();
|
||||
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;
|
||||
agent.skills = thread_skills;
|
||||
let mut history: Option<std::path::PathBuf> = 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<dyn Fn(ChatEvent) + Send + Sync> = 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, skills, alive, handle: handle.ok() }
|
||||
}
|
||||
|
||||
pub fn send_turn(&self, text: String, context: Option<String>) -> 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<String>, images: Vec<neutral::Image>) -> 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<std::path::PathBuf>) -> 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<Vec<String>, 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<String> = 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)
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
//! 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::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<AtomicU8>,
|
||||
/// The panel's event stream.
|
||||
pub sink: Arc<dyn Fn(ChatEvent) + Send + Sync>,
|
||||
/// Set by Stop: calls still arriving are refused.
|
||||
pub cancel: Arc<AtomicBool>,
|
||||
/// Set when a call changed the document, so the turn can end with a look at the canvas.
|
||||
pub edited: Arc<AtomicBool>,
|
||||
/// The skills `load_skill` answers from (a tool this endpoint adds to FigCraft's own).
|
||||
pub skills: crate::skills::SkillBook,
|
||||
}
|
||||
|
||||
/// A running endpoint; dropping it stops the listener.
|
||||
pub struct Endpoint {
|
||||
pub url: String,
|
||||
pub token: String,
|
||||
stop: Arc<AtomicBool>,
|
||||
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<Option<Value>>);
|
||||
|
||||
/// Start serving FigCraft's tools on a free loopback port.
|
||||
pub fn start(remote: Remote, gate: Gate) -> std::io::Result<Endpoint> {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0))?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let token = new_token().map_err(std::io::Error::other)?;
|
||||
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::<Job>();
|
||||
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<Job>) {
|
||||
let mut own = remote.clone();
|
||||
let mut server = figcraft_mcp::Server::new(Box::new(remote));
|
||||
while let Ok((msg, reply)) = inbox.recv() {
|
||||
let answer = handle_gated(&mut server, &mut own, &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, own: &mut Remote, gate: &Gate, msg: Value) -> Option<Value> {
|
||||
match msg.get("method").and_then(Value::as_str) {
|
||||
Some("tools/call") => {}
|
||||
Some("tools/list") => {
|
||||
let mut answer = server.handle(msg)?;
|
||||
if let Some(tools) = answer.pointer_mut("/result/tools").and_then(Value::as_array_mut) {
|
||||
tools.push(crate::skills::tool_definition());
|
||||
tools.push(crate::brief::tool_definition());
|
||||
}
|
||||
return Some(answer);
|
||||
}
|
||||
_ => 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() });
|
||||
// A call that arrives after Stop runs nothing, FigCraft's own tools included.
|
||||
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 name == crate::brief::TOOL_NAME {
|
||||
let (text, ok) = crate::brief::call(own, &args);
|
||||
if ok && (args.get("spec").is_some() || args.get("brief").is_some()) {
|
||||
gate.edited.store(true, Ordering::Relaxed);
|
||||
}
|
||||
(gate.sink)(ChatEvent::ToolEnd {
|
||||
id: call_id,
|
||||
name: name.clone(),
|
||||
ok,
|
||||
title: crate::session::tool_title(&name, &args),
|
||||
text: crate::session::summarize(&text),
|
||||
});
|
||||
return Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": !ok}}));
|
||||
}
|
||||
if name == crate::skills::TOOL_NAME {
|
||||
let (text, ok) = crate::skills::call(&gate.skills, &args);
|
||||
(gate.sink)(ChatEvent::ToolEnd {
|
||||
id: call_id,
|
||||
name: name.clone(),
|
||||
ok,
|
||||
title: crate::session::tool_title(&name, &args),
|
||||
text: crate::session::summarize(&text),
|
||||
});
|
||||
return Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": !ok}}));
|
||||
}
|
||||
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})"));
|
||||
}
|
||||
// Stop may have come while the Allow was waiting.
|
||||
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());
|
||||
}
|
||||
}
|
||||
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));
|
||||
if ok && crate::session::mutating(&name, &args) {
|
||||
gate.edited.store(true, Ordering::Relaxed);
|
||||
}
|
||||
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<Job>) {
|
||||
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<u8>,
|
||||
}
|
||||
|
||||
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<u8>,
|
||||
}
|
||||
|
||||
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<Value>) -> 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::<Value>(&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<Value> = 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<Option<Request>, u16> {
|
||||
let line = match read_line_limited(reader, MAX_HEADERS) {
|
||||
Ok(Some(l)) => l,
|
||||
Ok(None) => return Ok(None),
|
||||
Err(LineError::TooLong) => return Err(431),
|
||||
Err(LineError::Io) => 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 h = match read_line_limited(reader, MAX_HEADERS.saturating_sub(size)) {
|
||||
Ok(Some(h)) => h,
|
||||
Ok(None) | Err(LineError::Io) => return Err(400),
|
||||
Err(LineError::TooLong) => return Err(431),
|
||||
};
|
||||
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::<usize>().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 }))
|
||||
}
|
||||
|
||||
enum LineError {
|
||||
TooLong,
|
||||
Io,
|
||||
}
|
||||
|
||||
/// One line of at most `limit` bytes, read without keeping more than that; `None` at the end.
|
||||
fn read_line_limited(reader: &mut impl BufRead, limit: usize) -> Result<Option<String>, LineError> {
|
||||
use std::io::Read as _;
|
||||
let mut bytes = Vec::new();
|
||||
let read = reader.by_ref().take(limit as u64 + 1).read_until(b'\n', &mut bytes).map_err(|_| LineError::Io)?;
|
||||
if read == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if bytes.len() > limit {
|
||||
return Err(LineError::TooLong);
|
||||
}
|
||||
Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
|
||||
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",
|
||||
431 => "Request Header Fields 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 operating system's secure random number generator.
|
||||
fn new_token() -> Result<String, String> {
|
||||
let mut b = [0u8; 16];
|
||||
getrandom::fill(&mut b).map_err(|e| format!("no secure random numbers: {e}"))?;
|
||||
Ok(b.iter().map(|x| format!("{x:02x}")).collect())
|
||||
}
|
||||
|
||||
#[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<Value> {
|
||||
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 an_endless_header_is_refused_before_it_is_all_read() {
|
||||
let raw = format!("POST /mcp HTTP/1.1\r\nX-Long: {}", "a".repeat(MAX_HEADERS * 2));
|
||||
let mut reader = BufReader::new(raw.as_bytes());
|
||||
assert_eq!(read_request(&mut reader).err(), Some(431));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_differ() {
|
||||
assert_ne!(new_token(), new_token());
|
||||
assert_eq!(new_token().map(|t| t.len()), Ok(32));
|
||||
}
|
||||
}
|
||||
@@ -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<Image>,
|
||||
},
|
||||
}
|
||||
|
||||
#[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<Block>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn user_text(text: impl Into<String>) -> 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<String> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Image>) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! 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;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::config::Provider;
|
||||
use crate::http::{Http, read_error};
|
||||
use crate::neutral::{Block, Message, Role};
|
||||
use crate::{Invocation, Step, Usage};
|
||||
|
||||
/// What a stream that ended before the answer did is reported as.
|
||||
pub const INTERRUPTED: &str = "the connection closed before the answer finished; ask the agent to continue";
|
||||
|
||||
/// 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<Value> {
|
||||
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<Step, String> {
|
||||
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 events = crate::sse::spawn_events(reply.body);
|
||||
let mut step = Step::default();
|
||||
// Whether the endpoint said the answer is over (`finish_reason` or `[DONE]`); a stream that
|
||||
// just ends without it was cut off.
|
||||
let mut finished = false;
|
||||
// Tool calls arrive split across chunks: keyed by their `index`, their name once, their
|
||||
// arguments as JSON text joined together.
|
||||
let mut calls: BTreeMap<u64, (String, String, String)> = BTreeMap::new();
|
||||
while let Some(event) = crate::sse::next(&events, cancel)? {
|
||||
let data = event.data.trim();
|
||||
if data.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if data == "[DONE]" {
|
||||
finished = true;
|
||||
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();
|
||||
finished = true;
|
||||
}
|
||||
}
|
||||
if !finished {
|
||||
return Err(INTERRUPTED.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<u64, (String, String, String)> = 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
//! 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<bool> },
|
||||
/// 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<Message>,
|
||||
http: Http,
|
||||
backend: crate::bridge::Remote,
|
||||
system: String,
|
||||
tools: Vec<Value>,
|
||||
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<AtomicU8>,
|
||||
/// Whether a turn that changed the canvas ends with the agent looking at it once.
|
||||
pub review: Arc<AtomicBool>,
|
||||
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<Arc<dyn Fn(ChatEvent) + Send + Sync>>,
|
||||
/// Where a command-line agent runs (beside the saved chats); a temporary folder without one.
|
||||
pub workdir: Option<PathBuf>,
|
||||
/// 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<crate::mcp_http::Endpoint>,
|
||||
/// Set by the endpoint when the command-line agent changed the document this turn.
|
||||
cli_edited: Arc<AtomicBool>,
|
||||
/// The skills `load_skill` answers from.
|
||||
pub skills: crate::skills::SkillBook,
|
||||
}
|
||||
|
||||
impl Agent {
|
||||
pub fn new(provider: Provider, backend: crate::bridge::Remote) -> Self {
|
||||
let mut tools = figcraft_mcp::tool_definitions();
|
||||
tools.push(crate::skills::tool_definition());
|
||||
tools.push(crate::brief::tool_definition());
|
||||
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,
|
||||
cli_edited: Arc::new(AtomicBool::new(false)),
|
||||
skills: Arc::new(std::sync::RwLock::new(crate::skills::builtins())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<String>, out: &dyn Fn(ChatEvent), cancel: &Arc<AtomicBool>) -> 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<String>,
|
||||
images: Vec<crate::neutral::Image>,
|
||||
out: &dyn Fn(ChatEvent),
|
||||
cancel: &Arc<AtomicBool>,
|
||||
) -> 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();
|
||||
if self.messages.last().map(message_chars).unwrap_or(0) > self.budget() {
|
||||
self.messages.pop();
|
||||
return Err("this request is too large for the model's context window; attach fewer or smaller images, or shorten it".into());
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
let mut blocks = Vec::new();
|
||||
if !step.text.is_empty() {
|
||||
blocks.push(Block::Text(step.text.clone()));
|
||||
}
|
||||
// An answer cut off at the output limit may end inside a tool call's arguments: keep
|
||||
// its text, run none of its calls, and say so.
|
||||
if matches!(step.stop.as_str(), "length" | "max_tokens") {
|
||||
if !blocks.is_empty() {
|
||||
self.messages.push(Message { role: Role::Assistant, blocks });
|
||||
}
|
||||
return Err("the answer hit the model's output limit before it finished; ask the agent to continue".into());
|
||||
}
|
||||
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();
|
||||
let mut stopped = false;
|
||||
for call in step.calls {
|
||||
// Every call gets a result, run or not: a call without one fails the next request.
|
||||
if stopped || cancel.load(Ordering::Relaxed) {
|
||||
stopped = true;
|
||||
results.push(Block::ToolResult {
|
||||
id: call.id,
|
||||
name: call.name,
|
||||
ok: false,
|
||||
text: "Not run: the user stopped the agent".into(),
|
||||
images: vec![],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let outcome = self.run_tool(call, out, cancel);
|
||||
results.push(outcome);
|
||||
}
|
||||
self.messages.push(Message { role: Role::User, blocks: results });
|
||||
if stopped {
|
||||
out(ChatEvent::Done { stopped: true });
|
||||
return Ok(());
|
||||
}
|
||||
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<AtomicBool>,
|
||||
) -> Result<(), String> {
|
||||
self.cli_edited.store(false, Ordering::Relaxed);
|
||||
if self.cli_pass(prompt, images, out, cancel)? {
|
||||
out(ChatEvent::Done { stopped: true });
|
||||
return Ok(());
|
||||
}
|
||||
// One look at the canvas after a turn that changed it, as the API connections do: the
|
||||
// program gets the picture in the same conversation and fixes what it sees.
|
||||
if self.review.load(Ordering::Relaxed)
|
||||
&& self.cli_edited.load(Ordering::Relaxed)
|
||||
&& !cancel.load(Ordering::Relaxed)
|
||||
&& let Some(image) = self.look(out)
|
||||
{
|
||||
// The request itself is done; a model that can't take the picture leaves it at that.
|
||||
match self.cli_pass(REVIEW_PROMPT, &[image], out, cancel) {
|
||||
Ok(true) => {
|
||||
out(ChatEvent::Done { stopped: true });
|
||||
return Ok(());
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(e) => out(ChatEvent::Text(format!("(The check of the result did not run: {})", crate::neutral::clip(&e, 200)))),
|
||||
}
|
||||
}
|
||||
out(ChatEvent::Done { stopped: false });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run the command-line agent once; `true` when the person stopped it.
|
||||
fn cli_pass(
|
||||
&mut self,
|
||||
prompt: &str,
|
||||
images: &[crate::neutral::Image],
|
||||
out: &dyn Fn(ChatEvent),
|
||||
cancel: &Arc<AtomicBool>,
|
||||
) -> Result<bool, 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(),
|
||||
edited: self.cli_edited.clone(),
|
||||
skills: self.skills.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 {
|
||||
return Ok(true);
|
||||
}
|
||||
match outcome.error {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn stream(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc<AtomicBool>) -> Result<Step, String> {
|
||||
let mut on_text = |t: &str| {
|
||||
out(ChatEvent::Text(t.to_string()));
|
||||
};
|
||||
// A model that reads no images gets none, also from earlier in the conversation (a chat
|
||||
// begun on another connection); the saved conversation keeps them.
|
||||
let filtered;
|
||||
let messages: &[Message] = if self.provider.vision {
|
||||
&self.messages
|
||||
} else {
|
||||
filtered = without_images(&self.messages);
|
||||
&filtered
|
||||
};
|
||||
let result = match self.provider.kind {
|
||||
ApiKind::OpenAiCompletions => {
|
||||
crate::openai::stream(&self.http, &self.provider, &self.system, messages, &self.tools, &self.session, &mut on_text, cancel)
|
||||
}
|
||||
ApiKind::AnthropicMessages => {
|
||||
crate::anthropic::stream(&self.http, &self.provider, &self.system, 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<AtomicBool>) -> 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 call.name == crate::brief::TOOL_NAME {
|
||||
let (text, ok) = crate::brief::call(&mut self.backend, &call.args);
|
||||
if ok && (call.args.get("spec").is_some() || call.args.get("brief").is_some()) {
|
||||
self.did_edit = true;
|
||||
}
|
||||
out(ChatEvent::ToolEnd {
|
||||
id: call.id.clone(),
|
||||
name: call.name.clone(),
|
||||
ok,
|
||||
title: tool_title(&call.name, &call.args),
|
||||
text: summarize(&text),
|
||||
});
|
||||
return Block::ToolResult { id: call.id, name: call.name, ok, text, images: vec![] };
|
||||
}
|
||||
if call.name == crate::skills::TOOL_NAME {
|
||||
let (text, ok) = crate::skills::call(&self.skills, &call.args);
|
||||
out(ChatEvent::ToolEnd {
|
||||
id: call.id.clone(),
|
||||
name: call.name.clone(),
|
||||
ok,
|
||||
title: tool_title(&call.name, &call.args),
|
||||
text: summarize(&text),
|
||||
});
|
||||
return Block::ToolResult { id: call.id, name: call.name, ok, text, images: vec![] };
|
||||
}
|
||||
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<AtomicBool>) -> bool {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return false;
|
||||
}
|
||||
match self.look(out) {
|
||||
Some(image) => {
|
||||
self.messages.push(Message { role: Role::User, blocks: vec![Block::Text(REVIEW_PROMPT.into()), Block::Image(image)] });
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture the page for a review, shown as a step in the panel.
|
||||
fn look(&mut self, out: &dyn Fn(ChatEvent)) -> Option<crate::neutral::Image> {
|
||||
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().filter(|_| !result.is_error);
|
||||
out(ChatEvent::ToolEnd {
|
||||
id,
|
||||
name: "screenshot".into(),
|
||||
ok: image.is_some(),
|
||||
title: "Checking the result".into(),
|
||||
text: if image.is_some() { "Looking at the canvas".into() } else { crate::neutral::clip(&text, 200) },
|
||||
});
|
||||
image
|
||||
}
|
||||
|
||||
/// 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.budget();
|
||||
trim_messages(&mut self.messages, budget);
|
||||
}
|
||||
|
||||
/// Characters of conversation the model's context window takes, with room for the answer.
|
||||
fn budget(&self) -> usize {
|
||||
(self.provider.context_window as usize).saturating_mul(CHARS_PER_TOKEN).saturating_sub(24_000).clamp(60_000, 800_000)
|
||||
}
|
||||
}
|
||||
|
||||
/// The conversation without its images, for a model that reads none; each left-out image is named
|
||||
/// so the model knows something was there.
|
||||
fn without_images(messages: &[Message]) -> Vec<Message> {
|
||||
messages
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let mut blocks = Vec::with_capacity(m.blocks.len());
|
||||
for b in &m.blocks {
|
||||
match b {
|
||||
Block::Image(_) => blocks.push(Block::Text("[an image left out: this model does not read images]".into())),
|
||||
Block::ToolResult { id, name, ok, text, images } if !images.is_empty() => blocks.push(Block::ToolResult {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
ok: *ok,
|
||||
text: format!("{text}\n[{} image(s) left out: this model does not read images]", images.len()),
|
||||
images: vec![],
|
||||
}),
|
||||
other => blocks.push(other.clone()),
|
||||
}
|
||||
}
|
||||
Message { role: m.role, blocks }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Shorten the oldest messages until the conversation fits `budget`, keeping the last eight
|
||||
/// messages whole: the recent steps are what the model is working from. First old tool output and
|
||||
/// images go, then long old text; messages stay, so every tool call keeps its result.
|
||||
fn trim_messages(messages: &mut [Message], budget: usize) {
|
||||
let keep = messages.len().saturating_sub(8);
|
||||
let mut total: usize = messages.iter().map(message_chars).sum();
|
||||
for pass in 0..2 {
|
||||
let mut i = 0;
|
||||
while total > budget && i < keep {
|
||||
let before = message_chars(&messages[i]);
|
||||
for block in &mut messages[i].blocks {
|
||||
match block {
|
||||
Block::ToolResult { text, images, .. } if pass == 0 => {
|
||||
if text.len() > 200 {
|
||||
*text = "[older tool output left out]".to_string();
|
||||
}
|
||||
images.clear();
|
||||
}
|
||||
Block::Image(_) if pass == 0 => *block = Block::Text("[older image left out]".into()),
|
||||
Block::Text(t) if pass == 1 && t.len() > 2_000 => *t = "[older message shortened]".to_string(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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<Message>,
|
||||
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<ApiKind>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cli_session: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether a tool call can change what the canvas looks like (so a look at it is worth a review).
|
||||
pub(crate) fn mutating(name: &str, args: &Value) -> bool {
|
||||
match name {
|
||||
"create_node" | "set_properties" | "batch" | "undo" | "redo" => true,
|
||||
crate::brief::TOOL_NAME => args.get("spec").is_some() || args.get("brief").is_some(),
|
||||
"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::<usize>(),
|
||||
})
|
||||
.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 == crate::skills::TOOL_NAME {
|
||||
return format!("Skill: {}", args.get("name").and_then(Value::as_str).unwrap_or(""));
|
||||
}
|
||||
if name == crate::brief::TOOL_NAME {
|
||||
return if args.get("spec").is_some() || args.get("brief").is_some() {
|
||||
"Design system: make the 00 · Design System page".into()
|
||||
} else {
|
||||
"Design system: read the 00 · Design System page".into()
|
||||
};
|
||||
}
|
||||
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<String> {
|
||||
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).or_else(|| if cmd == "command.batch" { batch_reason(args.get("params"), 0) } else { None })
|
||||
}
|
||||
"batch" => batch_reason(Some(args), 0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first reason a step of a batch needs the person's Allow, nested batches included.
|
||||
fn batch_reason(params: Option<&Value>, depth: usize) -> Option<String> {
|
||||
// Deeper than the engine accepts: refuse to guess, ask.
|
||||
if depth > 16 {
|
||||
return Some("runs deeply nested commands".into());
|
||||
}
|
||||
params?.get("commands")?.as_array()?.iter().find_map(|step| {
|
||||
let cmd = step.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
command_reason(cmd).or_else(|| if cmd == "command.batch" { batch_reason(step.get("params"), depth + 1) } else { None })
|
||||
})
|
||||
}
|
||||
|
||||
fn command_reason(cmd: &str) -> Option<String> {
|
||||
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 ["plugin.", "plugins.", "library.", "libraries."].iter().any(|p| cmd.starts_with(p)) {
|
||||
return Some("installs or runs a plugin, or reaches a library server".into());
|
||||
}
|
||||
if cmd == "pref.publishServer" {
|
||||
return Some("changes where shared files are sent".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\
|
||||
- Read and change the file freely: every page and layer is yours to inspect (design_context, inspect_document, get_node, screenshot) \
|
||||
and to edit (create_node, set_properties, batch, run_command with any command: pages, layers, components, variables, styles, prototype). \
|
||||
Pages are part of the file's structure, like components: the request lists them with their frames. The design system lives on the page \
|
||||
'00 · Design System'; screens go on pages named by flow or area (create one with page.add when none fits). A page the user names with @ \
|
||||
means the frames on it.\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.\n\
|
||||
\n\
|
||||
How you work on a design request (new screens, pages, flows or components; not small edits to existing layers):\n\
|
||||
1. Foundations first. The file must have the page '00 · Design System'. If the request's page list has none, call `design_system` (no arguments) to check, \
|
||||
then propose a design system from what the user said: product and platform, primary colour (and secondary or accent if it helps), greys, light/dark, \
|
||||
heading and body fonts, corners, shadows, an open-source icon set and its style, tone and copy language. Give it in a few short lines and ask the user \
|
||||
to confirm or change it; stop there. When the user confirms (or asked you to go ahead without asking), call `design_system` with the spec: it makes \
|
||||
the page, the variables, the styles and the guidelines. Then lay out the foundations and base components on that page (the `Design system setup` skill). \
|
||||
When the page exists, read it first (`design_system` with no arguments for its guidelines, design_context for its frames).\n\
|
||||
2. Design with the system: Theme colours as {$var: name}, Sizes for spacing and corners, the text and shadow styles, existing components; \
|
||||
icons drawn in the brief's set and style, never emoji. Add a raw value only when nothing fits, and say so.\n\
|
||||
3. Before you say it is done, load the `Design review` skill and follow it: `design.audit` on what you made, `design.fix` for what it can repair, \
|
||||
then a screenshot for what no rule measures; fix what is safe to fix."
|
||||
.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());
|
||||
for cmd in ["plugins.runLast", "libraries.publish", "pref.publishServer"] {
|
||||
assert!(approval("run_command", &json!({"command": cmd})).is_some(), "{cmd}");
|
||||
}
|
||||
assert!(approval("screenshot", &json!({})).is_none());
|
||||
// Pages and the canvas are the agent's to read and change.
|
||||
for cmd in
|
||||
["page.add", "page.select", "page.rename", "page.move", "page.delete", "object.moveToPage", "node.set", "variable.create", "design.fix"]
|
||||
{
|
||||
assert!(approval("run_command", &json!({"command": cmd})).is_none(), "{cmd}");
|
||||
}
|
||||
assert!(approval("design_system", &json!({"spec": {}})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_command_inside_a_batch_still_asks() {
|
||||
let nested = json!({"commands": [{"command": "node.set"}, {"command": "command.batch", "params": {"commands": [{"command": "file.save"}]}}]});
|
||||
assert!(approval("batch", &nested).is_some());
|
||||
assert!(approval("run_command", &json!({"command": "command.batch", "params": nested})).is_some());
|
||||
assert!(approval("batch", &json!({"commands": [{"command": "node.set"}]})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_images_go_even_beside_short_text() {
|
||||
let image = crate::neutral::Image { mime: "image/png".into(), data: "A".repeat(5_000) };
|
||||
let mut messages: Vec<Message> = (0..30)
|
||||
.map(|_| Message {
|
||||
role: Role::User,
|
||||
blocks: vec![Block::ToolResult {
|
||||
id: "t".into(),
|
||||
name: "screenshot".into(),
|
||||
ok: true,
|
||||
text: "ok".into(),
|
||||
images: vec![image.clone()],
|
||||
}],
|
||||
})
|
||||
.collect();
|
||||
trim_messages(&mut messages, 60_000);
|
||||
let total: usize = messages.iter().map(message_chars).sum();
|
||||
assert!(total <= 60_000, "fits the budget: {total}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_only_model_gets_no_image_from_earlier_in_the_chat() {
|
||||
let messages = vec![Message {
|
||||
role: Role::User,
|
||||
blocks: vec![Block::Text("look".into()), Block::Image(crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() })],
|
||||
}];
|
||||
let sent = without_images(&messages);
|
||||
assert!(!sent[0].blocks.iter().any(|b| matches!(b, Block::Image(_))));
|
||||
assert!(matches!(messages[0].blocks[1], Block::Image(_)), "the conversation itself keeps it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimming_shortens_the_oldest_output_and_keeps_the_last_steps_whole() {
|
||||
let mut messages: Vec<Message> = (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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Skills: named instructions for a kind of work (a mobile screen, a landing page, a review…).
|
||||
//!
|
||||
//! A skill is a Markdown file with a small header:
|
||||
//!
|
||||
//! ```text
|
||||
//! ---
|
||||
//! name: Landing page
|
||||
//! description: When to use it, in one line (the model reads this to decide).
|
||||
//! ---
|
||||
//! The instructions.
|
||||
//! ```
|
||||
//!
|
||||
//! The app ships a few (built in, read-only); the person's own live in `agent-skills/` beside
|
||||
//! `agents.json`, and one with the same name as a built-in one replaces it. The person attaches a
|
||||
//! skill to a request with `/` in the composer; the model sees the list (names and descriptions)
|
||||
//! and loads one it needs with the `load_skill` tool, so only the skills used cost tokens.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The tool the model loads a skill with.
|
||||
pub const TOOL_NAME: &str = "load_skill";
|
||||
|
||||
/// The longest skill body kept (a skill is instructions, not a document).
|
||||
const MAX_BODY: usize = 20_000;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Skill {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub body: String,
|
||||
/// Shipped with the app (read-only).
|
||||
pub builtin: bool,
|
||||
/// The person's file, for one of their own.
|
||||
pub file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// The skills the agent can load, shared between the panel (which keeps it current) and the agent
|
||||
/// thread (which answers `load_skill`).
|
||||
pub type SkillBook = Arc<RwLock<Vec<Skill>>>;
|
||||
|
||||
/// Read a skill file's text: its header's name and description, and the body after it.
|
||||
pub fn parse(text: &str) -> Option<(String, String, String)> {
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
let rest = text.strip_prefix("---")?;
|
||||
let end = rest.find("\n---")?;
|
||||
let (head, body) = (&rest[..end], &rest[end + 4..]);
|
||||
let field = |key: &str| {
|
||||
head.lines().find_map(|l| {
|
||||
let (k, v) = l.split_once(':')?;
|
||||
(k.trim().eq_ignore_ascii_case(key)).then(|| v.trim().trim_matches('"').to_string())
|
||||
})
|
||||
};
|
||||
let name = field("name").filter(|n| !n.is_empty())?;
|
||||
let description = field("description").unwrap_or_default();
|
||||
let body = body.trim_start_matches(['\r', '\n']).trim_end().to_string();
|
||||
Some((name, description, body))
|
||||
}
|
||||
|
||||
/// A skill as the text of its file.
|
||||
pub fn to_text(name: &str, description: &str, body: &str) -> String {
|
||||
let one_line = |s: &str| s.replace(['\r', '\n'], " ").trim().to_string();
|
||||
format!("---\nname: {}\ndescription: {}\n---\n{}\n", one_line(name), one_line(description), body.trim())
|
||||
}
|
||||
|
||||
/// The built-in skills and the person's own from `dir` (theirs replace a built-in one of the same
|
||||
/// name), sorted by name.
|
||||
pub fn load(dir: Option<&Path>) -> Vec<Skill> {
|
||||
let mut skills = builtins();
|
||||
let mut own = Vec::new();
|
||||
if let Some(dir) = dir
|
||||
&& let Ok(entries) = std::fs::read_dir(dir)
|
||||
{
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
if path.extension().and_then(|x| x.to_str()) != Some("md") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
if let Some((name, description, body)) = parse(&text) {
|
||||
let body = crate::neutral::clip(&body, MAX_BODY);
|
||||
own.push(Skill { name, description, body, builtin: false, file: Some(path) });
|
||||
}
|
||||
}
|
||||
}
|
||||
for s in own {
|
||||
skills.retain(|b| !b.name.eq_ignore_ascii_case(&s.name));
|
||||
skills.push(s);
|
||||
}
|
||||
skills.sort_by_key(|s| s.name.to_lowercase());
|
||||
skills
|
||||
}
|
||||
|
||||
/// Write one of the person's skills to `dir` (replacing `old`, its file before a rename).
|
||||
pub fn save(dir: &Path, name: &str, description: &str, body: &str, old: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("a skill needs a name".into());
|
||||
}
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("can't create {}: {e}", dir.display()))?;
|
||||
let path = dir.join(format!("{}.md", slug(name)));
|
||||
let text = to_text(name, description, body);
|
||||
let write_err = |e: std::io::Error| format!("can't write {}: {e}", path.display());
|
||||
// Two names can share a file name ("Brand voice", "Brand-voice"): only this skill's own file is
|
||||
// replaced; any other file there, unreadable or not a skill included, is left alone.
|
||||
let own = old == Some(path.as_path())
|
||||
|| std::fs::read_to_string(&path).ok().and_then(|t| parse(&t)).is_some_and(|(other, _, _)| other.eq_ignore_ascii_case(name));
|
||||
if own {
|
||||
std::fs::write(&path, text).map_err(write_err)?;
|
||||
} else {
|
||||
use std::io::Write as _;
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| {
|
||||
if e.kind() == std::io::ErrorKind::AlreadyExists {
|
||||
format!("another file is saved as {}; give this skill a different name", path.display())
|
||||
} else {
|
||||
write_err(e)
|
||||
}
|
||||
})?;
|
||||
file.write_all(text.as_bytes()).map_err(write_err)?;
|
||||
}
|
||||
if let Some(old) = old
|
||||
&& old != path
|
||||
{
|
||||
let _ = std::fs::remove_file(old);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// A file name for a skill's name.
|
||||
fn slug(name: &str) -> String {
|
||||
let s: String = name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
|
||||
let s = s.split('-').filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-");
|
||||
if s.is_empty() { "skill".into() } else { s.chars().take(60).collect() }
|
||||
}
|
||||
|
||||
/// The skill named `name` (case does not matter).
|
||||
pub fn find(book: &SkillBook, name: &str) -> Option<Skill> {
|
||||
let name = name.trim().trim_start_matches('/');
|
||||
book.read().ok()?.iter().find(|s| s.name.eq_ignore_ascii_case(name)).cloned()
|
||||
}
|
||||
|
||||
/// What the model is told about the skills it can load.
|
||||
pub fn catalog(skills: &[Skill]) -> Option<String> {
|
||||
if skills.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut text = format!(
|
||||
"[Skills: instructions for kinds of work. When one fits the request, call `{TOOL_NAME}` with its name before you start, and follow it.]"
|
||||
);
|
||||
for s in skills {
|
||||
text.push_str(&format!("\n- {}: {}", s.name, s.description));
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The `load_skill` tool, as the tool list has it.
|
||||
pub fn tool_definition() -> Value {
|
||||
json!({
|
||||
"name": TOOL_NAME,
|
||||
"description": "Load a skill: instructions for a kind of work (the list of skills comes with the request). Call it before starting work that a skill fits.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"name": {"type": "string", "description": "The skill's name, as listed"}},
|
||||
"required": ["name"]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Answer a `load_skill` call: the skill's instructions, or why not (`false`).
|
||||
pub fn call(book: &SkillBook, args: &Value) -> (String, bool) {
|
||||
let name = args.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
match find(book, name) {
|
||||
Some(s) => (format!("Skill \"{}\":\n{}", s.name, s.body), true),
|
||||
None => {
|
||||
let names: Vec<String> = book.read().map(|b| b.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();
|
||||
(format!("No skill named \"{name}\". Skills: {}", names.join(", ")), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin(name: &str, description: &str, body: &str) -> Skill {
|
||||
Skill { name: name.into(), description: description.into(), body: body.trim().into(), builtin: true, file: None }
|
||||
}
|
||||
|
||||
/// The skills that come with the app (our own wording).
|
||||
pub fn builtins() -> Vec<Skill> {
|
||||
vec![
|
||||
builtin(
|
||||
"Mobile app screen",
|
||||
"Designing a phone app screen or flow (iOS or Android).",
|
||||
r#"
|
||||
- One frame per screen, 390 x 844, named after the screen. Several screens sit in a row, 80 apart.
|
||||
- Vertical auto layout for the screen; leave 47 at the top (status bar) and 34 at the bottom (home indicator).
|
||||
- Padding 16 or 20 at the sides; spacing in steps of 4 (8, 12, 16, 24, 32).
|
||||
- Touch targets at least 44 high; primary action at the bottom, full width, within thumb reach.
|
||||
- Type: title 28-34 bold, section 17-20 semibold, body 15-17, caption 12-13. At most three sizes per screen.
|
||||
- Navigation: a top bar with title and back, or a bottom tab bar with 3-5 items (icon and label).
|
||||
- Use the file's variables, styles and components first; make a component for anything repeated.
|
||||
- Real copy, not lorem ipsum, in the language the user writes in.
|
||||
"#,
|
||||
),
|
||||
builtin(
|
||||
"Landing page",
|
||||
"Designing a marketing website page or section (desktop first).",
|
||||
r#"
|
||||
- A 1440 wide frame, content at most 1200 wide and centred; vertical auto layout, sections 96-128 apart.
|
||||
- Order: navigation, hero (headline, one-line value, primary and secondary action, visual), proof (logos or numbers), features (3-6, icon, title, one sentence), how it works or a showcase, testimonials, pricing if asked, FAQ, final call to action, footer.
|
||||
- Hero headline 56-72, section titles 36-44, body 18. One primary colour for actions only.
|
||||
- Each section is its own frame named after it, so it can be moved or reused.
|
||||
- Real, specific copy for the product the user describes; no lorem ipsum.
|
||||
- When asked for mobile too, add a 390 wide frame with the same section names, stacked to one column.
|
||||
"#,
|
||||
),
|
||||
builtin(
|
||||
"Design review",
|
||||
"Checking a design for problems (contrast, spacing, alignment, consistency) and fixing them.",
|
||||
r#"
|
||||
Measure first, then judge. FigCraft's own checker does the measuring; you do what it cannot.
|
||||
1. If the file has a design brief, its spacing step, corners, brand colours and contrast target are already the review settings (design.configure); otherwise run design.configure with the grid, radii and brand colours the design uses.
|
||||
2. run_command design.audit on the selection, or on the frames you made (ids), with the Theme mode you designed in (modes: {Theme: Light}). Read the score, the counts and each finding (rule, node, message, fixable).
|
||||
3. run_command design.fix with the same scope (dryRun first if many layers change): it repairs the fixable findings in one undo step. Then design.audit again to confirm.
|
||||
4. Fix the rest by hand where it is safe (text colour for contrast, a gap onto the step, a raw colour onto a Theme variable); leave content and naming to the user unless asked.
|
||||
5. Then look: a screenshot of the frames, compared with the request, for what no rule measures: hierarchy, balance, alignment between sections, empty or crowded areas, copy that does not fit.
|
||||
6. Report briefly: the score before and after, what you fixed, and what is left as a suggestion with where it is.
|
||||
"#,
|
||||
),
|
||||
builtin(
|
||||
"Design system setup",
|
||||
"Making or completing the file's design system on the page '00 · Design System': tokens, styles, foundations and base components.",
|
||||
r#"
|
||||
- Everything goes on the page '00 · Design System', first in the file. `design_system` with a spec makes the page, the variables (Primitives, Theme with Light/Dark, Sizes), the text and shadow styles, the review settings and a 'Design guidelines' text; call it first when they are missing, and use what it made instead of a second set.
|
||||
- Lay the page out in sections side by side (frames with vertical auto layout, 80 apart, each with a heading in Heading 2): Colour (a swatch per Theme role, one frame per mode with variable.setMode), Type (a line per text style with its size and weight), Spacing and corners (bars and squares bound to the Sizes variables), Elevation (cards with Shadow/S, M, L), Icons (the set and style from the guidelines, with a few sample icons drawn as vectors on the icon grid), and the Design guidelines text.
|
||||
- Components on the same page, in a "Components" section: Button (Primary, Secondary, Ghost; Default, Hover, Disabled), Input (Default, Focus, Error), Card, Badge, Icon button, as component sets with auto layout, every colour, radius and gap bound to the variables (variable.bind, fill {$var}) and text in the text styles.
|
||||
- Check contrast of text on its background in both modes before finishing.
|
||||
"#,
|
||||
),
|
||||
builtin(
|
||||
"Dark mode",
|
||||
"Making a dark version of a design or adding a dark theme.",
|
||||
r#"
|
||||
- Prefer variables: add a Dark mode to the colour collection and set each semantic colour; switch the frame's mode instead of repainting layers.
|
||||
- Without variables, duplicate the frame beside the original, named "... / Dark", and recolour it.
|
||||
- Backgrounds near #0F1115-#1A1D23, surfaces a step lighter; text #E8EAED and muted #9AA0A6; keep 4.5:1 contrast.
|
||||
- Lower the saturation of bright brand colours a little; shadows become subtle borders or lighter surfaces.
|
||||
"#,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_skill_file_reads_back_as_it_was_written() {
|
||||
let text = to_text("Brand voice", "Writing copy\nfor us", "- Friendly\n- Short");
|
||||
let (name, description, body) = parse(&text).expect("a skill");
|
||||
assert_eq!(name, "Brand voice");
|
||||
assert_eq!(description, "Writing copy for us", "the description stays one line");
|
||||
assert_eq!(body, "- Friendly\n- Short");
|
||||
assert!(parse("no header here").is_none());
|
||||
assert!(parse("---\ndescription: x\n---\nbody").is_none(), "a skill needs a name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_persons_skill_replaces_a_builtin_one_of_the_same_name() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-skills-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
save(&dir, "landing PAGE", "Ours", "Our rules", None).expect("saved");
|
||||
let skills = load(Some(&dir));
|
||||
let landing: Vec<&Skill> = skills.iter().filter(|s| s.name.eq_ignore_ascii_case("landing page")).collect();
|
||||
assert_eq!(landing.len(), 1);
|
||||
assert!(!landing[0].builtin);
|
||||
assert_eq!(landing[0].body, "Our rules");
|
||||
assert!(skills.iter().any(|s| s.builtin), "the other built-in skills stay");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skill_never_overwrites_another_with_the_same_file_name() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-skills-clash-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let first = save(&dir, "Brand voice", "", "One", None).expect("saved");
|
||||
assert!(save(&dir, "Brand-voice", "", "Two", None).is_err(), "a different skill, the same file");
|
||||
save(&dir, "brand voice", "", "Edited", None).expect("the same skill saves again");
|
||||
save(&dir, "Brand voice", "", "Again", Some(&first)).expect("editing it in place");
|
||||
assert!(load(Some(&dir)).iter().any(|s| s.body == "Again"));
|
||||
let notes = dir.join("notes.md");
|
||||
std::fs::write(¬es, "not a skill").expect("write");
|
||||
assert!(save(&dir, "Notes", "", "Mine", None).is_err(), "a file that is not a skill stays");
|
||||
assert_eq!(std::fs::read_to_string(¬es).ok().as_deref(), Some("not a skill"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_skill_answers_with_the_instructions_or_the_names_there_are() {
|
||||
let book: SkillBook = Arc::new(RwLock::new(builtins()));
|
||||
let (text, ok) = call(&book, &json!({"name": "dark mode"}));
|
||||
assert!(ok);
|
||||
assert!(text.contains("variables"));
|
||||
let (text, ok) = call(&book, &json!({"name": "nope"}));
|
||||
assert!(!ok);
|
||||
assert!(text.contains("Dark mode"), "it lists what there is");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! 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, Read};
|
||||
use std::sync::mpsc::{Receiver, sync_channel};
|
||||
|
||||
/// The longest line read from a stream; a provider sending more without a newline is refused.
|
||||
pub const MAX_LINE: usize = 1024 * 1024;
|
||||
/// The most data one event may join.
|
||||
pub const MAX_EVENT: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// 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<R: BufRead> {
|
||||
reader: R,
|
||||
}
|
||||
|
||||
impl<R: BufRead> Sse<R> {
|
||||
pub fn new(reader: R) -> Self {
|
||||
Self { reader }
|
||||
}
|
||||
|
||||
/// One line, at most [`MAX_LINE`] long; `None` at the end of the stream.
|
||||
fn line(&mut self) -> Result<Option<String>, String> {
|
||||
let mut bytes = Vec::new();
|
||||
let read =
|
||||
(&mut self.reader).take(MAX_LINE as u64 + 1).read_until(b'\n', &mut bytes).map_err(|e| format!("reading the stream failed: {e}"))?;
|
||||
if read == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if bytes.len() > MAX_LINE && bytes.last() != Some(&b'\n') {
|
||||
return Err(format!("the stream sent a line longer than {MAX_LINE} bytes"));
|
||||
}
|
||||
Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
|
||||
/// The next event, `None` at the end of the stream.
|
||||
pub fn next_event(&mut self) -> Result<Option<Event>, String> {
|
||||
let mut name = String::new();
|
||||
let mut data: Vec<String> = Vec::new();
|
||||
let mut size = 0usize;
|
||||
loop {
|
||||
let Some(line) = self.line()? else {
|
||||
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 line.starts_with(':') {
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("event:") {
|
||||
name = rest.trim().to_string();
|
||||
} else if let Some(rest) = line.strip_prefix("data:") {
|
||||
let part = rest.strip_prefix(' ').unwrap_or(rest);
|
||||
size = size.saturating_add(part.len() + 1);
|
||||
if size > MAX_EVENT {
|
||||
return Err(format!("the stream sent an event larger than {MAX_EVENT} bytes"));
|
||||
}
|
||||
data.push(part.to_string());
|
||||
}
|
||||
// Other fields (`id:`, `retry:`) are not used by either dialect.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the stream's events on their own thread, so the caller can stop waiting at any moment
|
||||
/// (Stop) without depending on the network to answer. The thread ends at the end of the stream,
|
||||
/// on an error, or at its next event once the receiver is dropped.
|
||||
pub fn spawn_events(body: Box<dyn BufRead + Send>) -> Receiver<Result<Event, String>> {
|
||||
let (tx, rx) = sync_channel(64);
|
||||
let spawned = std::thread::Builder::new().name("figcraft-agent-sse".into()).spawn(move || {
|
||||
let mut sse = Sse::new(body);
|
||||
loop {
|
||||
match sse.next_event() {
|
||||
Ok(Some(e)) => {
|
||||
if tx.send(Ok(e)).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
Ok(None) => return,
|
||||
Err(e) => {
|
||||
let _ = tx.send(Err(e));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
let (tx, rx) = sync_channel(1);
|
||||
let _ = tx.send(Err(format!("can't read the answer: {e}")));
|
||||
return rx;
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// The next event from [`spawn_events`], checking `cancel` while waiting: `Err("stopped")` when it
|
||||
/// is set, `Ok(None)` at the end of the stream.
|
||||
pub fn next(events: &Receiver<Result<Event, String>>, cancel: &std::sync::atomic::AtomicBool) -> Result<Option<Event>, String> {
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err("stopped".to_string());
|
||||
}
|
||||
match events.recv_timeout(std::time::Duration::from_millis(100)) {
|
||||
Ok(Ok(e)) => return Ok(Some(e)),
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_endless_line_is_refused_instead_of_kept() {
|
||||
let long = format!("data: {}", "x".repeat(MAX_LINE + 10));
|
||||
let mut sse = Sse::new(Cursor::new(long.into_bytes()));
|
||||
assert!(sse.next_event().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_ends_the_wait_without_the_stream_answering() {
|
||||
// A reader that never sends anything.
|
||||
struct Silent;
|
||||
impl std::io::Read for Silent {
|
||||
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
let events = spawn_events(Box::new(std::io::BufReader::new(Silent)));
|
||||
let cancel = std::sync::atomic::AtomicBool::new(true);
|
||||
assert_eq!(next(&events, &cancel), Err("stopped".to_string()));
|
||||
}
|
||||
}
|
||||
@@ -52,5 +52,8 @@ 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 }
|
||||
# Colour emoji (COLR, sbix, CBDT) in the UI from the system's emoji face; the web build has none.
|
||||
craft-ui = { workspace = true, features = ["color_fonts"] }
|
||||
|
||||
@@ -12,13 +12,16 @@ 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"
|
||||
", changed" = ", changed"
|
||||
".fig (experimental)" = ".fig (experimental)"
|
||||
"1 step" = "1 step"
|
||||
"1 year" = "1 year"
|
||||
"1…9, 0" = "1…9, 0"
|
||||
"30 days" = "30 days"
|
||||
"90 days" = "90 days"
|
||||
"@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" = "@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}"
|
||||
"A built-in skill. Make a copy to change it; your copy replaces it." = "A built-in skill. Make a copy to change it; your copy replaces it."
|
||||
"A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "A collection of this file with these modes and variables: override their values per mode and add variables of its own"
|
||||
"A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "A .figcraft file with this name already exists. Choose its full name to confirm replacement."
|
||||
"A later vote" = "A later vote"
|
||||
@@ -59,6 +62,7 @@ name = "English"
|
||||
"Add effect" = "Add effect"
|
||||
"Add export setting" = "Add export setting"
|
||||
"Add fill" = "Add fill"
|
||||
"Add hover, pressed and disabled variants" = "Add hover, pressed and disabled variants"
|
||||
"Add interaction" = "Add interaction"
|
||||
"Add layout grid" = "Add layout grid"
|
||||
"Add library" = "Add library"
|
||||
@@ -79,17 +83,139 @@ 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"
|
||||
"Always check with a screenshot" = "Always check with a screenshot"
|
||||
"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}"
|
||||
"Bring this answer's changes back" = "Bring this answer's changes back"
|
||||
"Built in" = "Built in"
|
||||
"Can't attach {name}: {error}" = "Can't attach {name}: {error}"
|
||||
"Can't delete {path}: {error}" = "Can't delete {path}: {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}"
|
||||
"Changed 1 layer" = "Changed 1 layer"
|
||||
"Changed the file" = "Changed the file"
|
||||
"Changed {count} layers" = "Changed {count} layers"
|
||||
"Changes undone" = "Changes undone"
|
||||
"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"
|
||||
"Copy this code" = "Copy this code"
|
||||
"Couldn't download {name}: {why}" = "Couldn't download {name}: {why}"
|
||||
"Couldn't open {name}." = "Couldn't open {name}."
|
||||
"Default model" = "Default model"
|
||||
"Delete this chat" = "Delete this chat"
|
||||
"Deny" = "Deny"
|
||||
"Describe what to design… @ names a layer, / adds a skill" = "Describe what to design… @ names a layer, / adds a skill"
|
||||
"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"
|
||||
"Fill this with realistic content" = "Fill this with realistic content"
|
||||
"Fix the type hierarchy" = "Fix the type hierarchy"
|
||||
"Frame {start} isn't in this file: presenting from the start." = "Frame {start} isn't in this file: presenting from the start."
|
||||
"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:"
|
||||
"Instructions" = "Instructions"
|
||||
"Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits." = "Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits."
|
||||
"Layer" = "Layer"
|
||||
"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 copy to edit" = "Make a copy to edit"
|
||||
"Make a pricing section with three plans" = "Make a pricing section with three plans"
|
||||
"Make this responsive with auto layout" = "Make this responsive with auto layout"
|
||||
"Make three variations of this" = "Make three variations of this"
|
||||
"Manage connections…" = "Manage connections…"
|
||||
"Match the colours to the file's styles" = "Match the colours to the file's styles"
|
||||
"Model: {model}" = "Model: {model}"
|
||||
"New chat" = "New chat"
|
||||
"New skill" = "New skill"
|
||||
"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?"
|
||||
"Nothing to present." = "Nothing to present."
|
||||
"Nothing to present: {why}" = "Nothing to present: {why}"
|
||||
"On: after every answer that changed the canvas, the agent takes a screenshot, compares it with the request and fixes what is off (one more request). Off: it takes one only when it decides to." = "On: after every answer that changed the canvas, the agent takes a screenshot, compares it with the request and fixes what is off (one more request). Off: it takes one only when it decides to."
|
||||
"One line: the agent reads it to decide" = "One line: the agent reads it to decide"
|
||||
"Only a file on this site can be presented: {file}" = "Only a file on this site can be presented: {file}"
|
||||
"Lasso select" = "Lasso select"
|
||||
"Only the last answer can be undone here, while nothing else changed since. Use Edit > Undo for single steps." = "Only the last answer can be undone here, while nothing else changed since. Use Edit > Undo for single steps."
|
||||
"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}"
|
||||
"Point eraser" = "Point eraser"
|
||||
"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"
|
||||
"Rebuild as editable layers" = "Rebuild as editable layers"
|
||||
"Rebuild this screenshot as editable layers" = "Rebuild this screenshot as editable layers"
|
||||
"Recreate the attached screenshot as layers with auto layout" = "Recreate the attached screenshot as layers with auto layout"
|
||||
"Redo" = "Redo"
|
||||
"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}"
|
||||
"Rewrite the copy to be clearer and shorter" = "Rewrite the copy to be clearer and shorter"
|
||||
"Run everything without asking" = "Run everything without asking"
|
||||
"Running {tool}" = "Running {tool}"
|
||||
"Select the changed layers and zoom to them" = "Select the changed layers and zoom to them"
|
||||
"Select the layers this step changed and zoom to them" = "Select the layers this step changed and zoom to them"
|
||||
"Select this layer on the canvas" = "Select this layer on the canvas"
|
||||
"Send" = "Send"
|
||||
"Show 1 layer" = "Show 1 layer"
|
||||
"Show {count} layers" = "Show {count} layers"
|
||||
"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."
|
||||
"Skills" = "Skills"
|
||||
"Skills can't be saved: the app has no settings folder." = "Skills can't be saved: the app has no settings folder."
|
||||
"Something went wrong" = "Something went wrong"
|
||||
"Stopped." = "Stopped."
|
||||
"Stroke eraser" = "Stroke eraser"
|
||||
"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."
|
||||
"Those layers are no longer in this file." = "Those layers are no longer in this file."
|
||||
"Tidy up the spacing and alignment" = "Tidy up the spacing and alignment"
|
||||
"Translate the text to English" = "Translate the text to English"
|
||||
"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"
|
||||
"Undo" = "Undo"
|
||||
"Undo every change this answer made" = "Undo every change this answer made"
|
||||
"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}\""
|
||||
@@ -374,6 +500,15 @@ name = "English"
|
||||
"Open preview in a new window" = "Open preview in a new window"
|
||||
"Return preview to the editor" = "Return preview to the editor"
|
||||
"The contrast can't be told when a gradient, image or blend mode is in this fill or behind the layer" = "The contrast can't be told when a gradient, image or blend mode is in this fill or behind the layer"
|
||||
"Versions: {count}" = "Versions: {count}"
|
||||
"What should we design?" = "What should we design?"
|
||||
"When to use it" = "When to use it"
|
||||
"Working…" = "Working…"
|
||||
"Write a description for this component" = "Write a description for this component"
|
||||
"{count} steps" = "{count} steps"
|
||||
"{count} steps, {failed} failed" = "{count} steps, {failed} failed"
|
||||
"{count} tokens" = "{count} tokens"
|
||||
"{input} in · {output} out" = "{input} in · {output} out"
|
||||
"{level} needs {needed}:1 against {backdrop}" = "{level} needs {needed}:1 against {backdrop}"
|
||||
"Contributors" = "Contributors"
|
||||
"Contributors: {people} · Commits: {commits}" = "Contributors: {people} · Commits: {commits}"
|
||||
@@ -436,6 +571,10 @@ name = "English"
|
||||
"In code" = "In code"
|
||||
"Source file" = "Source file"
|
||||
"Variant value" = "Variant value"
|
||||
"{m} min {s} s" = "{m} min {s} s"
|
||||
"{name} is not an image this app reads: {error}" = "{name} is not an image this app reads: {error}"
|
||||
"{n} s" = "{n} s"
|
||||
"≈ ${cost} at API rates" = "≈ ${cost} at API rates"
|
||||
"⌘ click a padding field" = "⌘ click a padding field"
|
||||
"Ctrl+scroll" = "Ctrl+scroll"
|
||||
"Current name" = "Current name"
|
||||
@@ -1855,6 +1994,7 @@ name = "English"
|
||||
"Yellow" = "Yellow"
|
||||
"Yesterday" = "Yesterday"
|
||||
"You" = "You"
|
||||
"You edited the file while the agent worked, so Undo answer is off for this turn; use Edit › Undo." = "You edited the file while the agent worked, so Undo answer is off for this turn; use Edit › Undo."
|
||||
"You'll get the shared file as a new tab and edit it together." = "You'll get the shared file as a new tab and edit it together."
|
||||
"You're spotlighting: everyone follows your view" = "You're spotlighting: everyone follows your view"
|
||||
"Your copy of the file stays open" = "Your copy of the file stays open"
|
||||
|
||||
@@ -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).
|
||||
@@ -361,6 +376,7 @@ impl FigApp {
|
||||
LeftTab::File => i18n::tr("Layers"),
|
||||
LeftTab::Assets => i18n::tr("Assets"),
|
||||
LeftTab::Plugins => i18n::tr("Plugins"),
|
||||
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)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,334 @@
|
||||
//! The chat panel's own behaviour: how worker events become the conversation, and that a tool
|
||||
//! call really becomes a control request whose answer reaches the agent thread.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::chat::{Chat, Entry, ToolState};
|
||||
use crate::control::ControlReply;
|
||||
use figcraft_agent::ChatEvent;
|
||||
|
||||
#[test]
|
||||
fn streamed_text_and_tool_cards_fold_into_the_conversation() {
|
||||
let mut chat = Chat::default();
|
||||
chat.apply(ChatEvent::Text("Hel".into()));
|
||||
chat.apply(ChatEvent::Text("lo".into()));
|
||||
chat.apply(ChatEvent::ToolStart { id: "t1".into(), name: "run_command".into(), args: json!({"command": "frame.create"}) });
|
||||
chat.apply(ChatEvent::ToolEnd {
|
||||
id: "t1".into(),
|
||||
name: "run_command".into(),
|
||||
ok: true,
|
||||
title: "frame.create".into(),
|
||||
text: "created frame 12".into(),
|
||||
});
|
||||
assert_eq!(chat.entries.len(), 2, "one message, one card");
|
||||
match &chat.entries[0] {
|
||||
Entry::Assistant(text) => assert_eq!(text, "Hello"),
|
||||
_ => panic!("the streamed text is one assistant message"),
|
||||
}
|
||||
match &chat.entries[1] {
|
||||
Entry::Tool { title, summary, state, .. } => {
|
||||
assert_eq!(title, "frame.create");
|
||||
assert_eq!(summary, "created frame 12");
|
||||
assert_eq!(*state, ToolState::Ok);
|
||||
}
|
||||
_ => panic!("a tool call is a card"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_tool_turns_its_card_red_and_the_turn_ends_on_done() {
|
||||
let mut chat = Chat::default();
|
||||
chat.running = true;
|
||||
chat.apply(ChatEvent::ToolStart { id: "t1".into(), name: "save_file".into(), args: json!({}) });
|
||||
chat.apply(ChatEvent::ToolEnd { id: "t1".into(), name: "save_file".into(), ok: false, title: "save_file".into(), text: "denied".into() });
|
||||
chat.apply(ChatEvent::Done { stopped: true });
|
||||
assert!(!chat.running, "Done ends the turn");
|
||||
match &chat.entries[0] {
|
||||
Entry::Tool { state, .. } => assert_eq!(*state, ToolState::Failed),
|
||||
_ => panic!("a tool call is a card"),
|
||||
}
|
||||
assert!(chat.entries.iter().any(|e| matches!(e, Entry::Note(n) if n == "Stopped.")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_call_becomes_a_control_request_and_its_answer_comes_back() {
|
||||
let (bridge, remote) = figcraft_agent::bridge::pair("Test Agent", Arc::new(|| {}));
|
||||
let mut chat = Chat::default();
|
||||
chat.bridge = Some(bridge);
|
||||
|
||||
let agent = std::thread::spawn(move || remote.request("engine.execute", json!({"command": "frame.create"})));
|
||||
|
||||
// Wait for the call to cross the channel (a short bounded wait, not a timing assertion).
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut requests = Vec::new();
|
||||
while requests.is_empty() && Instant::now() < deadline {
|
||||
requests = chat.take_bridge_calls(None);
|
||||
if requests.is_empty() {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
assert_eq!(requests.len(), 1, "one tool call, one control request");
|
||||
assert_eq!(requests[0].method, "engine.execute");
|
||||
assert_eq!(requests[0].params["agent"], "Test Agent", "commands run as the agent");
|
||||
|
||||
let request = requests.remove(0);
|
||||
request.reply.send(ControlReply { id: json!(0), result: Ok(json!({"id": 3})) }).expect("the UI answers the call");
|
||||
chat.pump();
|
||||
|
||||
let answer = agent.join().expect("the agent thread finished");
|
||||
assert_eq!(answer, Ok(json!({"id": 3})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversations_are_saved_per_document_and_do_not_share_a_slug() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-chat-ui-{}", std::process::id()));
|
||||
let mut chat = Chat::default();
|
||||
chat.chats_dir = Some(dir.clone());
|
||||
chat.doc_key = Some(crate::chat::slug("/work/a.figcraft"));
|
||||
chat.entries.push(Entry::User("first".into()));
|
||||
chat.save_entries();
|
||||
let other = crate::chat::slug("/work/b.figcraft");
|
||||
assert_ne!(chat.doc_key.as_deref(), Some(other.as_str()), "two files, two conversations");
|
||||
let mut again = Chat::default();
|
||||
again.chats_dir = Some(dir.clone());
|
||||
again.doc_key = chat.doc_key.clone();
|
||||
again.entries = again.load_entries();
|
||||
assert_eq!(again.entries.len(), 1, "the conversation comes back");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_one_variant_asks_for_side_by_side_frames() {
|
||||
let text = crate::chat::variant_instruction(3);
|
||||
assert!(text.contains("3 versions"), "{text}");
|
||||
assert!(text.contains("96 px"), "each version has its own frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_usage_line_shows_a_cost_only_when_prices_are_filled_in() {
|
||||
let mut chat = Chat::default();
|
||||
chat.usage = figcraft_agent::Usage { input: 1_000_000, output: 0 };
|
||||
chat.agents.providers.push(figcraft_agent::Provider::new("p", figcraft_agent::ApiKind::OpenAiCompletions, "https://x.test/v1"));
|
||||
chat.agents.active = 0;
|
||||
assert!(chat.usage_line().contains("1000000 in"), "{}", chat.usage_line());
|
||||
assert!(!chat.usage_line().contains('$'), "no price, no estimate");
|
||||
chat.agents.providers[0].price_in = 3.0;
|
||||
assert!(chat.usage_line().contains("$3.0000"), "{}", chat.usage_line());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_permission_card_names_the_path_it_would_write() {
|
||||
assert_eq!(crate::chat::approval_detail(&json!({"path": "/work/out.png"})), "path: /work/out.png");
|
||||
assert_eq!(crate::chat::approval_detail(&json!({"command": "file.save"})), "command: file.save");
|
||||
assert_eq!(crate::chat::approval_detail(&json!({})), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_chat_keeps_the_last_one_in_the_history_and_it_opens_again() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-chat-history-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut chat = Chat::default();
|
||||
chat.chats_dir = Some(dir.clone());
|
||||
chat.doc_key = Some(crate::chat::slug("/work/b.figcraft"));
|
||||
chat.entries.push(Entry::User("first request".into()));
|
||||
chat.save_entries();
|
||||
chat.new_conversation();
|
||||
assert!(chat.entries.is_empty(), "the new chat starts empty");
|
||||
chat.entries.push(Entry::User("second request".into()));
|
||||
chat.save_entries();
|
||||
chat.queue.push("typed while it worked".into());
|
||||
chat.list_conversations();
|
||||
let titles: Vec<&str> = chat.past.iter().map(|p| p.title.as_str()).collect();
|
||||
assert!(titles.contains(&"first request") && titles.contains(&"second request"), "{titles:?}");
|
||||
let first = chat.past.iter().find(|p| p.title == "first request").map(|p| p.key.clone()).expect("the first chat is listed");
|
||||
let second = chat.past.iter().find(|p| p.title == "second request").map(|p| p.key.clone()).expect("the second chat is listed");
|
||||
chat.switch_conversation(first);
|
||||
assert!(matches!(chat.entries.first(), Some(Entry::User(t)) if t == "first request"), "the old chat comes back");
|
||||
assert!(chat.queue.is_empty(), "the queued request waits for its own chat");
|
||||
chat.switch_conversation(second);
|
||||
assert_eq!(chat.queue, ["typed while it worked"], "and is there again when that chat opens");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn node(s: &mut figcraft_engine::Session, params: serde_json::Value) -> Option<u64> {
|
||||
s.execute("node.create", ¶ms).ok()?["id"].as_u64()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_layer_counts_once_and_an_edited_child_counts_without_its_frame() {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let frame = node(&mut s, json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 200})).expect("created");
|
||||
let child = node(&mut s, json!({"type": "rectangle", "parent": frame, "x": 10, "y": 10, "width": 20, "height": 20})).expect("created");
|
||||
let before = s.ds().expect("a document").doc.clone();
|
||||
|
||||
let card = node(&mut s, json!({"type": "frame", "x": 300, "y": 0, "width": 120, "height": 80})).expect("created");
|
||||
node(&mut s, json!({"type": "rectangle", "parent": card, "x": 0, "y": 0, "width": 10, "height": 10})).expect("created");
|
||||
s.execute("node.set", &json!({"ids": [child], "width": 40})).expect("resized");
|
||||
let after = s.ds().expect("a document").doc.clone();
|
||||
|
||||
let changed = crate::chat::changed_layers(&before, &after);
|
||||
assert!(changed.contains(&card), "the new card");
|
||||
assert!(changed.contains(&child), "the edited child");
|
||||
assert!(!changed.contains(&frame), "not the frame that only holds the edit");
|
||||
assert_eq!(changed.len(), 2, "not each child of the new card: {changed:?}");
|
||||
assert!(crate::chat::changed_layers(&after, &after).is_empty());
|
||||
}
|
||||
|
||||
/// One of the agent's calls, counted as the control handler counts it.
|
||||
fn agent_node(chat: &mut Chat, s: &mut figcraft_engine::Session, params: serde_json::Value) -> Option<u64> {
|
||||
let before = chat.before_agent_call(s)?;
|
||||
let id = node(s, params);
|
||||
chat.after_agent_call(s, before);
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_can_be_undone_only_while_nothing_else_changed_after_it() {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let mut chat = Chat::default();
|
||||
chat.begin_turn(&s);
|
||||
agent_node(&mut chat, &mut s, json!({"type": "rectangle", "x": 0, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
agent_node(&mut chat, &mut s, json!({"type": "ellipse", "x": 40, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
chat.apply(ChatEvent::Done { stopped: false });
|
||||
chat.finish_turn(&s);
|
||||
let at = chat.entries.iter().position(|e| matches!(e, Entry::Changes { .. })).expect("a changes line after the answer");
|
||||
let Entry::Changes { layers, steps, .. } = &chat.entries[at] else { panic!("a changes line") };
|
||||
assert_eq!(layers.len(), 2);
|
||||
assert_eq!(*steps, 2, "both edits are undone together");
|
||||
assert!(chat.can_undo(at));
|
||||
|
||||
// The person edits after the answer: undoing the answer now would undo their edit first.
|
||||
node(&mut s, json!({"type": "rectangle", "x": 80, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
chat.finish_turn(&s);
|
||||
assert!(!chat.can_undo(at));
|
||||
|
||||
// They undo their edit and the answer's last step, then make an edit of their own: the undo
|
||||
// depth is back where the answer left it, but the last step there is theirs.
|
||||
s.execute("edit.undo", &json!({})).expect("undone");
|
||||
s.execute("edit.undo", &json!({})).expect("undone");
|
||||
node(&mut s, json!({"type": "rectangle", "x": 120, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
chat.finish_turn(&s);
|
||||
assert!(!chat.can_undo(at), "Undo answer would undo the person's edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_mixed_with_the_persons_edits_is_not_offered_for_undo() {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let mut chat = Chat::default();
|
||||
chat.begin_turn(&s);
|
||||
agent_node(&mut chat, &mut s, json!({"type": "rectangle", "x": 0, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
// The person adds a layer while it works.
|
||||
node(&mut s, json!({"type": "ellipse", "x": 40, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
chat.apply(ChatEvent::Done { stopped: false });
|
||||
chat.finish_turn(&s);
|
||||
let at = chat.entries.iter().position(|e| matches!(e, Entry::Changes { .. })).expect("the changes are still listed");
|
||||
assert!(!chat.can_undo(at), "undoing the answer would take the person's edit too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_step_the_person_undid_and_replaced_is_not_offered_for_undo() {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let mut chat = Chat::default();
|
||||
chat.begin_turn(&s);
|
||||
agent_node(&mut chat, &mut s, json!({"type": "rectangle", "x": 0, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
// The person undoes it and makes an edit of their own: the undo depth is back where the
|
||||
// agent left it, but the step there is theirs.
|
||||
s.execute("edit.undo", &json!({})).expect("undone");
|
||||
node(&mut s, json!({"type": "ellipse", "x": 40, "y": 0, "width": 20, "height": 20})).expect("created");
|
||||
chat.apply(ChatEvent::Done { stopped: false });
|
||||
chat.finish_turn(&s);
|
||||
let offered = chat.entries.iter().enumerate().any(|(i, e)| matches!(e, Entry::Changes { .. }) && chat.can_undo(i));
|
||||
assert!(!offered, "Undo answer would undo the person's edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_at_sign_starts_a_mention_only_at_a_word_start_and_before_the_cursor() {
|
||||
use crate::chat::token_query;
|
||||
assert_eq!(token_query("fix @But", 8, '@'), Some((4, "But".to_string())));
|
||||
assert_eq!(token_query("@", 1, '@'), Some((0, String::new())));
|
||||
assert_eq!(token_query("mail me@home", 12, '@'), None, "inside a word it is text");
|
||||
assert_eq!(token_query("fix @Button now", 15, '@'), None, "the cursor moved past it");
|
||||
assert_eq!(token_query("/land", 5, '/'), Some((0, "land".to_string())), "a skill");
|
||||
assert_eq!(token_query("and/or", 6, '/'), None, "a slash inside a word is text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mention_offers_components_before_other_layers_of_the_same_name() {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let frame = node(&mut s, json!({"type": "frame", "name": "Button row", "x": 0, "y": 0, "width": 200, "height": 60})).expect("created");
|
||||
let component = node(&mut s, json!({"type": "component", "name": "Button", "x": 300, "y": 0, "width": 80, "height": 32})).expect("created");
|
||||
node(&mut s, json!({"type": "rectangle", "name": "Card", "x": 0, "y": 100, "width": 20, "height": 20})).expect("created");
|
||||
let doc = s.ds().expect("a document").doc.clone();
|
||||
|
||||
let hits = crate::chat::mention_candidates(&doc, "butt");
|
||||
let ids: Vec<u64> = hits.iter().map(|h| h.layer.id).collect();
|
||||
assert_eq!(ids.first(), Some(&component), "the component first: {ids:?}");
|
||||
assert!(ids.contains(&frame));
|
||||
assert!(!hits.iter().any(|h| h.layer.name == "Card"), "only names that match");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_design_system_goes_once_per_conversation_until_it_changes() {
|
||||
let mut app = crate::FigApp::new(figcraft_engine::Session::new(), Box::new(crate::NoServices));
|
||||
assert!(crate::chat::design_system(&mut app).is_none(), "an empty file has none to tell");
|
||||
node(&mut app.session, json!({"type": "component", "name": "Button", "x": 0, "y": 0, "width": 80, "height": 32})).expect("created");
|
||||
let first = crate::chat::design_system(&mut app).expect("the components are told");
|
||||
assert!(first.contains("Button"));
|
||||
assert!(crate::chat::design_system(&mut app).is_none(), "not again while it is the same");
|
||||
node(&mut app.session, json!({"type": "component", "name": "Badge", "x": 0, "y": 60, "width": 40, "height": 20})).expect("created");
|
||||
assert!(crate::chat::design_system(&mut app).is_some_and(|t| t.contains("Badge")), "again once it changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_becomes_variables_and_styles_in_one_undo_step_and_again_without_copies() {
|
||||
use figcraft_agent::brief::{Brief, Existing};
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let brief = Brief::default();
|
||||
let run = |s: &mut figcraft_engine::Session| {
|
||||
let existing =
|
||||
Existing::from_lists(&s.execute("variable.list", &json!({})).expect("variables"), &s.execute("style.list", &json!({})).expect("styles"));
|
||||
s.execute("command.batch", &json!({"label": "Design system", "commands": brief.steps(&existing)}))
|
||||
};
|
||||
let depth = s.undo_depth().0;
|
||||
run(&mut s).expect("the steps run");
|
||||
assert_eq!(s.undo_depth().0, depth + 1, "one undo step");
|
||||
let vars = s.execute("variable.list", &json!({})).expect("variables");
|
||||
let theme = vars["collections"].as_array().into_iter().flatten().find(|c| c["name"] == "Theme").expect("a Theme collection");
|
||||
assert_eq!(theme["modes"].as_array().map(Vec::len), Some(2), "Light and Dark");
|
||||
let count = |s: &mut figcraft_engine::Session| {
|
||||
let v = s.execute("variable.list", &json!({})).expect("variables")["variables"].as_array().map_or(0, Vec::len);
|
||||
let st = s.execute("style.list", &json!({})).expect("styles").as_array().map_or(0, Vec::len);
|
||||
(v, st)
|
||||
};
|
||||
let made = count(&mut s);
|
||||
assert!(made.0 > 40 && made.1 >= 13, "{made:?}");
|
||||
|
||||
run(&mut s).expect("running again works");
|
||||
assert_eq!(count(&mut s), made, "no copies");
|
||||
|
||||
s.execute("edit.undo", &json!({})).expect("undo");
|
||||
s.execute("edit.undo", &json!({})).expect("undo");
|
||||
assert_eq!(count(&mut s), (0, 0), "one undo per run takes it all back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_is_told_the_pages_and_a_named_page_means_its_frames() {
|
||||
let mut app = crate::FigApp::new(figcraft_engine::Session::new(), Box::new(crate::NoServices));
|
||||
let home = node(&mut app.session, json!({"type": "frame", "name": "Home", "x": 0, "y": 0, "width": 390, "height": 844})).expect("created");
|
||||
app.session.execute("page.add", &json!({"name": "Checkout"})).expect("a page");
|
||||
let pages = app.session.execute("page.list", &json!({})).expect("pages");
|
||||
let first = pages[0]["id"].as_u64().expect("an id");
|
||||
let first_name = pages[0]["name"].as_str().unwrap_or_default().to_string();
|
||||
|
||||
let told = crate::chat::pages_context(&mut app).expect("the pages are told");
|
||||
assert!(told.contains("Checkout") && told.contains("\"Home\""), "{told}");
|
||||
assert!(crate::chat::pages_context(&mut app).is_none(), "not again while the same");
|
||||
|
||||
let page = crate::chat::LayerRef { id: first, name: first_name };
|
||||
let context = crate::chat::selection_context(&mut app, &[page]).expect("context");
|
||||
assert!(context.contains("the page"), "{context}");
|
||||
assert!(context.contains(&home.to_string()), "the frames on it are what the agent reads");
|
||||
}
|
||||
@@ -537,6 +537,14 @@ fn request_paint(app: &FigApp, ctx: &Context) {
|
||||
/// Work a logic-only callback can do safely: expire deadlines, admit or park screenshot requests,
|
||||
/// and answer state-only control requests for hidden windows. Input/geometry are never read here.
|
||||
pub fn background(app: &mut FigApp, ctx: &Context) {
|
||||
// The in-app agent's tool calls join the control queue, so routing, screenshots and the
|
||||
// automation roots apply exactly as they do for an attached MCP client.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let roots = app.automation_roots.clone();
|
||||
let calls = app.chat.take_bridge_calls(roots);
|
||||
app.control_queue.extend(calls);
|
||||
}
|
||||
let now = app.clock.now();
|
||||
expire(app, ctx, now);
|
||||
for r in std::mem::take(&mut app.control_queue) {
|
||||
@@ -612,6 +620,8 @@ pub fn background(app: &mut FigApp, ctx: &Context) {
|
||||
if !waiting.is_empty() {
|
||||
crate::repaint_in(ctx, NOT_DRAWING_AFTER);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
app.chat.pump();
|
||||
request_paint(app, ctx);
|
||||
}
|
||||
|
||||
@@ -645,6 +655,9 @@ pub fn drain(app: &mut FigApp, ctx: &Context) {
|
||||
// not when its discarded sizing pass runs. Passes after the first (`current_pass_index > 0`)
|
||||
// belong to such a frame and never add another count.
|
||||
settle_and_issue(app, ctx, viewport, now, epoch, spec);
|
||||
// Answers for the agent's tool calls arrived in this pass: hand them to its thread.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
app.chat.pump();
|
||||
request_paint(app, ctx);
|
||||
}
|
||||
|
||||
@@ -1218,6 +1231,8 @@ fn ui_set_view(app: &mut FigApp, ctx: &Context, p: &Value) -> Result<(), String>
|
||||
app.ui.left_tab = match t {
|
||||
"assets" => crate::LeftTab::Assets,
|
||||
"plugins" => crate::LeftTab::Plugins,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
"agent" => crate::LeftTab::Agent,
|
||||
_ => crate::LeftTab::File,
|
||||
};
|
||||
}
|
||||
@@ -1527,6 +1542,23 @@ fn front_only(session: &Session, front: Option<u64>, method: &str, p: &Value) ->
|
||||
|
||||
/// Handle one control method (also used by tests and the headless snapshot tool).
|
||||
pub fn handle(app: &mut FigApp, ctx: &Context, method: &str, p: &Value) -> Result<Value, String> {
|
||||
// The in-app agent's calls on the file its turn works in count their undo steps, so the
|
||||
// panel can tell its steps from the person's (Undo answer takes back only the agent's).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let ours = app.chat.running && p.get("agent").and_then(Value::as_str) == Some(figcraft_agent::AGENT_NAME);
|
||||
let before = if ours { app.chat.before_agent_call(&app.session) } else { None };
|
||||
let r = handle_method(app, ctx, method, p);
|
||||
if let Some(before) = before {
|
||||
app.chat.after_agent_call(&app.session, before);
|
||||
}
|
||||
r
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
handle_method(app, ctx, method, p)
|
||||
}
|
||||
|
||||
fn handle_method(app: &mut FigApp, ctx: &Context, method: &str, p: &Value) -> Result<Value, String> {
|
||||
if !DOCUMENT_METHODS.contains(&method) {
|
||||
front_only(&app.session, app.session.ds().ok().map(|d| d.uid), method, p)?;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ pub mod a11y;
|
||||
pub mod bidi;
|
||||
pub mod canvas;
|
||||
pub mod channel;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod chat;
|
||||
pub mod cjk;
|
||||
mod combo_menu;
|
||||
pub mod control;
|
||||
@@ -55,6 +57,8 @@ mod board_mind_outline_ui_tests;
|
||||
mod board_picker_tests;
|
||||
#[cfg(test)]
|
||||
mod board_ui_tests;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod chat_tests;
|
||||
#[cfg(test)]
|
||||
mod cjk_ui_size_tests;
|
||||
#[cfg(test)]
|
||||
@@ -930,6 +934,9 @@ pub struct FigApp {
|
||||
panels_unsaved: bool,
|
||||
/// Control-channel requests waiting for the next frame.
|
||||
pub control_queue: Vec<ControlRequest>,
|
||||
/// The in-app agent's panel: its conversation, the provider settings and the worker thread.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub chat: chat::Chat,
|
||||
/// Windows a control request waits for: the window's pass count when the wait began and the
|
||||
/// app-clock time it began, to tell a window that stopped drawing ([`control::background`]).
|
||||
control_waits: std::collections::BTreeMap<u64, (u64, f64)>,
|
||||
|
||||
@@ -479,6 +479,11 @@ pub fn popups(app: &mut FigApp, ctx: &egui::Context) {
|
||||
close = true;
|
||||
}
|
||||
let has_sel = !ids.is_empty();
|
||||
// The agent, first for a selection: ask about it, or one of the quick requests.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if has_sel && crate::chat::context_menu(app, ui, &t) {
|
||||
close = true;
|
||||
}
|
||||
// Sections in the selection add a contents toggle naming what it will do.
|
||||
let section_toggle = app.session.doc().ok().and_then(|doc| {
|
||||
let secs: Vec<bool> = ids
|
||||
|
||||
@@ -107,6 +107,9 @@ pub fn rail(app: &mut FigApp, ui: &mut Ui) -> bool {
|
||||
(Icon::Assets, tr("Assets"), Some(LeftTab::Assets)),
|
||||
(Icon::Styles, tr("Variables"), None),
|
||||
];
|
||||
// The Agent sits with the file tabs on the desktop: it takes the whole panel while it is open.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
items.insert(2, (Icon::Comment, tr("Agent"), Some(LeftTab::Agent)));
|
||||
if crate::dialogs::plugins_ui::any_docked(app) {
|
||||
items.push((Icon::Actions, tr("Plugins"), Some(LeftTab::Plugins)));
|
||||
}
|
||||
@@ -138,6 +141,9 @@ pub fn rail(app: &mut FigApp, ui: &mut Ui) -> bool {
|
||||
app.ui.open_left_panel();
|
||||
}
|
||||
app.ui.versions = Default::default();
|
||||
// Remember whether the window should open on the Agent tab next time.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
app.chat.remember_tab(tb == LeftTab::Agent && !app.ui.left_collapsed);
|
||||
}
|
||||
None => {
|
||||
app.ui.variables.get_or_insert_with(Default::default);
|
||||
@@ -156,6 +162,12 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
crate::versions::panel(app, ui);
|
||||
return;
|
||||
}
|
||||
// The Agent tab is the conversation alone: no file header, Pages or Layers.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if app.ui.left_tab == LeftTab::Agent {
|
||||
crate::chat::panel(app, ui);
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let full = ui.max_rect();
|
||||
// Header: file name (or "Assets") + branch menu + collapse.
|
||||
@@ -167,6 +179,8 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
if let Some(title) = match app.ui.left_tab {
|
||||
LeftTab::Assets => Some(tr("Assets")),
|
||||
LeftTab::Plugins => Some(tr("Plugins")),
|
||||
// Reached only in the browser build, where the tab has no conversation.
|
||||
LeftTab::Agent => Some(tr("Agent")),
|
||||
LeftTab::File => None,
|
||||
} {
|
||||
ui.painter().text(pos2(fx(head.min.x + 16.0), head.min.y + 24.0), align, title, semibold(13.0), t.text);
|
||||
@@ -208,7 +222,8 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.painter().line_segment([head.left_bottom(), head.right_bottom()], Stroke::new(1.0, t.border));
|
||||
match app.ui.left_tab {
|
||||
LeftTab::File => {
|
||||
// The browser build has no agent: its tab shows the file.
|
||||
LeftTab::File | LeftTab::Agent => {
|
||||
pages(app, ui);
|
||||
layers(app, ui);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ pub const MAX_CLIPBOARD_PNG_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Platform services the app crate provides (file dialogs, clipboard, URLs).
|
||||
pub trait Services {
|
||||
/// Where the in-app agent keeps `agents.json` (its providers and API keys): the app's
|
||||
/// settings folder on the desktop. `None` in the browser, which keeps no keys.
|
||||
fn agent_config_path(&self) -> Option<std::path::PathBuf> {
|
||||
None
|
||||
}
|
||||
fn pick_open(&mut self, _title: &str, _exts: &[&str]) -> DialogFuture {
|
||||
Box::pin(std::future::ready(None))
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ pub enum LeftTab {
|
||||
Assets,
|
||||
/// The plugin panels docked in the sidebar (shown only while one is open).
|
||||
Plugins,
|
||||
/// The agent's conversation, filling the panel (desktop builds).
|
||||
Agent,
|
||||
}
|
||||
|
||||
/// The window's title bar.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# FigCraft architecture
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (corrected the file I/O overview to include the existing best-effort `.fig` import and experimental export; earlier: the `vectordrawable` crate, L4: Android Vector Drawable export; the shared hub in `collab-net` and the `figcraft-server` app) · **Target:** Figma Design
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-01 · **Change:** minor (named the same-layer exceptions the layer check allows; earlier: corrected the file I/O overview to include the existing best-effort `.fig` import and experimental export; earlier: the `vectordrawable` crate, L4: Android Vector Drawable export; the shared hub in `collab-net` and the `figcraft-server` app) · **Target:** Figma Design
|
||||
|
||||
How FigCraft is built today. Engine first, a thin swappable UI, everything a command; a Figma-shaped
|
||||
data model (a scene graph of frames with auto layout, components and variables). ~108,800 lines of
|
||||
@@ -9,7 +9,9 @@ Rust (2026-10-10).
|
||||
## Crates and layers
|
||||
|
||||
`cargo xtask layers` enforces the layering (`xtask/src/layers.rs`): a crate may depend only on
|
||||
lower layers. Nothing below L6 depends on egui, eframe, rfd or winit, so the UI crate can be
|
||||
lower layers, apart from the same-layer edges listed in `same_layer_ok` there: `color` → `geom` (L0),
|
||||
`render` → `format` (L3), and within L6 `mcp` → `collab-net`, `agent` → `mcp` (the in-app agent
|
||||
serves the MCP tools) and `ui-egui` → `agent` (the Agent panel). Nothing below L6 depends on egui, eframe, rfd or winit, so the UI crate can be
|
||||
replaced.
|
||||
|
||||
| Layer | Crate | Lines | Role |
|
||||
@@ -30,6 +32,7 @@ replaced.
|
||||
| L5 | `figcraft-engine` | ~39.3k | Sessions, undo history (`Arc` snapshots), the command registry (`cmd/*`, `spec!`), pointer tools and vector edit mode, snapping and measuring, components sync, libraries, prototype runtime, Developer Mode code generation, the menu catalog (`catalog.rs`) and the keymap (`keymap.rs`), a panic guard |
|
||||
| L6 | `figcraft-ui-egui` | ~31.9k | The UI3-style frontend: canvas (render worker), toolbar, layers, Design/Prototype/Inspect panels, colour picker, menus, dialogs, presenter, comments, accessibility (AccessKit), the control channel server |
|
||||
| L6 | `figcraft-mcp` | ~2.4k | MCP server (JSON-RPC over stdio), headless or bridged to a running app |
|
||||
| L6 | `figcraft-agent` | ~1.6k | The in-app agent: OpenAI Completions and Anthropic Messages adapters, the tool-call loop over the MCP tools, and the bridge to the open window (desktop; [harness.md](harness.md)) |
|
||||
| L6 | `figcraft-collab-net` | ~3.0k | Live sessions over the network: the WebSocket transport (tungstenite, a reader and a writer thread per connection), the hub that runs a collaboration core server per open file for the session host the app embeds and for `figcraft-server` (behind a `Backend`), the joining and managing clients (publishing), invite links, presence relay and limits; the browser client; the only crate allowed networking dependencies |
|
||||
| apps | `figcraft`, `figcraft-cli`, `figcraft-web`, `figcraft-server` | ~3.2k | Desktop app (eframe + wgpu), command line, browser build (WASM, WebGPU/WebGL2), collaboration server (files, share links, persistence; [`server.md`](server.md)) |
|
||||
| plugins | `plugins/` (own workspace) | | Rust plugin SDK and two example plugins, built for wasm32 by `cargo xtask plugins` ([`plugins.md`](plugins.md)) |
|
||||
@@ -85,6 +88,7 @@ input.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-01 | minor | Named the same-layer dependencies `cargo xtask layers` allows (`same_layer_ok`), including L6 agent → mcp and ui-egui → agent. No capability or readiness change. |
|
||||
| 2026-11-04 | minor | Corrected the file I/O overview and format-crate row: best-effort `.fig` import and experimental export already exist in `figcraft-format`. No capability or readiness change. |
|
||||
| 2026-10-18 | minor | Added `vectordrawable` (L4), the Android Vector Drawable (XML) writer |
|
||||
| 2026-10-11 | minor | `collab-net` hosts through one hub for the app's sessions and the standalone server; added the `figcraft-server` app |
|
||||
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
# The in-app agent (harness)
|
||||
|
||||
FigCraft can run an AI agent **inside the app**: the Agent tab of the left sidebar, which edits the
|
||||
open document through the same commands and tools an external MCP client uses. This document is
|
||||
the module's contract: what it is made of, which lines it adds to the upstream tree, how to keep
|
||||
those lines rebasing cleanly, and what it deliberately does not do.
|
||||
|
||||
## Opening it
|
||||
|
||||
The rail (the far-left icon column) has an **Agent** tab beside File and Assets
|
||||
(`LeftTab::Agent`). While it is selected the left panel holds the conversation alone: a header
|
||||
(New chat, Connections), the messages, and the composer pinned to the bottom. File and Assets
|
||||
bring Pages and Layers back. The window remembers whether it was left on the Agent tab (`panel`
|
||||
in `agents.json`) and opens on it next time; a build with no settings folder (the browser, tests)
|
||||
never does, so every test that measures the File tab is unchanged.
|
||||
|
||||
The conversation reads like a chat: the person's messages in bubbles on the right, the agent's
|
||||
answers as plain text, and each run of tool calls folded into one line ("5 steps", "Running
|
||||
frame.create") that opens to show every call. A failed turn is a card with a way to check the
|
||||
connection; a permission request is a card with Allow and Deny. With no conversation yet, the tab
|
||||
offers a few example requests, or the connection choices when nothing is connected.
|
||||
|
||||
## Working with the canvas
|
||||
|
||||
- **Selection chips.** The layers selected on the canvas show as chips above the composer (icon and
|
||||
name). A request carries them: its context is their `inspect.designContext` and the agent is told
|
||||
their names and ids. A chip's × leaves that layer out of the next request (a new selection
|
||||
brings it back); clicking a chip selects the layer. The sent message shows the layers it carried,
|
||||
and clicking one there selects it again.
|
||||
- **@ names a layer.** Typing `@` at the start of a word lists the file's layers whose names hold
|
||||
what follows (components first, then pages, frames, instances, text, the rest; with nothing typed,
|
||||
only components, pages and frames). Arrows move, Enter or Tab picks, Escape closes. The pick
|
||||
replaces the typed word with `@Name` and joins the chips, so the layer goes with the request
|
||||
like a selected one, without selecting it.
|
||||
- **Suggestions for the selection.** With the composer empty, up to three requests for what is
|
||||
selected show above it (text: rewrite, translate, type hierarchy; a component: states, a check,
|
||||
a description; frames: spacing, auto layout, variations; instances and other layers their own).
|
||||
A click sends one.
|
||||
- **Design system.** A request carries the file's styles (`style.list`), variables
|
||||
(`variable.list`) and components (names and ids; a variant set once), with an instruction to
|
||||
build with them (`{$var}`, `fillStyle`, `textStyle`, `effectStyle`, `instance.create`) and to
|
||||
say when a raw value was needed. It goes once per conversation and again only when it changed
|
||||
(a hash of the text), so it does not cost tokens on every turn.
|
||||
- **Screenshot to layers.** With an image attached and the box empty, *Rebuild as editable
|
||||
layers* sends a short request; the model also gets fixed instructions (a new frame beside the
|
||||
content, nested auto layout, real text, the file's design system, then a screenshot to compare
|
||||
and fix) that the bubble does not show.
|
||||
- **Time and tokens.** Under each answer: how long it took and the tokens it used (the turn's
|
||||
difference in the provider's count; no count, time only).
|
||||
- **Pages.** A request carries the file's pages and the top-level frames on each (names and ids,
|
||||
which one is in front), once per conversation and again when they changed, with how to read
|
||||
one (`design_context` with its frames), open one (`page.select`, said aloud), add one
|
||||
(`page.add`) and move frames (`object.moveToPage`). The rules put the design system on
|
||||
`00 · Design System` and screens on pages named by flow; the list says when that page is missing. A page named with `@` stands
|
||||
for the frames on it. (The selection context also stopped sending a `maxBytes` that
|
||||
`inspect.designContext` refuses, which had left requests without it.)
|
||||
- **The design system page.** Every file's design system lives on the page `00 · Design System`,
|
||||
first in the file. The agent's `design_system` tool (`crates/agent/src/brief.rs`) reads it (the
|
||||
page, its *Design guidelines* text, the variable collections) or, with a spec (product,
|
||||
platform, language; primary, secondary, accent, greys, status colours, light/dark; heading,
|
||||
body and code fonts and a type scale; spacing step, corners, shadows, border; an open-source
|
||||
icon set by name with style, stroke and size; tone, imagery, contrast, notes), makes or updates
|
||||
it: the page, moved first; through `command.batch` in one undo step the Primitives collection
|
||||
(ten-step OKLCH ramps), Theme (roles aliasing them, Light and Dark), Sizes (space, radius,
|
||||
border, icon), ten text styles, three shadow styles and FigCraft's design review settings
|
||||
(`design.configure`: grid, radii, brand colours, AA/AAA preset); and a *Design guidelines* text
|
||||
on the page with the choices tokens can't hold. Running it again updates them instead of making
|
||||
copies. Icons are never downloaded: the agent draws them in the named set's manner or the person
|
||||
imports them.
|
||||
- **How the agent works.** Its rules (`app_rules` in `crates/agent/src/session.rs`) let it read
|
||||
and change every page and layer (no approval for canvas, page, variable or style commands; only
|
||||
files and the network ask), and give a design request three steps. (1) Foundations first: the
|
||||
file must have `00 · Design System`. Without it the agent proposes a design system in a few
|
||||
lines and waits for the person to confirm or change it, then calls `design_system` with the spec
|
||||
and lays out the foundations and base components on that page (*Design system setup* skill).
|
||||
With it, the agent reads it first. (2) Design with the system. (3) Before finishing, the *Design
|
||||
review* skill: `design.audit`, `design.fix`, `design.audit` again, then a screenshot for what no
|
||||
rule measures, with the score before and after. Small edits to existing layers skip step 1. The
|
||||
idea of starting from a design library with variables and themes comes from pen.dev's public
|
||||
documentation (docs.pencil.dev); nothing of its app was opened or copied (AGENTS.md, clean
|
||||
room).
|
||||
- **Screenshot check.** The agent can take a screenshot whenever it needs to. **Always check with
|
||||
a screenshot** in the composer's **+** menu (also Connections › Advanced) makes it take one
|
||||
after every answer that changed the canvas and fix what differs from the request.
|
||||
- **Skills.** Named instructions for a kind of work (`crates/agent/src/skills.rs`). Five come
|
||||
with the app (mobile app screen, landing page, design review, design system setup, dark mode); the person's own are Markdown files in `agent-skills/` beside `agents.json`
|
||||
(`---` header with `name` and `description`, then the instructions), and one with a built-in
|
||||
skill's name replaces it. The book icon in the header opens the Skills screen: the list, a
|
||||
read-only view of a built-in skill (*Make a copy to edit*), and an editor (name, when to use
|
||||
it, instructions; Save, Delete). Typing `/` at the start of a word lists the skills; the pick
|
||||
becomes a chip and its instructions go with the request (the bubble shows `/Name`). The model
|
||||
is told the list (names and descriptions, once per conversation and again when it changed) and
|
||||
loads one with the `load_skill` tool: the API-key loop answers it itself, and the loopback MCP
|
||||
endpoint adds it to FigCraft's tools for Claude Code, Codex and OpenCode.
|
||||
- **Ask agent.** The canvas's context menu, for a selection, starts with *Ask agent…* (open the tab
|
||||
with the selection attached and the composer focused) and *Agent quick actions* (tidy up, make a
|
||||
component with variants, three variations, a contrast check), which send at once. ⌘⇧M
|
||||
(Ctrl+Shift+M) does what *Ask agent…* does.
|
||||
- **Images.** The composer's **+** pastes an image from the clipboard or attaches a render of the
|
||||
selection (`file.export` PNG); ⌘V in the composer attaches a clipboard image; an image dropped
|
||||
on the Agent tab is attached instead of placed on the canvas. Images are scaled to 1568 px at
|
||||
most, sent as PNG, six per request at most. API-key models get them as image blocks (a model
|
||||
whose *reads images* is off is told they were left out); Claude Code reads them from a
|
||||
`stream-json` message on its input; Codex and OpenCode get files (`--image`, `--file`) written
|
||||
under `agent-chats/cli/attachments/`.
|
||||
- **Messages.** *Copy* under an answer, *Edit* under the last request (it goes back in the box),
|
||||
*Try again* on a failed turn. A request typed while the agent works is queued above the composer
|
||||
(removable) and sent when the turn ends; a failed turn holds the queue.
|
||||
- **History.** The clock in the header lists this file's chats; *New chat* keeps the last one there.
|
||||
Each chat is `<slug>[-<time>].ui.json` / `.context.json`, and `<slug>.current` names the one
|
||||
shown. *Delete this chat* removes its files.
|
||||
|
||||
## What it is
|
||||
|
||||
| Piece | Crate | Layer |
|
||||
|---|---|---|
|
||||
| Provider adapters, the tool-call loop, the bridge | `crates/agent` (`figcraft-agent`) | L6 |
|
||||
| The panel (composer, conversation, setup) | `crates/ui-egui/src/chat.rs` (ours) | L6 |
|
||||
| Tool surface | `figcraft-mcp`'s `tool_definitions` / `call_tool` (unchanged) | L6 |
|
||||
| Command execution | `figcraft-ui-egui`'s control queue (unchanged) | L6 |
|
||||
|
||||
The agent is **not** a second implementation of the tool set. It implements
|
||||
[`figcraft_mcp::Backend`] over a channel to the UI thread, so every tool call becomes the same
|
||||
control request `figcraft-cli mcp --attach` sends. Window routing, screenshot admission, automation
|
||||
roots and command behaviour are therefore identical for both.
|
||||
|
||||
```
|
||||
chat panel (UI thread)
|
||||
│ send prompt
|
||||
▼
|
||||
Worker thread ──── HTTPS + SSE ────► provider (OpenAI Completions / Anthropic Messages)
|
||||
│ tool calls
|
||||
▼
|
||||
Remote (Backend) ── Call ──► Chat::take_bridge_calls ──► app.control_queue
|
||||
│
|
||||
control::handle │ (UI thread)
|
||||
▼
|
||||
FigCraft session
|
||||
```
|
||||
|
||||
## Connecting a model
|
||||
|
||||
The **Connections** screen (the `…` button in the header, or the empty tab) has two groups, and
|
||||
neither asks for an endpoint, a model id or token limits.
|
||||
|
||||
**Use a subscription** runs a command-line agent the person already installed and signed in to,
|
||||
so their own plan pays for it and FigCraft never holds that login:
|
||||
|
||||
| Card | Program | Plan |
|
||||
|---|---|---|
|
||||
| Claude Code | `claude` | Claude Pro / Max |
|
||||
| Codex | `codex` | ChatGPT |
|
||||
| OpenCode | `opencode` | whatever OpenCode is signed in to (OpenCode Go, Zen, …) |
|
||||
|
||||
`cli::status` looks for the program on `PATH` and in the folders installers use (`~/.local/bin`,
|
||||
`~/.opencode/bin`, Homebrew, …) and asks it whether it is signed in. A card then shows
|
||||
**Connect**, or the install or sign-in command with a Copy button.
|
||||
|
||||
A turn runs the program once, non-interactively, and reads its JSON event stream (`cli.rs`): Claude
|
||||
Code with `-p --output-format stream-json --include-partial-messages`, Codex with `exec --json`,
|
||||
OpenCode with `run --format json`. The program keeps the conversation and the next turn resumes it
|
||||
by the session id it reported (kept in `<slug>.context.json`). Its built-in tools are left out
|
||||
(Claude Code: `--tools "" --strict-mcp-config`; OpenCode: an agent whose only tools are
|
||||
`figcraft_*`; Codex: a read-only sandbox) and FigCraft's tools are attached over MCP:
|
||||
|
||||
`mcp_http.rs` serves `figcraft_mcp::Server` on `127.0.0.1:<random port>/mcp` for the length of the
|
||||
conversation (Streamable HTTP, JSON answers only). It needs the bearer token handed to the child,
|
||||
and refuses a request with an `Origin` header or a non-loopback `Host`. Its tool calls go through
|
||||
the same Ask/Auto gate and the same bridge as the in-app loop, and their cards reach the panel from
|
||||
there, so the conversation looks the same whichever way the model is reached. The model picker
|
||||
offers the program's own aliases (Claude Code: sonnet, opus, haiku; OpenCode: `opencode models`),
|
||||
with **Default model** leaving the choice to the program.
|
||||
|
||||
**Use an API key** opens a card with one key field: Anthropic, OpenAI, OpenCode Go, OpenCode Zen,
|
||||
OpenRouter, DeepSeek, and the local Ollama and LM Studio (no key). **Connect** lists the
|
||||
endpoint's models (`GET {base}/models`) as the check that the key works, then picks a model with
|
||||
`config::pick_model`: the preset's preferred family, newest first, skipping small and non-chat
|
||||
models. A refused key, an unreachable host and a missing local server each get a plain message.
|
||||
|
||||
Everything else — endpoint, key, model by hand, reasoning, reads images, prices, the review pass —
|
||||
is under **Advanced** on the Connections screen. Switching model or connection is the model chip
|
||||
in the composer.
|
||||
|
||||
Connections are stored in `<settings folder>/agents.json`, mode `0600` on Unix because the file
|
||||
holds API keys. A connection left with neither a key nor a model (an older, half-finished setup)
|
||||
is dropped when the file is read. Env vars are not read; a proxy environment variable is honoured
|
||||
by `ureq` as usual.
|
||||
|
||||
### API-key dialects
|
||||
|
||||
- **OpenAI Completions** — `{base}/chat/completions`: OpenAI, OpenCode Zen/Go, OpenRouter,
|
||||
DeepSeek, Ollama, LM Studio, any compatible gateway. Requests carry `x-opencode-session` for
|
||||
`opencode.ai` hosts (stable id per conversation, for prompt cache affinity).
|
||||
- **Anthropic Messages** — `{base}/messages` with `x-api-key` and `anthropic-version: 2023-06-01`.
|
||||
|
||||
A provider is ready when it has a base URL and a model id; a subscription is always ready (an
|
||||
empty model means the program's default).
|
||||
|
||||
## Tools and permissions
|
||||
|
||||
The tool set is `figcraft_mcp::tool_definitions()` — `run_command`, `batch`, `create_node`,
|
||||
`set_properties`, `inspect_document`, `design_context`, `screenshot`, `export`, `undo`, and the
|
||||
rest. Tool results are translated to each dialect (OpenAI: `tool` messages plus a user message for
|
||||
images; Anthropic: `tool_result` blocks, images inside them).
|
||||
|
||||
Two permission modes, toggled in the composer:
|
||||
|
||||
| Mode | Canvas edits | Files, network, plugins, fonts, the share server |
|
||||
|---|---|---|
|
||||
| **Ask** (default) | run at once | ask: a card names the tool and why |
|
||||
| **Auto** | run at once | run at once |
|
||||
|
||||
A denial is returned to the model as a tool error, so it can continue with what it may do. Even in
|
||||
Auto, a confined app (`--automation-read-root`) confines the agent's writes.
|
||||
|
||||
Every command runs with `agent: "FigCraft Agent"`, so the app shows the agent's avatar and outline
|
||||
while it works and signs the comments it makes.
|
||||
|
||||
## Self-review
|
||||
|
||||
When a turn changed the canvas and **Look at the canvas after each change** is on (Connections ›
|
||||
Advanced, on by default), the agent takes one screenshot through the `screenshot` tool (a step
|
||||
named *Checking the result*), hands it back with a short instruction, and the model fixes what it
|
||||
sees or replies. One pass per turn, so the cost is one extra request with one image.
|
||||
|
||||
- API key: the loop continues with the picture; skipped when the model's **Reads images** is off.
|
||||
- Command-line agent: the endpoint notes when a tool call changed the document; after the run, the
|
||||
same conversation is resumed once with the picture (`--resume` / `--session`). A failed check is
|
||||
a line in the answer, not a failed request.
|
||||
|
||||
## Reasoning effort
|
||||
|
||||
Connections › Advanced has a **Reasoning** choice: Auto (nothing is sent), Low, Medium or High. For
|
||||
OpenAI-compatible endpoints it becomes `reasoning_effort`. The Anthropic adapter leaves the
|
||||
provider's own default alone in this version.
|
||||
|
||||
## Variants
|
||||
|
||||
The composer's **×1 / ×2 / ×3** button makes one request build that many versions side by side: the
|
||||
first exactly as asked, the others as alternatives in their own frames, 96 px apart. One worker
|
||||
still does the work in one turn, so there is no concurrency to reconcile; the extra cost is the
|
||||
model's own tool calls.
|
||||
|
||||
## Tokens and cost
|
||||
|
||||
The panel shows `{input} in · {output} out` after the first turn. Fill **In $/1M** and **Out $/1M**
|
||||
in Connections › Advanced and it adds `≈ $… at API rates` — an estimate from the provider's own usage
|
||||
numbers, not an invoice. With the prices empty, no amount is guessed.
|
||||
|
||||
## Stop
|
||||
|
||||
**Stop** interrupts the stream (or ends the command-line agent's process), denies any permission request still waiting for an answer, and
|
||||
leaves the edits already made. If the agent thread ever ends unexpectedly (a panic), the panel
|
||||
says so and starts a fresh worker on the next request instead of staying "working" forever.
|
||||
|
||||
## Chat history
|
||||
|
||||
Each document keeps its conversation under `<settings folder>/agent-chats/`:
|
||||
|
||||
| File | Holds |
|
||||
|---|---|
|
||||
| `<slug>.ui.json` | what the panel shows: messages, tool cards, notes (the last 200 lines) |
|
||||
| `<slug>.context.json` | the model's own messages and token usage, so a request after a restart continues the conversation |
|
||||
|
||||
`<slug>` is a readable part of the file path (or the document's name while unsaved) plus a hash of
|
||||
the whole string. New chat starts a new pair of files and keeps the old one in the history. Switching tabs switches the
|
||||
conversation; a running turn keeps the one it started with, and its edits stay pinned to the
|
||||
document and window it began in.
|
||||
|
||||
## Context
|
||||
|
||||
Each request carries a short `inspect.designContext` of the selection (or the page when nothing is
|
||||
selected), so "make this bigger" applies to what the person is looking at. The model reads more
|
||||
with the tools. Older tool output is shortened once the conversation passes 600 000 characters.
|
||||
|
||||
## What an answer changed
|
||||
|
||||
The panel keeps the document as each turn found it and as each step left it, and compares them
|
||||
(`changed_layers`): a new layer counts once (not each child), an edited child counts without the
|
||||
frame that only holds it, pages and library copies are left out.
|
||||
|
||||
- Each step in the opened *N steps* list has **Show N layers**: it selects them (on the page of the
|
||||
first) and zooms to them.
|
||||
- After an answer that changed the canvas, a line says *Changed N layers* with **Show** and
|
||||
**Undo**. Undo walks back every undo step the answer made at once, and is offered only for the
|
||||
last answer, made in this run of the app, on the document in front, while nothing else changed
|
||||
since (otherwise its hint points to Edit › Undo). After it, **Redo** brings the changes back on
|
||||
the same terms.
|
||||
|
||||
## The seams: every line this module adds to upstream files
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `Cargo.toml` | `figcraft-agent` workspace member and `ureq` |
|
||||
| `crates/agent/**` | new crate (ours entirely) |
|
||||
| `crates/ui-egui/Cargo.toml` | depends on `figcraft-agent` |
|
||||
| `crates/ui-egui/src/lib.rs` | `pub mod chat;` and `FigApp.chat` |
|
||||
| `crates/ui-egui/src/state.rs` | `LeftTab::Agent` |
|
||||
| `crates/ui-egui/src/app.rs` | initialise `chat`; read `agents.json` on the first frame and open on the Agent tab; ⌘⇧M (`chat::shortcut`); the panel's accessible name for the tab |
|
||||
| `crates/ui-egui/src/panels/layers.rs` | the Agent tab in the rail, remembering it, and the tab's arm in `left_panel` |
|
||||
| `crates/ui-egui/locales/en.toml` | the panel's English strings (English only, as feature PRs do) |
|
||||
| `crates/ui-egui/src/control.rs` | drain bridge calls, pump replies (two call sites); `ui.set {leftTab: "agent"}` |
|
||||
| `crates/ui-egui/src/menus.rs` | the canvas context menu's Agent entries (one call, for a selection) |
|
||||
| `crates/ui-egui/src/services.rs` | `agent_config_path` (defaulted method, no breakage) |
|
||||
| `apps/figcraft/src/services.rs` | the desktop path for `agents.json` |
|
||||
| `xtask/src/layers.rs` | table entry and two same-layer pairs |
|
||||
|
||||
Everything else lives in files upstream does not touch. Keep the table above current: it is the
|
||||
checklist for a `git rebase`.
|
||||
|
||||
## Browser build
|
||||
|
||||
The Agent tab is not in the browser build's rail (an `Agent` left tab falls back to File there);
|
||||
no keys are stored in a page. Provider calls from the browser would also face CORS, so the browser build is out of scope
|
||||
for now.
|
||||
|
||||
## Adding a provider dialect
|
||||
|
||||
Implement a module beside `openai.rs` / `anthropic.rs`:
|
||||
|
||||
1. `payload(...)` — the request body from `system`, `messages`, `tools`.
|
||||
2. `stream(...)` — send it, read SSE with `sse::Sse`, call `on_text` per delta, return a `Step`
|
||||
(text, `Invocation`s, stop reason, usage).
|
||||
3. Translate `neutral::Block` both ways; do not leak the dialect into `session.rs`.
|
||||
4. Add a case to `ApiKind` and to `Agent::stream`.
|
||||
|
||||
Tests are fixture-based: no network in CI.
|
||||
+10
-1
@@ -22,6 +22,8 @@ const TABLE: &[(&str, u8)] = &[
|
||||
("engine", 5),
|
||||
("ui-egui", 6),
|
||||
("mcp", 6),
|
||||
// The in-app agent: providers, the tool loop and the bridge to the open window.
|
||||
("agent", 6),
|
||||
// Live sessions over the network (WebSockets): above the engine, beside the UI.
|
||||
("collab-net", 6),
|
||||
];
|
||||
@@ -72,5 +74,12 @@ pub fn check(root: &std::path::Path) -> bool {
|
||||
fn same_layer_ok(from: &str, to: &str) -> bool {
|
||||
// Within L0: color uses geom types; within L2: text/layout/pathops/collab are independent;
|
||||
// within L6 the MCP server joins live sessions through collab-net.
|
||||
matches!((from, to), ("figcraft-color", "figcraft-geom") | ("figcraft-render", "figcraft-format") | ("figcraft-mcp", "figcraft-collab-net"))
|
||||
matches!(
|
||||
(from, to),
|
||||
("figcraft-color", "figcraft-geom")
|
||||
| ("figcraft-render", "figcraft-format")
|
||||
| ("figcraft-mcp", "figcraft-collab-net")
|
||||
| ("figcraft-agent", "figcraft-mcp")
|
||||
| ("figcraft-ui-egui", "figcraft-agent")
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user