diff --git a/Cargo.lock b/Cargo.lock index 3087b7a66..bb74a602e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4342,11 +4342,13 @@ version = "0.30.1" dependencies = [ "eframe", "egui", + "image", "js-sys", "log", "percent-encoding", "serde_json", "solidcraft-engine", + "solidcraft-mcp", "solidcraft-ui-egui", "url", "wasm-bindgen", diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index 7a7661a88..a456abe09 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -27,22 +27,24 @@ profile = ["solidcraft-engine/profile"] [dependencies] solidcraft-engine = { workspace = true } solidcraft-ui-egui = { workspace = true } +solidcraft-mcp = { workspace = true } egui = { workspace = true } log = { workspace = true } +serde_json = { workspace = true } url = "2" percent-encoding = "2" [target.'cfg(target_arch = "wasm32")'.dependencies] eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } +image = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -serde_json = { workspace = true } web-sys = { version = "0.3", features = [ - "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager", + "Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "Clipboard", "ClipboardItem", "StorageManager", "FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream", "WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", "StorageEvent", "IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", - "Headers", "ReadableStream", "ReadableStreamDefaultReader", + "Headers", "Request", "RequestMode", "RequestCredentials", "RequestRedirect", "AbortController", "AbortSignal", "IdbVersionChangeEvent", "DomStringList", "DomException", "IdbCursorWithValue", "IdbCursor", "ReadableStream", "ReadableStreamDefaultReader", "BeforeUnloadEvent", "Event", "EventTarget", "KeyboardEvent", "Response", "FormData", "RequestInit", "MediaQueryList", "Gamepad", "Performance", ] } diff --git a/apps/solidcraft-web/src/agent.rs b/apps/solidcraft-web/src/agent.rs new file mode 100644 index 000000000..229f4cba1 --- /dev/null +++ b/apps/solidcraft-web/src/agent.rs @@ -0,0 +1,1780 @@ +//! Browser-only transport for the original assistant. No process, server, or shared key. +use serde_json::{Value, json}; +use solidcraft_ui_egui::{ + ControlRequest, + agent_chat::{ + acp::ModelInfo, + agents::{self, Entry, Protocol}, + api_wire, attach, + backend::{BrowserServices, ChatBackend, Event, PlatformAgentContext, PromptPart, TestError, ToolStatus}, + }, +}; +use std::{ + cell::{Cell, RefCell}, + collections::VecDeque, + rc::Rc, + sync::mpsc::{self, Receiver, Sender}, +}; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use wasm_bindgen_futures::{JsFuture, spawn_local}; + +const TOOLS: &[&str] = &[ + "list_commands", + "describe_command", + "execute", + "inspect_design", + "measure", + "body_topology", + "set_parameter", + "batch", + "undo", + "redo", + "skill_reference", +]; +const PLATFORM_TOOLS: &[&str] = &[ + "list_commands", + "describe_command", + "execute", + "inspect_design", + "measure", + "body_topology", + "set_parameter", + "check_parameters", + "batch", + "screenshot", + "undo", + "redo", + "skill_reference", +]; +const MAX_RESPONSE: usize = 16 * 1024 * 1024; +const MAX_SSE_EVENT: usize = 2 * 1024 * 1024; +thread_local! { + static NETWORK_GENERATION: Cell = const { Cell::new(0) }; + static REQUESTS: RefCell> = const { RefCell::new(Vec::new()) }; +} +/// Account and document lifecycle also cancels connection tests and model-list requests. +pub fn cancel_all_requests() { + NETWORK_GENERATION.with(|generation| generation.set(generation.get().wrapping_add(1))); + REQUESTS.with(|requests| { + for request in requests.borrow_mut().drain(..) { + request.abort(); + } + }); +} + +fn tr(key: &str) -> String { + solidcraft_ui_egui::i18n::tr(key).into() +} +fn failure(value: JsValue) -> String { + value.as_string().unwrap_or_else(|| tr("vm.agent.network_error")) +} + +pub async fn delay(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(window) = web_sys::window() { + let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); + } + }); + let _ = JsFuture::from(promise).await; +} + +/// A browser request has its own abort signal, no application credentials, no redirects. +async fn request(entry: &Entry, key: Option<&str>, path: &str, body: Option<&Value>, abort: &web_sys::AbortController) -> Result { + if entry.base_url.len() > 4096 || entry.model.len() > 1024 || key.is_some_and(|key| key.len() > 16_384) { + return Err(tr("vm.agent.bad_response")); + } + let base = agents::normalize_url(&entry.base_url)?; + if !agents::key_safe_for(&base) { + return Err(tr("ui.ai_key_needs_https")); + } + let parsed = url::Url::parse(&base).map_err(|_| tr("ui.ai_bad_url"))?; + if !parsed.username().is_empty() || parsed.password().is_some() || parsed.query().is_some() || parsed.fragment().is_some() { + return Err(tr("ui.ai_bad_url")); + } + let protocol = entry.kind.protocol().ok_or_else(|| tr("vm.agent.api_only"))?; + let url = format!("{}/{}", base.trim_end_matches('/'), path); + let init = web_sys::RequestInit::new(); + init.set_method(if body.is_some() { "POST" } else { "GET" }); + init.set_mode(web_sys::RequestMode::Cors); + init.set_credentials(web_sys::RequestCredentials::Omit); + init.set_redirect(web_sys::RequestRedirect::Error); + init.set_signal(Some(&abort.signal())); + if let Some(body) = body { + init.set_body(&JsValue::from_str(&body.to_string())); + } + let req = web_sys::Request::new_with_str_and_init(&url, &init).map_err(failure)?; + req.headers().set("Content-Type", "application/json").map_err(failure)?; + if protocol == Protocol::Anthropic { + req.headers().set("anthropic-version", "2023-06-01").map_err(failure)?; + req.headers().set("anthropic-dangerous-direct-browser-access", "true").map_err(failure)?; + } + if let Some(key) = key.filter(|key| !key.is_empty()) { + req.headers() + .set( + if protocol == Protocol::Anthropic { "x-api-key" } else { "Authorization" }, + &if protocol == Protocol::Anthropic { key.into() } else { format!("Bearer {key}") }, + ) + .map_err(failure)?; + } + let window = web_sys::window().ok_or_else(|| tr("vm.agent.network_error"))?; + let timeout_abort = abort.clone(); + let timed_out = Rc::new(Cell::new(false)); + let timed = timed_out.clone(); + let timer = Closure::::new(move || { + timed.set(true); + timeout_abort.abort(); + }); + let timeout = window + .set_timeout_with_callback_and_timeout_and_arguments_0( + timer.as_ref().unchecked_ref(), + (entry.request_timeout_s.clamp(30, 3600) * 1000) as i32, + ) + .map_err(failure)?; + let scope = NETWORK_GENERATION.with(Cell::get); + REQUESTS.with(|requests| requests.borrow_mut().push(abort.clone())); + let result = async { + let response: web_sys::Response = JsFuture::from(window.fetch_with_request(&req)).await.map_err(failure)?.dyn_into().map_err(failure)?; + let status = response.status(); + if status == 401 || status == 403 { + return Err(tr("vm.agent.auth_error")); + } + if status == 429 { + return Err(tr("vm.agent.rate_limit")); + } + if !response.ok() { + return Err(format!("{} (HTTP {status})", tr("vm.agent.service_error"))); + } + // Bound the actual stream, including responses without Content-Length. + let stream = response.body().ok_or_else(|| tr("vm.agent.bad_response"))?; + let reader: web_sys::ReadableStreamDefaultReader = stream.get_reader().dyn_into().map_err(|value| failure(value.into()))?; + let mut bytes = Vec::new(); + loop { + let chunk = JsFuture::from(reader.read()).await.map_err(failure)?; + if js_sys::Reflect::get(&chunk, &"done".into()).map_err(failure)?.as_bool() == Some(true) { + break; + } + let chunk = js_sys::Uint8Array::new(&js_sys::Reflect::get(&chunk, &"value".into()).map_err(failure)?); + if bytes.len().saturating_add(chunk.length() as usize) > MAX_RESPONSE { + abort.abort(); + return Err(tr("vm.agent.bad_response")); + } + bytes.extend(chunk.to_vec()); + } + let value: Value = serde_json::from_slice(&bytes).map_err(|_| tr("vm.agent.bad_response"))?; + let valid = if body.is_none() { + value.get("data").is_some() + } else { + match protocol { + Protocol::OpenAi => value.pointer("/choices/0/message").is_some(), + Protocol::Anthropic => value.get("content").is_some(), + } + }; + if !valid { + return Err(tr("vm.agent.bad_response")); + } + Ok(value) + } + .await; + window.clear_timeout_with_handle(timeout); + REQUESTS.with(|requests| requests.borrow_mut().retain(|request| request != abort)); + if scope != NETWORK_GENERATION.with(Cell::get) { + return Err("cancelled".into()); + } + if timed_out.get() { Err(tr("vm.agent.timeout")) } else { result } +} + +fn path(protocol: Protocol) -> &'static str { + if protocol == Protocol::Anthropic { "messages" } else { "chat/completions" } +} +fn catalog() -> Value { + json!({"tools":solidcraft_mcp::tool_definitions().into_iter().filter(|tool| tool["name"].as_str().is_some_and(|name| TOOLS.contains(&name))).collect::>()}) +} +fn protocol_tools(protocol: Protocol, catalog: &Value) -> Vec { + match protocol { + Protocol::OpenAi => api_wire::openai_tools(catalog), + Protocol::Anthropic => api_wire::anthropic_tools(catalog), + } +} + +/// The same listing feeds the connection switcher and the settings model picker. +async fn model_list(entry: &Entry, key: Option<&str>, abort: &web_sys::AbortController) -> Result, String> { + let body = request(entry, key, "models", None, abort).await?; + let rows = body["data"].as_array().ok_or_else(|| tr("vm.agent.bad_response"))?; + let mut models: Vec = rows + .iter() + .take(512) + .filter_map(|model| { + let id: String = model["id"].as_str()?.chars().take(256).collect(); + if id.trim().is_empty() { + return None; + } + let name = model["display_name"].as_str().or_else(|| model["name"].as_str()).filter(|name| !name.trim().is_empty()).unwrap_or(&id); + Some(ModelInfo { name: name.chars().take(256).collect(), id, description: String::new() }) + }) + .collect(); + models.sort_by(|a, b| a.id.cmp(&b.id)); + models.dedup_by(|a, b| a.id == b.id); + Ok(models) +} + +use crate::agent_tools::{ControlReply, Replay}; + +async fn tool_call( + name: &str, + args: &Value, + tools: &Sender, + generation: &Cell, + turn: u64, + ctx: &egui::Context, +) -> Result { + platform_tool_call_allowed(name, args, tools, generation, turn, ctx, TOOLS).await +} + +async fn platform_tool_call_allowed( + name: &str, + args: &Value, + tools: &Sender, + generation: &Cell, + turn: u64, + ctx: &egui::Context, + allowed: &[&str], +) -> Result { + if allowed == TOOLS && args.to_string().len() > 256 * 1024 { + return Err(tr("vm.agent.bad_response")); + } + if !allowed.contains(&name) { + return Err(tr("vm.agent.tool_unavailable")); + } + let mut results = Vec::new(); + for _ in 0..4096 { + if generation.get() != turn { + return Err("cancelled".into()); + } + let mut replay = Replay { results: &results, at: 0, next: None }; + let result = solidcraft_mcp::call_tool(&mut replay, name, args); + let Some((method, params)) = replay.next else { + return Ok(result); + }; + let sent_method = method.clone(); + let sent_params = params.clone(); + let (req, rx) = ControlRequest::new(method, params); + tools.send(req).map_err(|_| "document released".to_string())?; + ctx.request_repaint(); + let deadline = js_sys::Date::now() + 330_000.0; + loop { + if generation.get() != turn { + return Err("cancelled".into()); + } + match rx.try_recv() { + Ok(value) => { + results.push(ControlReply { + method: sent_method.clone(), + params: sent_params.clone(), + result: if value["ok"] == true { + Ok(value["result"].clone()) + } else { + Err(value["error"].as_str().unwrap_or("tool failed").into()) + }, + }); + break; + } + Err(mpsc::TryRecvError::Disconnected) => return Err("document released".into()), + Err(mpsc::TryRecvError::Empty) => {} + } + if js_sys::Date::now() > deadline { + return Err(tr("vm.agent.timeout")); + } + delay(20).await; + } + } + Err(tr("vm.agent.tool_unavailable")) +} + +fn validate_schema(schema: &Value, value: &Value, path: &str, depth: usize) -> Result<(), String> { + if depth > 16 { + return Err(format!("{path}: schema nesting is too deep")); + } + let matches = |kind: &str| match kind { + "object" => value.is_object(), + "array" => value.is_array(), + "string" => value.is_string(), + "number" => value.is_number(), + "integer" => value.as_i64().is_some() || value.as_u64().is_some(), + "boolean" => value.is_boolean(), + "null" => value.is_null(), + _ => true, + }; + match schema.get("type") { + Some(Value::String(kind)) if !matches(kind) => return Err(format!("{path}: must be {kind}")), + Some(Value::Array(kinds)) if !kinds.iter().filter_map(Value::as_str).any(matches) => { + return Err(format!("{path}: has an unsupported type")); + } + _ => {} + } + if let Some(options) = schema.get("enum").and_then(Value::as_array) + && !options.contains(value) + { + return Err(format!("{path}: value is not allowed")); + } + if let Some(object) = value.as_object() { + let properties = schema.get("properties").and_then(Value::as_object); + for required in schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + if !object.contains_key(required) || object.get(required).is_some_and(Value::is_null) { + return Err(format!("{path}.{required}: required")); + } + } + for (name, child) in object { + let child_schema = properties.and_then(|entries| entries.get(name)); + if let Some(child_schema) = child_schema { + validate_schema(child_schema, child, &format!("{path}.{name}"), depth + 1)?; + } else if schema.get("additionalProperties") == Some(&Value::Bool(false)) { + return Err(format!("{path}.{name}: unknown property")); + } else if let Some(additional) = schema.get("additionalProperties").filter(|v| v.is_object()) { + validate_schema(additional, child, &format!("{path}.{name}"), depth + 1)?; + } + } + if schema.get("minProperties").and_then(Value::as_u64).is_some_and(|min| object.len() < min as usize) { + return Err(format!("{path}: too few properties")); + } + if schema.get("maxProperties").and_then(Value::as_u64).is_some_and(|max| object.len() > max as usize) { + return Err(format!("{path}: too many properties")); + } + } + if let Some(array) = value.as_array() { + if schema.get("minItems").and_then(Value::as_u64).is_some_and(|min| array.len() < min as usize) + || schema.get("maxItems").and_then(Value::as_u64).is_some_and(|max| array.len() > max as usize) + { + return Err(format!("{path}: array length is outside the allowed range")); + } + if let Some(item_schema) = schema.get("items") { + for (index, item) in array.iter().enumerate() { + validate_schema(item_schema, item, &format!("{path}[{index}]"), depth + 1)?; + } + } + } + if let Some(text) = value.as_str() + && (schema.get("minLength").and_then(Value::as_u64).is_some_and(|min| text.len() < min as usize) + || schema.get("maxLength").and_then(Value::as_u64).is_some_and(|max| text.len() > max as usize)) + { + return Err(format!("{path}: string length is outside the allowed range")); + } + if let Some(number) = value.as_f64() + && (!number.is_finite() + || schema.get("minimum").and_then(Value::as_f64).is_some_and(|min| number < min) + || schema.get("maximum").and_then(Value::as_f64).is_some_and(|max| number > max)) + { + return Err(format!("{path}: number is outside the allowed range")); + } + Ok(()) +} + +#[derive(Clone)] +struct PlatformCall { + code: String, + name: String, + arguments: Value, +} + +struct PlatformCompletion { + finish_reason: String, + output: Vec, +} + +fn sse_boundary(bytes: &[u8]) -> Option<(usize, usize)> { + let mut index = 0; + while index < bytes.len() { + if bytes.get(index..index + 2) == Some(b"\n\n") { + return Some((index, 2)); + } + if bytes.get(index..index + 4) == Some(b"\r\n\r\n") { + return Some((index, 4)); + } + index += 1; + } + None +} + +fn sse_event(block: &[u8]) -> Result, String> { + let text = std::str::from_utf8(block).map_err(|_| "CAD AI returned invalid UTF-8".to_string())?; + let mut event = "message".to_string(); + let mut data = Vec::new(); + for line in text.split('\n') { + let line = line.strip_suffix('\r').unwrap_or(line); + if line.starts_with(':') { + continue; + } + if let Some(value) = line.strip_prefix("event:") { + event = value.trim_start().to_string(); + } else if let Some(value) = line.strip_prefix("data:") { + data.push(value.strip_prefix(' ').unwrap_or(value)); + } + } + if data.is_empty() { + return Ok(None); + } + let envelope = serde_json::from_str(&data.join("\n")).map_err(|_| "CAD AI returned an invalid SSE event".to_string())?; + Ok(Some((event, envelope))) +} + +fn protocol_code() -> &'static str { + "cad-agent-v1" +} + +fn string_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> { + value.get(key).and_then(Value::as_str) +} + +fn valid_code(code: &str) -> bool { + !code.is_empty() && code.len() <= 64 && code.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') +} + +fn content_text(content: &[Value]) -> String { + content.iter().filter_map(|part| string_field(part, "text")).collect::>().join("\n") +} + +// Only positive limits advertised by the backend impose a quota. Missing/zero +// values do not acquire a second, hard-coded frontend ceiling. +fn platform_limit(limits: &Value, name: &str) -> Option { + limits.get(name).and_then(Value::as_u64).filter(|limit| *limit > 0) +} + +fn exceeds_platform_limit(limits: &Value, name: &str, used: usize) -> bool { + platform_limit(limits, name).is_some_and(|limit| used as u64 > limit) +} + +fn base64_size(data: &str) -> usize { + (data.len().saturating_mul(3) / 4).saturating_sub(data.bytes().rev().take_while(|byte| *byte == b'=').count().min(2)) +} + +fn platform_image(mime: &str, data: &str, limits: &Value) -> Result<(Value, u32, u32), String> { + if !matches!(mime, "image/png" | "image/jpeg") { + return Err("CAD AI images must use PNG or JPEG".into()); + } + let binary = web_sys::window().ok_or_else(|| tr("vm.agent.network_error"))?.atob(data).map_err(failure)?; + let bytes: Vec = binary.chars().map(|byte| byte as u8).collect(); + let mut reader = image::ImageReader::new(std::io::Cursor::new(&bytes)).with_guessed_format().map_err(|error| error.to_string())?; + let mut decode_limits = image::Limits::default(); + decode_limits.max_image_width = Some(8192); + decode_limits.max_image_height = Some(8192); + decode_limits.max_alloc = Some(128 << 20); + reader.limits(decode_limits); + let mut picture = reader.decode().map_err(|error| error.to_string())?; + let max_edge = platform_limit(limits, "imageMaxEdge").unwrap_or(8192).min(8192) as u32; + if picture.width().max(picture.height()) <= max_edge && !exceeds_platform_limit(limits, "imageBytes", bytes.len()) { + return Ok((json!({"type":"image","mimeType":mime,"data":data}), picture.width(), picture.height())); + } + if picture.width().max(picture.height()) > max_edge { + picture = picture.resize(max_edge, max_edge, image::imageops::FilterType::Triangle); + } + loop { + let mut encoded = Vec::new(); + picture.write_to(&mut std::io::Cursor::new(&mut encoded), image::ImageFormat::Png).map_err(|error| error.to_string())?; + if !exceeds_platform_limit(limits, "imageBytes", encoded.len()) { + return Ok(( + json!({"type":"image","mimeType":"image/png", + "data":solidcraft_ui_egui::agent_chat::backend::base64(&encoded)}), + picture.width(), + picture.height(), + )); + } + if picture.width().max(picture.height()) <= 1 { + return Err("CAD AI screenshot cannot fit backend imageBytes even at one pixel; no image was sent".into()); + } + picture = picture.resize((picture.width() / 2).max(1), (picture.height() / 2).max(1), image::imageops::FilterType::Triangle); + } +} + +fn validate_content(content: &Value, allow_image: bool, limits: &Value) -> Result<(), String> { + let blocks = content.as_array().ok_or_else(|| "CAD AI content must be an array".to_string())?; + if blocks.is_empty() || blocks.len() > 16 { + return Err("CAD AI content block limit exceeded".into()); + } + for block in blocks { + match string_field(block, "type") { + Some("text") => { + let text = string_field(block, "text").ok_or_else(|| "CAD AI text block is invalid".to_string())?; + if text.is_empty() || exceeds_platform_limit(limits, "textBytes", text.len()) { + return Err("CAD AI text limit exceeded".into()); + } + } + Some("image") if allow_image => { + let mime = string_field(block, "mimeType").ok_or_else(|| "CAD AI image block is invalid".to_string())?; + let data = string_field(block, "data").ok_or_else(|| "CAD AI image block is invalid".to_string())?; + let decoded = base64_size(data); + if !matches!(mime, "image/png" | "image/jpeg") || exceeds_platform_limit(limits, "imageBytes", decoded) || data.starts_with("data:") { + return Err("CAD AI image limit or format is invalid".into()); + } + } + _ => return Err("CAD AI content block type is not supported".into()), + } + } + Ok(()) +} + +fn trim_platform_history(history: &mut Vec, max_items: usize) { + while history.len() > max_items { + let next_user = + history.iter().enumerate().skip(1).find(|(_, item)| item["type"] == "message" && item["role"] == "user").map(|(index, _)| index); + let Some(end) = next_user else { break }; + history.drain(..end); + } +} + +struct PlatformBackend { + context: PlatformAgentContext, + limits: Value, + tools: std::collections::BTreeMap, + sender: Sender, + ctx: egui::Context, + events: Rc>>, + history: Rc>>, + generation: Rc>, + abort: Rc>>, +} + +fn random_code() -> Result { + let window = web_sys::window().ok_or_else(|| tr("vm.agent.network_error"))?; + let crypto = js_sys::Reflect::get(&window, &"crypto".into()).map_err(failure)?; + let random_uuid: js_sys::Function = js_sys::Reflect::get(&crypto, &"randomUUID".into()).map_err(failure)?.dyn_into().map_err(failure)?; + random_uuid.call0(&crypto).map_err(failure)?.as_string().ok_or_else(|| tr("vm.agent.network_error")) +} + +fn safe_platform_tools(context: &PlatformAgentContext) -> std::collections::BTreeMap { + context.capabilities["tools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|tool| { + let name = string_field(tool, "name")?; + if !PLATFORM_TOOLS.contains(&name) { + return None; + } + let parameters = tool.get("parameters")?.as_object()?; + if parameters.get("type").and_then(Value::as_str) != Some("object") { + return None; + } + Some((name.to_string(), tool.clone())) + }) + .collect() +} + +fn item_call(item: &Value) -> Result { + if item["type"] != "toolCall" { + return Err("CAD AI completed output contains a non-tool item".into()); + } + let code = string_field(item, "callCode").ok_or_else(|| "CAD AI tool call is missing callCode".to_string())?; + let name = string_field(item, "name").ok_or_else(|| "CAD AI tool call is missing its name".to_string())?; + let arguments = + item.get("arguments").filter(|value| value.is_object()).cloned().ok_or_else(|| "CAD AI tool arguments must be an object".to_string())?; + if !valid_code(code) || name.len() > 64 { + return Err("CAD AI tool call identifier or name is invalid".into()); + } + Ok(PlatformCall { code: code.to_string(), name: name.to_string(), arguments }) +} + +fn validate_output(output: &Value, finish: &str, limits: &Value) -> Result, String> { + let items = output.as_array().ok_or_else(|| "CAD AI completed output must be an array".to_string())?; + if items.is_empty() { + return Err("CAD AI completed output is empty".into()); + } + let mut calls = Vec::new(); + for item in items { + match string_field(item, "type") { + Some("message") => { + if string_field(item, "role") != Some("assistant") { + return Err("CAD AI output may only contain assistant messages".into()); + } + validate_content(&item["content"], false, limits)?; + } + Some("toolCall") if finish == "tool_calls" => calls.push(item_call(item)?), + _ => return Err("CAD AI completed output has an invalid item".into()), + } + } + if (finish == "tool_calls") != !calls.is_empty() { + return Err("CAD AI finishReason does not match its output".into()); + } + let mut seen = std::collections::BTreeSet::new(); + if calls.iter().any(|call| !seen.insert(call.code.as_str())) { + return Err("CAD AI output repeats a callCode".into()); + } + Ok(calls) +} + +fn history_call_codes(history: &[Value]) -> std::collections::BTreeSet { + history.iter().filter(|item| item["type"] == "toolCall").filter_map(|item| string_field(item, "callCode").map(str::to_string)).collect() +} + +fn history_usage(history: &[Value]) -> (usize, usize) { + let mut text_bytes = 0usize; + let mut images = 0usize; + for item in history { + if let Some(content) = item.get("content").and_then(Value::as_array) { + for part in content { + if part["type"] == "text" { + text_bytes = text_bytes.saturating_add(string_field(part, "text").map_or(0, str::len)); + } else if part["type"] == "image" { + images += 1; + } + } + } + if item["type"] == "toolCall" { + text_bytes = text_bytes.saturating_add(item["arguments"].to_string().len()); + } + } + (text_bytes, images) +} + +fn reserve_platform_image_slot(history: &mut Vec, limits: &Value) { + let Some(limit) = platform_limit(limits, "imagesPerRequest") else { return }; + let Some(current) = history.iter().rposition(|item| item["type"] == "message" && item["role"] == "user") else { return }; + // A new user message may need another screenshot. Free an old image only by + // removing its entire completed round, keeping all current call/result pairs. + if history_usage(&history[current..]).1 as u64 >= limit { + return; + } + while history_usage(history).1 as u64 >= limit { + let before = history.len(); + trim_platform_history(history, before.saturating_sub(1)); + if history.len() == before { + break; + } + } +} + +fn platform_request(history: &[Value], context: &PlatformAgentContext, turn: &str) -> Value { + // The host replaces this placeholder with the current revision's SHA-256. + // Account for its real wire length when measuring the request, too. + json!({"protocolVersion":protocol_code(), "documentSessionCode":context.document_session_code, + "turnCode":turn, "cadProjectCode":context.cad_project_code, "history":history, + "context":{"documentRevision":"0".repeat(64)}}) +} + +fn platform_request_limits(request: &Value, limits: &Value) -> Vec { + let history = request["history"].as_array().map(Vec::as_slice).unwrap_or_default(); + let (text, images) = history_usage(history); + let text = text.saturating_add(request["context"].to_string().len()); + [("requestBytes", request.to_string().len()), ("textBytes", text), ("imagesPerRequest", images), ("historyItems", history.len())] + .into_iter() + .filter_map(|(name, used)| platform_limit(limits, name).filter(|limit| used as u64 > *limit).map(|limit| format!("{name}={used}/{limit}"))) + .collect() +} + +fn platform_model_request( + history: &[Value], + context: &PlatformAgentContext, + turn: &str, + limits: &Value, + tools: &std::collections::BTreeMap, +) -> Result { + let mut request = platform_request(history, context, turn); + let (text, images) = history_usage(history); + let note = json!({"cadWebRuntime":{ + "backendLimits":limits, + "historyUsageBeforeThisNote":{"requestBytes":request.to_string().len(),"textBytes":text,"images":images,"historyItems":history.len()}, + "remainingImages":platform_limit(limits,"imagesPerRequest").map(|limit| limit.saturating_sub(images as u64)), + "availableTools":tools.keys().collect::>(), + "rules":"Respect these backend limits on every request, including all retained history and tool results. Missing or zero limits impose no frontend quota. There is no frontend per-turn model-call or change quota. Do not request screenshots when remainingImages is zero; inspect_design, measure and body_topology can verify the model without images. Screenshot source must be model; never request window, path, local files, network access or unavailable tools. Give view or camera, not both. The CAD renderer accepts dimensions from 16 to 8192 pixels, further bounded by imageMaxEdge when advertised. Keep tool queries and batch output small enough for toolResultTextBytes. Leave room for the next tool calls/results and this runtime note within textBytes, requestBytes and historyItems; finish with a concise progress report and ask the user to continue in a new message before exhausting them. Never retry a forbidden operation unchanged. Request pacing is automatic; do not waste tools to wait." + }}).to_string(); + // Put runtime context in an existing user content block, never an unrecognised + // request field or a client-supplied system prompt. Only the wire copy changes: + // updated budgets replace the note on each request instead of accumulating. + let content = request["history"] + .as_array_mut() + .and_then(|items| items.iter_mut().find(|item| item["type"] == "message" && item["role"] == "user")) + .and_then(|item| item.get_mut("content")) + .and_then(Value::as_array_mut) + .ok_or_else(|| "CAD AI history must start with a user message".to_string())?; + if let Some(block) = content.iter_mut().find(|block| string_field(block, "type") == Some("text")) { + let original = string_field(block, "text").unwrap_or_default(); + block["text"] = json!(format!("{original}\n\n[CAD Web runtime context]\n{note}")); + } else if content.len() < 16 { + content.push(json!({"type":"text","text":note})); + } else { + return Err("CAD AI user message has no room for runtime context".into()); + } + Ok(request) +} + +fn platform_tool_budget(name: &str, history: &[Value], limits: &Value) -> Option { + if name != "screenshot" { + return None; + } + let (_, images) = history_usage(history); + let limit = platform_limit(limits, "imagesPerRequest")?; + if (images as u64) < limit { + return None; + } + Some(json!({"isError":true,"content":[{"type":"text","text":format!( + "Screenshot not executed: backend imagesPerRequest={limit}, retained images={images}, remainingImages=0. The view and model were not changed. Do not call screenshot again in this turn. Use inspect_design, measure or body_topology, or ask the user to continue in a new message if another image is essential." + )}]})) +} + +fn prompt_history(parts: &[PromptPart], limits: &Value) -> Result { + let mut content = Vec::new(); + for part in parts { + match part { + PromptPart::Text(text) if !text.is_empty() => content.push(json!({"type":"text","text":text})), + PromptPart::Text(_) => {} + PromptPart::Image { mime, base64 } => { + content.push(platform_image(mime, base64, limits)?.0); + } + PromptPart::Document { .. } => return Err("CAD AI does not accept PDF attachments yet".into()), + } + } + validate_content(&Value::Array(content.clone()), true, limits)?; + Ok(json!({"type":"message","role":"user","content":content})) +} + +async fn platform_control( + method: &str, + params: Value, + sender: &Sender, + generation: &Cell, + turn: u64, + ctx: &egui::Context, +) -> Result { + if generation.get() != turn { + return Err("cancelled".into()); + } + let (request, reply) = ControlRequest::new(method, params); + sender.send(request).map_err(|_| "document released".to_string())?; + ctx.request_repaint(); + let deadline = js_sys::Date::now() + 330_000.0; + loop { + match reply.try_recv() { + Ok(result) => { + if result["ok"] == true { + return Ok(result["result"].clone()); + } + return Err(result["error"].as_str().unwrap_or("CAD command failed").to_string()); + } + Err(mpsc::TryRecvError::Disconnected) => return Err("document released".into()), + Err(mpsc::TryRecvError::Empty) => {} + } + if js_sys::Date::now() >= deadline { + return Err(tr("vm.agent.timeout")); + } + delay(20).await; + } +} + +async fn platform_screenshot( + args: &Value, + sender: &Sender, + generation: &Cell, + turn: u64, + ctx: &egui::Context, + limits: &Value, +) -> Result { + let max_edge = platform_limit(limits, "imageMaxEdge").unwrap_or(8192).min(8192); + if max_edge < 16 { + return Err("CAD AI screenshot imageMaxEdge is smaller than the renderer's minimum size (16 pixels)".into()); + } + let width = args["width"].as_u64().unwrap_or(960.min(max_edge)); + let height = args["height"].as_u64().unwrap_or(600.min(max_edge)); + if !(16..=max_edge).contains(&width) || !(16..=max_edge).contains(&height) { + return Err(format!("CAD AI screenshot dimensions must be between 16 and {max_edge} pixels; rendering was not started")); + } + if args.get("path").is_some_and(|value| !value.is_null()) || string_field(args, "source").is_some_and(|source| source != "model") { + return Err("CAD AI screenshot only supports the in-memory model view".into()); + } + if args.get("view").is_some_and(|value| !value.is_null()) && args.get("camera").is_some_and(|value| !value.is_null()) { + return Err("CAD AI screenshot accepts either view or camera".into()); + } + if let Some(camera) = args.get("camera").filter(|value| !value.is_null()) { + platform_control("engine.execute", json!({"command":"view.apply","params":{"camera":camera}}), sender, generation, turn, ctx).await?; + } else if let Some(view) = string_field(args, "view") { + if ["iso", "home", "front", "back", "top", "bottom", "left", "right", "fit"].contains(&view) { + platform_control("ui.view", json!({"view":view}), sender, generation, turn, ctx).await?; + if !matches!(view, "fit" | "home") { + platform_control("ui.view", json!({"view":"fit"}), sender, generation, turn, ctx).await?; + } + } else { + // As in the native screenshot tool, resolve saved views and standard-view + // aliases (for example isometric) through the engine's view command. + platform_control("engine.execute", json!({"command":"view.apply","params":{"view":view}}), sender, generation, turn, ctx).await?; + } + } + let rendered = platform_control( + "ui.render", + json!({"width":width,"height":height,"grid":args["grid"],"axes":args["axes"],"inline":true}), + sender, + generation, + turn, + ctx, + ) + .await?; + let data = string_field(&rendered, "pngBase64").ok_or_else(|| "CAD screenshot renderer returned no image".to_string())?; + let (image, width, height) = platform_image("image/png", data, limits)?; + Ok(json!({"content":[image, + {"type":"text","text":format!("CAD model view screenshot, {width} × {height} pixels") }]})) +} + +async fn platform_tool( + name: &str, + arguments: &Value, + schema: &Value, + sender: &Sender, + generation: &Cell, + turn: u64, + ctx: &egui::Context, + limits: &Value, +) -> Result { + let params = schema.get("parameters").ok_or_else(|| "CAD AI tool schema is missing".to_string())?; + validate_schema(params, arguments, name, 0)?; + if name == "screenshot" { + return match platform_screenshot(arguments, sender, generation, turn, ctx, limits).await { + Err(error) + if error.starts_with("invalid parameters for `view.apply`:") + || error.starts_with("unknown view `") + || error.starts_with("CAD AI screenshot ") => + { + Ok(json!({"isError":true,"content":[{"type":"text","text":error}, + {"type":"text","text":"Correct the screenshot arguments. Use iso, home, front, back, top, bottom, left, right, fit, or an existing saved view name. Omit view and camera to capture the current view. Supply either view or camera, not both; source must be model."}]})) + } + result => result, + }; + } + platform_tool_call_allowed(name, arguments, sender, generation, turn, ctx, PLATFORM_TOOLS).await +} + +async fn platform_request_step( + request: Value, + context: &PlatformAgentContext, + schemas: &std::collections::BTreeMap, + abort: &web_sys::AbortController, + on_start: &js_sys::Function, + generation: &Cell, + turn: u64, + events: &Rc>>, + ctx: &egui::Context, +) -> Result<(PlatformCompletion, Vec), String> { + if generation.get() != turn { + return Err("cancelled".into()); + } + let window = web_sys::window().ok_or_else(|| tr("vm.agent.network_error"))?; + let host = js_sys::Reflect::get(&window, &"__VIBEMAKE_CAD__".into()).map_err(failure)?; + let callback: js_sys::Function = js_sys::Reflect::get(&host, &"agentChat".into()).map_err(failure)?.dyn_into().map_err(failure)?; + let request_js = js_sys::JSON::parse(&request.to_string()).map_err(failure)?; + let promise: js_sys::Promise = callback.call3(&host, &request_js, &abort.signal(), on_start).map_err(failure)?.dyn_into().map_err(failure)?; + let response: web_sys::Response = JsFuture::from(promise).await.map_err(failure)?.dyn_into().map_err(failure)?; + if generation.get() != turn { + return Err("cancelled".into()); + } + if !response.ok() { + let status = response.status(); + let message = JsFuture::from(response.json().map_err(failure)?) + .await + .ok() + .and_then(|value| js_sys::Reflect::get(&value, &"message".into()).ok()?.as_string()); + return Err(message.unwrap_or_else(|| format!("CAD AI request failed (HTTP {status})"))); + } + if !response.headers().get("content-type").map_err(failure)?.unwrap_or_default().to_ascii_lowercase().contains("text/event-stream") { + return Err("CAD AI did not return an SSE stream".into()); + } + let stream = response.body().ok_or_else(|| "CAD AI stream is empty".to_string())?; + let reader: web_sys::ReadableStreamDefaultReader = stream.get_reader().dyn_into().map_err(|value| failure(value.into()))?; + let mut buffer = Vec::::new(); + let mut response_bytes = 0usize; + let mut request_id: Option = None; + let mut announced = Vec::::new(); + let mut streamed_text = String::new(); + let mut completed = None; + let result = async { + loop { + if generation.get() != turn { + return Err("cancelled".into()); + } + let chunk = JsFuture::from(reader.read()).await.map_err(failure)?; + if js_sys::Reflect::get(&chunk, &"done".into()).map_err(failure)?.as_bool() == Some(true) { + break; + } + let chunk = js_sys::Uint8Array::new(&js_sys::Reflect::get(&chunk, &"value".into()).map_err(failure)?); + response_bytes = response_bytes.saturating_add(chunk.length() as usize); + if response_bytes > MAX_RESPONSE { + return Err("CAD AI response exceeds its size limit".into()); + } + buffer.extend(chunk.to_vec()); + loop { + let Some((at, delimiter)) = sse_boundary(&buffer) else { break }; + if at > MAX_SSE_EVENT { + return Err("CAD AI SSE event exceeds its size limit".into()); + } + let block = buffer.drain(..at).collect::>(); + buffer.drain(..delimiter); + let Some((event, envelope)) = sse_event(&block)? else { continue }; + if string_field(&envelope, "code") != Some("OK") { + return Err(string_field(&envelope, "message").unwrap_or("CAD AI returned an error").to_string()); + } + let id = string_field(&envelope, "requestId") + .filter(|id| !id.is_empty() && id.len() <= 128) + .ok_or_else(|| "CAD AI SSE requestId is missing".to_string())?; + if request_id.as_deref().is_some_and(|previous| previous != id) { + return Err("CAD AI SSE requestId changed during the response".into()); + } + request_id = Some(id.to_string()); + let data = envelope.get("data").ok_or_else(|| "CAD AI SSE data is missing".to_string())?; + if string_field(data, "documentSessionCode") != Some(&context.document_session_code) + || string_field(data, "turnCode") != string_field(&request, "turnCode") + { + return Err("CAD AI SSE event belongs to another document or turn".into()); + } + match event.as_str() { + "text_delta" => { + let text = + string_field(data, "text").filter(|text| !text.is_empty()).ok_or_else(|| "CAD AI text delta is invalid".to_string())?; + streamed_text.push_str(text); + if exceeds_platform_limit(&context.capabilities["limits"], "textBytes", streamed_text.len()) { + return Err("CAD AI text limit exceeded".into()); + } + events.borrow_mut().push_back(Event::Text { thought: false, text: text.to_string() }); + ctx.request_repaint(); + } + "tool_call" => { + let call = PlatformCall { + code: string_field(data, "callCode") + .filter(|code| valid_code(code)) + .ok_or_else(|| "CAD AI callCode is invalid".to_string())? + .to_string(), + name: string_field(data, "name").ok_or_else(|| "CAD AI tool name is missing".to_string())?.to_string(), + arguments: data + .get("arguments") + .filter(|args| args.is_object()) + .cloned() + .ok_or_else(|| "CAD AI tool arguments are invalid".to_string())?, + }; + if !schemas.contains_key(&call.name) || announced.iter().any(|old| old.code == call.code) { + return Err("CAD AI announced an unknown or duplicate tool call".into()); + } + if let Some(schema) = schemas.get(&call.name) { + validate_schema(&schema["parameters"], &call.arguments, &call.name, 0)?; + } + let id = format!("{}:{}", string_field(&request, "turnCode").unwrap_or("turn"), call.code); + events.borrow_mut().push_back(Event::Tool { + id, + title: Some(call.name.clone()), + kind: None, + status: Some(ToolStatus::Pending), + input: Some(call.arguments.clone()), + output: None, + }); + ctx.request_repaint(); + announced.push(call); + } + "completed" => { + let finish = string_field(data, "finishReason").ok_or_else(|| "CAD AI completed event has no finishReason".to_string())?; + if !matches!(finish, "stop" | "tool_calls") { + return Err("CAD AI completed event has an unsupported finishReason".into()); + } + completed = Some(PlatformCompletion { + finish_reason: finish.to_string(), + output: data + .get("output") + .and_then(Value::as_array) + .cloned() + .ok_or_else(|| "CAD AI completed output is missing".to_string())?, + }); + return Ok(()); + } + "error" => return Err(string_field(&envelope, "message").unwrap_or("CAD AI request failed").to_string()), + _ => return Err(format!("CAD AI sent unsupported SSE event `{event}`")), + } + } + if buffer.len() > MAX_SSE_EVENT { + return Err("CAD AI SSE event exceeds its size limit".into()); + } + } + Err("CAD AI stream ended before completed".into()) + } + .await; + let _ = reader.cancel(); + reader.release_lock(); + result?; + let completion = completed.ok_or_else(|| "CAD AI stream ended before completed".to_string())?; + let output_text = completion + .output + .iter() + .filter(|item| item["type"] == "message") + .flat_map(|item| item["content"].as_array().into_iter().flatten()) + .filter_map(|part| string_field(part, "text")) + .collect::(); + if !streamed_text.is_empty() && streamed_text != output_text { + return Err("CAD AI completed output does not match its streamed text".into()); + } + if streamed_text.is_empty() && !output_text.is_empty() { + events.borrow_mut().push_back(Event::Text { thought: false, text: output_text }); + ctx.request_repaint(); + } + let calls = validate_output(&Value::Array(completion.output.clone()), &completion.finish_reason, &context.capabilities["limits"])?; + if calls.len() != announced.len() + || calls + .iter() + .zip(&announced) + .any(|(output, announced)| output.code != announced.code || output.name != announced.name || output.arguments != announced.arguments) + { + return Err("CAD AI completed output does not match its tool_call events".into()); + } + Ok((completion, calls)) +} + +fn tool_result_content(result: &Value, limits: &Value) -> Result<(Vec, bool), String> { + let mut is_error = result["isError"] == true; + let mut content = + result.get("content").and_then(Value::as_array).cloned().unwrap_or_else(|| vec![json!({"type":"text","text":result.to_string()})]); + let mut text_total = 0usize; + for block in &content { + match string_field(block, "type") { + Some("text") => text_total = text_total.saturating_add(string_field(block, "text").map_or(0, str::len)), + Some("image") => { + let data = string_field(block, "data").ok_or_else(|| "CAD tool returned invalid image data".to_string())?; + if !matches!(string_field(block, "mimeType"), Some("image/png" | "image/jpeg")) + || exceeds_platform_limit(limits, "imageBytes", base64_size(data)) + { + return Err("CAD tool image exceeds the platform limit".into()); + } + } + _ => return Err("CAD tool returned an unsupported result block".into()), + } + } + if let Some(limit) = platform_limit(limits, "toolResultTextBytes").filter(|limit| text_total as u64 > *limit) { + // The command has already run. Report a delivery failure without sending + // partial JSON or inviting a replay of an already applied modification. + let feedback = json!({ + "error":"tool_result_too_large", "textBytes":text_total, "toolResultTextBytes":limit, + "toolReportedError":is_error, + "recovery":"The tool ran, but its full result was withheld because it exceeds the backend text limit. No partial JSON was sent. Do not infer success or failure of individual changes from this delivery error and never replay modifications. Inspect the current design with a smaller query or read-only measurement before continuing." + }).to_string(); + if feedback.len() as u64 > limit { + return Err(format!( + "CAD AI tool result textBytes={text_total} exceeds backend toolResultTextBytes={limit}; the full result was withheld. Inspect with a smaller query; do not replay modifications." + )); + } + content = vec![json!({"type":"text","text":feedback})]; + is_error = true; + } + Ok((content, is_error)) +} + +async fn platform_turn( + parts: Vec, + context: PlatformAgentContext, + tools: std::collections::BTreeMap, + limits: Value, + sender: Sender, + ctx: egui::Context, + events: Rc>>, + history: Rc>>, + generation: Rc>, + abort_slot: Rc>>, + turn: u64, +) { + let result = async { + let mut next = history.borrow().clone(); + let user = prompt_history(&parts, &limits)?; + next.push(user); + let turn_code = random_code()?; + // As in the native assistant, a turn runs until completion, Stop or an error. + // Per-request resource and protocol limits still apply to each iteration. + loop { + if generation.get() != turn { + return Ok(()); + } + if let Some(max_items) = platform_limit(&limits, "historyItems") { + trim_platform_history(&mut next, usize::try_from(max_items).unwrap_or(usize::MAX)); + } + reserve_platform_image_slot(&mut next, &limits); + let request = loop { + let request = platform_model_request(&next, &context, &turn_code, &limits, &tools)?; + let exceeded = platform_request_limits(&request, &limits); + if exceeded.is_empty() { + break request; + } + let before = next.len(); + let keep = next.len().saturating_sub(1); + trim_platform_history(&mut next, keep); + if next.len() == before { + return Err(solidcraft_ui_egui::i18n::format("vm.agent.request_limits", &[("limits", &exceeded.join(", "))])); + } + }; + let controller = web_sys::AbortController::new().map_err(failure)?; + *abort_slot.borrow_mut() = Some(controller.clone()); + let window = web_sys::window().ok_or_else(|| tr("vm.agent.network_error"))?; + let timeout_abort = controller.clone(); + let timed_out = Rc::new(Cell::new(false)); + let timeout_state = timed_out.clone(); + let timer = Closure::::new(move || { + timeout_state.set(true); + timeout_abort.abort(); + }); + let timeout_ms = platform_limit(&limits, "requestTimeoutSeconds").map(|seconds| seconds.saturating_mul(1000).min(i32::MAX as u64) as i32); + // The host queues requests by account. Start the network/stream timeout only + // when fetch begins, so waiting for the next minute is cancellable, not a timeout. + let timeout = Rc::new(Cell::new(None)); + let start_timeout = timeout.clone(); + let start_window = window.clone(); + let start_timer = timer.as_ref().clone(); + let on_start = Closure:: Result<(), JsValue>>::new(move || { + if let Some(timeout_ms) = timeout_ms.filter(|_| start_timeout.get().is_none()) { + let id = start_window.set_timeout_with_callback_and_timeout_and_arguments_0(start_timer.unchecked_ref(), timeout_ms)?; + start_timeout.set(Some(id)); + } + Ok(()) + }); + let step = platform_request_step(request, &context, &tools, &controller, on_start.as_ref().unchecked_ref(), &generation, turn, &events, &ctx).await; + if let Some(timeout) = timeout.get() { + window.clear_timeout_with_handle(timeout); + } + *abort_slot.borrow_mut() = None; + if timed_out.get() { + return Err(tr("vm.agent.timeout")); + } + if generation.get() != turn { + return Ok(()); + } + let (completion, calls) = step?; + let used_codes = history_call_codes(&next); + if calls.iter().any(|call| used_codes.contains(&call.code)) { + return Err("CAD AI reused a callCode from this conversation".into()); + } + next.extend(completion.output.clone()); + if completion.finish_reason == "stop" { + *history.borrow_mut() = next; + return Ok(()); + } + for call in calls { + if generation.get() != turn { + return Ok(()); + } + let schema = tools.get(&call.name).ok_or_else(|| "CAD AI requested a tool that is not available".to_string())?; + let id = format!("{turn_code}:{}", call.code); + let result = match platform_tool_budget(&call.name, &next, &limits) { + Some(blocked) => Ok(blocked), + None => match validate_schema(&schema["parameters"], &call.arguments, &call.name, 0) { + Ok(()) => platform_tool(&call.name, &call.arguments, schema, &sender, &generation, turn, &ctx, &limits).await, + Err(error) => Ok(json!({"isError":true,"content":[{"type":"text","text":error}]})), + }, + }; + let (mut content, failed) = match result { + Ok(value) => tool_result_content(&value, &limits)?, + Err(error) if error == "cancelled" => return Ok(()), + Err(error) => return Err(error), + }; + // This is execution feedback for the next model call, paired with the original + // error. The model can inspect and correct arguments without replaying completed + // steps. Refusals and stale contexts still stop recovery. + if failed { + let feedback = json!({"recovery":"Analyse the tool error. Inspect the current design or command schema before correcting the failed step. Respect applied/not_run/rolled_back; never repeat already applied steps. Retry with corrected arguments. Do not retry a user denial, a stale context or a server-enforced limit."}).to_string(); + let size = content.iter().filter_map(|part| string_field(part, "text")).map(str::len).sum::(); + if !exceeds_platform_limit(&limits, "toolResultTextBytes", size.saturating_add(feedback.len())) { + content.push(json!({"type":"text","text":feedback})); + } + } + let result_value = json!({"content":content,"isError":failed}); + let output = content_text(&content).chars().take(20_000).collect::(); + events.borrow_mut().push_back(Event::Tool { + id, + title: Some(call.name.clone()), + kind: None, + status: Some(if failed { ToolStatus::Failed } else { ToolStatus::Completed }), + input: None, + output: Some(if output.is_empty() { "CAD screenshot captured".into() } else { output }), + }); + ctx.request_repaint(); + next.push(json!({"type":"toolResult","callCode":call.code,"isError":failed,"content":result_value["content"]})); + } + *history.borrow_mut() = next.clone(); + } + } + .await; + if generation.get() != turn { + return; + } + match result { + Ok(()) => events.borrow_mut().push_back(Event::TurnEnded { reason: String::new() }), + Err(error) => { + events.borrow_mut().push_back(Event::Error(error)); + events.borrow_mut().push_back(Event::TurnEnded { reason: "error".into() }); + } + } + abort_slot.borrow_mut().take(); + ctx.request_repaint(); +} + +impl PlatformBackend { + fn emit(&self, event: Event) { + self.events.borrow_mut().push_back(event); + self.ctx.request_repaint(); + } + + fn abort_pending(&self) { + self.generation.set(self.generation.get().wrapping_add(1)); + if let Some(controller) = self.abort.borrow_mut().take() { + controller.abort(); + } + } +} + +impl ChatBackend for PlatformBackend { + fn poll(&mut self) -> Vec { + self.events.borrow_mut().drain(..).collect() + } + + fn prompt(&mut self, parts: &[PromptPart]) { + let generation = self.generation.clone(); + let turn = generation.get().wrapping_add(1); + generation.set(turn); + let context = self.context.clone(); + let tools = self.tools.clone(); + let limits = self.limits.clone(); + let sender = self.sender.clone(); + let ctx = self.ctx.clone(); + let events = self.events.clone(); + let history = self.history.clone(); + let abort = self.abort.clone(); + spawn_local(platform_turn(parts.to_vec(), context, tools, limits, sender, ctx, events, history, generation, abort, turn)); + } + + fn cancel(&mut self) { + self.abort_pending(); + self.emit(Event::TurnEnded { reason: "cancelled".into() }); + } + + fn new_session(&mut self) { + self.abort_pending(); + self.history.borrow_mut().clear(); + let model = string_field(&self.context.capabilities, "model").unwrap_or("VibeMake CAD Agent").to_string(); + self.emit(Event::Ready { agent: model, images: true }); + } + + fn answer_permission(&mut self, _key: u64, _option: Option<&str>) {} + fn authenticate(&mut self, _method: &str) {} + + fn shutdown(&mut self, _wait: bool) { + self.abort_pending(); + } +} + +impl Drop for PlatformBackend { + fn drop(&mut self) { + self.shutdown(false); + } +} + +fn platform_limits(input: &Value) -> Value { + [ + "requestBytes", + "imageBytes", + "imageMaxEdge", + "imagesPerRequest", + "textBytes", + "toolResultTextBytes", + "historyItems", + "requestTimeoutSeconds", + "requestsPerMinute", + ] + .into_iter() + .filter_map(|name| platform_limit(input, name).map(|limit| (name.to_string(), json!(limit)))) + .collect::>() + .into() +} + +/// A harmless model request proves the actual tool-call shape, not just /models access. +async fn probe(entry: &Entry, key: Option<&str>, abort: &web_sys::AbortController) -> Result { + let protocol = entry.kind.protocol().ok_or_else(|| tr("vm.agent.api_only"))?; + if entry.model.trim().is_empty() { + return Err(tr("ui.ai_need_model")); + } + let list = json!({"tools":[{"name":"cad_connection_test","description":"Return ok=true. Connection test only; no model changes.","inputSchema":{"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"]}}]}); + let history = vec![json!({"role":"user","content":"Call cad_connection_test with ok=true. This only checks API compatibility."})]; + let mut body = api_wire::request_body(protocol, &entry.model, &history, &protocol_tools(protocol, &list), &entry.reasoning_effort, false); + body["tool_choice"] = match protocol { + Protocol::OpenAi => json!({"type":"function","function":{"name":"cad_connection_test"}}), + Protocol::Anthropic => json!({"type":"tool","name":"cad_connection_test"}), + }; + match request(entry, key, path(protocol), Some(&body), abort).await { + Ok(value) => Ok(api_wire::reply(protocol, &value) + .calls + .iter() + .any(|call| call.name == "cad_connection_test" && call.arguments.as_ref().is_ok_and(|args| args["ok"] == true))), + Err(error) if error.contains("HTTP 400") || error.contains("HTTP 422") => { + let history = vec![json!({"role":"user","content":"Reply OK. API connection test."})]; + let body = api_wire::request_body(protocol, &entry.model, &history, &[], "", false); + request(entry, key, path(protocol), Some(&body), abort).await?; + Ok(false) + } + Err(error) => Err(error), + } +} + +struct BrowserBackend { + entry: Rc>, + key: Option, + tools: Sender, + ctx: egui::Context, + events: Rc>>, + history: Rc>>, + generation: Rc>, + abort: Rc>>, + tools_enabled: Rc>>, +} +impl BrowserBackend { + fn emit(&self, event: Event) { + self.events.borrow_mut().push_back(event); + self.ctx.request_repaint(); + } + fn abort_pending(&self) { + self.generation.set(self.generation.get().wrapping_add(1)); + if let Some(abort) = self.abort.borrow_mut().take() { + abort.abort(); + } + } + fn start_probe(&self) { + let entry = self.entry.borrow().clone(); + let key = self.key.clone(); + let events = self.events.clone(); + let ctx = self.ctx.clone(); + let generation = self.generation.clone(); + let turn = generation.get(); + let abort = self.abort.clone(); + let supported = self.tools_enabled.clone(); + spawn_local(async move { + let Ok(controller) = web_sys::AbortController::new() else { + return; + }; + *abort.borrow_mut() = Some(controller.clone()); + let result = probe(&entry, key.as_deref(), &controller).await; + if generation.get() != turn { + return; + } + match result { + Ok(tools) => { + let listing = model_list(&entry, key.as_deref(), &controller).await; + if generation.get() != turn { + return; + } + let configured = ModelInfo { id: entry.model.clone(), name: entry.model.clone(), description: String::new() }; + let (mut available, note) = match listing { + Ok(models) => (models, None), + Err(error) => (Vec::new(), Some(error)), + }; + if !available.iter().any(|model| model.id == entry.model) { + available.insert(0, configured); + } + supported.set(Some(tools)); + let mut events = events.borrow_mut(); + events.push_back(Event::ToolsAvailable(tools)); + events.push_back(Event::ModelsNote(note)); + events.push_back(Event::Models { current: entry.model.clone(), available }); + events.push_back(Event::Ready { agent: entry.name, images: true }); + } + Err(error) => { + let mut events = events.borrow_mut(); + events.push_back(Event::Error(error.clone())); + events.push_back(Event::Exited { tail: vec![error] }); + } + } + abort.borrow_mut().take(); + ctx.request_repaint(); + }); + } +} +impl ChatBackend for BrowserBackend { + fn poll(&mut self) -> Vec { + self.events.borrow_mut().drain(..).collect() + } + fn prompt(&mut self, parts: &[PromptPart]) { + let generation = self.generation.clone(); + let turn = generation.get().wrapping_add(1); + generation.set(turn); + let entry = self.entry.clone(); + let key = self.key.clone(); + let tools = self.tools.clone(); + let ctx = self.ctx.clone(); + let supported = self.tools_enabled.clone(); + let events = self.events.clone(); + let history = self.history.clone(); + let abort = self.abort.clone(); + let parts = parts.to_vec(); + spawn_local(async move { + let emit = |event| { + if generation.get() == turn { + events.borrow_mut().push_back(event); + ctx.request_repaint(); + } + }; + let protocol = entry.borrow().kind.protocol().unwrap_or(Protocol::OpenAi); + + let mut messages = history.borrow().clone(); + messages.push(api_wire::user_message(protocol, &parts)); + api_wire::drop_old_views(&mut messages, 2); + if messages.len() > 240 { + let start = messages + .iter() + .enumerate() + .skip(messages.len() - 240) + .find(|(_, msg)| api_wire::starts_a_turn(msg)) + .map(|(index, _)| index) + .unwrap_or(0); + messages.drain(..start); + } + if protocol == Protocol::Anthropic { + api_wire::drop_thinking(&mut messages); + } + let outcome: Result<(), String> = async { + if supported.get().is_none() { + let configured = entry.borrow().clone(); + let controller = web_sys::AbortController::new().map_err(failure)?; + *abort.borrow_mut() = Some(controller.clone()); + let tools = probe(&configured, key.as_deref(), &controller).await?; + if generation.get() != turn { + return Ok(()); + } + supported.set(Some(tools)); + emit(Event::ToolsAvailable(tools)); + } + let offered = if supported.get() == Some(true) { protocol_tools(protocol, &catalog()) } else { Vec::new() }; + let mut next_tool = 0u64; + loop { + if generation.get() != turn { + return Ok(()); + } + let configured = entry.borrow().clone(); + let controller = web_sys::AbortController::new().map_err(failure)?; + *abort.borrow_mut() = Some(controller.clone()); + let body = api_wire::request_body(protocol, &configured.model, &messages, &offered, &configured.reasoning_effort, false); + let value = request(&configured, key.as_deref(), path(protocol), Some(&body), &controller).await?; + if generation.get() != turn { + return Ok(()); + } + let reply = api_wire::reply(protocol, &value); + if supported.get() != Some(true) && !reply.calls.is_empty() { + return Err(tr("vm.agent.chat_only")); + } + for (thought, text) in reply.text { + emit(Event::Text { thought, text }); + } + messages.push(reply.assistant); + if reply.calls.is_empty() { + *history.borrow_mut() = messages; + emit(Event::TurnEnded { reason: reply.stop.into() }); + return Ok(()); + } + let mut outputs = Vec::new(); + for call in reply.calls { + if generation.get() != turn { + return Ok(()); + } + let tool_id = format!("{}-{turn}-{next_tool}", call.id); + next_tool = next_tool.wrapping_add(1); + emit(Event::Tool { + id: tool_id.clone(), + title: Some(call.name.clone()), + kind: None, + status: Some(ToolStatus::InProgress), + input: call.arguments.as_ref().ok().cloned(), + output: None, + }); + let result = match &call.arguments { + Ok(args) => tool_call(&call.name, args, &tools, &generation, turn, &ctx).await, + Err(error) => Err(format!("Not run: {error}")), + }; + if generation.get() != turn { return Ok(()); } + let (text, failed) = match result { + Ok(result) => (result.to_string(), result["isError"] == true), + Err(error) => (error, true), + }; + emit(Event::Tool { + id: tool_id, + title: Some(call.name), + kind: None, + status: Some(if failed { ToolStatus::Failed } else { ToolStatus::Completed }), + input: None, + output: Some(text.chars().take(20_000).collect()), + }); + if protocol == Protocol::OpenAi { + messages.push(json!({"role":"tool","tool_call_id":call.id,"content":text.chars().take(20_000).collect::()})); + } else { + outputs.push(json!({"type":"tool_result","tool_use_id":call.id,"content":text.chars().take(20_000).collect::(),"is_error":failed})); + } + } + if !outputs.is_empty() { + messages.push(json!({"role":"user","content":outputs})); + } + *history.borrow_mut() = messages.clone(); + } + } + .await; + if let Err(error) = outcome { + emit(Event::Error(error)); + emit(Event::TurnEnded { reason: "error".into() }); + } + if generation.get() == turn { + abort.borrow_mut().take(); + } + }); + } + fn cancel(&mut self) { + self.abort_pending(); + self.emit(Event::TurnEnded { reason: "cancelled".into() }); + } + fn new_session(&mut self) { + // The panel already ended the old turn. A fresh chat must not start with a cancelled notice. + self.abort_pending(); + self.history.borrow_mut().clear(); + self.emit(Event::Ready { agent: self.entry.borrow().name.clone(), images: true }); + } + fn answer_permission(&mut self, _key: u64, _option: Option<&str>) {} + fn authenticate(&mut self, _method: &str) {} + fn set_model(&mut self, model: &str) { + if self.entry.borrow().model == model { + return; + } + self.cancel(); + self.entry.borrow_mut().model = model.into(); + self.tools_enabled.set(None); + } + fn set_request_timeout(&mut self, seconds: u64) { + self.entry.borrow_mut().request_timeout_s = seconds; + } + fn set_reasoning_effort(&mut self, effort: &str) { + self.entry.borrow_mut().reasoning_effort = agents::reasoning_effort(effort); + } + fn shutdown(&mut self, _wait: bool) { + self.cancel(); + self.key = None; + } +} +impl Drop for BrowserBackend { + fn drop(&mut self) { + self.shutdown(false); + } +} + +pub fn services() -> BrowserServices { + BrowserServices { + connect: Box::new(|entry, key, tools, ctx| { + let backend = BrowserBackend { + entry: Rc::new(RefCell::new(entry)), + key, + tools, + ctx, + events: Rc::default(), + history: Rc::default(), + generation: Rc::default(), + abort: Rc::default(), + tools_enabled: Rc::new(Cell::new(None)), + }; + backend.start_probe(); + Ok(Box::new(backend)) + }), + platform_connect: Some(Box::new(|mut context, sender, ctx| { + let model = string_field(&context.capabilities, "model").unwrap_or("VibeMake CAD Agent").to_string(); + let compatible = context.capabilities["protocolVersion"] == protocol_code() && context.capabilities["enabled"] == true; + let limits = platform_limits(&context.capabilities["limits"]); + context.capabilities["limits"] = limits.clone(); + let backend = PlatformBackend { + limits, + tools: safe_platform_tools(&context), + context, + sender, + ctx, + events: Rc::default(), + history: Rc::default(), + generation: Rc::default(), + abort: Rc::default(), + }; + if !compatible { + backend.emit(Event::Error(tr("vm.agent.platform_unavailable"))); + backend.emit(Event::Exited { tail: Vec::new() }); + } else { + let has_tools = !backend.tools.is_empty(); + backend.emit(Event::Documents(false)); + backend.emit(Event::ToolsAvailable(has_tools)); + backend.emit(Event::Ready { agent: model, images: true }); + } + Ok(Box::new(backend) as Box) + })), + list: Box::new(|protocol, url, key, ctx| { + let (tx, rx) = mpsc::channel(); + spawn_local(async move { + let entry = + Entry::from_config(&agents::AgentConfig { kind: protocol.kind(), base_url: url, request_timeout_s: 30, ..Default::default() }); + let result = async { + let abort = web_sys::AbortController::new().map_err(failure)?; + model_list(&entry, key.as_deref(), &abort).await + } + .await; + let _ = tx.send(result); + ctx.request_repaint(); + }); + rx + }), + test: Box::new(|entry, key, ctx| { + let (tx, rx) = mpsc::channel(); + spawn_local(async move { + let result = match web_sys::AbortController::new() { + Ok(abort) => probe(&entry, key.as_deref(), &abort) + .await + .and_then(|tools| if tools { Ok(tr("vm.agent.test_ok")) } else { Err(tr("vm.agent.chat_only")) }), + Err(error) => Err(failure(error)), + } + .map_err(TestError::Other); + let _ = tx.send(result); + ctx.request_repaint(); + }); + rx + }), + attach: Box::new(choose_attachment), + paste_picture: Box::new(paste_picture), + } +} + +fn paste_picture(ctx: egui::Context) -> Receiver> { + let (tx, rx) = mpsc::channel(); + // Begin the browser permission request in the button's user gesture. + let request = web_sys::window().and_then(|window| { + let clipboard = window.navigator().clipboard(); + js_sys::Reflect::get(&clipboard, &"read".into()).ok().filter(JsValue::is_function).map(|_| clipboard.read()) + }); + spawn_local(async move { + let result = async { + let request = request.ok_or_else(|| tr("vm.agent.clipboard_error"))?; + let items = JsFuture::from(request).await.map_err(|_| tr("vm.agent.clipboard_error"))?; + for value in js_sys::Array::from(&items).iter().take(attach::MAX_FILES) { + let item: web_sys::ClipboardItem = value.dyn_into().map_err(failure)?; + for mime in item.types().iter().filter_map(|value| value.as_string()) { + let extension = match mime.as_str() { + "image/png" => "png", + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + _ => continue, + }; + let blob: web_sys::Blob = + JsFuture::from(item.get_type(&mime)).await.map_err(|_| tr("vm.agent.clipboard_error"))?.dyn_into().map_err(failure)?; + if blob.size() > 40.0 * 1024.0 * 1024.0 { + return Err(tr("vm.agent.file_error")); + } + let bytes = js_sys::Uint8Array::new(&JsFuture::from(blob.array_buffer()).await.map_err(failure)?).to_vec(); + return attach::picture(format!("pasted picture.{}", extension), &bytes); + } + } + Err(tr("ui.agent_chat_no_picture")) + } + .await; + let _ = tx.send(result); + ctx.request_repaint(); + }); + rx +} + +fn choose_attachment(ctx: egui::Context) -> Receiver> { + let (tx, rx) = mpsc::channel(); + spawn_local(async move { + let result = pick_attachment().await; + let _ = tx.send(result); + ctx.request_repaint(); + }); + rx +} + +fn attachment_bytes(name: String, bytes: &[u8]) -> Result { + match attach::kind(std::path::Path::new(&name)) { + attach::Kind::Picture if bytes.len() <= 40 * 1024 * 1024 => attach::picture(name, bytes), + attach::Kind::Text if bytes.len() <= 256 * 1024 => Ok(attach::Attachment { + id: 0, + name, + content: attach::Content::Text(std::sync::Arc::new(String::from_utf8(bytes.to_vec()).map_err(|_| tr("vm.agent.file_error"))?)), + thumb: None, + }), + _ => Err(tr("vm.agent.file_error")), + } +} + +/// Consume assistant drops before the general file importer and the embedded host discard them. +pub fn take_attachment_drops(app: &mut solidcraft_ui_egui::SolveApp, ctx: &egui::Context, raw: &mut egui::RawInput) { + let over_chat = ctx.pointer_hover_pos().is_some_and(|point| app.agent_chat.panel_rect.is_some_and(|rect| rect.contains(point))); + if raw.dropped_files.is_empty() + || app.platform.is_locked() + || !solidcraft_ui_egui::agent_chat::shown(app) + || !app.agent_chat.open + || app.preferences.agent_chat_minimized + || !over_chat + { + return; + } + let dropped = std::mem::take(&mut raw.dropped_files); + let (tx, rx) = mpsc::channel(); + let remaining = solidcraft_ui_egui::agent_chat::receive_browser_attachments(app, dropped.len(), rx); + if remaining == 0 { + return; + } + let ctx = ctx.clone(); + spawn_local(async move { + for file in dropped.into_iter().take(remaining) { + let name = file.path().file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_else(|| "dropped".into()); + let limit = match attach::kind(std::path::Path::new(&name)) { + attach::Kind::Picture => 40.0 * 1024.0 * 1024.0, + attach::Kind::Text => 256.0 * 1024.0, + _ => 0.0, + }; + let size = file.web_file().map(|file| file.size()).unwrap_or(f64::INFINITY); + let result = if limit == 0.0 || !size.is_finite() || size < 0.0 || size > limit { + Err(tr("vm.agent.file_error")) + } else { + file.bytes_async().await.map_err(|_| tr("vm.agent.file_error")).and_then(|bytes| attachment_bytes(name, &bytes)) + }; + if tx.send(result).is_err() { + break; + } + ctx.request_repaint(); + } + }); +} + +async fn pick_attachment() -> Result { + let document = web_sys::window().and_then(|window| window.document()).ok_or_else(|| tr("vm.agent.file_error"))?; + let input: web_sys::HtmlInputElement = + document.create_element("input").map_err(failure)?.dyn_into().map_err(|value: web_sys::Element| failure(value.into()))?; + input.set_type("file"); + let extensions: Vec<_> = attach::extensions() + .into_iter() + .filter(|extension| matches!(attach::kind(std::path::Path::new(&format!("file.{extension}"))), attach::Kind::Picture | attach::Kind::Text)) + .map(|extension| format!(".{extension}")) + .collect(); + input.set_accept(&extensions.join(",")); + let mut change = None; + let mut cancel = None; + let choice = js_sys::Promise::new(&mut |resolve, _| { + let selected = input.clone(); + let changed = resolve.clone(); + let on_change = Closure::::new(move || { + let value = selected.files().and_then(|files| files.get(0)).map(JsValue::from).unwrap_or(JsValue::NULL); + let _ = changed.call1(&JsValue::NULL, &value); + }); + let on_cancel = Closure::::new(move || { + let _ = resolve.call1(&JsValue::NULL, &JsValue::NULL); + }); + input.set_onchange(Some(on_change.as_ref().unchecked_ref())); + let _ = input.add_event_listener_with_callback("cancel", on_cancel.as_ref().unchecked_ref()); + change = Some(on_change); + cancel = Some(on_cancel); + }); + input.click(); + let selected = JsFuture::from(choice).await.map_err(failure)?; + input.set_onchange(None); + if let Some(cancel) = &cancel { + let _ = input.remove_event_listener_with_callback("cancel", cancel.as_ref().unchecked_ref()); + } + drop((change, cancel)); + if selected.is_null() { + return Err(String::new()); + } + let file: web_sys::File = selected.dyn_into().map_err(failure)?; + if file.size() > 40.0 * 1024.0 * 1024.0 { + return Err(tr("vm.agent.file_error")); + } + let name = file.name(); + let bytes = js_sys::Uint8Array::new(&JsFuture::from(file.array_buffer()).await.map_err(failure)?).to_vec(); + attachment_bytes(name, &bytes) +} diff --git a/apps/solidcraft-web/src/agent_storage.rs b/apps/solidcraft-web/src/agent_storage.rs new file mode 100644 index 000000000..e1ed37e4b --- /dev/null +++ b/apps/solidcraft-web/src/agent_storage.rs @@ -0,0 +1,421 @@ +//! Account-partitioned assistant credentials. Opt-in browser storage is not an OS keychain. +use serde_json::{Value, json}; +use solidcraft_ui_egui::{ + SolveApp, + agent_chat::{self, backend::Secrets}, +}; +use std::{ + cell::RefCell, + collections::{BTreeMap, BTreeSet}, + sync::{Arc, Mutex}, +}; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use wasm_bindgen_futures::{JsFuture, spawn_local}; + +#[derive(Default)] +struct Data { + owner: Option, + generation: u64, + loaded: bool, + keys: BTreeMap, + remembered: BTreeSet, + notice: Option, + profile: String, +} +#[derive(Clone, Default)] +pub struct BrowserSecrets(Arc>); +#[derive(Default)] +struct Writes { + pending: BTreeMap, + running: BTreeSet, +} +thread_local! { + static STORE: BrowserSecrets = BrowserSecrets::default(); + // Pending deletions and opt-in changes outlive a logout, independently of live credentials. + static WRITES: RefCell = RefCell::default(); +} +fn tr(key: &str) -> String { + solidcraft_ui_egui::i18n::tr(key).into() +} +fn storage_error(_: JsValue) -> String { + tr("vm.agent.storage_failed") +} +pub fn secrets() -> Arc { + STORE.with(|store| Arc::new(store.clone())) +} + +async fn bounded(promise: js_sys::Promise) -> Result { + let window = web_sys::window().ok_or(JsValue::NULL)?; + let mut timer = None; + let mut handle = None; + let timeout = js_sys::Promise::new(&mut |_, reject| { + let callback = Closure::::new(move || { + let _ = reject.call0(&JsValue::NULL); + }); + handle = window.set_timeout_with_callback_and_timeout_and_arguments_0(callback.as_ref().unchecked_ref(), 5000).ok(); + timer = Some(callback); + }); + let result = JsFuture::from(js_sys::Promise::race(&js_sys::Array::of2(&promise, &timeout))).await; + if let Some(handle) = handle { + window.clear_timeout_with_handle(handle); + } + drop(timer); + result +} + +async fn database() -> Result { + let factory = web_sys::window().and_then(|window| window.indexed_db().ok().flatten()).ok_or_else(|| tr("vm.agent.storage_failed"))?; + let req = factory.open_with_u32("vm.cad.agent.credentials.v1", 1).map_err(storage_error)?; + let upgrade_req = req.clone(); + let upgrade = Closure::::new(move || { + if let Ok(value) = upgrade_req.result() + && let Ok(db) = value.dyn_into::() + { + let _ = db.create_object_store("credentials"); + } + }); + req.set_onupgradeneeded(Some(upgrade.as_ref().unchecked_ref())); + let waiting = req.clone(); + let mut success = None; + let mut failure = None; + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let waiting = waiting.clone(); + let ok = Closure::::new(move || { + if let Ok(value) = waiting.result() { + let _ = resolve.call1(&JsValue::NULL, &value); + } + }); + let bad = Closure::::new(move || { + let _ = reject.call0(&JsValue::NULL); + }); + req.set_onsuccess(Some(ok.as_ref().unchecked_ref())); + req.set_onerror(Some(bad.as_ref().unchecked_ref())); + req.set_onblocked(Some(bad.as_ref().unchecked_ref())); + success = Some(ok); + failure = Some(bad); + }); + let value = bounded(promise).await; + req.set_onsuccess(None); + req.set_onerror(None); + req.set_onblocked(None); + req.set_onupgradeneeded(None); + if value.is_err() { + let late = req.clone(); + let close = Closure::::once(move || { + late.set_onsuccess(None); + if let Ok(value) = late.result() + && let Ok(db) = value.dyn_into::() + { + db.close(); + } + }) + .into_js_value(); + req.set_onsuccess(Some(close.unchecked_ref())); + } + drop((success, failure, upgrade)); + value.map_err(storage_error)?.dyn_into().map_err(storage_error) +} + +async fn stored(owner: &str, write: Option) -> Result { + let db = database().await?; + let result = async { + let tx = db + .transaction_with_str_and_mode( + "credentials", + if write.is_some() { web_sys::IdbTransactionMode::Readwrite } else { web_sys::IdbTransactionMode::Readonly }, + ) + .map_err(storage_error)?; + let store = tx.object_store("credentials").map_err(storage_error)?; + let req = match write { + Some(value) => store.put_with_key(&value.into(), &owner.into()), + None => store.get(&owner.into()), + } + .map_err(storage_error)?; + let mut complete = None; + let mut failure = None; + let mut aborted = None; + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let ok = Closure::::new(move || { + let _ = resolve.call0(&JsValue::NULL); + }); + let rejected = reject.clone(); + let bad = Closure::::new(move || { + let _ = rejected.call0(&JsValue::NULL); + }); + let abort = Closure::::new(move || { + let _ = reject.call0(&JsValue::NULL); + }); + tx.set_oncomplete(Some(ok.as_ref().unchecked_ref())); + tx.set_onerror(Some(bad.as_ref().unchecked_ref())); + tx.set_onabort(Some(abort.as_ref().unchecked_ref())); + complete = Some(ok); + failure = Some(bad); + aborted = Some(abort); + }); + let outcome = bounded(promise).await; + if outcome.is_err() { + let _ = tx.abort(); + } + tx.set_oncomplete(None); + tx.set_onerror(None); + tx.set_onabort(None); + drop((complete, failure, aborted)); + outcome.map_err(storage_error)?; + Ok(req.result().map_err(storage_error)?.as_string().unwrap_or_default()) + } + .await; + db.close(); + result +} + +pub fn activate(owner: &str) -> bool { + STORE.with(|store| { + let Ok(mut data) = store.0.lock() else { + return false; + }; + if data.owner.as_deref() == Some(owner) { + return data.loaded; + } + if WRITES.with(|writes| writes.borrow().running.contains(owner)) { + return false; + } + data.generation = data.generation.wrapping_add(1); + let generation = data.generation; + data.owner = Some(owner.into()); + data.loaded = false; + data.keys.clear(); + data.remembered.clear(); + data.notice = None; + data.profile.clear(); + let owner = owner.to_owned(); + let store = store.clone(); + spawn_local(async move { + let result = stored(&owner, None).await; + let Ok(mut data) = store.0.lock() else { + return; + }; + if data.generation != generation { + return; + } + match result { + Ok(value) => { + let keys: BTreeMap = serde_json::from_str(&value).unwrap_or_default(); + data.keys = keys.into_iter().take(128).filter(|(id, key)| id.len() <= 256 && key.len() <= 16_384).collect(); + data.remembered = data.keys.keys().cloned().collect(); + } + Err(error) => data.notice = Some(error), + } + data.loaded = true; + }); + false + }) +} + +pub fn clear_context() { + crate::agent::cancel_all_requests(); + STORE.with(|store| { + if let Ok(mut data) = store.0.lock() { + data.generation = data.generation.wrapping_add(1); + data.owner = None; + data.loaded = false; + data.keys.clear(); + data.remembered.clear(); + data.profile.clear(); + } + }); +} + +fn agent_pref(key: &str) -> bool { + key == "agents" || key == "connect_ai_apps" || key.starts_with("agent_") || key.starts_with("ai_") +} + +/// Shared visual settings must never carry another account's agents or grants. +pub fn shared_preferences(encoded: &str) -> String { + let Ok(mut value) = serde_json::from_str::(encoded) else { + return "{}".into(); + }; + fn strip(value: &mut Value) { + match value { + Value::Object(object) => { + object.retain(|key, _| !agent_pref(key)); + for value in object.values_mut() { + strip(value); + } + } + Value::Array(array) => { + for value in array { + strip(value); + } + } + _ => {} + } + } + strip(&mut value); + value.to_string() +} +pub fn load_profile(app: &mut SolveApp, owner: &str) { + agent_chat::disconnect(app); + app.agent_chat = Default::default(); + let stored = web_sys::window() + .and_then(|window| window.local_storage().ok().flatten()) + .and_then(|store| store.get_item(&format!("vm.cad.agent.profile.{owner}")).ok().flatten()); + let saved: Value = stored.as_deref().and_then(|value| serde_json::from_str(value).ok()).unwrap_or(Value::Null); + if let Ok(mut current) = serde_json::to_value(&app.preferences) { + let defaults = serde_json::to_value(solidcraft_ui_egui::prefs::Prefs::default()).unwrap_or(Value::Null); + if let Some(current) = current.as_object_mut() { + for (key, default) in defaults.as_object().into_iter().flatten().filter(|(key, _)| agent_pref(key)) { + current.insert(key.clone(), saved.get(key).unwrap_or(default).clone()); + } + if saved.is_null() { + current.insert("ai_permissions".into(), json!("ask")); + } + } + if let Ok(preferences) = serde_json::from_value(current) { + app.preferences = preferences; + } + } + app.preferences.agents.retain(|agent| agent.kind.is_api()); + app.preferences.agent_chat_popped = false; + app.preferences.agent_off_thread = false; + app.preferences.agent_control = false; + app.preferences.connect_ai_apps = false; + for agent in &mut app.preferences.agents { + agent.key = app.services.secrets.as_ref().and_then(|store| store.get(&agent.id).ok().flatten()).is_some(); + } +} + +pub fn save_profile(app: &SolveApp) { + STORE.with(|store| { + let Ok(mut data) = store.0.lock() else { + return; + }; + let Some(owner) = data.owner.clone().filter(|_| data.loaded) else { + return; + }; + if app + .platform + .agent_context + .as_deref() + .and_then(|context| serde_json::from_str::(context).ok()) + .and_then(|context| context["userId"].as_str().map(str::to_owned)) + .as_deref() + != Some(&owner) + { + return; + } + let Ok(encoded) = serde_json::from_str::(&app.prefs()) else { + return; + }; + let value = &encoded["preferences"]; + let profile: serde_json::Map = + value.as_object().into_iter().flatten().filter(|(key, _)| agent_pref(key)).map(|(key, value)| (key.clone(), value.clone())).collect(); + let value = Value::Object(profile).to_string(); + if value != data.profile { + let result = web_sys::window() + .and_then(|window| window.local_storage().ok().flatten()) + .map(|storage| storage.set_item(&format!("vm.cad.agent.profile.{owner}"), &value)); + if matches!(result, Some(Ok(()))) { + data.profile = value; + } + } + }); +} + +fn flush(store: BrowserSecrets) { + let Ok(data) = store.0.lock() else { + return; + }; + let Some(owner) = data.owner.clone() else { + return; + }; + let keys: BTreeMap<_, _> = data.keys.iter().filter(|(id, _)| data.remembered.contains(*id)).map(|(id, key)| (id.clone(), key.clone())).collect(); + let value = serde_json::to_string(&keys).unwrap_or_default(); + let generation = data.generation; + drop(data); + let start = WRITES.with(|writes| { + let mut writes = writes.borrow_mut(); + writes.pending.insert(owner.clone(), (value, generation)); + writes.running.insert(owner.clone()) + }); + if !start { + return; + } + spawn_local(async move { + loop { + let next = WRITES.with(|writes| { + let mut writes = writes.borrow_mut(); + let next = writes.pending.remove(&owner); + if next.is_none() { + writes.running.remove(&owner); + } + next + }); + let Some((value, generation)) = next else { return }; + let result = stored(&owner, Some(value)).await; + if let Err(error) = result + && let Ok(mut data) = store.0.lock() + && data.generation == generation + && data.owner.as_deref() == Some(&owner) + { + data.notice = Some(error); + data.remembered.clear(); + } + } + }); +} + +impl Secrets for BrowserSecrets { + fn get(&self, id: &str) -> Result, String> { + let data = self.0.lock().map_err(|_| tr("vm.agent.storage_failed"))?; + if !data.loaded { + return Err(tr("vm.agent.loading_keys")); + } + Ok(data.keys.get(id).cloned()) + } + fn set(&self, id: &str, secret: &str) -> Result<(), String> { + if secret.len() > 16_384 { + return Err(tr("vm.agent.bad_key")); + } + let mut data = self.0.lock().map_err(|_| tr("vm.agent.storage_failed"))?; + if !data.loaded || data.owner.is_none() { + return Err(tr("vm.agent.loading_keys")); + } + data.keys.insert(id.into(), secret.into()); + Ok(()) + } + fn delete(&self, id: &str) -> Result<(), String> { + { + let mut data = self.0.lock().map_err(|_| tr("vm.agent.storage_failed"))?; + data.keys.remove(id); + data.remembered.remove(id); + } + flush(self.clone()); + Ok(()) + } + fn remember(&self, id: &str, remember: bool) -> Result<(), String> { + { + let mut data = self.0.lock().map_err(|_| tr("vm.agent.storage_failed"))?; + if remember && data.keys.contains_key(id) { + data.remembered.insert(id.into()); + } else { + data.remembered.remove(id); + } + } + flush(self.clone()); + Ok(()) + } + fn remembered(&self, id: &str) -> bool { + self.0.lock().is_ok_and(|data| data.remembered.contains(id)) + } + fn clear_remembered(&self) -> Result<(), String> { + { + let mut data = self.0.lock().map_err(|_| tr("vm.agent.storage_failed"))?; + data.remembered.clear(); + } + flush(self.clone()); + Ok(()) + } + fn notice(&self) -> Option { + self.0.lock().ok().and_then(|mut data| data.notice.take()) + } +} diff --git a/apps/solidcraft-web/src/agent_tools.rs b/apps/solidcraft-web/src/agent_tools.rs new file mode 100644 index 000000000..039e61b2b --- /dev/null +++ b/apps/solidcraft-web/src/agent_tools.rs @@ -0,0 +1,38 @@ +//! Nonblocking adapter to the original MCP contracts. Cached replies never execute geometry. +use serde_json::Value; + +pub struct ControlReply { + pub method: String, + pub params: Value, + pub result: Result, +} + +/// Rerun pure request planning against an immutable, checked prefix of real control replies. +/// Only the first missing request is emitted. The caller asynchronously obtains its result. +pub struct Replay<'a> { + pub results: &'a [ControlReply], + pub at: usize, + pub next: Option<(String, Value)>, +} +impl solidcraft_mcp::Backend for Replay<'_> { + fn call(&mut self, method: &str, params: Value) -> Result { + let index = self.at; + self.at += 1; + if let Some(value) = self.results.get(index) { + if value.method != method || value.params != params { + return Err("inconsistent browser tool plan; no command was replayed".into()); + } + return value.result.clone(); + } + if self.next.is_none() { + self.next = Some((method.into(), params)); + } + Err("still running: awaiting browser control reply".into()) + } + fn has_ui(&self) -> bool { + true + } + fn describe(&self) -> String { + "VibeMake CAD browser".into() + } +} diff --git a/apps/solidcraft-web/src/install.rs b/apps/solidcraft-web/src/install.rs index e8ae0bd91..54791e07b 100644 --- a/apps/solidcraft-web/src/install.rs +++ b/apps/solidcraft-web/src/install.rs @@ -23,9 +23,9 @@ fn prompt() { let _ = js_sys::Reflect::set(&window, &OFFER.into(), &JsValue::NULL); } let shown = js_sys::Reflect::get(&offer, &"prompt".into()) - .and_then(|f| f.dyn_into::().map_err(JsValue::from)) + .and_then(|f| f.dyn_into::()) .and_then(|f| f.call0(&offer)) - .and_then(|p| p.dyn_into::().map_err(JsValue::from)); + .and_then(|p| p.dyn_into::()); match shown { // Accepted or dismissed, the browser handles it; a refusal is only logged. Ok(p) => wasm_bindgen_futures::spawn_local(async move { diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index ec3bd8ace..ca6940fcf 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -6,6 +6,12 @@ //! `?webgpu`), `?sample` opens the sample part. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(target_arch = "wasm32")] +mod agent; +#[cfg(target_arch = "wasm32")] +mod agent_storage; +#[cfg(any(target_arch = "wasm32", test))] +mod agent_tools; #[cfg(target_arch = "wasm32")] mod api; #[cfg(any(target_arch = "wasm32", test))] @@ -18,6 +24,8 @@ mod files; mod install; #[cfg(target_arch = "wasm32")] mod linked; +#[cfg(target_arch = "wasm32")] +mod platform; #[cfg(any(target_arch = "wasm32", test))] mod space_mouse; @@ -40,6 +48,7 @@ fn query_flag(query: &str, name: &str) -> bool { struct Launch { open: Option, embed: bool, + platform: bool, } #[cfg(any(target_arch = "wasm32", test))] @@ -59,7 +68,7 @@ impl Launch { } fn persists(&self) -> bool { - !self.embed + !self.embed && !self.platform } fn full_app_url(&self, mut url: url::Url) -> String { @@ -176,6 +185,19 @@ mod web { /// draws it with reversed depth, whose precision follows the distance from the eye (#1434). const DEPTH_BITS: u8 = 32; + /// Chromium can reset the native caret to zero when committing an IME composition in + /// eframe's 1px-wide input. Give its input bridge room for a glyph; egui still owns the + /// visible editor and its selection, including edits in the middle of a message. + fn prepare_text_agent(canvas: &web_sys::HtmlCanvasElement) { + let Some(input) = canvas.next_element_sibling().and_then(|element| element.dyn_into::().ok()) else { + return; + }; + let style = input.style(); + if let Err(error) = style.set_property("width", "32px").and_then(|()| style.set_property("opacity", "0")) { + log::warn!("could not size the browser text input: {error:?}"); + } + } + /// The loading animation (assets/styles/web/loading-logo.svg) settles into the finished mark /// about 3.2 s after the page starts; this adds a short hold. The app doesn't land before it. const LOADING_MIN_MS: f64 = 3600.0; @@ -284,6 +306,7 @@ mod web { linked: crate::linked::Download, full_url: Option, api: Api, + platform: Option, files: Rc, /// When the last autosave was (seconds), and the revision it holds (none stored: `None`). autosaved_at: f64, @@ -322,20 +345,21 @@ mod web { let live = std::mem::replace(&mut self.app.preferences.language, saved); let prefs = self.app.prefs(); self.app.preferences.language = live; - prefs + if self.launch.platform { crate::agent_storage::shared_preferences(&prefs) } else { prefs } } /// A settings change goes to the browser's storage in the frame it is made, and from /// there to the other open tabs (#8644). Input is what changes settings, so a frame /// without any is skipped; eframe's own save still catches anything else. fn store_prefs(&mut self, ctx: &egui::Context) { - if !self.launch.persists() || ctx.input(|i| i.events.is_empty()) { + if (!self.launch.persists() && !self.launch.platform) || ctx.input(|i| i.events.is_empty()) { return; } let prefs = self.persisted_prefs(); let Some(prefs) = self.prefs_writer.take(prefs) else { return }; - let stored = - web_sys::window().and_then(|w| w.local_storage().ok().flatten()).map(|s| s.set_item(solidcraft_ui_egui::prefs::STORAGE_KEY, &prefs)); + let stored = web_sys::window() + .and_then(|w| w.local_storage().ok().flatten()) + .map(|s| s.set_item(if self.launch.platform { "vm.cad.engine.prefs" } else { solidcraft_ui_egui::prefs::STORAGE_KEY }, &prefs)); if !matches!(stored, Some(Ok(()))) { log::warn!("settings: the browser's storage did not take them; they are saved again later"); self.prefs_writer = crate::PrefsWriter::default(); @@ -353,6 +377,13 @@ mod web { /// Files from the computer, writes to store, messages and the autosave. fn files_tick(&mut self, ctx: &egui::Context) { + if self.launch.platform { + files::flush(&self.files); + for (text, error) in self.files.messages.borrow_mut().drain(..) { + self.app.set_status(text, error); + } + return; + } if !self.launch.persists() { return; } @@ -731,6 +762,9 @@ mod web { if !installed && solidcraft_ui_egui::fonts::needs_cjk_font(effective) { log::warn!("script font unavailable; showing English for this session"); } + if let Some(platform) = &mut self.platform { + platform.font_failed = !installed; + } self.font.finished(installed, &mut self.app.preferences.language); self.apply_fonts(ctx); ctx.request_repaint(); @@ -776,7 +810,11 @@ mod web { self.font_fetch_kind = Some(kind); let slot = self.font_result.clone(); let ctx = ctx.clone(); - let path = path.to_owned(); + let path = if self.launch.platform && kind == "zh" { + crate::platform::config("chineseFont").unwrap_or_else(|| path.to_owned()) + } else { + path.to_owned() + }; wasm_bindgen_futures::spawn_local(async move { let res = fetch_font_bytes(&path).await.map(|bytes| (path, bytes)); *slot.borrow_mut() = Some(res); @@ -789,10 +827,22 @@ mod web { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { // First: a language another tab chose fetches its font this frame. self.load_other_tabs_prefs(); + if self.platform.as_ref().is_some_and(|platform| platform.retry_font) { + self.font = Default::default(); + if let Some(platform) = &mut self.platform { + platform.retry_font = false; + } + } self.tick_font(ctx); + let font_ready = self.script_font_ready(); + if let Some(platform) = &mut self.platform { + platform.tick(&mut self.app, font_ready); + } self.app.logic(ctx); self.api.poll(); - self.space_mouse.logic(&mut self.app, ctx); + if !self.app.platform.is_locked() { + self.space_mouse.logic(&mut self.app, ctx); + } self.files_tick(ctx); UNSAVED.with(|u| u.set(solidcraft_ui_egui::documents::any_dirty(&self.app))); DESIGN_SHOWN.with(|d| d.set(solidcraft_ui_egui::toolbar::design_shown(&self.app))); @@ -802,6 +852,7 @@ mod web { if let Some(delay) = self.wheel_gestures.update(raw, now) { ctx.request_repaint_after(delay); } + crate::agent::take_attachment_drops(&mut self.app, ctx, raw); if self.launch.persists() { let theme = solidcraft_ui_egui::prefs::theme_drop_target(&self.app, ctx); files::take_drops(&self.files, raw, theme); @@ -811,6 +862,10 @@ mod web { // Before the app's own hook, which adds the control channel's events. self.space_mouse.raw_input_hook(ctx, self.app.preferences.space_mouse_enabled, raw); self.app.raw_input_hook(raw); + if self.app.platform.is_locked() { + raw.events.clear(); + raw.dropped_files.clear(); + } } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.linked.tick(&mut self.app, ui.ctx()); @@ -889,12 +944,19 @@ mod web { eframe::WebLogger::init(log::LevelFilter::Info).ok(); wasm_bindgen_futures::spawn_local(async { let Some(window) = web_sys::window() else { return }; - let launch = crate::Launch::parse(&query()); + let mut launch = crate::Launch::parse(&query()); + launch.platform = crate::platform::enabled(); + if launch.platform { + launch.open = None; + launch.embed = false; + } if launch.persists() { ask_before_unload(&window); } leave_tab_switching_to_browser(&window); - keep_ctrl_w_for_the_design(&window); + if !launch.platform { + keep_ctrl_w_for_the_design(&window); + } let Some(document) = window.document() else { return }; let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::().ok()) else { log::error!("missing "); @@ -908,7 +970,7 @@ mod web { } let result = eframe::WebRunner::new() .start( - canvas, + canvas.clone(), options, Box::new(move |cc| { solidcraft_ui_egui::fonts::setup_fonts(&cc.egui_ctx); @@ -918,7 +980,17 @@ mod web { } let (panel, opener, saver, shown) = (files.clone(), files.clone(), files.clone(), files.clone()); let (restorable, restorer) = (files.clone(), files.clone()); - let services = if launch.embed { Services::default() } else { Services { + let services = if launch.platform { + let upload = files.clone(); + Services { + pick_open: Some(Box::new(move |exts: &[&str]| Box::pin(files::pick_upload(&upload, exts)))), + pick_save: Some(Box::new(move |name: &str, _exts: &[&str]| Box::pin(std::future::ready(Some(format!("{}{name}", files::DOWNLOADS)))))), + download_design: Some(Box::new(files::download)), + browser_agent: Some(crate::agent::services()), + secrets: Some(crate::agent_storage::secrets()), + ..Default::default() + } + } else if launch.embed { Services::default() } else { Services { // Open shows the browser's open dialog for a design where it has one // (the file keeps its handle, so Save writes back to it), else the // browser's files window. A command that reads another kind of file @@ -962,6 +1034,15 @@ mod web { let (sender, receiver) = std::sync::mpsc::channel(); let mut app = SolveApp::new(Session::default(), services).with_control(receiver); app.embedded = launch.embed; + if launch.platform { + if let Some(prefs) = window.local_storage().ok().flatten().and_then(|storage| storage.get_item("vm.cad.engine.prefs").ok().flatten()) { app.load_prefs(&crate::agent_storage::shared_preferences(&prefs)); } + else { + app.preferences.theme = "vibemake-dark".into(); + app.preferences.viewport_theme = solidcraft_ui_egui::theme::ViewportTheme::Dark; + } + app.preferences.language = crate::platform::config("locale").filter(|locale| locale == "en").unwrap_or_else(|| "zh".into()); + app.enable_vibemake(); + } // Listening before reading: settings another tab writes from now on are // newer than those read here. let other_tab_prefs = PrefsInbox::default(); @@ -975,14 +1056,14 @@ mod web { // eframe's web painter has no stencil buffer. app.set_wgpu(rs, DEPTH_BITS, 0, 1); } - if launch.open.is_none() && crate::query_flag(&query(), "sample") { + if !launch.platform && launch.open.is_none() && crate::query_flag(&query(), "sample") { if let Err(e) = app.session.run_script(&solidcraft_engine::sample::script()) { app.set_status(format!("sample: {e}"), true); } app.session.doc_mut().name = "Sample Plate".into(); app.session.mark_saved(); } - if launch.open.is_none() && !crate::query_flag(&query(), "sample") { + if !launch.platform && launch.open.is_none() && !crate::query_flag(&query(), "sample") { // The empty design takes Units of new designs (#1205). The sample // part is built in millimetres and is left that way. solidcraft_ui_egui::prefs::apply_new_design(&mut app); @@ -990,6 +1071,7 @@ mod web { app.home.show(rev); } let api = Api::install(sender, cc.egui_ctx.clone()).map_err(|e| format!("SolidCraft browser API: {e:?}"))?; + let platform = if launch.platform { Some(crate::platform::Bridge::install(cc.egui_ctx.clone()).map_err(|e| format!("VibeMake bridge: {e:?}"))?) } else { None }; let font_language = app.preferences.language.clone(); let linked = crate::linked::Download::start(launch.open.as_deref(), &cc.egui_ctx); let full_url = window.location().href().ok().and_then(|value| url::Url::parse(&value).ok()).map(|url| launch.full_app_url(url)); @@ -999,6 +1081,7 @@ mod web { linked, full_url, api, + platform, files, autosaved_at: f64::NEG_INFINITY, autosaved: None, @@ -1020,6 +1103,9 @@ mod web { }), ) .await; + if result.is_ok() { + prepare_text_agent(&canvas); + } if let Some(el) = document.get_element_by_id(LOADING_ID) { match result { Ok(()) => dismiss_loading(el), @@ -1176,4 +1262,54 @@ mod tests { assert_eq!(settings_written(Some(key), None), None, "removed settings leave this tab's"); assert_eq!(settings_written(None, None), None, "clearing all storage leaves this tab's settings"); } + #[test] + fn browser_mcp_replay_executes_only_missing_requests_and_checks_expectations() { + use crate::agent_tools::{ControlReply, Replay}; + use serde_json::json; + let args = json!({"command":"solid.box","params":{"length":2,"width":3,"height":4},"expect":{"bodies":1,"volume_mm3":24}}); + let mut replies = Vec::new(); + let mut sent = Vec::new(); + for result in [json!({"feature":"Box"}), json!({"body_count":1,"total":{"volume_mm3":24},"bodies":[]})] { + let mut planner = Replay { results: &replies, at: 0, next: None }; + solidcraft_mcp::call_tool(&mut planner, "execute", &args); + let (method, params) = planner.next.expect("one missing request"); + sent.push((method.clone(), params.clone())); + replies.push(ControlReply { method, params, result: Ok(result) }); + } + let mut planner = Replay { results: &replies, at: 0, next: None }; + let answer = solidcraft_mcp::call_tool(&mut planner, "execute", &args); + assert!(planner.next.is_none()); + assert_ne!(answer["isError"], true); + assert_eq!(sent.len(), 2); + assert_eq!(sent[0].1["command"], "solid.box"); + assert_eq!(sent[1].1["command"], "inspect.measure"); + // A changed argument cannot reuse a reply from a different operation. + let mut planner = Replay { results: &replies, at: 0, next: None }; + let answer = solidcraft_mcp::call_tool(&mut planner, "execute", &json!({"command":"solid.sphere","params":{}})); + assert_eq!(answer["isError"], true); + assert!(planner.next.is_none()); + } + + #[test] + fn browser_mcp_batch_failure_does_not_resend_steps_or_hide_rollback() { + use crate::agent_tools::{ControlReply, Replay}; + use serde_json::json; + let args = json!({"commands":[{"command":"solid.box","params":{}},{"command":"solid.box","params":{}}]}); + let mut planner = Replay { results: &[], at: 0, next: None }; + solidcraft_mcp::call_tool(&mut planner, "batch", &args); + let (method, params) = planner.next.expect("native batch dispatch"); + assert_eq!(method, "engine.batch"); + let replies = [ControlReply { + method, + params, + result: Ok( + json!({"ok":false,"applied":[],"failed":{"index":1,"command":"solid.box","error":"invalid dimensions"},"rolled_back":true,"undone":1}), + ), + }]; + let mut planner = Replay { results: &replies, at: 0, next: None }; + let answer = solidcraft_mcp::call_tool(&mut planner, "batch", &args); + assert_eq!(answer["isError"], true); + assert!(answer.to_string().contains("rolled_back")); + assert!(planner.next.is_none(), "no fallback can apply the steps a second time"); + } } diff --git a/apps/solidcraft-web/src/platform.rs b/apps/solidcraft-web/src/platform.rs new file mode 100644 index 000000000..6b60b04ef --- /dev/null +++ b/apps/solidcraft-web/src/platform.rs @@ -0,0 +1,442 @@ +//! Binary product bridge. The host owns identity/network; Rust owns documents and save baselines. +use std::{cell::RefCell, collections::BTreeMap, io::Cursor, rc::Rc, sync::atomic::Ordering}; + +use js_sys::{Function, Object, Promise, Reflect, Uint8Array}; +use serde_json::{Value, json}; +use solidcraft_engine::{SaveBaseline, Session, io}; +use solidcraft_ui_egui::SolveApp; +use wasm_bindgen::{JsCast as _, JsValue, closure::Closure}; + +const MAX_PENDING: usize = 32; +const MAX_SNAPSHOTS: usize = 4; +const MAX_BYTES: usize = 256 * 1024 * 1024; + +struct Request { + method: &'static str, + args: JsValue, + resolve: Function, + reject: Function, + context_generation: u64, +} +struct Snapshot { + binding: String, + baseline: SaveBaseline, +} + +#[derive(Clone)] +pub struct Bridge { + requests: Rc>>, + listeners: Rc>>, + next_listener: Rc>, + context_generation: Rc>, + ctx: egui::Context, + binding: Option, + project: Option, + snapshots: Rc>>, + last_state: String, + pub font_failed: bool, + pub retry_font: bool, +} + +pub fn config(name: &str) -> Option { + let window = web_sys::window()?; + let config = Reflect::get(&window, &"__VIBEMAKE_CAD__".into()).ok()?; + Reflect::get(&config, &name.into()).ok()?.as_string() +} + +pub fn enabled() -> bool { + config("buildId").is_some() +} + +fn field(args: &JsValue, name: &str) -> JsValue { + Reflect::get(args, &name.into()).unwrap_or(JsValue::UNDEFINED) +} +fn text(args: &JsValue, name: &str) -> Option { + field(args, name).as_string() +} +fn js(value: Value) -> Result { + js_sys::JSON::parse(&value.to_string()) +} +fn value(value: JsValue) -> Result, JsValue> { + if value.is_null() || value.is_undefined() { + return Ok(None); + } + let encoded = js_sys::JSON::stringify(&value)?.as_string().ok_or_else(|| error("BAD_AGENT_CAPABILITIES"))?; + serde_json::from_str(&encoded).map(Some).map_err(|_| error("BAD_AGENT_CAPABILITIES")) +} +fn error(code: &str) -> JsValue { + let error: JsValue = js_sys::Error::new(code).into(); + let _ = Reflect::set(&error, &"code".into(), &code.into()); + error +} +fn uuid() -> Result { + let window = web_sys::window().ok_or_else(|| error("NO_WINDOW"))?; + let crypto = Reflect::get(&window, &"crypto".into())?; + let function: Function = Reflect::get(&crypto, &"randomUUID".into())?.dyn_into()?; + function.call0(&crypto)?.as_string().ok_or_else(|| error("UUID_UNAVAILABLE")) +} +fn bytes(value: JsValue) -> Result, JsValue> { + if !value.is_instance_of::() { + return Err(error("BINARY_REQUIRED")); + } + let array = Uint8Array::new(&value); + if array.length() == 0 || array.length() as usize > MAX_BYTES { + return Err(error("SOURCE_TOO_LARGE")); + } + Ok(array.to_vec()) +} +fn open(bytes: &[u8]) -> Result { + let doc = io::read_design(bytes).map_err(|_| error("BAD_DESIGN"))?; + // Cloud projects must be self-contained. Never resolve local/network design links. + if !doc.links.is_empty() { + return Err(error("BAD_DESIGN")); + } + let saved = if io::is_design_container(bytes) { + io::DesignContainerReader::new(Cursor::new(bytes)).ok().and_then(|mut reader| reader.geometry()) + } else { + None + }; + Ok(Session::opened(doc, saved.as_ref())) +} + +impl Bridge { + pub fn install(ctx: egui::Context) -> Result { + let bridge = Self { + requests: Rc::default(), + listeners: Rc::default(), + next_listener: Rc::new(std::cell::Cell::new(0)), + context_generation: Rc::default(), + ctx, + binding: None, + project: None, + snapshots: Rc::default(), + last_state: String::new(), + font_failed: false, + retry_font: false, + }; + let object = Object::new(); + for method in [ + "ready", + "openProject", + "validateProject", + "createSnapshot", + "acknowledgeSave", + "releaseSnapshot", + "getState", + "setLocale", + "setInteractionLocked", + "setAgentContext", + "releaseProject", + "requestSave", + "showMenu", + ] { + let queue = bridge.clone(); + let function = Closure:: Promise>::new(move |args| queue.request(method, args)).into_js_value(); + Reflect::set(&object, &method.into(), &function)?; + } + let subscribed = bridge.clone(); + let subscribe = Closure:: JsValue>::new(move |callback: Function| { + let id = subscribed.next_listener.get().wrapping_add(1); + subscribed.next_listener.set(id); + if subscribed.listeners.borrow().len() < MAX_PENDING { + subscribed.listeners.borrow_mut().insert(id, callback); + } + let listeners = subscribed.listeners.clone(); + Closure::::new(move || { + listeners.borrow_mut().remove(&id); + }) + .into_js_value() + }) + .into_js_value(); + Reflect::set(&object, &"subscribe".into(), &subscribe)?; + let window = web_sys::window().ok_or_else(|| error("NO_WINDOW"))?; + Reflect::set(&window, &"vibemakeCad".into(), &object)?; + Ok(bridge) + } + + fn request(&self, method: &'static str, args: JsValue) -> Promise { + if self.requests.borrow().len() >= MAX_PENDING { + return Promise::reject(&error("TOO_MANY_REQUESTS")); + } + if method == "setAgentContext" { + self.context_generation.set(self.context_generation.get().wrapping_add(1)); + } + let context_generation = self.context_generation.get(); + Promise::new(&mut |resolve, reject| { + self.requests.borrow_mut().push(Request { method, args: args.clone(), resolve, reject, context_generation }); + self.ctx.request_repaint(); + }) + } + + pub fn tick(&mut self, app: &mut SolveApp, font_ready: bool) { + let requests = std::mem::take(&mut *self.requests.borrow_mut()); + for request in requests { + if request.method == "setAgentContext" && request.context_generation != self.context_generation.get() { + let _ = request.reject.call1(&JsValue::UNDEFINED, &error("STALE_AGENT_CONTEXT")); + continue; + } + if request.method == "ready" && !font_ready && !self.font_failed { + self.requests.borrow_mut().push(request); + continue; + } + if request.method == "setAgentContext" + && !request.args.is_null() + && !request.args.is_undefined() + && text(&request.args, "binding").as_deref() == self.binding.as_deref() + && text(&request.args, "projectId").as_deref() == self.project.as_deref() + && text(&request.args, "sessionId").is_some_and(|session| !session.is_empty() && session.len() <= 128) + && text(&request.args, "documentSessionCode").is_some_and(|code| !code.is_empty() && code.len() <= 64) + && let Some(owner) = text(&request.args, "userId").filter(|owner| !owner.is_empty() && owner.len() <= 256) + && (app.platform.enabled || crate::agent_storage::activate(&owner)) + { + let context = json!({"userId":owner,"projectId":text(&request.args,"projectId"),"binding":text(&request.args,"binding"),"sessionId":text(&request.args,"sessionId"),"documentSessionCode":text(&request.args,"documentSessionCode")}).to_string(); + if app.platform.agent_context.as_ref().is_some_and(|old| old != &context) { + self.clear_agent(app); + } + } + let result = self.handle(app, request.method, request.args); + match result { + Ok(value) => { + let _ = request.resolve.call1(&JsValue::UNDEFINED, &value); + } + Err(error) => { + let _ = request.reject.call1(&JsValue::UNDEFINED, &error); + } + } + } + if !app.platform.enabled && app.platform.agent_context.is_some() { + crate::agent_storage::save_profile(app); + } + let intent = app.platform.intent.take(); + let mut state = self.state(app); + if let Some(intent) = intent { + state["intent"] = json!(intent); + } + let encoded = state.to_string(); + if encoded != self.last_state { + self.last_state = encoded; + if let Ok(state) = js(state) { + let callbacks: Vec<_> = self.listeners.borrow().values().cloned().collect(); + for callback in callbacks { + let _ = callback.call1(&JsValue::UNDEFINED, &state); + } + } + } + // Browser subscriptions and Promise responses still settle while the canvas is inert. + self.ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + + fn state(&self, app: &SolveApp) -> Value { + json!({"assistant":solidcraft_ui_egui::agent_chat::platform_status(app), "binding": self.binding, "dirty": app.session.is_dirty(), "canUndo": !app.session.undo.is_empty(), "canRedo": !app.session.redo.is_empty(), "revision": format!("{}:{:?}", app.session.revision, app.session.visibility), + "fontFailed": self.font_failed, "pendingMoves": !app.session.pending_moves.is_empty() || app.tree.occurrence_move.is_some(), "snapshotAvailable": app.platform_snapshot_available(), "locked": app.platform.is_locked(), "locale": app.preferences.language}) + } + + fn handle(&mut self, app: &mut SolveApp, method: &str, args: JsValue) -> Result { + match method { + "ready" => { + if self.font_failed { + Err(error("FONT_UNAVAILABLE")) + } else { + js( + json!({"bridgeVersion":1, "engineBuild":config("buildId"), "capabilities":{"assistant":app.services.browser_agent.is_some(), "projectCover":true}}), + ) + } + } + "setLocale" => { + let language = args.as_string().ok_or_else(|| error("BAD_LOCALE"))?; + if !matches!(language.as_str(), "zh" | "en") { + return Err(error("BAD_LOCALE")); + } + app.preferences.language = language; + self.font_failed = false; + self.retry_font = true; + Ok(JsValue::UNDEFINED) + } + "setInteractionLocked" => { + let locked = args.as_bool().ok_or_else(|| error("BAD_LOCK"))?; + if locked { + solidcraft_ui_egui::agent_chat::cancel(app); + } + app.platform.locked.store(locked, Ordering::Relaxed); + Ok(JsValue::UNDEFINED) + } + "setAgentContext" => { + if args.is_null() || args.is_undefined() { + self.clear_agent(app); + return Ok(JsValue::UNDEFINED); + } + let owner = + text(&args, "userId").filter(|value| !value.is_empty() && value.len() <= 256).ok_or_else(|| error("BAD_AGENT_CONTEXT"))?; + let project = text(&args, "projectId").ok_or_else(|| error("BAD_AGENT_CONTEXT"))?; + let binding = text(&args, "binding").ok_or_else(|| error("BAD_AGENT_CONTEXT"))?; + let session = + text(&args, "sessionId").filter(|value| !value.is_empty() && value.len() <= 128).ok_or_else(|| error("BAD_AGENT_CONTEXT"))?; + let document_session = text(&args, "documentSessionCode") + .filter(|value| { + !value.is_empty() && value.len() <= 64 && value.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') + }) + .ok_or_else(|| error("BAD_AGENT_CONTEXT"))?; + if self.binding.as_deref() != Some(&binding) || self.project.as_deref() != Some(&project) { + return Err(error("STALE_BINDING")); + } + let capabilities = value(field(&args, "aiCapabilities"))?; + let context = + json!({"userId":owner,"projectId":project,"binding":binding,"sessionId":session,"documentSessionCode":document_session}) + .to_string(); + let changed = app.platform.agent_context.as_deref() != Some(&context) + || app.platform.agent_capabilities != capabilities + || app.platform.agent_document_session_code.as_deref() != Some(&document_session); + if changed { + if !app.platform.enabled { + crate::agent_storage::save_profile(app); + crate::agent_storage::load_profile(app, &owner); + } + solidcraft_ui_egui::agent_chat::disconnect(app); + app.agent_chat = Default::default(); + app.platform.agent_context = Some(context); + app.platform.agent_capabilities = capabilities; + app.platform.agent_document_session_code = Some(document_session); + app.platform.agent_project_code = Some(project); + solidcraft_ui_egui::agent_chat::begin(app); + } + Ok(JsValue::UNDEFINED) + } + "validateProject" => { + let _ = open(&bytes(args)?)?; + Ok(JsValue::TRUE) + } + "openProject" => { + let project = text(&args, "projectId").ok_or_else(|| error("BAD_PROJECT"))?; + if project.len() > 128 || project.is_empty() { + return Err(error("BAD_PROJECT")); + } + let incoming = field(&args, "bytes"); + let mut session = if incoming.is_null() || incoming.is_undefined() { Session::default() } else { open(&bytes(incoming)?)? }; + if field(&args, "saved").as_bool() != Some(true) { + session.mark_unsaved(); + } + session.set_command_check(app.session.command_check()); + let binding = uuid()?; + // Adoption is the only mutation, after every validation above succeeds. + self.clear_agent(app); + app.adopt_platform_project(session); + self.binding = Some(binding.clone()); + self.project = Some(project); + self.snapshots.borrow_mut().clear(); + js(json!({"binding":binding})) + } + "releaseProject" => { + self.clear_agent(app); + let mut session = Session::default(); + session.set_command_check(app.session.command_check()); + app.adopt_platform_project(session); + app.platform.locked.store(true, Ordering::Relaxed); + self.binding = None; + self.project = None; + self.snapshots.borrow_mut().clear(); + Ok(JsValue::UNDEFINED) + } + "requestSave" => { + solidcraft_ui_egui::toolbar::save(app); + Ok(JsValue::UNDEFINED) + } + "showMenu" => { + let menu = args.as_string().ok_or_else(|| error("BAD_MENU"))?; + if app.platform.is_locked() { + return Err(error("HOST_INTERACTION_LOCKED")); + } + if menu == "assistant" { + if !solidcraft_ui_egui::agent_chat::shown(app) { + return Err(error("ASSISTANT_UNAVAILABLE")); + } + solidcraft_ui_egui::agent_chat::toggle(app); + return Ok(JsValue::UNDEFINED); + } + app.platform.menu_request = Some(match menu.as_str() { + "file" => "file", + "preferences" => "preferences", + "help" => "help", + _ => return Err(error("BAD_MENU")), + }); + Ok(JsValue::UNDEFINED) + } + "getState" => js(self.state(app)), + "createSnapshot" => { + let binding = self.binding.clone().ok_or_else(|| error("NO_DOCUMENT"))?; + if !app.platform_snapshot_available() { + return Err(error("SNAPSHOT_BUSY")); + } + if self.snapshots.borrow().len() >= MAX_SNAPSHOTS { + return Err(error("SNAPSHOT_LIMIT")); + } + let id = text(&args, "snapshotId").map(Ok).unwrap_or_else(uuid)?; + if id.len() != 36 || self.snapshots.borrow().contains_key(&id) { + return Err(error("BAD_SNAPSHOT_ID")); + } + let baseline = app.session.save_baseline(); + let bytes = + app.session.design_container(io::DesignCompression::Fast, false, true).map_err(|e| error(&format!("SNAPSHOT_FAILED: {e}")))?; + if bytes.len() > MAX_BYTES { + return Err(error("SOURCE_TOO_LARGE")); + } + let result = js( + json!({"binding":binding, "snapshotId":id, "revision":format!("{}:{:?}", app.session.revision, app.session.visibility), + "containerFormat":"solidcraft-container/1", "documentFormat":solidcraft_engine::doc::format::format_string(solidcraft_engine::doc::format::FORMAT), + "engineBuild":config("buildId"), "byteLength":bytes.len()}), + )?; + Reflect::set(&result, &"bytes".into(), &Uint8Array::from(bytes.as_slice()))?; + // Capture before returning to JavaScript: cover and native bytes share this + // exact baseline, even if the person continues modelling during the upload. + if field(&args, "includeCover").as_bool() == Some(true) { + let cover = match app.session.design_cover() { + Some(bytes) => { + let cover = js(json!({"mimeType":"image/png", "width":640, "height":400}))?; + Reflect::set(&cover, &"bytes".into(), &Uint8Array::from(bytes.as_slice()))?; + cover + } + None => JsValue::NULL, + }; + Reflect::set(&result, &"cover".into(), &cover)?; + } + self.snapshots.borrow_mut().insert(id, Snapshot { binding, baseline }); + Ok(result) + } + "acknowledgeSave" => { + let binding = text(&args, "binding").ok_or_else(|| error("STALE_BINDING"))?; + if self.binding.as_deref() != Some(&binding) { + return Err(error("STALE_BINDING")); + } + let id = text(&args, "snapshotId").ok_or_else(|| error("BAD_SNAPSHOT_ID"))?; + let snapshots = self.snapshots.borrow(); + let snapshot = snapshots.get(&id).ok_or_else(|| error("SNAPSHOT_RELEASED"))?; + if snapshot.binding != binding { + return Err(error("STALE_BINDING")); + } + app.session.acknowledge_baseline(&snapshot.baseline); + Ok(JsValue::UNDEFINED) + } + "releaseSnapshot" => { + if let Some(id) = args.as_string() { + self.snapshots.borrow_mut().remove(&id); + } + Ok(JsValue::UNDEFINED) + } + _ => Err(error("UNKNOWN_METHOD")), + } + } + + fn clear_agent(&mut self, app: &mut SolveApp) { + if !app.platform.enabled { + crate::agent_storage::save_profile(app); + } + solidcraft_ui_egui::agent_chat::disconnect(app); + app.agent_chat = Default::default(); + app.platform.agent_context = None; + app.platform.agent_capabilities = None; + app.platform.agent_document_session_code = None; + app.platform.agent_project_code = None; + if !app.platform.enabled { + crate::agent_storage::clear_context(); + } + } +} diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index b5bf7e7ab..60cea93ef 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -549,6 +549,7 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services easyprint_upload: Some(std::sync::Arc::new(easyprint_upload)), browser_files: None, agent_http: Some(std::sync::Arc::new(agent_http)), + browser_agent: None, secrets: Some(std::sync::Arc::new(Keychain)), show_in_folder: Some(Box::new(|path| { let folder = std::path::Path::new(path).parent().unwrap_or_else(|| std::path::Path::new(".")); diff --git a/assets/locales/pending/vibemake-agent-recovery.json b/assets/locales/pending/vibemake-agent-recovery.json new file mode 100644 index 000000000..0f39e8929 --- /dev/null +++ b/assets/locales/pending/vibemake-agent-recovery.json @@ -0,0 +1,27 @@ +{ + "de": { + "vm.agent.call_limit": "Das Aufruflimit dieser Nachricht ist erreicht. Abgeschlossene Änderungen bleiben erhalten. Senden Sie eine neue Nachricht, um fortzufahren.", + "vm.agent.change_limit": "Diese Aktion überschreitet das Limit von {limit} CAD-Änderungen pro Nachricht. Abgeschlossene Änderungen bleiben erhalten. Senden Sie eine neue Nachricht, um fortzufahren.", + "vm.agent.intro": "Beschreiben Sie das Modell, das Sie erstellen oder ändern möchten, oder lassen Sie den Assistenten den aktuellen Entwurf prüfen." + }, + "en": { + "vm.agent.call_limit": "The model call limit for this message has been reached. Completed changes are kept. Send a new message to continue.", + "vm.agent.change_limit": "This operation exceeds the budget of {limit} CAD changes per message. Completed changes are kept. Send a new message to continue.", + "vm.agent.intro": "Describe the model you want to create or change, or ask the assistant to inspect the current design." + }, + "ja": { + "vm.agent.call_limit": "このメッセージのモデル呼び出し回数の上限に達しました。完了した変更は保持されます。新しいメッセージを送信して続行してください。", + "vm.agent.change_limit": "この操作は、1メッセージあたり{limit}回のCAD変更の上限を超えます。完了した変更は保持されます。新しいメッセージを送信して続行してください。", + "vm.agent.intro": "作成・変更したいモデルを説明するか、現在の設計の確認をアシスタントに依頼してください。" + }, + "ko": { + "vm.agent.call_limit": "이 메시지의 모델 호출 횟수 제한에 도달했습니다. 완료된 변경은 유지됩니다. 새 메시지를 보내 계속하세요.", + "vm.agent.change_limit": "이 작업은 메시지당 CAD 변경 {limit}회 제한을 초과합니다. 완료된 변경은 유지됩니다. 새 메시지를 보내 계속하세요.", + "vm.agent.intro": "만들거나 수정할 모델을 설명하거나 현재 설계를 확인해 달라고 요청하세요." + }, + "zh": { + "vm.agent.call_limit": "本轮已达到模型调用次数上限,已完成的修改会保留。请发送新消息继续。", + "vm.agent.change_limit": "当前操作超出本轮 {limit} 次 CAD 修改的剩余额度,已完成的修改会保留。请发送新消息继续。", + "vm.agent.intro": "描述你想创建或修改的模型,或让助手检查当前设计。" + } +} diff --git a/assets/locales/pending/vibemake-agent-request-limits.json b/assets/locales/pending/vibemake-agent-request-limits.json new file mode 100644 index 000000000..d40ebd578 --- /dev/null +++ b/assets/locales/pending/vibemake-agent-request-limits.json @@ -0,0 +1,8 @@ +{ + "en": { + "vm.agent.request_limits": "The CAD AI request exceeds the backend limits: {limits}. This turn cannot be trimmed further. Continue in a new message or start a new chat." + }, + "zh": { + "vm.agent.request_limits": "CAD AI 请求超过后端限制:{limits}。当前轮次已无法继续裁剪,请发送新消息继续,或开启新聊天。" + } +} diff --git a/assets/locales/pending/vibemake-assistant-parity.json b/assets/locales/pending/vibemake-assistant-parity.json new file mode 100644 index 000000000..1fa9d9b84 --- /dev/null +++ b/assets/locales/pending/vibemake-assistant-parity.json @@ -0,0 +1,37 @@ +{ + "de": { + "vm.agent.clipboard_error": "Der Browser kann das Bild nicht aus der Zwischenablage lesen. Erlauben Sie den Zugriff oder verwenden Sie „Datei hinzufügen“.", + "vm.agent.native_controls": "Geometrieberechnungen im Hintergrund, der Steuerkanal und externe App-Verbindungen benötigen zusätzliche Web-Laufzeitunterstützung und sind derzeit nicht verfügbar.", + "vm.agent.preset_note": "Originale Dienstvorlagen. Browserzugriff, CORS und Modellprotokoll müssen weiterhin unterstützt werden; lokale Dienste laufen auf Ihrem Computer.", + "vm.agent.runtime_required": "Lokale Agenten und Befehle benötigen einen Assistentendienst oder eine lokale Verbindung. Dieser Browser unterstützt derzeit Modell-APIs.", + "vm.agent.window_unavailable": "Separate Systemfenster sind in diesem Web-Editor nicht verfügbar. Docken Sie den Assistenten links oder rechts an." + }, + "en": { + "vm.agent.clipboard_error": "The browser cannot read a picture from the clipboard. Allow clipboard access or use Add a file.", + "vm.agent.native_controls": "Background geometry, the control channel and external app connections need additional Web runtime support and are currently unavailable.", + "vm.agent.preset_note": "Original service presets. Browser access, CORS and the model protocol must still be supported; local services run on your computer.", + "vm.agent.runtime_required": "Local agents and commands need an assistant service or local connector. This browser currently supports model APIs.", + "vm.agent.window_unavailable": "Independent system windows are unavailable in this web editor. Dock the assistant on the left or right." + }, + "ja": { + "vm.agent.clipboard_error": "ブラウザーでクリップボードの画像を読み取れません。アクセスを許可するか、「ファイルを追加」を使用してください。", + "vm.agent.native_controls": "バックグラウンドの形状計算、制御チャネル、外部アプリ接続には追加のWeb実行環境への対応が必要なため、現在は使用できません。", + "vm.agent.preset_note": "オリジナルのサービス設定です。ブラウザーアクセス、CORS、モデルのプロトコルへの対応が必要です。ローカルサービスはお使いのコンピューターで動作します。", + "vm.agent.runtime_required": "ローカルエージェントとコマンドには、アシスタントサービスまたはローカル接続プログラムが必要です。このブラウザーは現在、モデルAPIに対応しています。", + "vm.agent.window_unavailable": "このWebエディターでは独立したシステムウィンドウを使用できません。アシスタントを左または右に配置してください。" + }, + "ko": { + "vm.agent.clipboard_error": "브라우저가 클립보드의 그림을 읽을 수 없습니다. 클립보드 접근을 허용하거나 파일 추가를 사용하세요.", + "vm.agent.native_controls": "백그라운드 형상 계산, 제어 채널 및 외부 앱 연결에는 추가 웹 실행 환경 지원이 필요하며 현재 사용할 수 없습니다.", + "vm.agent.preset_note": "원본 서비스 설정입니다. 브라우저 접근, CORS 및 모델 프로토콜 지원이 필요합니다. 로컬 서비스는 사용자 컴퓨터에서 실행됩니다.", + "vm.agent.runtime_required": "로컬 에이전트와 명령에는 어시스턴트 서비스 또는 로컬 연결 프로그램이 필요합니다. 현재 이 브라우저는 모델 API를 지원합니다.", + "vm.agent.window_unavailable": "이 웹 편집기에서는 독립 시스템 창을 사용할 수 없습니다. 어시스턴트를 왼쪽 또는 오른쪽에 배치하세요." + }, + "zh": { + "vm.agent.clipboard_error": "浏览器无法读取剪贴板图片。请允许剪贴板访问,或使用“添加文件”上传图片。", + "vm.agent.native_controls": "后台几何计算、控制通道和外部应用连接需要额外的 Web 运行适配,当前不可用。", + "vm.agent.preset_note": "沿用原版服务预设。服务仍需支持浏览器访问、CORS 和所选模型协议;本地服务运行在你的电脑上。", + "vm.agent.runtime_required": "本机智能体和命令需要助手服务或本地连接程序。当前浏览器支持模型 API 连接。", + "vm.agent.window_unavailable": "此 Web 编辑器暂不支持独立系统窗口。可将助手停靠在左侧或右侧。" + } +} diff --git a/assets/locales/pending/vibemake-assistant.json b/assets/locales/pending/vibemake-assistant.json new file mode 100644 index 000000000..d38d05ab9 --- /dev/null +++ b/assets/locales/pending/vibemake-assistant.json @@ -0,0 +1,182 @@ +{ + "ar": { + "vm.agent.api_only": "يدعم مساعد الويب اتصالات واجهة API للنماذج فقط.", + "vm.agent.auth_error": "رفضت خدمة النموذج مفتاح API ‏(401/403). لا يتأثر تسجيل الدخول إلى VibeMake.", + "vm.agent.bad_key": "مفتاح API طويل جدًا.", + "vm.agent.bad_response": "أعادت خدمة النموذج استجابة غير صالحة أو تتجاوز الحجم المسموح.", + "vm.agent.chat_only": "محادثة فقط: لم يجتز هذا النموذج اختبار استدعاء الأدوات ولا يمكنه تعديل CAD.", + "vm.agent.clear_keys": "حذف جميع المفاتيح المحفوظة لهذا الحساب", + "vm.agent.connection_note": "يتصل هذا المتصفح مباشرة بخدمة النموذج التي تحددها. يجب أن تسمح الخدمة بوصول المتصفح وطلبات CORS. لا تُرسل رموز VibeMake أو ملفات Cookie.", + "vm.agent.connection_test": "التحقق من استجابة النموذج واستدعاء أداة لا يغير التصميم", + "vm.agent.delete_key": "حذف مفتاح API", + "vm.agent.file_error": "أرفق صورة بحجم لا يتجاوز 40 MiB أو نص UTF-8 بحجم لا يتجاوز 256 KiB. استورد ملفات CAD من قائمة الملف.", + "vm.agent.key_hint": "اختياري؛ يبقى في ذاكرة الصفحة افتراضيًا", + "vm.agent.key_note": "دون تحديد الخيار، يبقى المفتاح في ذاكرة هذه الصفحة فقط. عند تحديده، يُحفظ في هذا المتصفح لهذا الحساب. هذا ليس مخزن مفاتيح النظام؛ قد تصل إليه نصوص من المصدر نفسه.", + "vm.agent.key_present": "يوجد مفتاح في هذه الصفحة. اترك الحقل فارغًا للاحتفاظ به للخدمة نفسها.", + "vm.agent.loading_keys": "جارٍ تحميل بيانات اعتماد المساعد. أعد المحاولة لاحقًا.", + "vm.agent.model_changed": "تغير النموذج. أُوقفت جولة الذكاء الاصطناعي والعمليات التي تنتظر الموافقة. تابع باستخدام أحدث نموذج.", + "vm.agent.network_error": "تعذر الاتصال بخدمة النموذج. تحقق من العنوان وأذونات المتصفح وCORS والوصول إلى الشبكة المحلية وحالة الخدمة.", + "vm.agent.no_history": "تُحفظ المحادثات خلال جلسة هذه الصفحة فقط.", + "vm.agent.notice": "تبقى تعديلات الذكاء الاصطناعي محلية حتى تحفظها يدويًا في السحابة. راجع النتيجة قبل الحفظ.", + "vm.agent.permission_note": "حتى إذن «الكل» لا يتيح فتح مشاريع أخرى أو الحفظ في السحابة أو استخدام ميزات سطح المكتب.", + "vm.agent.rate_limit": "وصلت خدمة النموذج إلى حد معدل الطلبات (429). أعد المحاولة لاحقًا.", + "vm.agent.remember_key": "تذكر في هذا المتصفح", + "vm.agent.service_error": "رفضت خدمة النموذج الطلب. تحقق من عنوان الخدمة والنموذج والبروتوكول.", + "vm.agent.setup": "أضف واجهة API للنموذج من التفضيلات ← المساعد. أدخل عنوان خدمتك والنموذج ومفتاح API إن لزم.", + "vm.agent.storage_failed": "تعذر حفظ مفتاح المساعد. لا يزال المفتاح في ذاكرة الصفحة قابلًا للاستخدام. تحقق من أذونات التخزين في المتصفح.", + "vm.agent.test_ok": "تم التحقق من طلب النموذج واستدعاء الأدوات في المتصفح.", + "vm.agent.timeout": "انتهت مهلة طلب خدمة النموذج. أعد المحاولة أو عدّل مهلة الطلب.", + "vm.agent.tool_failed": "فشلت أداة CAD أو رُفضت. أُوقفت الخطوات التالية وتبقى التعديلات المكتملة.", + "vm.agent.tool_unavailable": "هذه الأداة غير متاحة في مساعد الويب." + }, + "en": { + "vm.agent.api_only": "Web assistant supports API connections only.", + "vm.agent.auth_error": "The model service rejected the API key (401/403). VibeMake sign-in is unchanged.", + "vm.agent.bad_key": "The API key is too long.", + "vm.agent.bad_response": "The model service returned an invalid or oversized response.", + "vm.agent.chat_only": "Chat only: this model has not passed tool calling and cannot modify CAD.", + "vm.agent.clear_keys": "Remove all remembered keys for this account", + "vm.agent.connection_note": "Connect directly from this browser to your own model service. Browser access and CORS must be allowed by that service. No VibeMake token or cookies are sent.", + "vm.agent.connection_test": "Verify a model response and a harmless tool call", + "vm.agent.delete_key": "Delete API key", + "vm.agent.file_error": "Attach an image (up to 40 MiB) or a UTF-8 text file (up to 256 KiB). Import CAD through the File menu.", + "vm.agent.key_hint": "optional; page memory by default", + "vm.agent.key_note": "Unchecked: key stays in this page memory. Checked: saved in this browser for this account. This is not an OS keychain; scripts on this site may access it.", + "vm.agent.key_present": "A key is available in this page. Leave blank to keep it for the same service.", + "vm.agent.loading_keys": "Assistant credentials are still loading. Please try again.", + "vm.agent.model_changed": "The model changed. This AI turn and its pending approvals were stopped. Continue using the latest model.", + "vm.agent.network_error": "Cannot reach the model service. Check its URL, browser/CORS permissions, local network access and service status.", + "vm.agent.no_history": "Conversations last for this page only.", + "vm.agent.notice": "AI changes stay local until you manually save to cloud. Review the result before saving.", + "vm.agent.permission_note": "Even All cannot open other projects, save to cloud or access desktop features.", + "vm.agent.rate_limit": "The model service is rate limited (429). Please try later.", + "vm.agent.remember_key": "Remember in this browser", + "vm.agent.service_error": "The model service rejected the request. Check the endpoint, model and protocol.", + "vm.agent.setup": "Add a model API in Preferences → Assistant. Use your own endpoint, model and optional API key.", + "vm.agent.storage_failed": "Assistant credentials could not be remembered. The current memory key remains usable. Check browser storage permissions.", + "vm.agent.test_ok": "Browser model request and tool calling verified.", + "vm.agent.timeout": "The model service request timed out. Retry or adjust its request timeout.", + "vm.agent.tool_failed": "A CAD tool failed or was denied. Further steps were stopped; completed changes remain.", + "vm.agent.tool_unavailable": "This tool is unavailable in the Web assistant." + }, + "he": { + "vm.agent.api_only": "עוזר הדפדפן תומך רק בחיבורי API למודלים.", + "vm.agent.auth_error": "שירות המודל דחה את מפתח ה־API ‏(401/403). הכניסה ל־VibeMake לא השתנתה.", + "vm.agent.bad_key": "מפתח ה־API ארוך מדי.", + "vm.agent.bad_response": "שירות המודל החזיר תשובה לא תקינה או גדולה מהמותר.", + "vm.agent.chat_only": "שיחה בלבד: המודל לא עבר אימות קריאה לכלים ואינו יכול לשנות CAD.", + "vm.agent.clear_keys": "מחיקת כל המפתחות שנשמרו לחשבון זה", + "vm.agent.connection_note": "הדפדפן מתחבר ישירות לשירות המודל שלך. השירות חייב לאפשר גישה מהדפדפן ו־CORS. אסימוני VibeMake וקובצי Cookie אינם נשלחים.", + "vm.agent.connection_test": "אימות תשובת המודל וקריאה לכלי שאינו משנה את התכנון", + "vm.agent.delete_key": "מחיקת מפתח API", + "vm.agent.file_error": "אפשר לצרף תמונה עד 40 MiB או טקסט UTF-8 עד 256 KiB. יש לייבא CAD דרך תפריט הקובץ.", + "vm.agent.key_hint": "אופציונלי; בזיכרון הדף כברירת מחדל", + "vm.agent.key_note": "ללא סימון, המפתח נשמר רק בזיכרון דף זה. בסימון, הוא נשמר בדפדפן לחשבון זה. זה אינו מחזיק המפתחות של מערכת ההפעלה; סקריפטים מאותו מקור עשויים לגשת אליו.", + "vm.agent.key_present": "יש מפתח בדף זה. השאר ריק כדי לשמור אותו עבור אותו שירות.", + "vm.agent.loading_keys": "פרטי הגישה לעוזר עדיין נטענים. נסה שוב מאוחר יותר.", + "vm.agent.model_changed": "המודל השתנה. סבב ה־AI והפעולות הממתינות לאישור נעצרו. המשך עם המודל העדכני.", + "vm.agent.network_error": "לא ניתן להתחבר לשירות המודל. בדוק כתובת, הרשאות דפדפן ו־CORS, גישה לרשת המקומית ומצב השירות.", + "vm.agent.no_history": "השיחות נשמרות רק בהפעלה הנוכחית של הדף.", + "vm.agent.notice": "שינויי AI נשארים מקומיים עד לשמירה ידנית בענן. בדוק את התוצאה לפני השמירה.", + "vm.agent.permission_note": "גם הרשאת הכול אינה מאפשרת פתיחת פרויקטים אחרים, שמירה בענן או שימוש בתכונות שולחן עבודה.", + "vm.agent.rate_limit": "שירות המודל הגביל את קצב הבקשות (429). נסה שוב מאוחר יותר.", + "vm.agent.remember_key": "זכור בדפדפן זה", + "vm.agent.service_error": "שירות המודל דחה את הבקשה. בדוק את הכתובת, המודל והפרוטוקול.", + "vm.agent.setup": "הוסף API של מודל דרך העדפות ← עוזר. הזן כתובת שירות, מודל ומפתח API לפי הצורך.", + "vm.agent.storage_failed": "לא ניתן לשמור את מפתח העוזר. המפתח שבזיכרון הדף עדיין זמין. בדוק את הרשאות האחסון בדפדפן.", + "vm.agent.test_ok": "בקשת מודל וקריאה לכלים אומתו בדפדפן.", + "vm.agent.timeout": "הזמן הקצוב לבקשת שירות המודל הסתיים. נסה שוב או שנה את הזמן הקצוב.", + "vm.agent.tool_failed": "כלי CAD נכשל או נדחה. השלבים הבאים נעצרו; השינויים שכבר בוצעו נשמרים.", + "vm.agent.tool_unavailable": "כלי זה אינו זמין בעוזר הדפדפן." + }, + "ja": { + "vm.agent.api_only": "Web アシスタントはモデル API 接続のみをサポートします。", + "vm.agent.auth_error": "モデルサービスが API キーを拒否しました(401/403)。VibeMake のログインには影響しません。", + "vm.agent.bad_key": "API キーが長すぎます。", + "vm.agent.bad_response": "モデルサービスの応答が無効、またはサイズ制限を超えています。", + "vm.agent.chat_only": "チャットのみ:このモデルはツール呼び出しの検証に合格していないため、CAD を変更できません。", + "vm.agent.clear_keys": "このアカウントで記憶したすべてのキーを削除", + "vm.agent.connection_note": "このブラウザーから指定したモデルサービスに直接接続します。サービス側でブラウザーと CORS を許可してください。VibeMake のトークンや Cookie は送信しません。", + "vm.agent.connection_test": "モデルの応答と変更を行わないツール呼び出しを検証", + "vm.agent.delete_key": "API キーを削除", + "vm.agent.file_error": "画像(40 MiB 以下)または UTF-8 テキスト(256 KiB 以下)を添付できます。CAD はファイルメニューからインポートしてください。", + "vm.agent.key_hint": "任意。既定ではページのメモリーにのみ保持", + "vm.agent.key_note": "未選択の場合、キーはこのページのメモリー内のみ保持します。選択すると、このアカウント用にブラウザーに保存します。OS のキーチェーンではなく、同一サイトのスクリプトからアクセスされる可能性があります。", + "vm.agent.key_present": "このページにはキーがあります。同じサービスで保持するには空欄のままにしてください。", + "vm.agent.loading_keys": "アシスタントの認証情報を読み込み中です。しばらくしてから再試行してください。", + "vm.agent.model_changed": "モデルが変更されました。この AI ターンと未承認の操作を停止しました。最新のモデルで続行してください。", + "vm.agent.network_error": "モデルサービスに接続できません。URL、ブラウザーと CORS の権限、ローカルネットワークへのアクセス、サービスの状態を確認してください。", + "vm.agent.no_history": "会話は現在のページでのみ保持されます。", + "vm.agent.notice": "AI の変更は手動でクラウドに保存するまでローカルに保持されます。保存前に結果を確認してください。", + "vm.agent.permission_note": "「すべて」でも他のプロジェクトを開く、クラウドに保存する、デスクトップ専用機能を使うことはできません。", + "vm.agent.rate_limit": "モデルサービスのレート制限に達しました(429)。後で再試行してください。", + "vm.agent.remember_key": "このブラウザーに記憶する", + "vm.agent.service_error": "モデルサービスがリクエストを拒否しました。接続先、モデルとプロトコルを確認してください。", + "vm.agent.setup": "「環境設定 → アシスタント」で独自のモデル API を追加し、接続先、モデルと必要に応じて API キーを指定してください。", + "vm.agent.storage_failed": "アシスタントのキーを記憶できませんでした。現在のメモリー内のキーは使用できます。ブラウザーの保存権限を確認してください。", + "vm.agent.test_ok": "ブラウザーでのモデルリクエストとツール呼び出しを検証しました。", + "vm.agent.timeout": "モデルサービスのリクエストがタイムアウトしました。再試行するか、タイムアウトを調整してください。", + "vm.agent.tool_failed": "CAD ツールが失敗したか拒否されました。後続の操作は停止しました。完了した変更は保持されます。", + "vm.agent.tool_unavailable": "このツールは Web アシスタントで使用できません。" + }, + "vi": { + "vm.agent.api_only": "Trợ lý Web chỉ hỗ trợ kết nối API mô hình.", + "vm.agent.auth_error": "Dịch vụ mô hình từ chối khóa API (401/403). Đăng nhập VibeMake không bị ảnh hưởng.", + "vm.agent.bad_key": "Khóa API quá dài.", + "vm.agent.bad_response": "Dịch vụ mô hình trả về phản hồi không hợp lệ hoặc quá lớn.", + "vm.agent.chat_only": "Chỉ trò chuyện: mô hình này chưa vượt qua kiểm tra gọi công cụ và không thể sửa CAD.", + "vm.agent.clear_keys": "Xóa mọi khóa đã ghi nhớ cho tài khoản này", + "vm.agent.connection_note": "Trình duyệt kết nối trực tiếp tới dịch vụ mô hình của bạn. Dịch vụ phải cho phép truy cập từ trình duyệt và CORS. Không gửi token hay Cookie của VibeMake.", + "vm.agent.connection_test": "Kiểm tra phản hồi mô hình và lời gọi công cụ không thay đổi thiết kế", + "vm.agent.delete_key": "Xóa khóa API", + "vm.agent.file_error": "Đính kèm ảnh (tối đa 40 MiB) hoặc văn bản UTF-8 (tối đa 256 KiB). Nhập CAD qua trình đơn Tệp.", + "vm.agent.key_hint": "không bắt buộc; mặc định chỉ lưu trong bộ nhớ trang", + "vm.agent.key_note": "Không chọn: khóa chỉ nằm trong bộ nhớ trang này. Chọn: lưu trong trình duyệt cho tài khoản này. Đây không phải kho khóa hệ điều hành; mã cùng nguồn có thể truy cập.", + "vm.agent.key_present": "Trang này đã có khóa. Để trống để giữ khóa cho cùng dịch vụ.", + "vm.agent.loading_keys": "Đang tải thông tin xác thực trợ lý. Vui lòng thử lại sau.", + "vm.agent.model_changed": "Mô hình đã thay đổi. Lượt AI và các thao tác chờ duyệt đã dừng. Hãy tiếp tục với mô hình mới nhất.", + "vm.agent.network_error": "Không thể kết nối dịch vụ mô hình. Kiểm tra URL, quyền trình duyệt/CORS, truy cập mạng cục bộ và trạng thái dịch vụ.", + "vm.agent.no_history": "Hội thoại chỉ được giữ trong phiên trang hiện tại.", + "vm.agent.notice": "Thay đổi của AI chỉ nằm cục bộ cho đến khi bạn lưu lên đám mây. Kiểm tra kết quả trước khi lưu.", + "vm.agent.permission_note": "Ngay cả quyền Tất cả cũng không cho phép mở dự án khác, lưu lên đám mây hay dùng tính năng máy tính để bàn.", + "vm.agent.rate_limit": "Dịch vụ mô hình bị giới hạn tần suất (429). Vui lòng thử lại sau.", + "vm.agent.remember_key": "Ghi nhớ trong trình duyệt này", + "vm.agent.service_error": "Dịch vụ mô hình từ chối yêu cầu. Kiểm tra địa chỉ, mô hình và giao thức.", + "vm.agent.setup": "Thêm API mô hình trong Tùy chọn → Trợ lý. Nhập địa chỉ dịch vụ, mô hình và khóa API nếu cần.", + "vm.agent.storage_failed": "Không thể ghi nhớ khóa trợ lý. Khóa trong bộ nhớ hiện tại vẫn dùng được. Kiểm tra quyền lưu trữ của trình duyệt.", + "vm.agent.test_ok": "Đã xác minh yêu cầu mô hình và gọi công cụ trong trình duyệt.", + "vm.agent.timeout": "Yêu cầu dịch vụ mô hình hết thời gian chờ. Thử lại hoặc điều chỉnh thời gian chờ.", + "vm.agent.tool_failed": "Công cụ CAD thất bại hoặc bị từ chối. Các bước tiếp theo đã dừng; thay đổi đã hoàn tất được giữ lại.", + "vm.agent.tool_unavailable": "Công cụ này không khả dụng trong trợ lý Web." + }, + "zh": { + "vm.agent.api_only": "网页版助手仅支持模型 API 连接。", + "vm.agent.auth_error": "模型服务拒绝了 API Key(401/403),不影响 VibeMake 登录。", + "vm.agent.bad_key": "API Key 长度超出限制。", + "vm.agent.bad_response": "模型服务返回的响应格式错误或超出大小限制。", + "vm.agent.chat_only": "仅支持聊天:此模型未通过工具调用验证,不能修改 CAD。", + "vm.agent.clear_keys": "清除本账号全部已记住的密钥", + "vm.agent.connection_note": "浏览器直接连接你配置的模型服务;服务需允许浏览器访问及跨域请求。不发送 VibeMake 登录令牌或 Cookie。", + "vm.agent.connection_test": "验证模型响应及无修改的工具调用", + "vm.agent.delete_key": "删除密钥", + "vm.agent.file_error": "请附加图片(不超过 40 MiB)或 UTF-8 文本(不超过 256 KiB)。CAD 文件请从文件菜单导入。", + "vm.agent.key_hint": "可选,默认仅保存在当前页面内存", + "vm.agent.key_note": "不勾选时密钥仅保留在当前页面内存;勾选后按账号保存到本浏览器。这不是系统钥匙串,同源脚本可能访问。", + "vm.agent.key_present": "当前页面已有密钥;相同服务可留空保留。", + "vm.agent.loading_keys": "助手凭据正在加载,请稍后重试。", + "vm.agent.model_changed": "模型已变化,本轮 AI 任务及待审批操作已停止,请基于最新模型继续。", + "vm.agent.network_error": "无法连接模型服务。请检查服务地址、浏览器或跨域权限、本机网络访问权限及服务状态。", + "vm.agent.no_history": "对话仅保留在当前页面会话。", + "vm.agent.notice": "AI 修改需手动保存到云端;保存前请检查结果。", + "vm.agent.permission_note": "即使选择“全部”,也不能打开其他项目、保存到云端或使用桌面专用功能。", + "vm.agent.rate_limit": "模型服务触发限流(429),请稍后重试。", + "vm.agent.remember_key": "在本浏览器记住", + "vm.agent.service_error": "模型服务拒绝了请求,请检查地址、模型名称及协议。", + "vm.agent.setup": "请在“首选项 → 助手”中添加模型 API,填写自己的服务地址、模型及可选 API Key。", + "vm.agent.storage_failed": "助手密钥未能记住;当前页面内存中的密钥仍可使用。请检查浏览器存储权限。", + "vm.agent.test_ok": "浏览器模型请求与工具调用验证通过。", + "vm.agent.timeout": "模型服务请求超时,请重试或调整请求超时设置。", + "vm.agent.tool_failed": "CAD 工具执行失败或被拒绝,后续步骤已停止,已完成的修改会保留。", + "vm.agent.tool_unavailable": "网页版助手不提供此工具。" + } +} diff --git a/assets/locales/pending/vibemake-platform-agent.json b/assets/locales/pending/vibemake-platform-agent.json new file mode 100644 index 000000000..da018cc63 --- /dev/null +++ b/assets/locales/pending/vibemake-platform-agent.json @@ -0,0 +1,22 @@ +{ + "de": { + "vm.agent.platform_mode": "Plattform-Agent · {model}", + "vm.agent.platform_unavailable": "Der CAD-Agent ist derzeit nicht verfügbar oder verwendet ein inkompatibles Protokoll." + }, + "en": { + "vm.agent.platform_mode": "Platform Agent · {model}", + "vm.agent.platform_unavailable": "The CAD Agent is unavailable or uses an incompatible protocol." + }, + "ja": { + "vm.agent.platform_mode": "プラットフォームエージェント · {model}", + "vm.agent.platform_unavailable": "CAD エージェントは現在利用できないか、互換性のないプロトコルを使用しています。" + }, + "ko": { + "vm.agent.platform_mode": "플랫폼 에이전트 · {model}", + "vm.agent.platform_unavailable": "CAD 에이전트를 사용할 수 없거나 호환되지 않는 프로토콜을 사용하고 있습니다." + }, + "zh": { + "vm.agent.platform_mode": "平台智能体 · {model}", + "vm.agent.platform_unavailable": "CAD 智能体当前不可用,或使用了不兼容的协议。" + } +} diff --git a/assets/locales/pending/vibemake-platform.json b/assets/locales/pending/vibemake-platform.json new file mode 100644 index 000000000..38f3c8fba --- /dev/null +++ b/assets/locales/pending/vibemake-platform.json @@ -0,0 +1,32 @@ +{ + "ar": { + "vibemake.about": "حول VibeMake CAD", + "vibemake.description": "تصميم CAD بارامتري ومواد وتصْيير عبر الإنترنت. مبني على محرك SolidCraft مفتوح المصدر (MIT OR Apache-2.0).", + "vibemake.host_managed": "نفّذ هذه العملية من خلال إدارة المشاريع في VibeMake CAD." + }, + "en": { + "vibemake.about": "About VibeMake CAD", + "vibemake.description": "Online parametric CAD, materials and rendering. Based on the open-source SolidCraft engine (MIT OR Apache-2.0).", + "vibemake.host_managed": "This document is managed by VibeMake CAD. Use the project controls." + }, + "he": { + "vibemake.about": "אודות VibeMake CAD", + "vibemake.description": "CAD פרמטרי, חומרים ורינדור מקוונים. מבוסס על מנוע SolidCraft בקוד פתוח (MIT OR Apache-2.0).", + "vibemake.host_managed": "יש לבצע פעולה זו דרך ניהול הפרויקטים של VibeMake CAD." + }, + "ja": { + "vibemake.about": "VibeMake CAD について", + "vibemake.description": "オンラインのパラメトリック CAD、マテリアルとレンダリング。オープンソースの SolidCraft エンジン(MIT OR Apache-2.0)を基盤としています。", + "vibemake.host_managed": "この操作は VibeMake CAD のプロジェクト管理で行ってください。" + }, + "vi": { + "vibemake.about": "Giới thiệu VibeMake CAD", + "vibemake.description": "CAD tham số, vật liệu và kết xuất trực tuyến. Dựa trên bộ máy SolidCraft mã nguồn mở (MIT OR Apache-2.0).", + "vibemake.host_managed": "Thực hiện thao tác này qua chức năng quản lý dự án của VibeMake CAD." + }, + "zh": { + "vibemake.about": "关于 VibeMake CAD", + "vibemake.description": "在线参数化 CAD、材质与渲染。基于 SolidCraft 开源引擎(MIT OR Apache-2.0)。", + "vibemake.host_managed": "此工程由 VibeMake CAD 管理,请使用项目操作。" + } +} diff --git a/assets/styles/ui/themes/vibemake-dark.json b/assets/styles/ui/themes/vibemake-dark.json new file mode 100644 index 000000000..cacecf153 --- /dev/null +++ b/assets/styles/ui/themes/vibemake-dark.json @@ -0,0 +1,37 @@ +{ + "order": 260, + "provenance": "VibeMake product palette supplied by the project owner; original integration", + "base": "dark", + "format": "solidcraft-theme/1", + "name": "VibeMake Dark", + "colors": { + "accent": "#c8ff3e", + "accent_soft": "#252f12", + "app_bar": "#0b0c0f", + "app_bar_hover": "#15181c", + "app_bar_hover_button": "#20251b", + "app_bar_separator": "#262b32", + "app_bar_tab_active": "#15181c", + "app_bar_text": "#f3f4f6", + "border": "#262b32", + "control_border": "#30363e", + "control_fill": "#15181c", + "dialog_bg": "#0f1114", + "dialog_body": "#0f1114", + "dialog_border": "#262b32", + "dialog_footer": "#0b0c0f", + "dialog_label": "#c9cdd3", + "dialog_rule": "#262b32", + "field": "#07080a", + "form_dim": "#8f96a0", + "form_ink": "#f3f4f6", + "form_primary": "#c8ff3e", + "form_primary_fill": "#c8ff3e", + "hover": "#20251b", + "icon": "#c9cdd3", + "on_accent": "#0d1203", + "panel": "#0f1114", + "text": "#f3f4f6", + "text_dim": "#8f96a0" + } +} diff --git a/attribution/pending/vibemake-platform.md b/attribution/pending/vibemake-platform.md new file mode 100644 index 000000000..3ed0bafe9 --- /dev/null +++ b/attribution/pending/vibemake-platform.md @@ -0,0 +1,4 @@ +| File | Author | Source | Licence | +| --- | --- | --- | --- | +| assets/styles/ui/themes/vibemake-dark.json | VibeMake integration contributors | Project owner supplied VibeMake palette; original theme | MIT OR Apache-2.0 | +| assets/locales/pending/vibemake-platform.json | VibeMake integration contributors | Original translations | MIT OR Apache-2.0 | diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 2f36c7b61..a460637c6 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -657,6 +657,12 @@ impl Session { self.design_container_at(self.path.as_deref(), compression, preview, cache) } + /// A bounded 640 × 400 isometric project cover from warm display meshes. No evaluation, + /// camera mutation or save acknowledgement; unavailable pictures leave the old cover intact. + pub fn design_cover(&self) -> Option> { + thumbnail::cover(self) + } + fn design_container_at( &self, path: Option<&str>, diff --git a/crates/engine/src/cmd/file_thumbnail.rs b/crates/engine/src/cmd/file_thumbnail.rs index c377b1c73..e3e0f2805 100644 --- a/crates/engine/src/cmd/file_thumbnail.rs +++ b/crates/engine/src/cmd/file_thumbnail.rs @@ -3,12 +3,25 @@ use crate::Session; use solidcraft_geom::Aabb3; use solidcraft_render::{Camera, Rgb, Scene, SceneMesh, StandardView}; +const THUMBNAIL_DISTANCE_SCALE: f64 = 0.7; + pub(super) fn saved(s: &Session) -> Option> { - let (scene, camera) = scene(s)?; let [width, height] = solidcraft_io::THUMBNAIL_SIZE; - // Drawn by the renderer the host installed (the GPU); none installed, no thumbnail. + picture(s, u32::try_from(width).ok()?, u32::try_from(height).ok()?, 1.) +} + +pub(super) fn cover(s: &Session) -> Option> { + // Keep the fit's safety margin for thin or tall models. Portable thumbnails retain + // their existing closer crop; project cards must show the whole model. + picture(s, 640, 400, 1. / THUMBNAIL_DISTANCE_SCALE) +} + +fn picture(s: &Session, width: u32, height: u32, distance_scale: f64) -> Option> { + let (scene, mut camera) = scene(s)?; + camera.distance *= distance_scale; + // Drawn by the renderer the host installed; none installed, no picture. let renderer = crate::capture::installed()?; - crate::capture::png_with(Some(&*renderer), &scene, &camera, u32::try_from(width).ok()?, u32::try_from(height).ok()?).ok().map(|p| p.bytes) + crate::capture::png_with(Some(&*renderer), &scene, &camera, width, height).ok().map(|p| p.bytes) } /// What the thumbnail shows: the shown bodies' warm display meshes in their colours, iso, fitted. @@ -45,7 +58,7 @@ fn scene(s: &Session) -> Option<(Scene, Camera)> { let mut camera = Camera::default(); camera.set_view(StandardView::Iso); camera.fit(&bounds); - camera.distance *= 0.7; + camera.distance *= THUMBNAIL_DISTANCE_SCALE; scene.radius = (bounds.diagonal() * 0.5).max(camera.half_height()).max(10.); scene.background = Some((crate::view::colors::BG_TOP, crate::view::colors::BG_BOTTOM)); Some((scene, camera)) @@ -55,6 +68,31 @@ fn scene(s: &Session) -> Option<(Scene, Camera)> { mod tests { use super::*; + #[test] + fn project_cover_is_fixed_size_and_leaves_the_design_and_save_baseline_alone() { + crate::capture::install_test_renderer(); + let mut session = Session::default(); + session.execute("solid.box", &serde_json::json!({"length":10,"width":20,"height":30})).unwrap(); + assert!(session.design_cover().is_none(), "capturing never evaluates a cold model"); + for body in &session.world_state().unwrap().bodies { + body.mesh(); + } + let document = session.doc.clone(); + let revision = session.revision; + let history = session.undo.len(); + let png = session.design_cover().unwrap(); + assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n"); + assert_eq!(&png[16..20], &640u32.to_be_bytes()); + assert_eq!(&png[20..24], &400u32.to_be_bytes()); + assert_eq!(session.design_cover(), Some(png)); + assert_eq!(session.doc, document); + assert_eq!(session.revision, revision); + assert_eq!(session.undo.len(), history); + assert!(session.is_dirty()); + assert_eq!(scene(&session).unwrap().1.yaw, StandardView::Iso.angles().0); + assert_eq!(scene(&session).unwrap().1.pitch, StandardView::Iso.angles().1); + } + #[test] fn portable_thumbnail_preserves_saved_visibility() { crate::capture::install_test_renderer(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 72bf80b26..121e2c4be 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -437,6 +437,13 @@ impl ComputedCommands { /// let the command run or `Err(reason)` to refuse it. pub type CommandCheck = Arc std::result::Result<(), String> + Send + Sync>; +/// Immutable native-save identity, independent of paths, names adopted by Save As and live edits. +#[derive(Clone)] +pub struct SaveBaseline { + document: Arc, + visibility: Visibility, +} + /// An editing session on one design. /// Starts an upload of a file (its name, its bytes) to EasyPrint and returns at once; the host /// reports how it went and opens the answer itself. `Err`: it couldn't start. @@ -848,6 +855,12 @@ impl Session { } } + /// Replace a cloud project while retaining user preferences, without cross-project checkpoints. + pub fn replace_host_design(&mut self, fresh: Session) { + self.replace_design(fresh); + self.checkpoints.clear(); + } + /// Become `fresh` (another design opened, recovered or started), keeping the settings that /// are the user's rather than the design's: `auto_project` is a preference (#680). /// Checkpoints survive too: a batch that failed after `file.new` or `doc.open` goes back @@ -940,6 +953,18 @@ impl Session { } } + /// Capture the committed design without declaring that an external save succeeded. + pub fn save_baseline(&self) -> SaveBaseline { + SaveBaseline { document: self.doc.clone(), visibility: self.visibility.clone() } + } + + /// Acknowledge exactly the captured design. Newer edits and metadata remain untouched. + pub fn acknowledge_baseline(&mut self, baseline: &SaveBaseline) { + self.forget_dirty_answer(); + self.saved = baseline.document.clone(); + self.saved_visibility = baseline.visibility.clone(); + } + pub fn mark_saved(&mut self) { self.forget_dirty_answer(); self.saved = self.doc.clone(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 402905920..6f26da987 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5162,3 +5162,41 @@ fn a_command_check_that_panics_refuses_the_command() { assert!(matches!(r, Err(EngineError::Internal(..))), "{r:?}"); assert!(s.doc.features.is_empty()); } + +#[test] +fn cloud_snapshot_acknowledges_only_captured_content_without_renaming_live_document() { + let mut session = Session::default(); + session.doc_mut().name = "S7".into(); + let captured = session.save_baseline(); + session.doc_mut().name = "S8".into(); + session.acknowledge_baseline(&captured); + assert!(session.is_dirty(), "newer edits are not in the acknowledged upload"); + assert_eq!(session.doc.name, "S8"); + assert!(session.path.is_none()); + session.doc_mut().name = "S7".into(); + assert!(!session.is_dirty(), "dirty compares native content, not revision counters"); +} + +#[test] +fn cloud_snapshot_serialization_does_not_mark_the_live_document_saved() { + let mut session = Session::default(); + session.doc_mut().name = "Unsaved".into(); + let baseline = session.save_baseline(); + let bytes = session.design_container(io::DesignCompression::Fast, false, false).unwrap(); + assert!(session.is_dirty()); + let reopened = io::read_design(&bytes).unwrap(); + assert_eq!(reopened.name, "Unsaved"); + session.acknowledge_baseline(&baseline); + assert!(!session.is_dirty()); +} + +#[test] +fn host_project_replacement_drops_checkpoints_from_the_previous_project() { + let mut session = Session::default(); + let previous = session.checkpoint(); + let mut cloud = Session::default(); + cloud.doc_mut().name = "Cloud project".into(); + session.replace_host_design(cloud); + assert!(session.restore_checkpoint(previous).is_err()); + assert_eq!(session.doc.name, "Cloud project"); +} diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs index 145b94579..19e793073 100644 --- a/crates/ui-egui/src/agent_chat/agents.rs +++ b/crates/ui-egui/src/agent_chat/agents.rs @@ -189,7 +189,7 @@ pub struct Entry { } impl Entry { - fn from_config(c: &AgentConfig) -> Entry { + pub fn from_config(c: &AgentConfig) -> Entry { Entry { id: c.id.clone(), name: if c.name.trim().is_empty() { c.id.clone() } else { c.name.clone() }, @@ -260,6 +260,9 @@ pub fn entries(app: &crate::SolveApp) -> Vec { entry.login = if *signed_in { "signed_in" } else { "signed_out" }; } } + if cfg!(target_arch = "wasm32") { + out.retain(|entry| entry.kind.is_api()); + } out } diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index e3bc37ecb..b6145021f 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -18,6 +18,7 @@ use serde_json::{Map, Value, json}; use super::MODEL_LIST_CAP; use super::acp::ModelInfo; use super::agents::Protocol; +use super::api_wire::*; use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus}; use super::process::{AgentProcess, FromAgent, ProcessHandle}; @@ -32,8 +33,6 @@ const MAX_HISTORY: usize = 240; /// otherwise each attached view makes every later request bigger, until the endpoint refuses it. const MAX_HISTORY_IMAGES: usize = 2; /// What an older view becomes in the history. -const DROPPED_VIEW_NOTE: &str = "[an earlier picture of the view, removed to keep the request small]"; -const DROPPED_THINKING_NOTE: &str = "[earlier reasoning, removed with older history]"; /// How long one tool call may take (it may wait for the user's Allow, declined after four /// minutes). It does not depend on the endpoint's request timeout: a tool call is SolidCraft's own /// work and the user's answer, never a wait for the model, so a longer request timeout does not @@ -41,9 +40,6 @@ const DROPPED_THINKING_NOTE: &str = "[earlier reasoning, removed with older hist const TOOL_TIMEOUT: Duration = Duration::from_secs(330); /// How often a waiting request or tool call looks at the cancel flag. const CANCEL_POLL: Duration = Duration::from_millis(40); -/// The Anthropic Messages API requires `max_tokens`; it caps one answer, which is plenty for a -/// chat reply and for the tool calls in it. -const ANTHROPIC_MAX_TOKENS: u64 = 8192; /// The API version sent to Anthropic-compatible endpoints. It is the version every such endpoint /// knows: DeepSeek ignores it, Qwen does not require it, and the Claude API still accepts it. const ANTHROPIC_VERSION: &str = "2023-06-01"; @@ -1177,38 +1173,14 @@ impl Worker { /// The request body in the endpoint's shape: the system note is a message for OpenAI and a /// top-level field for Anthropic. fn body(&self) -> Value { - match self.cfg.protocol { - Protocol::OpenAi => { - let mut messages = Vec::with_capacity(self.history.len() + 1); - messages.push(json!({"role": "system", "content": super::acp::SYSTEM_NOTE})); - messages.extend(self.history.iter().cloned()); - let mut body = json!({"model": self.cfg.model, "messages": messages}); - if let Some(effort) = self.reasoning_effort() { - // The user's choice goes out on every request, ahead of any `none` the - // endpoint once asked for (#10241). - body["reasoning_effort"] = json!(effort); - } - if !self.tools.is_empty() { - body["tools"] = Value::Array(self.tools.clone()); - if self.no_reasoning.get() && self.reasoning_effort().is_none() { - body["reasoning_effort"] = json!("none"); - } - } - body - } - Protocol::Anthropic => { - let mut body = json!({ - "model": self.cfg.model, - "max_tokens": ANTHROPIC_MAX_TOKENS, - "system": super::acp::SYSTEM_NOTE, - "messages": &self.history, - }); - if !self.tools.is_empty() { - body["tools"] = Value::Array(self.tools.clone()); - } - body - } - } + super::api_wire::request_body( + self.cfg.protocol, + &self.cfg.model, + &self.history, + &self.tools, + self.reasoning_effort().unwrap_or(""), + self.no_reasoning.get(), + ) } fn post_to(&self, url: String, headers: Vec<(String, String)>, body: &Value) -> Result<(u16, Value), String> { @@ -1311,297 +1283,6 @@ pub fn http_error(status: u16, body: &Value) -> String { ) } -/// A tool call's arguments as an object: the JSON text a model sends (or an object, for servers -/// that send one), or why they cannot be used. Missing or empty arguments are an empty object. -fn tool_arguments(raw: Option<&Value>) -> Result { - let text = match raw { - None | Some(Value::Null) => return Ok(json!({})), - Some(v @ Value::Object(_)) => return Ok(v.clone()), - Some(Value::String(s)) => s.trim(), - Some(_) => return Err("the tool arguments must be a JSON object".into()), - }; - if text.is_empty() { - return Ok(json!({})); - } - match serde_json::from_str::(text) { - Ok(v @ Value::Object(_)) => Ok(v), - Ok(_) => Err("the tool arguments must be a JSON object".into()), - Err(e) => Err(format!("the tool arguments were not valid JSON ({e}); send the call again with a JSON object")), - } -} - -/// The message for what the user typed (and the view, as the endpoint's own content blocks). -fn user_message(protocol: Protocol, parts: &[PromptPart]) -> Value { - let images = parts.iter().any(|p| matches!(p, PromptPart::Image { .. })); - if !images { - let text: Vec<&str> = parts.iter().filter_map(|p| if let PromptPart::Text(t) = p { Some(t.as_str()) } else { None }).collect(); - return json!({"role": "user", "content": text.join("\n")}); - } - let content: Vec = parts - .iter() - .filter_map(|p| match (protocol, p) { - (_, PromptPart::Text(t)) => Some(json!({"type": "text", "text": t})), - (Protocol::OpenAi, PromptPart::Image { mime, base64 }) => { - Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})) - } - (Protocol::Anthropic, PromptPart::Image { mime, base64 }) => { - Some(json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": base64}})) - } - // These endpoints take no documents (the chat doesn't send any); the message names the file. - (_, PromptPart::Document { .. }) => None, - }) - .collect(); - json!({"role": "user", "content": content}) -} - -/// Whether a history message starts a turn: a user message that is not only tool results. -fn starts_a_turn(message: &Value) -> bool { - message["role"] == "user" && !message["content"].as_array().is_some_and(|blocks| blocks.iter().any(|b| b["type"] == "tool_result")) -} - -/// One tool call the endpoint asked for. -#[derive(Debug)] -struct Call { - id: String, - name: String, - /// The arguments as an object, or why they cannot be used. - arguments: Result, -} - -/// An answer from the endpoint, in the protocol's shape. -#[derive(Debug)] -struct Reply { - /// Text to show: `(thought, text)` in the order it came. - text: Vec<(bool, String)>, - calls: Vec, - /// The assistant message to keep in the history, in the endpoint's own shape. Tool calls are - /// capped to the ones the loop answers, so every call kept here gets a result. - assistant: Value, - /// Why the answer stopped, as the turn-end reason the chat knows: empty for a normal end, - /// `max_tokens` for an answer cut off at its length limit, `refusal` when the model declined. - stop: &'static str, -} - -/// The turn-end reason for an Anthropic `stop_reason` or an OpenAI `finish_reason`. Anything -/// else, including a value a server made up, is a normal end. -fn stop_reason(reason: Option<&str>) -> &'static str { - match reason { - Some("max_tokens" | "length") => "max_tokens", - Some("refusal" | "content_filter") => "refusal", - _ => "", - } -} - -/// The answer in the endpoint's shape. -fn reply(protocol: Protocol, body: &Value) -> Reply { - match protocol { - Protocol::OpenAi => openai_reply(body), - Protocol::Anthropic => anthropic_reply(body), - } -} - -/// A `reasoning_details` array safe to replay: streaming-only `index` members -/// are dropped (gateways reject them), thinking content is kept. -fn sanitize_reasoning_details(details: Option<&Value>) -> Option { - let items = details?.as_array()?; - if items.iter().all(|d| matches!(d, Value::Object(_)) && d.get("index").is_none()) { - return Some(Value::Array(items.clone())); - } - let clean: Vec = items - .iter() - .filter_map(|d| { - let mut c = d.as_object()?.clone(); - c.remove("index"); - Some(Value::Object(c)) - }) - .collect(); - Some(Value::Array(clean)) -} - -fn openai_reply(body: &Value) -> Reply { - let message = body.pointer("/choices/0/message").cloned().unwrap_or(Value::Null); - let text = message.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()).map(|t| vec![(false, t.to_string())]).unwrap_or_default(); - let refused = message.get("refusal").and_then(Value::as_str).is_some_and(|r| !r.trim().is_empty()); - let stop = if refused { "refusal" } else { stop_reason(body.pointer("/choices/0/finish_reason").and_then(Value::as_str)) }; - // No more than the loop answers: every call kept here must get a `tool` message. A call cut - // off at the length limit is incomplete, so none is run or kept. - let raw: Vec = message - .get("tool_calls") - .and_then(Value::as_array) - .filter(|_| stop != "max_tokens") - .map(|a| a.iter().take(32).cloned().collect()) - .unwrap_or_default(); - let calls = raw - .iter() - .enumerate() - .map(|(i, c)| Call { - id: c.get("id").and_then(Value::as_str).map_or_else(|| format!("call-{i}"), str::to_string), - name: c.pointer("/function/name").and_then(Value::as_str).unwrap_or("").to_string(), - arguments: tool_arguments(c.pointer("/function/arguments")), - }) - .collect(); - let mut assistant = json!({"role": "assistant", "content": message.get("content").cloned().unwrap_or(Value::Null)}); - // Thinking models (Kimi K3 and kin) need their reasoning back on the next - // tool request: replay exactly what the endpoint sent, nothing invented. - for key in ["reasoning_content", "reasoning", "refusal"] { - if let Some(v) = message.get(key) - && !v.is_null() - { - assistant[key] = v.clone(); - } - } - if let Some(clean) = sanitize_reasoning_details(message.get("reasoning_details")) { - assistant["reasoning_details"] = clean; - } - if !raw.is_empty() { - assistant["tool_calls"] = Value::Array(raw); - } - Reply { text, calls, assistant, stop } -} - -fn anthropic_reply(body: &Value) -> Reply { - let content = body.get("content").cloned().unwrap_or(Value::Null); - let stop = stop_reason(body.get("stop_reason").and_then(Value::as_str)); - let mut text = Vec::new(); - let mut calls = Vec::new(); - let assistant = match &content { - Value::Array(blocks) => { - // Keep the answer as it came (thinking blocks and signatures included), but leave out - // tool calls beyond the loop's cap so every `tool_use` kept gets its `tool_result`. - let mut kept = Vec::new(); - for (i, block) in blocks.iter().take(128).enumerate() { - match block.get("type").and_then(Value::as_str) { - Some("text") => { - if let Some(t) = block.get("text").and_then(Value::as_str).filter(|t| !t.trim().is_empty()) { - text.push((false, t.to_string())); - } - kept.push(block.clone()); - } - Some("thinking") => { - let thought = block.get("thinking").or_else(|| block.get("text")); - if let Some(t) = thought.and_then(Value::as_str).filter(|t| !t.trim().is_empty()) { - text.push((true, t.to_string())); - } - kept.push(block.clone()); - } - // A call cut off at the length limit has incomplete input: not run, not kept. - Some("tool_use") if stop == "max_tokens" => {} - Some("tool_use") if calls.len() < 32 => { - calls.push(Call { - id: block.get("id").and_then(Value::as_str).map_or_else(|| format!("toolu-{i}"), str::to_string), - name: block.get("name").and_then(Value::as_str).unwrap_or("").to_string(), - arguments: match block.get("input") { - None | Some(Value::Null) => Ok(json!({})), - Some(v @ Value::Object(_)) => Ok(v.clone()), - Some(_) => Err("the tool arguments must be a JSON object".into()), - }, - }); - kept.push(block.clone()); - } - Some("tool_use") => {} - _ => kept.push(block.clone()), - } - } - json!({"role": "assistant", "content": kept}) - } - // An endpoint that answers with plain text instead of content blocks. - Value::String(s) => { - if !s.trim().is_empty() { - text.push((false, s.clone())); - } - json!({"role": "assistant", "content": content.clone()}) - } - _ => json!({"role": "assistant", "content": content.clone()}), - }; - Reply { text, calls, assistant, stop } -} - -/// Keeps the newest `keep` pictures of the view in the history and swaps every older one for a -/// short note, so the model still knows a view was shown. Text is never touched. Pictures come -/// as OpenAI `image_url` parts or Anthropic `image` blocks, depending on the endpoint. True when -/// a picture was swapped. -fn drop_old_views(history: &mut [Value], keep: usize) -> bool { - let mut seen = 0; - let mut dropped = false; - for msg in history.iter_mut().rev() { - let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; - for part in content.iter_mut().rev() { - if !matches!(part.get("type").and_then(Value::as_str), Some("image_url" | "image")) { - continue; - } - seen += 1; - if seen > keep { - *part = json!({"type": "text", "text": DROPPED_VIEW_NOTE}); - dropped = true; - } - } - } - dropped -} - -/// Takes Anthropic thinking blocks out of every earlier reply. Each one is signed against all -/// the conversation before it, so once a dropped view or trimmed message changes that, the API -/// refuses the whole request (#9417); leaving earlier thinking out is allowed. A reply that was -/// only thinking keeps a note, as the API takes no assistant message without content. -fn drop_thinking(history: &mut [Value]) { - for msg in history.iter_mut().filter(|m| m["role"] == "assistant") { - let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; - let before = content.len(); - content.retain(|b| !matches!(b.get("type").and_then(Value::as_str), Some("thinking" | "redacted_thinking"))); - if content.is_empty() && before > 0 { - content.push(json!({"type": "text", "text": DROPPED_THINKING_NOTE})); - } - } -} - -/// MCP `tools/list` as OpenAI function tools (the hidden ones left out). -pub fn openai_tools(list: &Value) -> Vec { - list.get("tools") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .take(128) - .filter_map(|t| { - let name = t.get("name")?.as_str()?; - if HIDDEN_TOOLS.contains(&name) { - return None; - } - let params = t.get("inputSchema").cloned().filter(Value::is_object).unwrap_or(json!({"type": "object", "properties": {}})); - Some(json!({"type": "function", "function": { - "name": name, - "description": t.get("description").and_then(Value::as_str).unwrap_or(""), - "parameters": params, - }})) - }) - .collect() - }) - .unwrap_or_default() -} - -/// MCP `tools/list` as Anthropic tools (the hidden ones left out). -pub fn anthropic_tools(list: &Value) -> Vec { - list.get("tools") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .take(128) - .filter_map(|t| { - let name = t.get("name")?.as_str()?; - if HIDDEN_TOOLS.contains(&name) { - return None; - } - let schema = t.get("inputSchema").cloned().filter(Value::is_object).unwrap_or(json!({"type": "object", "properties": {}})); - Some(json!({ - "name": name, - "description": t.get("description").and_then(Value::as_str).unwrap_or(""), - "input_schema": schema, - })) - }) - .collect() - }) - .unwrap_or_default() -} - /// The offered tools' names, whichever shape the endpoint takes. fn tool_names(list: &Value) -> Vec { list.get("tools") diff --git a/crates/ui-egui/src/agent_chat/api_wire.rs b/crates/ui-egui/src/agent_chat/api_wire.rs new file mode 100644 index 000000000..6649f4a67 --- /dev/null +++ b/crates/ui-egui/src/agent_chat/api_wire.rs @@ -0,0 +1,324 @@ +//! Protocol-only API messages, shared by desktop and browser transports. +use super::{agents::Protocol, backend::PromptPart}; +use serde_json::{Value, json}; +pub const ANTHROPIC_MAX_TOKENS: u64 = 8192; +const HIDDEN_TOOLS: &[&str] = &["crash_reports"]; +pub const DROPPED_VIEW_NOTE: &str = "[an earlier picture of the view, removed to keep the request small]"; +pub const DROPPED_THINKING_NOTE: &str = "[earlier reasoning, removed with older history]"; +/// A tool call's arguments as an object: the JSON text a model sends (or an object, for servers +/// that send one), or why they cannot be used. Missing or empty arguments are an empty object. +pub fn tool_arguments(raw: Option<&Value>) -> Result { + let text = match raw { + None | Some(Value::Null) => return Ok(json!({})), + Some(v @ Value::Object(_)) => return Ok(v.clone()), + Some(Value::String(s)) => s.trim(), + Some(_) => return Err("the tool arguments must be a JSON object".into()), + }; + if text.is_empty() { + return Ok(json!({})); + } + match serde_json::from_str::(text) { + Ok(v @ Value::Object(_)) => Ok(v), + Ok(_) => Err("the tool arguments must be a JSON object".into()), + Err(e) => Err(format!("the tool arguments were not valid JSON ({e}); send the call again with a JSON object")), + } +} + +/// The message for what the user typed (and the view, as the endpoint's own content blocks). +pub fn user_message(protocol: Protocol, parts: &[PromptPart]) -> Value { + let images = parts.iter().any(|p| matches!(p, PromptPart::Image { .. })); + if !images { + let text: Vec<&str> = parts.iter().filter_map(|p| if let PromptPart::Text(t) = p { Some(t.as_str()) } else { None }).collect(); + return json!({"role": "user", "content": text.join("\n")}); + } + let content: Vec = parts + .iter() + .filter_map(|p| match (protocol, p) { + (_, PromptPart::Text(t)) => Some(json!({"type": "text", "text": t})), + (Protocol::OpenAi, PromptPart::Image { mime, base64 }) => { + Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})) + } + (Protocol::Anthropic, PromptPart::Image { mime, base64 }) => { + Some(json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": base64}})) + } + // These endpoints take no documents (the chat doesn't send any); the message names the file. + (_, PromptPart::Document { .. }) => None, + }) + .collect(); + json!({"role": "user", "content": content}) +} + +/// Whether a history message starts a turn: a user message that is not only tool results. +pub fn starts_a_turn(message: &Value) -> bool { + message["role"] == "user" && !message["content"].as_array().is_some_and(|blocks| blocks.iter().any(|b| b["type"] == "tool_result")) +} + +/// One tool call the endpoint asked for. +#[derive(Debug)] +pub struct Call { + pub id: String, + pub name: String, + /// The arguments as an object, or why they cannot be used. + pub arguments: Result, +} + +/// An answer from the endpoint, in the protocol's shape. +#[derive(Debug)] +pub struct Reply { + /// Text to show: `(thought, text)` in the order it came. + pub text: Vec<(bool, String)>, + pub calls: Vec, + /// The assistant message to keep in the history, in the endpoint's own shape. Tool calls are + /// capped to the ones the loop answers, so every call kept here gets a result. + pub assistant: Value, + /// Why the answer stopped, as the turn-end reason the chat knows: empty for a normal end, + /// `max_tokens` for an answer cut off at its length limit, `refusal` when the model declined. + pub stop: &'static str, +} + +/// The turn-end reason for an Anthropic `stop_reason` or an OpenAI `finish_reason`. Anything +/// else, including a value a server made up, is a normal end. +pub fn stop_reason(reason: Option<&str>) -> &'static str { + match reason { + Some("max_tokens" | "length") => "max_tokens", + Some("refusal" | "content_filter") => "refusal", + _ => "", + } +} + +/// The answer in the endpoint's shape. +pub fn reply(protocol: Protocol, body: &Value) -> Reply { + match protocol { + Protocol::OpenAi => openai_reply(body), + Protocol::Anthropic => anthropic_reply(body), + } +} + +/// A `reasoning_details` array safe to replay: streaming-only `index` members +/// are dropped (gateways reject them), thinking content is kept. +pub fn sanitize_reasoning_details(details: Option<&Value>) -> Option { + let items = details?.as_array()?; + if items.iter().all(|d| matches!(d, Value::Object(_)) && d.get("index").is_none()) { + return Some(Value::Array(items.clone())); + } + let clean: Vec = items + .iter() + .filter_map(|d| { + let mut c = d.as_object()?.clone(); + c.remove("index"); + Some(Value::Object(c)) + }) + .collect(); + Some(Value::Array(clean)) +} + +pub fn openai_reply(body: &Value) -> Reply { + let message = body.pointer("/choices/0/message").cloned().unwrap_or(Value::Null); + let text = message.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()).map(|t| vec![(false, t.to_string())]).unwrap_or_default(); + let refused = message.get("refusal").and_then(Value::as_str).is_some_and(|r| !r.trim().is_empty()); + let stop = if refused { "refusal" } else { stop_reason(body.pointer("/choices/0/finish_reason").and_then(Value::as_str)) }; + // No more than the loop answers: every call kept here must get a `tool` message. A call cut + // off at the length limit is incomplete, so none is run or kept. + let raw: Vec = message + .get("tool_calls") + .and_then(Value::as_array) + .filter(|_| stop != "max_tokens") + .map(|a| a.iter().take(32).cloned().collect()) + .unwrap_or_default(); + let calls = raw + .iter() + .enumerate() + .map(|(i, c)| Call { + id: c.get("id").and_then(Value::as_str).map_or_else(|| format!("call-{i}"), str::to_string), + name: c.pointer("/function/name").and_then(Value::as_str).unwrap_or("").to_string(), + arguments: tool_arguments(c.pointer("/function/arguments")), + }) + .collect(); + let mut assistant = json!({"role": "assistant", "content": message.get("content").cloned().unwrap_or(Value::Null)}); + // Thinking models (Kimi K3 and kin) need their reasoning back on the next + // tool request: replay exactly what the endpoint sent, nothing invented. + for key in ["reasoning_content", "reasoning", "refusal"] { + if let Some(v) = message.get(key) + && !v.is_null() + { + assistant[key] = v.clone(); + } + } + if let Some(clean) = sanitize_reasoning_details(message.get("reasoning_details")) { + assistant["reasoning_details"] = clean; + } + if !raw.is_empty() { + assistant["tool_calls"] = Value::Array(raw); + } + Reply { text, calls, assistant, stop } +} + +pub fn anthropic_reply(body: &Value) -> Reply { + let content = body.get("content").cloned().unwrap_or(Value::Null); + let stop = stop_reason(body.get("stop_reason").and_then(Value::as_str)); + let mut text = Vec::new(); + let mut calls = Vec::new(); + let assistant = match &content { + Value::Array(blocks) => { + // Keep the answer as it came (thinking blocks and signatures included), but leave out + // tool calls beyond the loop's cap so every `tool_use` kept gets its `tool_result`. + let mut kept = Vec::new(); + for (i, block) in blocks.iter().take(128).enumerate() { + match block.get("type").and_then(Value::as_str) { + Some("text") => { + if let Some(t) = block.get("text").and_then(Value::as_str).filter(|t| !t.trim().is_empty()) { + text.push((false, t.to_string())); + } + kept.push(block.clone()); + } + Some("thinking") => { + let thought = block.get("thinking").or_else(|| block.get("text")); + if let Some(t) = thought.and_then(Value::as_str).filter(|t| !t.trim().is_empty()) { + text.push((true, t.to_string())); + } + kept.push(block.clone()); + } + // A call cut off at the length limit has incomplete input: not run, not kept. + Some("tool_use") if stop == "max_tokens" => {} + Some("tool_use") if calls.len() < 32 => { + calls.push(Call { + id: block.get("id").and_then(Value::as_str).map_or_else(|| format!("toolu-{i}"), str::to_string), + name: block.get("name").and_then(Value::as_str).unwrap_or("").to_string(), + arguments: match block.get("input") { + None | Some(Value::Null) => Ok(json!({})), + Some(v @ Value::Object(_)) => Ok(v.clone()), + Some(_) => Err("the tool arguments must be a JSON object".into()), + }, + }); + kept.push(block.clone()); + } + Some("tool_use") => {} + _ => kept.push(block.clone()), + } + } + json!({"role": "assistant", "content": kept}) + } + // An endpoint that answers with plain text instead of content blocks. + Value::String(s) => { + if !s.trim().is_empty() { + text.push((false, s.clone())); + } + json!({"role": "assistant", "content": content.clone()}) + } + _ => json!({"role": "assistant", "content": content.clone()}), + }; + Reply { text, calls, assistant, stop } +} + +/// Keeps the newest `keep` pictures of the view in the history and swaps every older one for a +/// short note, so the model still knows a view was shown. Text is never touched. Pictures come +/// as OpenAI `image_url` parts or Anthropic `image` blocks, depending on the endpoint. True when +/// a picture was swapped. +pub fn drop_old_views(history: &mut [Value], keep: usize) -> bool { + let mut seen = 0; + let mut dropped = false; + for msg in history.iter_mut().rev() { + let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; + for part in content.iter_mut().rev() { + if !matches!(part.get("type").and_then(Value::as_str), Some("image_url" | "image")) { + continue; + } + seen += 1; + if seen > keep { + *part = json!({"type": "text", "text": DROPPED_VIEW_NOTE}); + dropped = true; + } + } + } + dropped +} + +/// Takes Anthropic thinking blocks out of every earlier reply. Each one is signed against all +/// the conversation before it, so once a dropped view or trimmed message changes that, the API +/// refuses the whole request (#9417); leaving earlier thinking out is allowed. A reply that was +/// only thinking keeps a note, as the API takes no assistant message without content. +pub fn drop_thinking(history: &mut [Value]) { + for msg in history.iter_mut().filter(|m| m["role"] == "assistant") { + let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; + let before = content.len(); + content.retain(|b| !matches!(b.get("type").and_then(Value::as_str), Some("thinking" | "redacted_thinking"))); + if content.is_empty() && before > 0 { + content.push(json!({"type": "text", "text": DROPPED_THINKING_NOTE})); + } + } +} + +/// MCP `tools/list` as OpenAI function tools (the hidden ones left out). +pub fn openai_tools(list: &Value) -> Vec { + list.get("tools") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(128) + .filter_map(|t| { + let name = t.get("name")?.as_str()?; + if HIDDEN_TOOLS.contains(&name) { + return None; + } + let params = t.get("inputSchema").cloned().filter(Value::is_object).unwrap_or(json!({"type": "object", "properties": {}})); + Some(json!({"type": "function", "function": { + "name": name, + "description": t.get("description").and_then(Value::as_str).unwrap_or(""), + "parameters": params, + }})) + }) + .collect() + }) + .unwrap_or_default() +} + +/// MCP `tools/list` as Anthropic tools (the hidden ones left out). +pub fn anthropic_tools(list: &Value) -> Vec { + list.get("tools") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .take(128) + .filter_map(|t| { + let name = t.get("name")?.as_str()?; + if HIDDEN_TOOLS.contains(&name) { + return None; + } + let schema = t.get("inputSchema").cloned().filter(Value::is_object).unwrap_or(json!({"type": "object", "properties": {}})); + Some(json!({ + "name": name, + "description": t.get("description").and_then(Value::as_str).unwrap_or(""), + "input_schema": schema, + })) + }) + .collect() + }) + .unwrap_or_default() +} + +/// Build an API request without performing I/O or reading credentials. +pub fn request_body(protocol: Protocol, model: &str, history: &[Value], tools: &[Value], effort: &str, no_reasoning: bool) -> Value { + match protocol { + Protocol::OpenAi => { + let mut messages = vec![json!({"role":"system","content":super::acp::SYSTEM_NOTE})]; + messages.extend_from_slice(history); + let mut body = json!({"model":model,"messages":messages}); + if !tools.is_empty() { + body["tools"] = json!(tools); + } + if !effort.is_empty() { + body["reasoning_effort"] = json!(effort); + } else if no_reasoning && !tools.is_empty() { + body["reasoning_effort"] = json!("none"); + } + body + } + Protocol::Anthropic => { + let mut body = json!({"model":model,"max_tokens":ANTHROPIC_MAX_TOKENS,"system":super::acp::SYSTEM_NOTE,"messages":history}); + if !tools.is_empty() { + body["tools"] = json!(tools); + } + body + } + } +} diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index 926aae003..25817f38c 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -38,7 +38,7 @@ pub const MAX_SENT_BYTES: usize = 3_750_000; /// A picture is not halved below this to fit; past it, it is refused. const MIN_SIDE: u32 = 64; /// Largest picture decoded (pixels on a side), so a hostile header can't ask for gigabytes. -const MAX_DECODE_SIDE: u32 = 20_000; +const MAX_DECODE_SIDE: u32 = if cfg!(target_arch = "wasm32") { 8192 } else { 20_000 }; /// The chip's picture. const THUMB: u32 = 64; @@ -259,7 +259,7 @@ fn picture_within(name: String, bytes: &[u8], limit: usize) -> Result Result, String>; fn set(&self, id: &str, secret: &str) -> Result<(), String>; fn delete(&self, id: &str) -> Result<(), String>; + /// Browser-only opt-in persistence; native keychain storage keeps its existing behavior. + fn remember(&self, _id: &str, _remember: bool) -> Result<(), String> { + Ok(()) + } + fn remembered(&self, _id: &str) -> bool { + false + } + fn clear_remembered(&self) -> Result<(), String> { + Ok(()) + } + fn notice(&self) -> Option { + None + } } /// Standard base64 with padding (RFC 4648), for pictures in messages. @@ -218,6 +231,35 @@ pub fn content_blocks(parts: &[PromptPart]) -> Vec { .collect() } +/// Browser host services: async tasks report through the existing nonblocking event queues. +pub type ModelListTask = std::sync::mpsc::Receiver, String>>; +pub type ConnectionTask = std::sync::mpsc::Receiver>; +pub type BrowserConnect = dyn Fn( + super::agents::Entry, + Option, + std::sync::mpsc::Sender, + egui::Context, +) -> Result, String>; +pub type BrowserList = dyn Fn(super::agents::Protocol, String, Option, egui::Context) -> ModelListTask; +pub type BrowserTest = dyn Fn(super::agents::Entry, Option, egui::Context) -> ConnectionTask; +pub type BrowserAttachment = dyn Fn(egui::Context) -> std::sync::mpsc::Receiver>; +#[derive(Clone, Debug)] +pub struct PlatformAgentContext { + pub document_session_code: String, + pub cad_project_code: Option, + pub capabilities: Value, +} +pub type PlatformConnect = + dyn Fn(PlatformAgentContext, std::sync::mpsc::Sender, egui::Context) -> Result, String>; +pub struct BrowserServices { + pub connect: Box, + pub platform_connect: Option>, + pub list: Box, + pub test: Box, + pub attach: Box, + pub paste_picture: Box, +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/agent_chat/gate.rs b/crates/ui-egui/src/agent_chat/gate.rs index 633d190b2..b9e508317 100644 --- a/crates/ui-egui/src/agent_chat/gate.rs +++ b/crates/ui-egui/src/agent_chat/gate.rs @@ -111,6 +111,34 @@ fn names_a_file(id: &str, params: &Value) -> Option { .or_else(|| AMBIGUOUS_KEYS.iter().find_map(|k| o.get(*k).and_then(|v| first(v, by_nature)))) } +/// Platform restrictions are independent of approval mode, including "All" and remembered +/// grants. Browser tools operate only on the currently bound in-memory document. +pub fn platform_allowed(method: &str, params: &Value) -> bool { + let allowed = |id: &str, params: &Value| { + !crate::platform::host_managed(id) + && !crate::platform::unavailable(id) + && !id.starts_with("file.") + && !id.starts_with("doc.") + && !id.starts_with("library.") + && !id.starts_with("app.") + && !id.starts_with("prefs.") + && !id.starts_with("diagnostics.") + && !id.contains(".export") + && !id.contains(".import") + && id != "render.start" + && names_a_file(id, params).is_none() + }; + match method { + "engine.execute" => allowed(params["command"].as_str().unwrap_or(""), ¶ms["params"]), + "engine.batch" => params["commands"].as_array().is_some_and(|steps| { + steps.iter().all(|step| allowed(step["command"].as_str().or_else(|| step["id"].as_str()).unwrap_or(""), &step["params"])) + }), + "engine.commands" | "document.inspect" | "ui.view" => true, + "ui.render" => names_a_file("ui.render.export", params).is_none(), + _ => false, + } +} + /// One command as the agent would run it. `undo_left`: steps this turn may still undo without /// reaching changes made before it. pub fn command(id: &str, params: &Value, undo_left: usize) -> Verdict { @@ -359,5 +387,29 @@ mod tests { let elsewhere = json!({"path": "/home/u/Desktop/shot.png", "allow_paths": ["/tmp/solidcraft-mcp-41-a3", "/home/u/Desktop"]}); assert!(matches!(request("ui.screenshot", &elsewhere, 0), Verdict::Ask(_))); assert_eq!(request("ui.render", &json!({"width": 400}), 0), Verdict::Run { change: false }); + assert_eq!(request("ui.render", &json!({"width": 400, "inline": true}), 0), Verdict::Run { change: false }); + assert!(!platform_allowed("ui.render", &json!({"path": "/tmp/model.png", "inline": true}))); + } + #[test] + fn platform_limits_apply_even_when_the_user_allows_every_tool() { + for id in [ + "file.new", + "file.save", + "doc.open", + "view.next_tab", + "file.export", + "component.insert_design", + "prefs.set", + "plugin.run", + "diagnostics.crash_reports", + ] { + assert!(!platform_allowed("engine.execute", &json!({"command":id,"params":{}})), "{id}"); + } + assert!(!platform_allowed("engine.batch", &json!({"commands":[{"command":"solid.box"},{"command":"file.new"}]}))); + assert!(!platform_allowed("engine.execute", &json!({"command":"sketch.insert","params":{"filename":"hidden.step"}}))); + assert!(platform_allowed("engine.execute", &json!({"command":"solid.box","params":{"length":3}}))); + assert!(platform_allowed("engine.execute", &json!({"command":"solid.sweep","params":{"path":["c1"]}}))); + assert!(platform_allowed("document.inspect", &json!({}))); + assert!(!platform_allowed("ui.agent_chat", &json!({"permissions":"all"}))); } } diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 24966a753..56f5567a3 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -13,7 +13,7 @@ //! - Here: the conversation, turns (each one undoes as one step), and the requests waiting for //! Allow or Deny. -// The web build shows only a note: the process side is desktop only. +// Native process adapters remain desktop-only; Web injects browser transport services. #![cfg_attr(target_arch = "wasm32", allow(dead_code, unused_imports))] pub mod acp; @@ -22,6 +22,7 @@ mod acp_client; pub mod agents; #[cfg(not(target_arch = "wasm32"))] mod api_client; +pub mod api_wire; pub mod attach; pub mod backend; pub mod context; @@ -130,7 +131,6 @@ struct Decode { } /// How a picture can be drawn now. -#[cfg(not(target_arch = "wasm32"))] pub enum Shown { /// Still being decoded: a repaint comes when it is in. Loading, @@ -169,17 +169,24 @@ impl Picture { } Shown::Loading } + #[cfg(target_arch = "wasm32")] + fn texture(&self, ctx: &egui::Context) -> Shown { + let done = self + .decode + .texture + .get_or_init(|| decode_picture(&self.bytes).map(|image| ctx.load_texture("sc_agent_chat_picture", image, egui::TextureOptions::LINEAR))); + done.clone().map_or(Shown::Failed, Shown::Ready) + } } /// Decode a picture in any format the app reads, within limits (it came through the attachment /// checks already; a hostile header still can't ask for gigabytes here). -#[cfg(not(target_arch = "wasm32"))] fn decode_picture(bytes: &[u8]) -> Option { let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; let mut limits = image::Limits::default(); - limits.max_image_width = Some(20_000); - limits.max_image_height = Some(20_000); - limits.max_alloc = Some(1 << 30); + limits.max_image_width = Some(if cfg!(target_arch = "wasm32") { 8192 } else { 20_000 }); + limits.max_image_height = limits.max_image_width; + limits.max_alloc = Some(if cfg!(target_arch = "wasm32") { 128 << 20 } else { 1 << 30 }); reader.limits(limits); let rgba = reader.decode().ok()?.to_rgba8(); let size = [usize::try_from(rgba.width()).ok()?, usize::try_from(rgba.height()).ok()?]; @@ -327,6 +334,11 @@ struct ModelRevert { #[derive(Default)] pub struct AgentChat { + #[cfg(target_arch = "wasm32")] + pub detecting: Option<()>, + pub expected_revision: Option, + expected_doc: Option>, + pub browser_attachment: Option>>, /// The panel is shown (View menu, the application bar's chat button, Ctrl+Shift+A). pub open: bool, /// Only while dispatching this conversation's own admitted tool request. Window state: @@ -865,12 +877,14 @@ enum Outcome { /// The AI features are on (the master switch in Settings → AI) and this is the desktop app. pub fn shown(app: &SolveApp) -> bool { - app.preferences.ai_features && cfg!(not(target_arch = "wasm32")) + (app.platform.enabled || app.preferences.ai_features) + && (cfg!(not(target_arch = "wasm32")) + || (app.platform.enabled && app.services.browser_agent.is_some() && app.platform.agent_context.is_some())) } /// The Assistant button in the application bar is shown (honours the existing preference). pub fn app_bar_button_shown(app: &SolveApp) -> bool { - shown(app) && app.preferences.ai_toolbar_button + shown(app) && (app.platform.enabled || app.preferences.ai_toolbar_button) } /// The application bar's status mark, independent of panel layout and painting. @@ -949,6 +963,7 @@ pub(crate) fn find_cli() -> Option { /// The agent's working folder: an empty folder of SolidCraft's own, so an agent's own file tools /// (where it has them) see nothing of the user's. +#[cfg(not(target_arch = "wasm32"))] fn working_dir() -> std::path::PathBuf { let d = solidcraft_engine::recovery::data_dir() .map(|d| d.join("agent-chat").join("work")) @@ -1074,7 +1089,7 @@ pub fn begin(app: &mut SolveApp) { if app.preferences.agent_chat_open_at_start { app.agent_chat.open = true; } - app.agent_chat.connect_at_start = app.preferences.agent_connect_at_start; + app.agent_chat.connect_at_start = app.platform.enabled || app.preferences.agent_connect_at_start; } /// Connect at start, once the installed agents are known (the one started last may be one of @@ -1133,6 +1148,10 @@ pub(crate) fn with_tool_request( let before = app.agent_chat.turn.as_ref().filter(|_| own).map(|t| (app.session.doc.clone(), t.start_doc.clone(), t.start_undo)); let previous = std::mem::replace(&mut app.agent_chat.following_document, own); let result = run(app); + if own && app.platform.enabled { + app.agent_chat.expected_revision = Some(app.session.design_revision()); + app.agent_chat.expected_doc = Some(app.session.doc.clone()); + } app.agent_chat.following_document = previous; if let Some((doc, start_doc, start_undo)) = before && Arc::ptr_eq(&doc, &app.session.doc) @@ -1331,12 +1350,9 @@ fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, co State::Ready => start_turn_with(app, text, image, at, files, interrupted.then_some(INTERRUPT_NOTE)), s => { app.agent_chat.queued = Some((text, image, at, files)); - #[cfg(not(target_arch = "wasm32"))] if !s.running() { connect(app, ctx); } - #[cfg(target_arch = "wasm32")] - let _ = (s, ctx); } } } @@ -1406,6 +1422,7 @@ pub fn new_chat(app: &mut SolveApp) { chat.pending.clear(); chat.attachments.clear(); chat.loading.clear(); + chat.browser_attachment = None; chat.pending_edit = None; chat.queued = None; chat.last = None; @@ -1484,6 +1501,8 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option std::result::Result>) -> usize { + if app.agent_chat.browser_attachment.is_some() { + return 0; + } + let remaining = attach::MAX_FILES.saturating_sub(app.agent_chat.files()); + if count > remaining { + app.agent_chat.notice(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_FILES.to_string())]), true); + } + if remaining > 0 { + app.agent_chat.browser_attachment = Some(rx); + } + remaining +} + /// Add a picture from the clipboard (RGBA rows, as the system gives them) to the next message. pub fn attach_rgba(app: &mut SolveApp, width: usize, height: usize, rgba: &[u8]) -> std::result::Result { if app.agent_chat.files() >= attach::MAX_FILES { @@ -1610,6 +1644,50 @@ pub fn cancel(app: &mut SolveApp) { app.agent_chat.stopped = true; crate::edit_in_place::forget_after_turn(app); interrupt(app); + if app.platform.enabled { + // A browser tool can be queued just before Stop. It must not be admitted under the + // next turn's approval, even when Stop and Send arrive in the same frame. + if let Some(rx) = &app.agent_chat.tools_rx { + for req in rx.try_iter() { + let _ = req.reply.send(crate::control::cancelled_chat_response()); + } + } + end_turn(app); + } +} + +/// A human command ends the AI undo group before it changes the document. Read-only commands +/// and selection/camera navigation may continue; trusted assistant dispatch bypasses this hook. +pub(crate) fn before_command(app: &mut SolveApp, id: &str) { + if app.platform.enabled + && !app.agent_chat.following_document + && app.agent_chat.turn.is_some() + && (matches!(id, "edit.undo" | "edit.redo") || solidcraft_engine::command_specs().iter().any(|spec| spec.id == id && spec.undoable)) + { + cancel(app); + app.agent_chat.notice(tr("vm.agent.model_changed"), false); + } +} + +/// Also catch direct interactive mutations. Keep the human's trailing undo steps outside the +/// AI group, and invalidate the trusted flag even if that history has already been cleared. +fn changed_outside_turn(app: &mut SolveApp) { + let boundary = app.agent_chat.expected_doc.as_ref().and_then(|doc| app.session.undo.iter().position(|step| Arc::ptr_eq(&step.doc, doc))); + let tail = boundary.map(|index| app.session.undo.split_off(index)); + let expected = app.agent_chat.expected_doc.clone(); + if tail.is_none() + && let Some(turn) = app.agent_chat.turn.take() + { + turn.active.store(false, std::sync::atomic::Ordering::Relaxed); + } + cancel(app); + if let Some(tail) = tail { + if let (Some(Item::Changes { doc, .. }), Some(expected)) = (app.agent_chat.items.last_mut(), expected) { + *doc = expected; + } + app.session.undo.extend(tail); + } + app.agent_chat.notice(tr("vm.agent.model_changed"), false); } /// Ask the agent to stop the message it is on and decline what waits for approval. @@ -1639,6 +1717,10 @@ pub fn approve(app: &mut SolveApp, id: u64, allow: bool) { /// Allow a held request and remember to allow its tool for this agent from now on. pub fn approve_always(app: &mut SolveApp, id: u64) { + if app.platform.enabled && !platform_tool_valid(app) { + approve(app, id, false); + return; + } let tool = app.agent_chat.items.iter().find_map(|i| match i { Item::Approval { id: x, tool, .. } if *x == id => Some(tool.clone()), _ => None, @@ -1694,6 +1776,13 @@ fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str> } fn approve_with(app: &mut SolveApp, id: u64, allow: bool, why: &str) { + let allow = allow + && (!app.platform.enabled + || (!app.platform.is_locked() + && app.platform.agent_context.is_some() + && app.platform_snapshot_available() + && app.agent_chat.expected_revision == Some(app.session.design_revision()))); + let chat = &mut app.agent_chat; let Some(i) = chat.held.iter().position(|h| h.id == id) else { return }; let h = chat.held.remove(i); @@ -1796,13 +1885,25 @@ pub fn undo_changes(app: &mut SolveApp, index: usize) { /// The requests the agent's tools sent through the chat's endpoint: each one passes the gate. fn pump_tools(app: &mut SolveApp) { let Some(rx) = app.agent_chat.tools_rx.take() else { return }; + if app.platform.enabled && (app.platform.is_locked() || !app.platform_snapshot_available() || app.platform.agent_context.is_none()) { + for req in rx.try_iter() { + let _ = req.reply.send(json!({"ok":false,"error":"HOST_INTERACTION_LOCKED"})); + } + app.agent_chat.tools_rx = Some(rx); + return; + } let configured = app.preferences.agent_chat_turn_limit; - let limit = if configured == 0 { u32::MAX } else { configured.clamp(1, 1000) }; + // Local assistant preferences must not cap a platform agent's turn. + let limit = if app.platform.enabled || configured == 0 { u32::MAX } else { configured.clamp(1, 1000) }; for mut req in rx.try_iter().take(64) { let refuse = |req: ControlRequest, e: String| { let _ = req.reply.send(json!({"ok": false, "error": e})); }; let undo_len = app.session.undo.len(); + if app.platform.enabled && !gate::platform_allowed(&req.method, &req.params) { + refuse(req, "HOST_CAPABILITY_UNAVAILABLE: this tool cannot access files or replace the bound project".into()); + continue; + } let Some(turn) = app.agent_chat.turn.as_mut() else { refuse(req, "the agent chat has no message in progress".into()); continue; @@ -1810,6 +1911,7 @@ fn pump_tools(app: &mut SolveApp) { req.chat_turn = Some(Arc::clone(&turn.active)); turn.requests += 1; // Requests without folders of their own stay inside the chat's working folder. + #[cfg(not(target_arch = "wasm32"))] if let Some(o) = req.params.as_object_mut() && !o.contains_key("allow_paths") { @@ -1817,9 +1919,13 @@ fn pump_tools(app: &mut SolveApp) { } let undo_left = undo_len.saturating_sub(turn.start_undo); // The permission mode (the agent's own, else the global one) and "always allow" answers. - let mode = agents::mode_for(&app.preferences, &app.agent_chat.running_id); + let mode = if app.platform.enabled && app.preferences.ai_permissions == agents::Mode::All { + agents::Mode::Edits + } else { + agents::mode_for(&app.preferences, &app.agent_chat.running_id) + }; let tool = gate::tool_key(&req.method, &req.params); - let always = agents::always_allowed(&app.preferences, &app.agent_chat.running_id, &tool); + let always = !app.platform.enabled && agents::always_allowed(&app.preferences, &app.agent_chat.running_id, &tool); let verdict = match gate::request(&req.method, &req.params, undo_left) { gate::Verdict::Ask(_) if mode == agents::Mode::All || always => gate::Verdict::Run { change: true }, gate::Verdict::Run { change: true } if mode == agents::Mode::Ask && !always => { @@ -1909,6 +2015,38 @@ pub(crate) fn take_loaded(app: &mut SolveApp, ctx: &egui::Context) { } pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { + // Selection, camera commands and refreshes also bump Session::revision. Only a change to + // the design invalidates a platform turn; otherwise a tool failure can stop its own recovery. + let revision = app.session.design_revision(); + if app.platform.enabled && app.agent_chat.turn.is_some() && (app.platform.is_locked() || app.agent_chat.expected_revision != Some(revision)) { + if app.agent_chat.expected_revision != Some(revision) { + changed_outside_turn(app); + } else { + cancel(app); + } + } + // A browser drop can contain several files. Keep its receiver until the producer closes it. + while let Some(rx) = &app.agent_chat.browser_attachment { + match rx.try_recv() { + Ok(Ok(file)) => { + if app.agent_chat.files() < attach::MAX_FILES { + let _ = app.agent_chat.add_file(file); + } else { + app.agent_chat.notice(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_FILES.to_string())]), true); + } + } + Ok(Err(error)) if !error.is_empty() => app.agent_chat.notice(error, true), + Ok(Err(_)) => {} + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + app.agent_chat.browser_attachment = None; + } + } + } + if let Some(error) = app.services.secrets.as_ref().and_then(|store| store.notice()) { + app.agent_chat.notice(error, true); + } + settings::poll_tests(&mut app.agent_chat); #[cfg(not(target_arch = "wasm32"))] if let Some(rx) = &app.agent_chat.detecting @@ -1992,9 +2130,9 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { settings::poll_capabilities(app, ctx); - settings::poll_listing(app, ctx); - connect_at_start(app, ctx); } + settings::poll_listing(app, ctx); + connect_at_start(app, ctx); pump_tools(app); if !app.agent_chat.held.is_empty() || app.agent_chat.state() == State::Busy { ctx.request_repaint_after(std::time::Duration::from_millis(250)); @@ -2067,6 +2205,12 @@ pub fn set_custom_model(app: &mut SolveApp, text: &str) -> bool { /// Switch a legacy ACP agent or an endpoint to `model`: it shows as current at once and is /// remembered for this agent; an endpoint also keeps it as its default model. fn send_model(app: &mut SolveApp, model: &str) { + if app.platform.enabled && app.agent_chat.model != model { + if app.agent_chat.turn.is_some() { + cancel(app); + } + app.agent_chat.tools_available = None; + } let agent = app.agent_chat.running_id.clone(); let chat = &mut app.agent_chat; let unlisted = !chat.models.iter().any(|m| m.id == model); @@ -2104,7 +2248,7 @@ fn apply_saved_model(app: &mut SolveApp) { /// Whether the model picker shows: only for an agent that reports models. pub fn models_shown(app: &SolveApp) -> bool { - !app.agent_chat.models.is_empty() && app.agent_chat.state().running() + !app.platform.enabled && !app.agent_chat.models.is_empty() && app.agent_chat.state().running() } /// Longest provider name kept from an agent's model list. @@ -2292,6 +2436,9 @@ fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_o /// `permission` (an option id, or `"cancel"`), `approve` (`true`/`false`, the oldest held /// request), `cancel` (Stop), `send_now` (steer: stop, then send the queue), `remove_pending` (index), `undo` (the newest message's changes); returns the panel's state. pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result { + if app.platform.enabled && (app.platform.is_locked() || app.platform.agent_context.is_none()) { + return Err("HOST_INTERACTION_LOCKED".into()); + } if let Some(e) = p.get("features").and_then(Value::as_bool) { app.preferences.ai_features = e; } @@ -2318,6 +2465,9 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Result { + if app.platform.enabled && !matches!(k, "api" | "anthropic") { + return Err("HOST_CAPABILITY_UNAVAILABLE".into()); + } let (kind, protocol) = match k { "installed" => (settings::AddKind::Installed, None), "custom" => (settings::AddKind::Custom, None), @@ -2392,7 +2545,7 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Result Result Value { "modes": c.modes.iter().map(|(id, name)| json!({"id": id, "name": name})).collect::>(), "mode": c.mode, "open": c.open, - "side": app.preferences.agent_chat_side, - "minimized": app.preferences.agent_chat_minimized, - "popped": app.preferences.agent_chat_popped, + "side": if app.platform.enabled { "right" } else { &app.preferences.agent_chat_side }, + "minimized": !app.platform.enabled && app.preferences.agent_chat_minimized, + "popped": !app.platform.enabled && app.preferences.agent_chat_popped, "window": app.preferences.agent_chat_window, "width": app.preferences.agent_chat_width, "state": c.state().id(), @@ -2559,5 +2714,113 @@ pub fn status(app: &SolveApp) -> Value { state } +/// Public product state intentionally excludes credentials, messages and authorization data. +pub fn platform_status(app: &SolveApp) -> Value { + let panel_fraction = app + .agent_chat + .panel_rect + .zip(app.agent_chat.dock_space) + .filter(|(panel, space)| panel.is_finite() && space.is_finite() && space.width() > 0.0) + .map(|(panel, space)| (panel.width() / space.width()).clamp(0.0, 0.5)); + json!({"available":app.services.browser_agent.is_some(), "enabled":shown(app), "toolbar":app.platform.enabled || app.preferences.ai_toolbar_button, + "fullHeight":app.platform.enabled, "panelFraction":panel_fraction, + "open":app.agent_chat.open && shown(app), "connection":app.agent_chat.state().id(), + "running":app.agent_chat.turn.is_some(), "pendingApprovals":app.agent_chat.held.len()}) +} + +/// Recheck immediately before dispatch, after approval and after any intervening UI input. +pub(crate) fn platform_tool_valid(app: &mut SolveApp) -> bool { + if !app.platform.enabled { + return true; + } + if app.agent_chat.expected_revision != Some(app.session.design_revision()) { + changed_outside_turn(app); + return false; + } + !app.platform.is_locked() && app.platform.agent_context.is_some() && app.platform_snapshot_available() && app.agent_chat.turn.is_some() +} + #[cfg(test)] mod tests; + +/// Connect an API agent without native processes or a loopback control server. +#[cfg(target_arch = "wasm32")] +pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { + disconnect(app); + if app.platform.is_locked() || app.platform.agent_context.is_none() { + return; + } + if app.platform.enabled { + let (Some(service), Some(capabilities), Some(document_session_code)) = + (app.services.browser_agent.as_ref(), app.platform.agent_capabilities.clone(), app.platform.agent_document_session_code.clone()) + else { + app.agent_chat.notice(tr("vm.agent.service_error"), true); + app.agent_chat.state = Some(State::Failed); + return; + }; + let Some(connect) = service.platform_connect.as_ref() else { + app.agent_chat.notice(tr("vm.agent.service_error"), true); + app.agent_chat.state = Some(State::Failed); + return; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let platform = + backend::PlatformAgentContext { document_session_code, cad_project_code: app.platform.agent_project_code.clone(), capabilities }; + match connect(platform, tx.clone(), ctx.clone()) { + Ok(backend) => { + let chat = &mut app.agent_chat; + chat.backend = Some(backend); + chat.tools_tx = Some(tx); + chat.tools_rx = Some(rx); + chat.running_id = "vibemake-platform".into(); + chat.running_endpoint.clear(); + chat.state = Some(State::Starting); + chat.tools_available = None; + } + Err(error) => { + app.agent_chat.notice(error, true); + app.agent_chat.state = Some(State::Failed); + } + } + return; + } + let Some(entry) = agents::current(app).filter(|entry| entry.kind.is_api()) else { + settings::open_add(app); + return; + }; + let key = app.services.secrets.as_ref().and_then(|store| store.get(&entry.id).ok().flatten()); + let (tx, rx) = std::sync::mpsc::channel(); + let Some(service) = &app.services.browser_agent else { + return; + }; + match (service.connect)(entry.clone(), key, tx.clone(), ctx.clone()) { + Ok(backend) => { + let chat = &mut app.agent_chat; + chat.backend = Some(backend); + chat.tools_tx = Some(tx); + chat.tools_rx = Some(rx); + chat.running_id = entry.id.clone(); + chat.running_endpoint = entry.base_url; + chat.state = Some(State::Starting); + chat.tools_available = None; + app.preferences.agent_last = entry.id; + } + Err(error) => { + app.agent_chat.notice(error, true); + app.agent_chat.state = Some(State::Failed); + } + } +} + +#[cfg(target_arch = "wasm32")] +pub fn refresh(_app: &mut SolveApp, _ctx: &egui::Context) {} + +#[cfg(target_arch = "wasm32")] +fn connect_at_start(app: &mut SolveApp, ctx: &egui::Context) { + if app.agent_chat.connect_at_start && !app.platform.is_locked() && app.platform.agent_context.is_some() { + app.agent_chat.connect_at_start = false; + if app.agent_chat.state.is_none() && (app.platform.enabled || app.preferences.agent_connect_at_start) { + connect(app, ctx); + } + } +} diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index b7388ca0c..dadac4c64 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -48,9 +48,7 @@ fn panel_id(left: bool) -> Id { } /// The largest thumbnail of a message's picture, and its largest preview while hovered (points). -#[cfg(not(target_arch = "wasm32"))] const THUMB_MAX: (f32, f32) = (150.0, 56.0); -#[cfg(not(target_arch = "wasm32"))] const PREVIEW_MAX: (f32, f32) = (560.0, 380.0); /// Forget the panel's own idea of its width, so the preference applies on the next frame. @@ -59,11 +57,16 @@ pub fn forget_width(ctx: &egui::Context) { for left in [true, false] { d.remove::(panel_id(left)); } + d.remove::(Id::new("sc_agent_chat_split")); }); } /// Show or hide the panel (a folded panel unfolds first). pub fn toggle(app: &mut SolveApp) { + if app.platform.enabled { + app.agent_chat.open = true; + return; + } let c = &mut app.agent_chat; if !c.open { c.open = true; @@ -88,7 +91,8 @@ pub fn tip(app: &SolveApp) -> String { /// panel in this window, never label selections belonging to another native viewport. /// Called before layout so even a click and a shortcut in the same frame are routed here. pub(crate) fn owns_keyboard_input(app: &mut SolveApp, ctx: &egui::Context) -> bool { - let rect = app.agent_chat.panel_rect.filter(|_| shown(app) && app.agent_chat.open && !app.preferences.agent_chat_minimized); + let rect = + app.agent_chat.panel_rect.filter(|_| shown(app) && app.agent_chat.open && (app.platform.enabled || !app.preferences.agent_chat_minimized)); let Some(rect) = rect else { app.agent_chat.keyboard_owned = false; return false; @@ -107,6 +111,9 @@ pub(crate) fn owns_keyboard_input(app: &mut SolveApp, ctx: &egui::Context) -> bo pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); poll(app, &ctx); + if app.platform.enabled { + app.agent_chat.open = shown(app); + } // Set again below if the chat is drawn this frame. app.agent_chat.drop_rect = None; // Retain the previous card for shortcut hover routing below; clear it when hidden. @@ -130,6 +137,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if !app.agent_chat.open { return; } + if app.platform.enabled { + split_panel(app, ui); + gallery_window(app, &ctx); + show_drop_hint(app, &ctx); + return; + } // Look for installed agents the first time the panel opens (in the background). #[cfg(not(target_arch = "wasm32"))] if app.agent_chat.detection.is_none() && app.agent_chat.detecting.is_none() { @@ -169,7 +182,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ); crate::scenario::publish_rect("agent_chat:panel", r.response.rect); app.agent_chat.panel_rect = Some(r.response.rect); - #[cfg(not(target_arch = "wasm32"))] gallery_window(app, &ctx); app.agent_chat.drop_rect = Some(r.response.rect); show_drop_hint(app, &ctx); @@ -179,9 +191,73 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } } +/// Product-host chat reserves its own full-height column before any CAD chrome is laid out. +/// Local floating, folded and pop-out preferences belong to the standalone application. +fn split_panel(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let available = ui.available_rect_before_wrap(); + app.agent_chat.dock_space = Some(available); + let maximum = MAX_WIDTH.min(available.width().max(0.0) * 0.5); + let minimum = MIN_WIDTH.min(maximum); + let width = app.preferences.agent_chat_width.clamp(minimum, maximum); + let host = Container::new(ui.ctx(), Surface::ApplicationBar); + let panel = host.edge("sc_agent_chat_split", Edge::Right).default_size(width).size_range(minimum..=maximum).resizable(true); + let response = host.show_edge(ui, panel, host.edge_frame(t.dialog_body), |ui| { + ui_kit::scope(ui, |ui| { + split_header(app, ui); + desktop_body(app, ui); + }); + }); + let rect = response.response.rect; + app.agent_chat.panel_rect = Some(rect); + app.agent_chat.drop_rect = Some(rect); + crate::scenario::publish_rect("agent_chat:panel", rect); + crate::scenario::publish_handle("agent_chat:resize", pos2(rect.left(), rect.center().y)); + let width = rect.width(); + if width.is_finite() && (MIN_WIDTH..=MAX_WIDTH).contains(&width) { + app.preferences.agent_chat_width = width; + } +} + +/// The title uses the same square, full-width application band as the host's menu bar. +fn split_header(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let host = Container::new(ui.ctx(), Surface::ApplicationBar); + let header = host.edge("sc_agent_chat_split_header", Edge::Top).exact_size(crate::platform::app_bar_height(ui.ctx())).resizable(false); + let response = host.show_edge(ui, header, host.edge_frame(t.app_bar), |ui| { + let rect = ui.max_rect(); + let content = rect.shrink2(vec2(t.space_12, 0.0)); + let mut row = ui.new_child(egui::UiBuilder::new().max_rect(content).layout(Layout::left_to_right(Align::Center))); + row.label(RichText::new(tr("ui.assistant")).semibold().color(t.app_bar_text).size(t.font_heading)); + let state = app.agent_chat.state(); + let waiting = app.agent_chat.waiting() > 0; + let ink = if waiting { + t.warning + } else { + match state { + State::Ready => t.agent_ok, + State::Busy | State::Starting => t.accent, + State::NeedsAuth => t.warning, + State::Exited | State::Failed => t.error, + State::Off => t.text_dim, + } + }; + let (dot, response) = row.allocate_exact_size(vec2(t.space_12, t.space_16), Sense::hover()); + row.painter().circle_filled(dot.center(), t.space_3, ink); + response.on_hover_text(if waiting { tr("ui.agent_chat_waiting") } else { state.label() }); + row.with_layout(Layout::right_to_left(Align::Center), |ui| { + if glyph_button(ui, "newchat", tr("ui.agent_chat_new")).clicked() { + request_new_chat(app); + } + }); + }); + crate::scenario::publish_rect("agent_chat:header", response.response.rect); +} + /// Horizontal room reserved before the history and browser when Assistant is on the left. pub(crate) fn left_inset(app: &SolveApp, available: Rect) -> f32 { - if Container::for_layout(app.ui.layout, Surface::Panel).floating() + if !app.platform.enabled + && Container::for_layout(app.ui.layout, Surface::Panel).floating() && shown(app) && app.agent_chat.open && !app.preferences.agent_chat_popped @@ -197,7 +273,8 @@ pub(crate) fn left_inset(app: &SolveApp, available: Rect) -> f32 { /// Assistant-specific precedence over tool sheets. Keep this out of the shared container: /// ordinary tool panels never reserve an outside rail for themselves. pub(crate) fn tool_space(app: &SolveApp, mut available: Rect) -> Rect { - if Container::for_layout(app.ui.layout, Surface::Panel).floating() + if !app.platform.enabled + && Container::for_layout(app.ui.layout, Surface::Panel).floating() && shown(app) && app.agent_chat.open && !app.preferences.agent_chat_popped @@ -281,7 +358,6 @@ fn floating(app: &mut SolveApp, ui: &mut egui::Ui) { app.agent_chat.drop_rect = Some(rect); crate::scenario::publish_rect("agent_chat:panel", rect); } - #[cfg(not(target_arch = "wasm32"))] gallery_window(app, &ctx); } @@ -294,7 +370,6 @@ const CHIP_PAD: f32 = 13.0; const CHIP_CROSS: f32 = 14.0; /// One thing in a group's rows: its heading, a chip for an item, or the "+N more" note. -#[cfg(not(target_arch = "wasm32"))] enum ChipPart<'a> { Heading(String), /// An item and its place among all of the context's items. @@ -306,7 +381,6 @@ enum ChipPart<'a> { /// each and a chip per item; hovering a chip tells what is known about it. The rows are filled by /// hand: egui wraps plain widgets, not framed ones, and one row wider than the chat would widen /// the whole panel. -#[cfg(not(target_arch = "wasm32"))] fn context_chips(ui: &mut egui::Ui, context: &Context, removable: bool) -> Option { let mut removed = None; if context.is_empty() { @@ -394,14 +468,12 @@ fn context_chips(ui: &mut egui::Ui, context: &Context, removable: bool) -> Optio } /// `s` cut to `max` characters, with an ellipsis. -#[cfg(not(target_arch = "wasm32"))] fn shorten(s: &str, max: usize) -> String { if s.chars().count() <= max { s.to_string() } else { format!("{}…", s.chars().take(max.saturating_sub(1)).collect::()) } } /// The pictures of a message as small thumbnails in a row. Hovering one shows it bigger for as long /// as the pointer stays; a click returns its place in the row, to open the viewer there. -#[cfg(not(target_arch = "wasm32"))] fn picture_strip(ui: &mut egui::Ui, n: usize, pictures: &[Picture]) -> Option { let t = Tokens::get(); let mut clicked = None; @@ -440,7 +512,6 @@ fn picture_strip(ui: &mut egui::Ui, n: usize, pictures: &[Picture]) -> Option egui::Vec2 { let scale = (max.x / size.x.max(1.0)).min(max.y / size.y.max(1.0)).min(2.0); vec2((size.x * scale).max(1.0), (size.y * scale).max(1.0)) @@ -448,7 +519,6 @@ fn fit(size: egui::Vec2, max: egui::Vec2) -> egui::Vec2 { /// The viewer: a message's pictures over the app, one at a time with a counter, Previous and Next /// (also the arrow keys), closed with the button, Esc or a click outside. -#[cfg(not(target_arch = "wasm32"))] fn gallery_window(app: &mut SolveApp, ctx: &egui::Context) { let Some(mut gallery) = app.agent_chat.gallery.take() else { return }; let count = gallery.pictures.len(); @@ -513,7 +583,6 @@ fn show_drop_hint(app: &SolveApp, ctx: &egui::Context) { } /// Where dragged files will go: a tinted zone over the chat with a line of text. -#[cfg(not(target_arch = "wasm32"))] fn drop_hint(ctx: &egui::Context, area: Rect) { let t = Tokens::get(); let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, Id::new("sc_agent_chat_drop_hint"))); @@ -634,11 +703,12 @@ fn glyph_button(ui: &mut egui::Ui, kind: &str, tip: &str) -> egui::Response { ui.painter().rect_filled(r, t.radius_sm, t.hover); } let c = r.center(); - let s = Stroke::new(1.4, t.text); + let ink = if ui.is_enabled() { t.text } else { t.text_dim }; + let s = Stroke::new(1.4, ink); let p = ui.painter(); match kind { "minimize" => { - ui_kit::disclosure(p, c, true, t.text); + ui_kit::disclosure(p, c, true, ink); } "close" => { p.line_segment([c + vec2(-4.5, -4.5), c + vec2(4.5, 4.5)], s); @@ -767,7 +837,6 @@ fn header(app: &mut SolveApp, ui: &mut egui::Ui, left: bool) { if !popped && glyph_button(ui, "minimize", tr("ui.agent_chat_minimize")).clicked() { app.preferences.agent_chat_minimized = true; } - #[cfg(not(target_arch = "wasm32"))] if glyph_button( ui, "newchat", @@ -777,10 +846,13 @@ fn header(app: &mut SolveApp, ui: &mut egui::Ui, left: bool) { { request_new_chat(app); } - #[cfg(not(target_arch = "wasm32"))] { let (kind, tip) = if popped { ("dock", "ui.agent_chat_dock") } else { ("pop_out", "ui.agent_chat_pop_out") }; - if glyph_button(ui, kind, tr(tip)).clicked() { + let response = ui + .add_enabled_ui(!cfg!(target_arch = "wasm32"), |ui| glyph_button(ui, kind, tr(tip))) + .inner + .on_disabled_hover_text(tr("vm.agent.window_unavailable")); + if response.clicked() { app.preferences.agent_chat_popped = !popped; } } @@ -831,18 +903,14 @@ fn dock_drag(app: &mut SolveApp, ui: &egui::Ui, drag: &egui::Response, left: boo fn body(app: &mut SolveApp, ui: &mut egui::Ui, left: bool) { header(app, ui, left); - #[cfg(not(target_arch = "wasm32"))] - ui_kit::assistant_controls(ui, |ui| switcher(app, ui)); - #[cfg(target_arch = "wasm32")] - { - ui.label(tr("ui.agent_chat_desktop_only")); + if !app.platform.enabled { + ui_kit::assistant_controls(ui, |ui| switcher(app, ui)); } - #[cfg(not(target_arch = "wasm32"))] desktop_body(app, ui); } -#[cfg(not(target_arch = "wasm32"))] fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { + #[cfg(not(target_arch = "wasm32"))] if app.agent_chat.detection.is_none() && app.agent_chat.detecting.is_none() { refresh(app, ui.ctx()); } @@ -925,6 +993,7 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { }) .inner; crate::scenario::publish_rect("agent_chat:input", r.rect); + crate::scenario::publish_handle("agent_chat:input", r.rect.center()); // macOS shows a window's cursors only while it is the active window: over the text box of a // chat window that isn't, the pointer stays an arrow. Coming from the main window, the chat // window becomes active, so the text cursor shows and the first click places the caret. @@ -1025,9 +1094,9 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { pick_clicked = picker.clicked(); if let Some(turn) = &app.agent_chat.turn { let n = turn.changes.to_string(); - let count = match app.preferences.agent_chat_turn_limit { - 0 => trf("ui.agent_chat_changes_n", &[("n", &n)]), - limit => trf("ui.agent_chat_changes_of", &[("n", &n), ("limit", &limit.to_string())]), + let count = match (app.platform.enabled, app.preferences.agent_chat_turn_limit) { + (true, _) | (_, 0) => trf("ui.agent_chat_changes_n", &[("n", &n)]), + (_, limit) => trf("ui.agent_chat_changes_of", &[("n", &n), ("limit", &limit.to_string())]), }; ui.label(RichText::new(count).color(Tokens::get().text_dim).size(Tokens::get().font_small)); } @@ -1077,9 +1146,11 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) { /// The header's second row: the agent this conversation uses (a compact switcher), the agent's /// own mode when it has modes, and the state of its login. -#[cfg(not(target_arch = "wasm32"))] fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); + if app.platform.enabled { + return; + } let all = agents::entries(app); let current = agents::current(app); // An advertised (even empty) config list replaces the older ACP model/mode pickers. @@ -1224,15 +1295,12 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { } } -#[cfg(not(target_arch = "wasm32"))] const FLATPAK_OVERRIDE: &str = "flatpak override --user io.tangencylabs.solidcraft --filesystem=~/.nvm:ro --filesystem=~/.local/bin:ro --filesystem=~/.local/share/claude:ro --filesystem=~/.claude --filesystem=~/.claude.json --share=network"; -#[cfg(not(target_arch = "wasm32"))] pub(super) fn no_agents_message() -> String { if std::env::var_os("FLATPAK_ID").is_some() { tr("ui.agent_chat_flatpak_none_found") } else { tr("ui.agent_chat_none_found") }.to_string() } -#[cfg(not(target_arch = "wasm32"))] pub(super) fn no_agents(ui: &mut egui::Ui) { let flatpak = std::env::var_os("FLATPAK_ID").is_some(); let style = if flatpak { ui_kit::Text::Report("none", false) } else { ui_kit::Text::Note("none") }; @@ -1250,7 +1318,6 @@ pub(super) fn no_agents(ui: &mut egui::Ui) { /// The width of a provider or model picker: its label's, from the usual picker width up to 200 /// points and never wider than the panel, so a short name is read whole and a long one truncates. -#[cfg(not(target_arch = "wasm32"))] fn picker_width(ui: &egui::Ui, label: &str) -> f32 { let t = Tokens::get(); let label: String = label.chars().take(64).collect(); @@ -1261,7 +1328,6 @@ fn picker_width(ui: &egui::Ui, label: &str) -> f32 { /// An agent's select options are authoritative. Compact value pickers share a strip below the /// agent switcher; only a narrow chat wraps them, rather than spending two full rows per option. -#[cfg(not(target_arch = "wasm32"))] fn config_selects(app: &mut SolveApp, ui: &mut egui::Ui, options: &[acp::ConfigOption]) { let t = Tokens::get(); let pending = app.agent_chat.config_pending; @@ -1295,7 +1361,6 @@ fn config_selects(app: &mut SolveApp, ui: &mut egui::Ui, options: &[acp::ConfigO } } -#[cfg(not(target_arch = "wasm32"))] fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOption, width: f32, pending: bool) { let t = Tokens::get(); let current = option.options.iter().find(|choice| choice.value == option.current_value); @@ -1410,7 +1475,6 @@ fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOpti } } -#[cfg(not(target_arch = "wasm32"))] fn compact_text(text: &str, max_chars: usize) -> String { let mut chars = text.chars(); let short: String = chars.by_ref().take(max_chars).collect(); @@ -1443,11 +1507,12 @@ mod config_ui_tests { fn draw_switcher(app: &mut SolveApp, ctx: &egui::Context, width: f32) { crate::scenario::clear_handles(); let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(width, 700.0)); - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { ui.allocate_ui(vec2(width - 16.0, 600.0), |ui| { ui_kit::scope(ui, |ui| switcher(app, ui)); }); }); + output.textures_delta.clear(); } #[test] @@ -1519,13 +1584,11 @@ mod config_ui_tests { /// What is drawn under the agent switcher keeps the switcher's side margin (#10172): it starts /// where the switcher's fields start, not at the panel's edge. -#[cfg(not(target_arch = "wasm32"))] fn inset(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(Tokens::get().space_12 as i8, 0)).show(ui, add).inner } /// Before the first connection: what's installed, how to install the rest, and Add agent. -#[cfg(not(target_arch = "wasm32"))] fn picker(app: &mut SolveApp, ui: &mut egui::Ui) { let open = app.agent_chat.picking.unwrap_or(!app.agent_chat.state().running() && app.agent_chat.items.is_empty()); if !open { @@ -1585,7 +1648,6 @@ fn agent_list(app: &mut SolveApp, ui: &mut egui::Ui) { } } -#[cfg(not(target_arch = "wasm32"))] fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::section(ui, "authentication", tr("ui.agent_chat_auth_title"), true, |ui| { ui.set_width(ui.available_width()); @@ -1636,7 +1698,6 @@ fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) { /// The visible **Copy message** button of one transcript message (#10675): copies the whole /// message — the prompt as entered, or the assistant's original Markdown — and nothing else. /// A streaming reply copies the stable text received so far, which is what `text` holds. -#[cfg(not(target_arch = "wasm32"))] fn copy_message_button(ui: &mut egui::Ui, n: usize, text: &str) { let b = ui_kit::button(ui, tr("ui.agent_chat_copy_message"), ui_kit::Button::Small); crate::scenario::publish_handle(&format!("agent_chat:copy:{n}"), b.rect.center()); @@ -1649,7 +1710,6 @@ fn copy_message_button(ui: &mut egui::Ui, n: usize, text: &str) { /// visible button, on the whole message area, beside the composer's own text menu. /// The area stays hover-only so partial text selection keeps working, so the menu opens on a /// right-click released over it rather than on a click the response itself would report. -#[cfg(not(target_arch = "wasm32"))] fn copy_message_menu(ui: &egui::Ui, response: &egui::Response, n: usize, text: &str) { crate::scenario::publish_rect(&format!("agent_chat:msg:{n}"), response.rect); let opened = ui @@ -1676,7 +1736,6 @@ fn copy_message_menu(ui: &egui::Ui, response: &egui::Response, n: usize, text: & } } -#[cfg(not(target_arch = "wasm32"))] fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); let mut answer: Option<(usize, Option)> = None; @@ -1707,7 +1766,9 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { context_chips(ui, context, false); files_line(ui, files.iter().map(String::as_str)); if copyable { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| copy_message_button(ui, n, text)); + ui.allocate_ui_with_layout(vec2(ui.available_width(), t.control_height), Layout::right_to_left(Align::Center), |ui| { + copy_message_button(ui, n, text); + }); } }); if copyable { @@ -1937,16 +1998,25 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { slot.1 = buf; } if app.agent_chat.items.is_empty() && app.agent_chat.pending.is_empty() { - if agents::entries(app).is_empty() && app.agent_chat.detecting.is_none() { - ui_kit::assistant_empty(ui, tr("ui.agent_chat_setup_title"), tr("ui.agent_chat_setup_body"), |ui| { - if ui_kit::primary_button(ui, tr("ui.agent_chat_open_settings")).clicked() { - crate::prefs::open_at(app, crate::prefs::PAGE_ASSISTANT); - } - }); + if !app.platform.enabled && agents::entries(app).is_empty() && app.agent_chat.detecting.is_none() { + ui_kit::assistant_empty( + ui, + tr("ui.agent_chat_setup_title"), + tr(if app.services.browser_agent.is_some() { "vm.agent.setup" } else { "ui.agent_chat_setup_body" }), + |ui| { + if ui_kit::primary_button(ui, tr("ui.agent_chat_open_settings")).clicked() { + crate::prefs::open_at(app, crate::prefs::PAGE_ASSISTANT); + } + }, + ); } else { ui_kit::assistant_prose(ui, |ui| { - ui.label(RichText::new(tr("ui.agent_chat_intro")).color(t.text_dim)); - ui.label(RichText::new(tr("ui.agent_chat_privacy")).color(t.text_dim).size(t.font_small)); + ui.label(RichText::new(tr(if app.platform.enabled { "vm.agent.intro" } else { "ui.agent_chat_intro" })).color(t.text_dim)); + ui.label( + RichText::new(tr(if app.services.browser_agent.is_some() { "vm.agent.no_history" } else { "ui.agent_chat_privacy" })) + .color(t.text_dim) + .size(t.font_small), + ); }); } } @@ -1982,7 +2052,6 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { } /// The files that went (or will go) with a message, by name. -#[cfg(not(target_arch = "wasm32"))] fn files_line<'a>(ui: &mut egui::Ui, names: impl Iterator) { let list = names.collect::>().join(", "); if !list.is_empty() { @@ -1997,7 +2066,6 @@ const CHIP_W: f32 = 170.0; /// The files for the next message, as chips in rows that fit the chat: a picture's thumbnail (or /// a file mark), the name cut to fit, and a × that takes the file off. Laid out by hand: egui /// wraps plain widgets, not framed groups, and one row wider than the chat widens all below it. -#[cfg(not(target_arch = "wasm32"))] fn attachment_chips(app: &mut SolveApp, ui: &mut egui::Ui) { let chat = &mut app.agent_chat; // Thumbnails of files no longer on the message are let go. @@ -2043,14 +2111,12 @@ fn attachment_chips(app: &mut SolveApp, ui: &mut egui::Ui) { } /// What a chip's × says: an imported part stays in the design when it comes off the message. -#[cfg(not(target_arch = "wasm32"))] pub(super) fn remove_tip(f: &attach::Attachment) -> &'static str { tr(if matches!(f.content, attach::Content::Imported) { "ui.agent_chat_remove_imported" } else { "ui.agent_chat_remove_file" }) } /// The chip of a file still being read or imported: a spinner, the name, and a × that takes it /// off (an import goes on: its part lands in the design). -#[cfg(not(target_arch = "wasm32"))] fn loading_chip(ui: &mut egui::Ui, name: &str, importing: bool, i: usize, w: f32) -> bool { let t = Tokens::get(); let mut clicked = false; @@ -2087,7 +2153,6 @@ fn loading_chip(ui: &mut egui::Ui, name: &str, importing: bool, i: usize, w: f32 } /// One file chip, `w` wide in all; true when its × was clicked. -#[cfg(not(target_arch = "wasm32"))] fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap, f: &attach::Attachment, i: usize, w: f32) -> bool { let t = Tokens::get(); let mut clicked = false; @@ -2180,7 +2245,6 @@ fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) { } /// A tool call as its card shows it. -#[cfg(not(target_arch = "wasm32"))] struct ToolCall<'a> { /// The agent's title, shown when there are no words for the call. title: &'a str, @@ -2193,13 +2257,11 @@ struct ToolCall<'a> { } /// Longest raw text shown under a card's Details (characters). -#[cfg(not(target_arch = "wasm32"))] const MAX_DETAIL: usize = 8000; /// A tool call as a card: its state and what it did in words on one line (the agent's own title /// when there are none); a click on the line unfolds Details, the raw arguments and what it /// returned. -#[cfg(not(target_arch = "wasm32"))] fn tool_card(ui: &mut egui::Ui, n: usize, call: &ToolCall) { let t = Tokens::get(); let status = call.status; @@ -2259,7 +2321,6 @@ fn tool_card(ui: &mut egui::Ui, n: usize, call: &ToolCall) { } /// One part of a card's Details: its heading and the raw text, cut short and scrolling. -#[cfg(not(target_arch = "wasm32"))] fn tool_detail(ui: &mut egui::Ui, heading: &str, text: &str, id: Id) { let t = Tokens::get(); ui.label(RichText::new(heading).size(t.font_small).color(t.text_dim)); @@ -2275,7 +2336,6 @@ fn tool_detail(ui: &mut egui::Ui, heading: &str, text: &str, id: Id) { /// A small status mark drawn as a shape (no glyph a system font might lack): filled when the /// step is running or done, hollow while it waits. -#[cfg(not(target_arch = "wasm32"))] fn status_dot(ui: &mut egui::Ui, color: Color32, filled: bool) { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover()); if filled { @@ -2450,6 +2510,35 @@ mod tests { } } + #[test] + fn assistant_prompt_and_copy_action_stay_compact_inside_a_tall_panel() { + for width in [280.0, 440.0, 760.0] { + let ctx = crate::fonts::test_context(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.agent_chat.items.push(Item::User { + text: "Make a plate".into(), + image: false, + pictures: Vec::new(), + context: Context::default(), + files: Vec::new(), + }); + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width + 16.0, 900.0))), ..Default::default() }; + for _ in 0..2 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui(input.clone(), |ui| { + ui.set_width(width); + let top = ui.cursor().min.y; + ui_kit::scope(ui, |ui| conversation(&mut app, ui)); + let bottom = ui.cursor().min.y; + let copy = crate::scenario::handle_at("agent_chat:copy:0").expect("the prompt retains its Copy action"); + assert!(bottom - top < Tokens::get().control_height * 4.0, "a short prompt must not consume the panel height: {top}..{bottom}"); + assert!(copy.y > top && copy.y < bottom && copy.x < width + 16.0, "Copy stays inside the compact bubble: {copy:?}"); + }); + output.textures_delta.clear(); + } + } + } + #[test] fn assistant_agent_mode_and_model_wrap_without_escaping_narrow_width() { let ctx = crate::fonts::test_context(); @@ -2496,3 +2585,56 @@ mod tests { } } } + +#[cfg(target_arch = "wasm32")] +fn agent_list(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.platform.enabled { + return; + } + ui.horizontal(|ui| { + ui_kit::text(ui, tr("ui.agent_chat_pick"), ui_kit::Text::Inline); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui_kit::button(ui, tr("ui.agent_chat_refresh"), ui_kit::Button::Enabled(false)).on_disabled_hover_text(tr("vm.agent.runtime_required")); + if ui_kit::button(ui, tr("ui.ai_add_agent"), ui_kit::Button::Small).clicked() { + settings::open_add(app); + } + }); + }); + let selected = agents::current(app).map(|entry| entry.id); + for entry in agents::entries(app) { + let response = ui_kit::list_picker(ui, &entry.id, &entry.name, selected.as_deref() == Some(&entry.id)).on_hover_text(entry.detail()); + crate::scenario::publish_handle(&format!("agent_chat:pick:{}", entry.id), response.rect.center()); + if response.clicked() { + app.agent_chat.agent_id = Some(entry.id); + } + } +} +#[cfg(target_arch = "wasm32")] +fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) { + let (mut choose, mut paste) = (false, false); + let response = ui_kit::action_menu(ui, "+", |ui| { + let enabled = app.agent_chat.browser_attachment.is_none() && app.agent_chat.files() < attach::MAX_FILES; + let file = ui_kit::button(ui, tr("ui.agent_chat_add_file"), ui_kit::Button::Enabled(enabled)); + crate::scenario::publish_handle("agent_chat:add_file", file.rect.center()); + let picture = ui_kit::button(ui, tr("ui.agent_chat_paste_picture"), ui_kit::Button::Enabled(enabled)); + crate::scenario::publish_handle("agent_chat:paste_picture", picture.rect.center()); + if file.clicked() { + choose = true; + ui.close(); + } + if picture.clicked() { + paste = true; + ui.close(); + } + }); + crate::scenario::publish_handle("agent_chat:add", response.response.rect.center()); + response.response.on_hover_text(tr("ui.agent_chat_add")); + if let Some(service) = &app.services.browser_agent { + if choose { + app.agent_chat.browser_attachment = Some((service.attach)(ui.ctx().clone())); + } + if paste { + app.agent_chat.browser_attachment = Some((service.paste_picture)(ui.ctx().clone())); + } + } +} diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index 07f584e70..067a6011d 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -37,6 +37,7 @@ pub struct AddState { pub editing: Option, /// Editing an endpoint whose key is in the keychain: an empty key field keeps it. pub saved_key: bool, + pub remember_key: bool, test: Option, /// The endpoint the model picker lists: what the fields said when they were last left. listing: Option, @@ -86,10 +87,8 @@ pub struct State { checking: Option, /// Endpoints' models as they were last listed here, or why they could not be. endpoint_models: std::collections::HashMap, String>>, - #[cfg(not(target_arch = "wasm32"))] listing: Option, /// An agent card's picker asked for this listing (with the agent whose key goes along). - #[cfg(not(target_arch = "wasm32"))] card_listing: Option<(ListingKey, String)>, } @@ -134,7 +133,6 @@ fn model_choices<'a>(models: &'a [acp::ModelInfo], rows: &'a [(String, Option, String>>, @@ -177,9 +175,9 @@ fn start_listing(app: &mut SolveApp, ctx: &egui::Context, key: ListingKey, secre } /// Take in a finished listing, and start the one an agent card asked for. -#[cfg(not(target_arch = "wasm32"))] pub(super) fn poll_listing(app: &mut SolveApp, ctx: &egui::Context) { use std::sync::mpsc::TryRecvError; + let browser = app.services.browser_agent.is_some(); let state = &mut app.agent_chat.settings; if let Some(listing) = &state.listing { let result = match listing.rx.try_recv() { @@ -193,19 +191,26 @@ pub(super) fn poll_listing(app: &mut SolveApp, ctx: &egui::Context) { let Some((key, agent)) = state.card_listing.take() else { return }; let secrets = app.services.secrets.clone().filter(|_| key.2); start_listing(app, ctx, key, move || match secrets { - Some(secrets) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + Some(secrets) => secrets.get(&agent).map_err(|e| secret_error(e, browser)), None => Ok(None), }); } /// The Add dialog's listing, of what its fields said when last left, never of a half-typed address. -#[cfg(not(target_arch = "wasm32"))] fn list_for_dialog(app: &mut SolveApp, ctx: &egui::Context) { + let browser = app.services.browser_agent.is_some(); let state = &mut app.agent_chat.settings; let Some(s) = state.add.as_mut().filter(|s| s.kind == AddKind::Api) else { return }; let typed = Some(s.key.trim().to_string()).filter(|typed| !typed.is_empty()); // Editing an agent whose key is kept: the listing goes with that key, read on its thread. - let stored = s.editing.clone().filter(|_| s.saved_key && typed.is_none()); + let stored = s.editing.clone().filter(|id| { + s.saved_key + && typed.is_none() + && (app.services.browser_agent.is_none() + || app.preferences.agents.iter().any(|old| { + old.id == *id && old.kind == s.protocol.kind() && agents::normalize_url(&s.base_url).as_deref() == Ok(old.base_url.as_str()) + })) + }); if std::mem::take(&mut s.list_again) { s.listing = listing_key(s.protocol, &s.base_url, typed.is_some() || stored.is_some()); // Asked again: what failed may work now, with another key or the server back up. @@ -222,11 +227,15 @@ fn list_for_dialog(app: &mut SolveApp, ctx: &egui::Context) { let typed = typed.filter(|_| key.2); let stored = stored.filter(|_| key.2).and_then(|agent| app.services.secrets.clone().map(|secrets| (secrets, agent))); start_listing(app, ctx, key, move || match stored { - Some((secrets, agent)) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + Some((secrets, agent)) => secrets.get(&agent).map_err(|e| secret_error(e, browser)), None => Ok(typed), }); } +fn secret_error(error: String, browser: bool) -> String { + if browser { error } else { trf("ui.ai_keychain_error", &[("error", &error)]) } +} + #[cfg(not(target_arch = "wasm32"))] struct CapabilityCheck { key: (String, String), @@ -300,7 +309,9 @@ pub(super) fn model_warning(app: &SolveApp) -> Option { if let Some((key, _)) = capability_selection(app) { return capability_warning(&key.1, app.agent_chat.settings.capabilities.get(&key).copied().flatten()); } - let _ = app; + if app.services.browser_agent.is_some() && app.agent_chat.tools_available == Some(false) { + return Some(tr("vm.agent.chat_only").into()); + } None } @@ -311,10 +322,12 @@ fn capability_warning(model: &str, tools: Option) -> Option { /// Open the Add agent dialog. pub fn open_add(app: &mut SolveApp) { - let preset = agents::OPENAI_PRESETS.first(); + let preset = if app.services.browser_agent.is_some() { None } else { agents::OPENAI_PRESETS.first() }; app.agent_chat.settings.add = Some(AddState { base_url: preset.map(|p| p.base_url.to_string()).unwrap_or_default(), name: preset.map(|p| p.name.to_string()).unwrap_or_default(), + kind: if app.services.browser_agent.is_some() { AddKind::Api } else { AddKind::Installed }, + preset: if app.services.browser_agent.is_some() { agents::OPENAI_PRESETS.len() } else { 0 }, request_timeout_s: agents::DEFAULT_REQUEST_TIMEOUT_S, list_again: true, ..Default::default() @@ -349,6 +362,7 @@ pub fn open_edit(app: &mut SolveApp, id: &str) -> bool { s.base_url = c.base_url.clone(); s.model = c.model.clone(); s.saved_key = c.key; + s.remember_key = app.services.secrets.as_ref().is_some_and(|store| store.remembered(&c.id)); } else { s.kind = AddKind::Custom; s.command = c.command.clone(); @@ -372,10 +386,21 @@ pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize) s.list_again = true; } +/// A browser credential belongs to one protocol and endpoint, including when a preset changes it. +fn choose_endpoint(s: &mut AddState, protocol: Protocol, index: usize, browser: bool) { + let old = (s.protocol, s.base_url.clone()); + choose_preset(s, protocol, index); + if browser && old != (s.protocol, s.base_url.clone()) { + s.key.clear(); + s.saved_key = false; + s.remember_key = false; + } +} + /// Run a connection test in the background (it starts the agent briefly, or asks the endpoint /// for its models). #[cfg(not(target_arch = "wasm32"))] -fn start_test(app: &SolveApp, e: &agents::Entry, key: Option) -> Test { +fn start_test(app: &SolveApp, e: &agents::Entry, key: Option, _ctx: &egui::Context) -> Test { let (tx, rx) = std::sync::mpsc::channel(); match e.kind { Kind::Acp => { @@ -436,11 +461,18 @@ fn test_line(ui: &mut egui::Ui, test: &Option<&Test>) { /// remain accessible on hover, and high-risk permissions always retain a visible warning. pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::settings_heading(ui, tr("prefs.assistant"), tr("ai.prefs.intro")); + if app.platform.enabled { + let model = app.platform.agent_capabilities.as_ref().and_then(|caps| caps["model"].as_str()).unwrap_or("VibeMake CAD Agent"); + ui_kit::settings_section(ui, "platform_agent", tr("ui.agent_chat_pick"), |ui| { + ui_kit::text(ui, &trf("vm.agent.platform_mode", &[("model", model)]), ui_kit::Text::Inline); + }); + return; + } ui_kit::settings_section(ui, "assistant_availability", tr("ai.prefs.availability"), |ui| { let response = ui_kit::checkbox(ui, tr("ui.ai_show_features"), &mut app.preferences.ai_features).on_hover_text(tr("ui.ai_show_features_note")); crate::scenario::publish_handle("prefs:ai_features", response.rect.center()); - if !cfg!(target_arch = "wasm32") { + { if app.preferences.ai_features { let response = ui_kit::checkbox(ui, tr("ui.ai_toolbar_button"), &mut app.preferences.ai_toolbar_button) .on_hover_text(tr("ui.ai_toolbar_button_note")); @@ -452,28 +484,39 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { .on_hover_text(tr("ai.prefs.open_at_start_note")); crate::scenario::publish_handle("prefs:agent_chat_open_at_start", response.rect.center()); } - let response = ui_kit::checkbox(ui, tr("ai.prefs.background_commands"), &mut app.preferences.agent_off_thread) - .on_hover_text(tr("ui.agent_off_thread_note")); - crate::scenario::publish_handle("prefs:agent_off_thread", response.rect.center()); - let response = ui_kit::checkbox(ui, tr("ai.prefs.allow_control"), &mut app.preferences.agent_control) - .on_hover_text(tr("ai.prefs.allow_control_note")); - crate::scenario::publish_handle("prefs:agent_control", response.rect.center()); - let response = ui_kit::checkbox(ui, tr("ai.prefs.connect_apps"), &mut app.preferences.connect_ai_apps) - .on_hover_text(tr("ai.prefs.connect_apps_note")); - crate::scenario::publish_handle("prefs:connect_ai_apps", response.rect.center()); + ui.add_enabled_ui(!cfg!(target_arch = "wasm32"), |ui| { + let response = ui_kit::checkbox(ui, tr("ai.prefs.background_commands"), &mut app.preferences.agent_off_thread) + .on_hover_text(tr("ui.agent_off_thread_note")); + crate::scenario::publish_handle("prefs:agent_off_thread", response.rect.center()); + let response = ui_kit::checkbox(ui, tr("ai.prefs.allow_control"), &mut app.preferences.agent_control) + .on_hover_text(tr("ai.prefs.allow_control_note")); + crate::scenario::publish_handle("prefs:agent_control", response.rect.center()); + let response = ui_kit::checkbox(ui, tr("ai.prefs.connect_apps"), &mut app.preferences.connect_ai_apps) + .on_hover_text(tr("ai.prefs.connect_apps_note")); + crate::scenario::publish_handle("prefs:connect_ai_apps", response.rect.center()); + }) + .response + .on_disabled_hover_text(tr("vm.agent.native_controls")); } - if cfg!(target_arch = "wasm32") { - ui_kit::text(ui, tr("ui.agent_chat_desktop_only"), ui_kit::Text::Hint("desktop")); + if app.services.browser_agent.is_some() { + ui_kit::text(ui, tr("vm.agent.connection_note"), ui_kit::Text::Hint("browser")); } }); - if !cfg!(target_arch = "wasm32") && app.preferences.ai_features { + if app.preferences.ai_features && (!cfg!(target_arch = "wasm32") || app.services.browser_agent.is_some()) { #[cfg(not(target_arch = "wasm32"))] { let browsing = !crate::prefs_search::querying(ui) || app.prefs_window.section == crate::prefs::PAGE_ASSISTANT; if browsing && app.agent_chat.detection.is_none() && app.agent_chat.detecting.is_none() { refresh(app, &ui.ctx().clone()); } - agents_section(app, ui); + } + agents_section(app, ui); + if app.services.browser_agent.is_some() + && ui_kit::button(ui, tr("vm.agent.clear_keys"), ui_kit::Button::Normal).clicked() + && let Some(store) = &app.services.secrets + && let Err(error) = store.clear_remembered() + { + app.agent_chat.notice(error, true); } permissions_section(app, ui); panel_section(app, ui); @@ -510,9 +553,11 @@ fn permissions_section(app: &mut SolveApp, ui: &mut egui::Ui) { app.preferences.ai_permissions = *mode; } if app.preferences.ai_permissions == Mode::All { - ui_kit::text(ui, tr("ui.ai_mode_all_warning"), ui_kit::Text::Report("permissions_warning", true)); + let warning = if app.services.browser_agent.is_some() { "vm.agent.notice" } else { "ui.ai_mode_all_warning" }; + ui_kit::text(ui, tr(warning), ui_kit::Text::Report("permissions_warning", true)); } - ui_kit::text(ui, tr("ai.prefs.permission_scope"), ui_kit::Text::Hint("scope")).on_hover_text(tr("ui.ai_modes_scope")); + let scope = if app.services.browser_agent.is_some() { "vm.agent.permission_note" } else { "ai.prefs.permission_scope" }; + ui_kit::text(ui, tr(scope), ui_kit::Text::Hint("scope")).on_hover_text(tr(scope)); let remembered: Vec<_> = app .preferences .agent_always_allow @@ -547,8 +592,22 @@ fn panel_section(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::row(ui, tr("ui.agent_chat_side"), |ui| { let p = &mut app.preferences; let mut selected = if p.agent_chat_popped { 2 } else { usize::from(p.agent_chat_side != "left") }; + let browser = app.services.browser_agent.is_some(); let options = [tr("ui.agent_chat_left"), tr("ui.agent_chat_right"), tr("ui.agent_chat_own_window")]; - if ui_kit::segmented(ui, &mut selected, &options, ui_kit::Segments { intrinsic: true, ..Default::default() }) { + let enabled = [true, true, !browser]; + let disabled = [None, None, browser.then(|| tr("vm.agent.window_unavailable"))]; + if ui_kit::segmented( + ui, + &mut selected, + &options, + ui_kit::Segments { + intrinsic: true, + enabled: &enabled, + disabled: &disabled, + targets: &["prefs:agent_chat_side:left", "prefs:agent_chat_side:right", "prefs:agent_chat_side:window"], + ..Default::default() + }, + ) { p.agent_chat_popped = selected == 2; if selected < 2 { p.agent_chat_side = if selected == 0 { "left" } else { "right" }.into(); @@ -566,7 +625,8 @@ fn panel_section(app: &mut SolveApp, ui: &mut egui::Ui) { } }); }); - ui_kit::text(ui, tr("ai.prefs.privacy_note"), ui_kit::Text::Hint("privacy")); + let privacy = if app.services.browser_agent.is_some() { "vm.agent.key_note" } else { "ai.prefs.privacy_note" }; + ui_kit::text(ui, tr(privacy), ui_kit::Text::Hint("privacy")); }); } @@ -593,11 +653,11 @@ fn pointer_section(app: &mut SolveApp, ui: &mut egui::Ui) { } /// The agents: found and added, with Test, Default, a permission override and Remove. -#[cfg(not(target_arch = "wasm32"))] fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { let all = agents::entries(app); let d = &app.preferences.agent_default; let default = if all.iter().any(|e| &e.id == d) { Some(d.clone()) } else { all.first().map(|e| e.id.clone()) }; + let mut delete_key = None; let mut remove: Option = None; let mut test: Option = None; let mut edit: Option = None; @@ -634,10 +694,14 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { } let test_button = ui_kit::button(ui, tr("ui.ai_test"), ui_kit::Button::Small); crate::scenario::publish_handle(&format!("prefs:ai_test:{}", entry.id), test_button.rect.center()); - let tip = match entry.kind { - Kind::Acp => "ui.ai_test_acp_tip", - Kind::Api => "ui.ai_test_api_tip", - Kind::Anthropic => "ui.ai_test_anthropic_tip", + let tip = if app.services.browser_agent.is_some() { + "vm.agent.connection_test" + } else { + match entry.kind { + Kind::Acp => "ui.ai_test_acp_tip", + Kind::Api => "ui.ai_test_api_tip", + Kind::Anthropic => "ui.ai_test_anthropic_tip", + } }; if test_button.on_hover_text(tr(tip)).clicked() { test = Some(entry.clone()); @@ -649,6 +713,12 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { edit = Some(entry.id.clone()); } } + if app.services.browser_agent.is_some() + && entry.key + && ui_kit::button(ui, tr("vm.agent.delete_key"), ui_kit::Button::Ghost).clicked() + { + delete_key = Some(entry.id.clone()); + } if !entry.found && ui_kit::button(ui, tr("ui.ai_remove"), ui_kit::Button::Ghost).clicked() { remove = Some(entry.id.clone()); } @@ -766,8 +836,9 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { }); } if app.preferences.agent_permissions.get(&entry.id) == Some(&Mode::All) { - ui_kit::text(ui, tr("ai.prefs.override_all_warning"), ui_kit::Text::Report("agent_permissions_warning", true)) - .on_hover_text(tr("ui.ai_mode_all_warning")); + ui_kit::text(ui, tr("ai.prefs.override_all_warning"), ui_kit::Text::Report("agent_permissions_warning", true)).on_hover_text( + tr(if app.services.browser_agent.is_some() { "vm.agent.permission_note" } else { "ui.ai_mode_all_warning" }), + ); } test_line(ui, &app.agent_chat.settings.tests.get(&entry.id)); }); @@ -779,14 +850,16 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { if button.clicked() { open_add(app); } - if ui_kit::button(ui, tr("ui.agent_chat_refresh"), ui_kit::Button::Enabled(app.agent_chat.detecting.is_none())).clicked() { + if app.services.browser_agent.is_none() + && ui_kit::button(ui, tr("ui.agent_chat_refresh"), ui_kit::Button::Enabled(app.agent_chat.detecting.is_none())).clicked() + { refresh(app, &ui.ctx().clone()); } }); }); if let Some(e) = test { let key = if e.key { app.services.secrets.as_ref().and_then(|s| s.get(&e.id).ok().flatten()) } else { None }; - let started = start_test(app, &e, key); + let started = start_test(app, &e, key, ui.ctx()); app.agent_chat.settings.tests.insert(e.id.clone(), started); } if let Some(id) = edit { @@ -825,7 +898,23 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { { b.set_reasoning_effort(&effort); } + if let Some(id) = delete_key { + if let Some(store) = &app.services.secrets + && let Err(error) = store.delete(&id) + { + app.agent_chat.notice(error, true); + } + if let Some(agent) = app.preferences.agents.iter_mut().find(|agent| agent.id == id) { + agent.key = false; + } + if app.agent_chat.running_id == id { + disconnect(app); + } + } if let Some(id) = remove { + if app.services.browser_agent.is_some() && app.agent_chat.running_id == id { + disconnect(app); + } app.agent_chat.login_results.remove(&id); app.agent_chat.settings.tests.remove(&id); app.preferences.agents.retain(|a| a.id != id); @@ -857,6 +946,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { #[cfg(target_arch = "wasm32")] let found: Vec = Vec::new(); let has_keychain = app.services.secrets.is_some(); + let browser = app.services.browser_agent.is_some(); let mut open = true; let mut add = false; let mut test = false; @@ -877,8 +967,15 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::row(ui, tr("ui.ai_kind"), |ui| { let mut selected = kinds.iter().position(|(k, _)| *k == s.kind).unwrap_or(0); let labels = kinds.map(|(_, key)| tr(key)); - if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { compact: true, ..Default::default() }) - && let Some((kind, _)) = kinds.get(selected) + let enabled = [!browser, !browser, true]; + let reason = browser.then(|| tr("vm.agent.runtime_required")); + let disabled = [reason, reason, None]; + if ui_kit::segmented( + ui, + &mut selected, + &labels, + ui_kit::Segments { compact: true, enabled: &enabled, disabled: &disabled, ..Default::default() }, + ) && let Some((kind, _)) = kinds.get(selected) { s.kind = *kind; s.error = None; @@ -890,6 +987,9 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { } } }); + if browser { + ui_kit::text(ui, tr("vm.agent.runtime_required"), ui_kit::Text::Note("browser_runtime")); + } } match s.kind { AddKind::Installed => { @@ -939,7 +1039,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { compact: true, ..Default::default() }) && let Some(protocol) = [Protocol::OpenAi, Protocol::Anthropic].get(selected) { - choose_preset(s, *protocol, 0); + choose_endpoint(s, *protocol, 0, browser); } for (name, key) in [("openai", "ui.ai_add_api"), ("anthropic", "ui.ai_add_anthropic")] { if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_protocol"), tr(key))) { @@ -955,18 +1055,29 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { let response = ui_kit::list_picker(ui, preset, preset, s.preset == index); crate::scenario::publish_handle(&format!("ai_add:preset:{preset}"), response.rect.center()); if response.clicked() { - choose_preset(s, s.protocol, index); + choose_endpoint(s, s.protocol, index, browser); } } }); crate::scenario::publish_handle("ai_add:preset", picker.rect.center()); }); + if browser { + ui_kit::text(ui, tr("vm.agent.preset_note"), ui_kit::Text::Note("browser_presets")); + } ui_kit::row(ui, tr("ui.ai_name"), |ui| { ui_kit::text_field(ui, &mut s.name, ""); }); ui_kit::row(ui, tr("ui.ai_base_url"), |ui| { - s.list_again |= - ui_kit::cell_editor(ui, egui::Id::new("sc_ai_add_url"), &mut s.base_url, tr("ui.ai_url_hint"), false).lost_focus(); + let field = ui_kit::cell_editor(ui, egui::Id::new("sc_ai_add_url"), &mut s.base_url, tr("ui.ai_url_hint"), false); + crate::scenario::publish_target("ai_add:url", field.rect); + s.list_again |= field.lost_focus(); + if browser && field.changed() { + s.preset = agents::presets(s.protocol).len(); + s.key.clear(); + s.saved_key = false; + s.remember_key = false; + s.test = None; + } }); ui_kit::row(ui, tr("ui.ai_model"), |ui| { let (models, note) = listed_for(&app.agent_chat.settings.endpoint_models, s.listing.as_ref()); @@ -1002,13 +1113,27 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { }); ui_kit::row(ui, tr("ui.ai_key"), |ui| { ui.add_enabled_ui(has_keychain, |ui| { - let hint = tr(if s.saved_key { "ui.ai_key_keep_hint" } else { "ui.ai_key_hint" }); + let hint = tr(if s.saved_key && browser { + "vm.agent.key_present" + } else if s.saved_key { + "ui.ai_key_keep_hint" + } else if browser { + "vm.agent.key_hint" + } else { + "ui.ai_key_hint" + }); let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, hint); crate::scenario::publish_target("ai_add:key", r.rect); s.list_again |= r.lost_focus(); }); }); - ui_kit::text(ui, tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }), ui_kit::Text::Note("keychain")); + if browser { + let response = ui_kit::checkbox(ui, tr("vm.agent.remember_key"), &mut s.remember_key); + crate::scenario::publish_handle("ai_add:remember", response.rect.center()); + ui_kit::text(ui, tr("vm.agent.key_note"), ui_kit::Text::Note("browser_key")); + } else { + ui_kit::text(ui, tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }), ui_kit::Text::Note("keychain")); + } if ui_kit::button(ui, tr("ui.ai_test"), ui_kit::Button::Normal).clicked() { test = true; } @@ -1024,41 +1149,46 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { } add |= action == ui_kit::Action::Ok; open &= !closed && action != ui_kit::Action::Cancel; - #[cfg(not(target_arch = "wasm32"))] list_for_dialog(app, ctx); - if test { - #[cfg(not(target_arch = "wasm32"))] - if let Some(s) = app.agent_chat.settings.add.as_ref() { - let url = agents::normalize_url(&s.base_url); - let e = agents::Entry { - id: String::new(), - name: s.name.clone(), - kind: s.protocol.kind(), - argv: Vec::new(), - version: None, - login: "", - found: false, - base_url: url.clone().unwrap_or_default(), - model: s.model.trim().to_string(), - key: false, - request_timeout_s: s.request_timeout_s, - reasoning_effort: agents::reasoning_effort(&s.reasoning_effort), - problem: None, - install: "", - }; - // Editing with the key field left empty tests with the stored key, which is only ever - // sent where a saved key may go (HTTPS or this computer). - let key = Some(s.key.trim().to_string()).filter(|k| !k.is_empty()).or_else(|| { - let id = s.editing.as_deref().filter(|_| s.saved_key && url.as_deref().is_ok_and(agents::key_safe_for))?; - app.services.secrets.as_ref().and_then(|store| store.get(id).ok().flatten()) - }); - let result = match url { - Ok(_) => start_test(app, &e, key), - Err(err) => Test::Done(Err(TestError::Other(err))), - }; - if let Some(s) = app.agent_chat.settings.add.as_mut() { - s.test = Some(result); - } + if test && let Some(s) = app.agent_chat.settings.add.as_ref() { + let url = agents::normalize_url(&s.base_url); + let e = agents::Entry { + id: String::new(), + name: s.name.clone(), + kind: s.protocol.kind(), + argv: Vec::new(), + version: None, + login: "", + found: false, + base_url: url.clone().unwrap_or_default(), + model: s.model.trim().to_string(), + key: false, + request_timeout_s: s.request_timeout_s, + reasoning_effort: agents::reasoning_effort(&s.reasoning_effort), + problem: None, + install: "", + }; + // Editing with the key field left empty tests with the stored key, which is only ever + // sent where a saved key may go (HTTPS or this computer). + let key = Some(s.key.trim().to_string()).filter(|k| !k.is_empty()).or_else(|| { + let id = s.editing.as_deref().filter(|_| { + s.saved_key + && url.as_deref().is_ok_and(agents::key_safe_for) + && (app.services.browser_agent.is_none() + || app.preferences.agents.iter().any(|old| { + Some(old.id.as_str()) == s.editing.as_deref() + && old.kind == s.protocol.kind() + && url.as_deref() == Ok(old.base_url.as_str()) + })) + })?; + app.services.secrets.as_ref().and_then(|store| store.get(id).ok().flatten()) + }); + let result = match url { + Ok(_) => start_test(app, &e, key, ctx), + Err(err) => Test::Done(Err(TestError::Other(err))), + }; + if let Some(s) = app.agent_chat.settings.add.as_mut() { + s.test = Some(result); } } if add { @@ -1102,7 +1232,7 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { } AddKind::Api => { c.kind = s.protocol.kind(); - c.ollama = s.protocol == Protocol::OpenAi && s.preset == 0; + c.ollama = app.services.browser_agent.is_none() && s.protocol == Protocol::OpenAi && s.preset == 0; c.base_url = agents::normalize_url(&s.base_url)?; c.model = s.model.trim().to_string(); c.request_timeout_s = s.request_timeout_s.clamp(agents::MIN_REQUEST_TIMEOUT_S, agents::MAX_REQUEST_TIMEOUT_S); @@ -1112,7 +1242,12 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { } key = Some(s.key.trim().to_string()).filter(|k| !k.is_empty()); // Editing with the key field left empty keeps the stored key. - let kept = key.is_none() && editing.is_some() && s.saved_key; + let kept = key.is_none() + && editing.is_some() + && s.saved_key + && (app.services.browser_agent.is_none() + || editing + .is_some_and(|index| app.preferences.agents.get(index).is_some_and(|old| old.base_url == c.base_url && old.kind == c.kind))); if (key.is_some() || kept) && !agents::key_safe_for(&c.base_url) { return Err(tr("ui.ai_key_needs_https").to_string()); } @@ -1126,11 +1261,24 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { if c.name.is_empty() { c.name = c.id.clone(); } + if app.services.browser_agent.is_some() + && let Some(index) = editing + && let Some(old) = app.preferences.agents.get(index) + && (old.base_url != c.base_url || old.kind != c.kind) + && let Some(store) = &app.services.secrets + { + store.delete(&c.id)?; + } if let Some(k) = key { let Some(store) = &app.services.secrets else { return Err(tr("ui.ai_no_keychain").to_string()) }; - store.set(&c.id, &k).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)]))?; + store.set(&c.id, &k).map_err(|e| secret_error(e, app.services.browser_agent.is_some()))?; c.key = true; } + if app.services.browser_agent.is_some() + && let Some(store) = &app.services.secrets + { + store.remember(&c.id, s.remember_key)?; + } let Some(at) = editing else { app.preferences.agents.push(c); return Ok(()); @@ -1154,7 +1302,9 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> { app.agent_chat.login_results.remove(&id); // The running conversation takes a new timeout from its next request on; the rest // applies the next time the agent connects. - if app.agent_chat.running_id == id + if app.services.browser_agent.is_some() && app.agent_chat.running_id == id { + disconnect(app); + } else if app.agent_chat.running_id == id && let Some(b) = app.agent_chat.backend.as_mut() { b.set_request_timeout(secs); @@ -1172,6 +1322,36 @@ mod card_tests { use crate::scenario::{self, Harness}; use serde_json::json; + #[test] + fn browser_preset_changes_never_carry_a_key_to_another_endpoint() { + let mut s = AddState { + protocol: Protocol::OpenAi, + base_url: "https://old.example/v1".into(), + key: "synthetic-key".into(), + saved_key: true, + remember_key: true, + ..Default::default() + }; + choose_endpoint(&mut s, Protocol::Anthropic, 0, true); + assert_eq!(s.base_url, agents::ANTHROPIC_PRESETS[0].base_url); + assert!(s.key.is_empty()); + assert!(!s.saved_key && !s.remember_key); + s.key = "new-synthetic-key".into(); + s.saved_key = true; + choose_endpoint(&mut s, Protocol::Anthropic, 0, true); + assert_eq!(s.key, "new-synthetic-key", "the same endpoint retains its draft credential"); + choose_endpoint(&mut s, Protocol::Anthropic, agents::ANTHROPIC_PRESETS.len(), true); + assert!(s.base_url.is_empty() && s.key.is_empty() && !s.saved_key); + } + + #[test] + fn native_presets_keep_the_original_key_behaviour() { + let mut s = AddState { key: "synthetic-key".into(), saved_key: true, ..Default::default() }; + choose_endpoint(&mut s, Protocol::Anthropic, 0, false); + assert_eq!(s.key, "synthetic-key"); + assert!(s.saved_key); + } + #[test] fn cached_model_warning_follows_endpoint_model_and_agent_selection() { let mut h = Harness::new(); @@ -1687,3 +1867,34 @@ mod card_tests { assert_eq!(seen.lock().unwrap().len(), 1, "listed once"); } } + +#[cfg(target_arch = "wasm32")] +fn start_listing(app: &mut SolveApp, ctx: &egui::Context, key: ListingKey, secret: impl FnOnce() -> Result, String> + Send + 'static) { + let state = &mut app.agent_chat.settings; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + if state.endpoint_models.len() >= ENDPOINT_LISTINGS_CAP { + state.endpoint_models.clear(); + } + let result = secret().and_then(|secret| { + app.services + .browser_agent + .as_ref() + .map(|service| (service.list)(key.0, key.1.clone(), secret, ctx.clone())) + .ok_or_else(|| tr("ui.ai_no_http").to_string()) + }); + match result { + Ok(rx) => state.listing = Some(ModelListing { key, rx }), + Err(error) => { + state.endpoint_models.insert(key, Err(error)); + } + } +} +#[cfg(target_arch = "wasm32")] +fn start_test(app: &SolveApp, entry: &agents::Entry, key: Option, ctx: &egui::Context) -> Test { + match &app.services.browser_agent { + Some(service) => Test::Running((service.test)(entry.clone(), key, ctx.clone())), + None => Test::Done(Err(TestError::Other(tr("ui.ai_no_http").into()))), + } +} diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 0d151563f..5aa7b0ff3 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1,4 +1,44 @@ use super::*; + +#[test] +fn browser_drop_results_preserve_all_files_and_respect_the_attachment_limit() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let ctx = crate::fonts::test_context(); + let (tx, rx) = channel(); + assert_eq!(receive_browser_attachments(&mut app, 2, rx), attach::MAX_FILES); + for name in ["first.md", "second.svg"] { + tx.send(Ok(attach::Attachment { id: 0, name: name.into(), content: attach::Content::Text(std::sync::Arc::new("test".into())), thumb: None })) + .unwrap(); + } + drop(tx); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.attachments.iter().map(|file| file.name.as_str()).collect::>(), ["first.md", "second.svg"]); + assert!(app.agent_chat.browser_attachment.is_none()); + let (tx, rx) = channel(); + assert_eq!(receive_browser_attachments(&mut app, 20, rx), attach::MAX_FILES - 2); + for i in 0..20 { + tx.send(Ok(attach::Attachment { + id: 0, + name: format!("{i}.txt"), + content: attach::Content::Text(std::sync::Arc::new("test".into())), + thumb: None, + })) + .unwrap(); + } + drop(tx); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES); +} + +#[test] +fn clearing_a_chat_discards_its_pending_browser_file_receiver() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let (tx, rx) = channel(); + receive_browser_attachments(&mut app, 1, rx); + new_chat(&mut app); + assert!(tx.send(Err("late file from previous account".into())).is_err()); + assert!(app.agent_chat.attachments.is_empty()); +} use std::sync::mpsc::channel; fn transcript_clipboard_harness(layout: crate::shell::LayoutMode) -> crate::scenario::Harness { @@ -4459,3 +4499,196 @@ fn a_picture_only_prompt_and_a_thought_have_no_copy_message_action() { assert!(crate::scenario::handle_at("agent_chat:copy:1").is_none(), "a thought has no copy action"); assert!(h.widget("Copy message").is_none(), "nothing to click"); } + +#[test] +fn platform_turn_ignores_a_saved_local_assistant_change_limit() { + let (mut app, tx) = app_in_a_turn(); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + app.preferences.agent_chat_turn_limit = 1; + for i in 0..3 { + let response = ask(&tx, "engine.execute", boxed(f64::from(i) * 20.0)); + frame(&mut app); + assert_eq!(response.try_recv().unwrap()["ok"], true); + } + assert_eq!(app.session.model.state().bodies.len(), 3); + assert_eq!(app.agent_chat.turn.as_ref().unwrap().changes, 3); + assert_eq!(app.preferences.agent_chat_turn_limit, 1, "the native assistant preference is preserved"); +} + +#[test] +fn platform_assistant_is_a_permanent_full_height_right_column() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for (width, height) in [(1440, 1000), (1024, 720), (821, 600)] { + let mut h = narrow_chat(); + h.app.home.open = false; + h.app.platform.enabled = true; + h.app.ui.layout = layout; + h.app.preferences.agent_chat_side = "left".into(); + h.app.preferences.agent_chat_minimized = true; + h.app.preferences.agent_chat_popped = true; + h.app.agent_chat.open = false; + h.call("ui.resize", json!({"width":width,"height":height})); + h.frames(4); + let panel = crate::scenario::rect_of("agent_chat:panel").expect("permanent assistant"); + let bar = crate::scenario::rect_of("platform:appbar").expect("CAD menu bar"); + let header = crate::scenario::rect_of("agent_chat:header").expect("assistant title bar"); + assert!(panel.top().abs() < 1.0 && (panel.bottom() - height as f32).abs() < 1.0, "full height: {panel:?}"); + assert!((panel.right() - width as f32).abs() < 1.0, "right edge: {panel:?}"); + assert!(panel.width() <= width as f32 * 0.5 + 1.0, "the CAD column keeps at least half the page"); + assert!((bar.right() - panel.left()).abs() < 1.0, "the menu ends at the divider"); + assert!((bar.top() - header.top()).abs() < 1.0 && (bar.height() - header.height()).abs() < 1.0, "aligned title bars"); + assert!((header.height() - 42.0).abs() < 1.0); + assert!(h.app.viewport.rect.expect("model viewport").right() <= panel.left() + 1.0, "the model viewport excludes the assistant"); + for handle in ["close", "minimize", "pop_out", "grip"] { + assert!(crate::scenario::handle_at(&format!("agent_chat:{handle}")).is_none(), "no {handle} affordance"); + } + assert!(crate::scenario::handle_at("agent_chat:newchat").is_some()); + assert!(crate::scenario::handle_at("agent_chat:input").is_some()); + panel::toggle(&mut h.app); + panel::toggle(&mut h.app); + h.call("ui.agent_chat", json!({"open":false,"minimized":true,"popped":true,"side":"left"})); + h.frames(3); + assert!(h.app.agent_chat.open); + let state = status(&h.app); + assert_eq!(state["side"], "right"); + assert_eq!(state["minimized"], false); + assert_eq!(state["popped"], false); + assert_eq!(platform_status(&h.app)["fullHeight"], true); + assert!(h.app.preferences.agent_chat_minimized && h.app.preferences.agent_chat_popped, "standalone preferences survive"); + } + } +} + +#[test] +fn platform_assistant_header_stays_aligned_at_cad_ui_zoom_levels() { + for zoom in [0.8, 1.0, 1.25] { + let mut h = narrow_chat(); + h.app.home.open = false; + h.app.platform.enabled = true; + h.app.preferences.ui_scale = zoom; + h.ctx.set_zoom_factor(zoom); + h.frames(4); + let header = crate::scenario::rect_of("agent_chat:header").unwrap(); + let bar = crate::scenario::rect_of("platform:appbar").unwrap(); + assert!((header.height() * zoom - 42.0).abs() < 1.0, "zoom {zoom}: {header:?}"); + assert!((bar.height() - header.height()).abs() < 1.0); + } +} + +#[test] +fn platform_manual_edit_invalidates_queued_tools_and_keeps_undo_separate() { + let mut app = SolveApp::new(Default::default(), Default::default()); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + start_turn(&mut app, "Create box".into(), false, None, Vec::new()); + let active = app.agent_chat.turn.as_ref().unwrap().active.clone(); + with_tool_request(&mut app, Some(&active), |app| app.run("solid.box", json!({"length":2,"width":3,"height":4,"body_name":"AI"}))).unwrap(); + let (mut late, receiver) = ControlRequest::new("engine.execute", json!({"command":"solid.box","params":{}})); + late.chat_turn = Some(active.clone()); + app.run("solid.box", json!({"length":3,"width":4,"height":5,"body_name":"Human"})).unwrap(); + assert!(!active.load(std::sync::atomic::Ordering::Relaxed)); + assert!(late.refuse_cancelled_chat()); + assert_eq!(receiver.try_recv().unwrap()["ok"], false); + assert_eq!(app.session.undo.len(), 2); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.model.state().bodies.len(), 1); + assert!(app.session.model.state().bodies.iter().any(|body| body.name == "AI")); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.model.state().bodies.is_empty()); +} + +#[test] +fn platform_refresh_and_selection_do_not_stop_error_recovery() { + let mut app = SolveApp::new(Default::default(), Default::default()); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + start_turn(&mut app, "Create box".into(), false, None, Vec::new()); + let active = app.agent_chat.turn.as_ref().unwrap().active.clone(); + let revision = app.session.revision; + app.run("select.clear", json!({})).unwrap(); + app.session.refresh(); + assert!(app.session.revision > revision); + poll(&mut app, &egui::Context::default()); + assert!(active.load(std::sync::atomic::Ordering::Relaxed)); + assert!(app.agent_chat.turn.is_some()); + assert!(platform_tool_valid(&mut app)); +} + +#[test] +fn platform_failed_batch_can_be_corrected_after_rollback() { + let mut app = SolveApp::new(Default::default(), Default::default()); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + start_turn(&mut app, "Create box".into(), false, None, Vec::new()); + let active = app.agent_chat.turn.as_ref().unwrap().active.clone(); + let (mut req, _receiver) = ControlRequest::new( + "engine.batch", + json!({"commands":[ + {"command":"solid.box","params":{"length":2,"width":3,"height":4}}, + {"command":"parameters.change","params":{"name":"missing?","expression":"3 mm"}} + ]}), + ); + req.chat_turn = Some(active.clone()); + let crate::control::Outcome::Done(outcome) = crate::control::handle(&mut app, &egui::Context::default(), &req) else { + panic!("a batch returns its result synchronously"); + }; + assert_eq!(outcome["result"]["rolled_back"], true, "{outcome}"); + assert!(app.session.model.state().bodies.is_empty()); + app.session.refresh(); + poll(&mut app, &egui::Context::default()); + assert!(platform_tool_valid(&mut app)); + with_tool_request(&mut app, Some(&active), |app| app.run("solid.box", json!({"length":2,"width":3,"height":4}))).unwrap(); + assert_eq!(app.session.model.state().bodies.len(), 1); +} + +#[test] +fn platform_direct_document_change_still_stops_the_turn() { + let mut app = SolveApp::new(Default::default(), Default::default()); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + start_turn(&mut app, "Create box".into(), false, None, Vec::new()); + let active = app.agent_chat.turn.as_ref().unwrap().active.clone(); + app.session.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); + poll(&mut app, &egui::Context::default()); + assert!(!active.load(std::sync::atomic::Ordering::Relaxed)); + assert!(app.agent_chat.turn.is_none()); +} + +#[test] +fn platform_stale_approval_does_not_execute_or_remember_a_grant() { + let mut app = SolveApp::new(Default::default(), Default::default()); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + start_turn(&mut app, "Create box".into(), false, None, Vec::new()); + let (mut req, receiver) = ControlRequest::new("engine.execute", json!({"command":"solid.box","params":{}})); + req.chat_turn = app.agent_chat.turn.as_ref().map(|turn| turn.active.clone()); + app.agent_chat.items.push(Item::Approval { id: 1, title: "solid.box".into(), tool: "solid.box".into(), answer: None }); + app.agent_chat.held.push(Held { id: 1, req, since: 0.0 }); + app.session.execute("solid.box", &json!({"length":2,"width":3,"height":4})).unwrap(); + approve_always(&mut app, 1); + assert_eq!(receiver.try_recv().unwrap()["ok"], false); + assert!(app.agent_chat.held.is_empty()); + assert!(app.preferences.agent_always_allow.is_empty()); + assert_eq!(app.session.model.state().bodies.len(), 1); +} + +#[test] +fn platform_stop_rejects_unadmitted_tools_before_the_next_turn() { + let mut app = SolveApp::new(Default::default(), Default::default()); + app.platform.enabled = true; + app.platform.agent_context = Some("test-binding".into()); + let (tx, rx) = channel(); + app.agent_chat.tools_rx = Some(rx); + start_turn(&mut app, "Create box".into(), false, None, Vec::new()); + let (req, response) = ControlRequest::new("engine.execute", json!({"command":"solid.box","params":{"length":2,"width":3,"height":4}})); + tx.send(req).unwrap(); + cancel(&mut app); + start_turn(&mut app, "Read latest design".into(), false, None, Vec::new()); + pump_tools(&mut app); + assert_eq!(response.try_recv().unwrap()["ok"], false, "Stop also rejects requests that have not reached the approval gate"); + assert!(app.agent_chat.held.is_empty(), "the old tool must not request approval in the new turn"); + assert!(app.control_held.is_empty()); + assert_eq!(app.agent_chat.turn.as_ref().unwrap().requests, 0); + assert!(app.session.model.state().bodies.is_empty()); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7aea70fe4..1e18b4d93 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -518,6 +518,9 @@ pub fn view_png(app: &SolveApp, w: u32, h: u32) -> Result, String> { } pub fn handle(app: &mut SolveApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + if req.chat_turn.is_some() && !crate::agent_chat::platform_tool_valid(app) { + return err("STALE_AGENT_CONTEXT_OR_INTERACTION"); + } crate::agent_chat::with_tool_request(app, req.chat_turn.as_ref(), |app| handle_request(app, ctx, req)) } @@ -603,6 +606,13 @@ fn switch_checked(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Val } fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> Outcome { + if app.platform.enabled && matches!(method, "ui.documents" | "ui.home" | "app.quit") { + return err("HOST_MANAGED_DOCUMENT: use window.vibemakeCad"); + } + if app.platform.is_locked() && !matches!(method, "engine.commands" | "document.inspect" | "ui.state") { + return err("HOST_INTERACTION_LOCKED"); + } + crate::render_workspace::sync_backend(app); let s = |k: &str| p.get(k).and_then(Value::as_str); let f = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()); @@ -1315,6 +1325,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> }; // What drew it (gpu, gpu-software or cpu), and the warning a CPU render carries. let (renderer, warning) = (png.renderer, solidcraft_engine::capture::warning(png.renderer)); + if p.get("inline").and_then(Value::as_bool) == Some(true) { + return ok(json!({"bytes": png.bytes.len(), "renderer": renderer, "warning": warning, + "pngBase64": crate::agent_chat::backend::base64(&png.bytes)})); + } match s("path") { Some(path) => match vfs::check(path).and_then(|()| std::fs::write(path, &png.bytes)) { Ok(()) => ok(json!({"path": path, "bytes": png.bytes.len(), "renderer": renderer, "warning": warning})), @@ -1781,6 +1795,23 @@ mod tests { std::fs::read(path).unwrap() } + #[test] + fn inline_model_render_returns_png_without_writing_a_file() { + if !crate::gpu::test_picture_renderer() { + return; + } + let mut app = SolveApp::new(Session::default(), Services::default()); + let (request, _reply) = ControlRequest::new("ui.render", json!({"width": 32, "height": 24, "inline": true})); + match handle(&mut app, &crate::fonts::test_context(), &request) { + Outcome::Done(value) => { + assert_eq!(value["ok"], true, "{value}"); + assert_eq!(value["result"]["bytes"].as_u64().is_some(), true); + assert!(value["result"]["pngBase64"].as_str().is_some_and(|png| png.starts_with("iVBORw0KGgo"))); + } + Outcome::Screenshot { .. } => panic!("ui.render took a screenshot"), + } + } + /// `ui.render` draws in the window's theme (#974): its background is the viewport's, light /// or dark, and with the 3D view in the other theme's colours, the view's (#4146). #[test] @@ -2625,4 +2656,24 @@ mod tests { assert_eq!(r["ok"], true, "{r}"); assert_eq!(r["result"]["open"], true, "the sample was asked for: {r}"); } + #[test] + fn vibemake_platform_rejects_rebinding_and_locks_programmatic_edits() { + let mut h = crate::scenario::Harness::new(); + h.app.enable_vibemake(); + let result = h.call("ui.documents", json!({"action":"new"})); + assert_eq!(result["ok"], false); + h.app.platform.locked.store(false, std::sync::atomic::Ordering::Relaxed); + for command in ["file.new", "doc.open", "file.save", "file.save_as"] { + let result = h.call("engine.execute", json!({"command":command,"params":{}})); + assert_eq!(result["ok"], false, "{result}"); + assert!(result["error"].as_str().unwrap_or_default().contains("HOST_MANAGED_DOCUMENT"), "{result}"); + } + let name = h.app.session.doc.name.clone(); + crate::documents::new_design(&mut h.app); + assert_eq!(h.app.platform.intent, Some("new")); + assert_eq!(h.app.session.doc.name, name); + h.app.platform.locked.store(true, std::sync::atomic::Ordering::Relaxed); + assert!(!h.app.platform_snapshot_available() || h.app.session.pending_moves.is_empty()); + assert!(h.app.session.execute("file.new", &json!({})).is_err()); + } } diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 0107729e3..bc883fbd2 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -476,6 +476,10 @@ pub fn adopt(app: &mut SolveApp, session: Session) { /// takes Units of new designs (#1205): a launch starts on that empty design, so returning /// here used to leave it in millimetres. pub fn new_design(app: &mut SolveApp) { + if app.platform.enabled { + app.platform.intent = Some("new"); + return; + } if app.file_picker_busy() { return; } @@ -494,6 +498,10 @@ pub fn new_design(app: &mut SolveApp) { /// Create a new tab directly; the File view chooses units before using [`new_design`]. /// An untouched blank launch design is reused. pub fn new_tab(app: &mut SolveApp) { + if app.platform.enabled { + app.platform.intent = Some("new"); + return; + } if app.file_picker_busy() { return; } @@ -513,6 +521,10 @@ pub fn new_tab(app: &mut SolveApp) { /// new or already showing, takes Units of new designs so a cancelled open is not millimetres /// when the preference says otherwise. pub fn prepare_open(app: &mut SolveApp) { + if app.platform.enabled { + app.platform.intent = Some("new"); + return; + } if active_is_blank(app) { crate::prefs::apply_new_design(app); return; @@ -526,6 +538,9 @@ pub fn prepare_open(app: &mut SolveApp) { /// Close tab `i`: asks first when it has unsaved changes (`force`: close anyway). pub fn close(app: &mut SolveApp, i: usize, force: bool) { + if app.platform.enabled { + return; + } if app.file_picker_busy() { return; } diff --git a/crates/ui-egui/src/help.rs b/crates/ui-egui/src/help.rs index 6de7e260c..8f902da5d 100644 --- a/crates/ui-egui/src/help.rs +++ b/crates/ui-egui/src/help.rs @@ -51,6 +51,9 @@ pub fn available(app: &SolveApp, item: &str) -> bool { /// `connect`, `install_cli` (macOS). pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) { app.help.menu = false; + if app.platform.enabled && !matches!(item, "about" | "shortcuts" | "messages") { + return; + } if !available(app, item) { return; } @@ -146,13 +149,15 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) { ] .into_iter() .filter(|(id, ..)| *id != "install_cli" || cfg!(target_os = "macos")) + .filter(|(id, ..)| !app.platform.enabled || matches!(*id, "about" | "shortcuts" | "messages")) { + let label = if app.platform.enabled && id == "about" { app.tr("vibemake.about") } else { label }; let item = crate::context_menu::Item::action(id, label, icon).on_if(available(app, id)); if crate::context_menu::list_row(ui, &item).is_some() { pick = Some(id); } // A layout without the version in the application bar lists it here. - if id == "about" && app.header.version == crate::toolbar::VersionPlace::HelpMenu { + if !app.platform.enabled && id == "about" && app.header.version == crate::toolbar::VersionPlace::HelpMenu { let label = crate::i18n::format("help.version", &[("version", crate::update::current_version())]); if crate::context_menu::list_row(ui, &crate::context_menu::Item::action("version", &label, "update")).is_some() { pick = Some("version"); @@ -181,49 +186,57 @@ fn about(app: &mut SolveApp, ctx: &egui::Context) { if !app.help.about { return; } - let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_about"), "help", crate::i18n::tr_label("About SolidCraft")) - .cards(2.0) - .actions("", "Close", None) - .show(ctx, true, |ui| { - ui_kit::text( - ui, - &crate::i18n::format("help.build", &[("version", VERSION), ("commit", COMMIT), ("date", BUILD_DATE)]), - ui_kit::Text::Report("version", false), - ); - ui_kit::text( - ui, - crate::i18n::tr_label("Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0."), - ui_kit::Text::Note("description"), - ); - let copy = ui_kit::button(ui, crate::i18n::tr_label("Copy diagnostic information"), ui_kit::Button::Normal); - crate::scenario::publish_target("about:copy_diagnostics", copy.rect); - if copy.clicked() { - ctx.copy_text(diagnostics(app)); - } - egui::ScrollArea::vertical().max_height(crate::theme::Tokens::get().control_height * 15.0).show(ui, |ui| { - ui_kit::section(ui, "attributions", crate::i18n::tr("help.attributions"), false, |ui| { - ui_kit::text(ui, ATTRIBUTION, ui_kit::Text::Report("attributions", false)); - }); - ui_kit::section(ui, "fonts", crate::i18n::tr("help.fonts"), false, |ui| { - ui_kit::text(ui, crate::i18n::tr("help.font_details"), ui_kit::Text::Report("fonts", false)); - }); - ui_kit::section(ui, "licences", crate::i18n::tr("help.licences"), false, |ui| { - for (id, title, text) in - [("notice", "help.notice", NOTICE), ("mit", "help.mit", LICENSE_MIT), ("apache", "help.apache", LICENSE_APACHE)] - { - ui_kit::section(ui, id, crate::i18n::tr(title), false, |ui| { - ui_kit::text(ui, text, ui_kit::Text::Report(id, false)); - }); - } - ui_kit::section(ui, "third_party", crate::i18n::tr("help.third_party"), false, |ui| { - if ui_kit::button(ui, crate::i18n::tr_label("Copy all licences"), ui_kit::Button::Normal).clicked() { - ctx.copy_text(solidcraft_engine::licences::all()); - } - ui_kit::text_lines(ui, "sc_third_party", THIRD_PARTY); + let (closed, action) = ui_kit::Window::new( + egui::Id::new("sc_about"), + "help", + if app.platform.enabled { crate::i18n::tr("vibemake.about") } else { crate::i18n::tr_label("About SolidCraft") }, + ) + .cards(2.0) + .actions("", "Close", None) + .show(ctx, true, |ui| { + ui_kit::text( + ui, + &crate::i18n::format("help.build", &[("version", VERSION), ("commit", COMMIT), ("date", BUILD_DATE)]), + ui_kit::Text::Report("version", false), + ); + ui_kit::text( + ui, + if app.platform.enabled { + crate::i18n::tr("vibemake.description") + } else { + crate::i18n::tr_label("Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.") + }, + ui_kit::Text::Note("description"), + ); + let copy = ui_kit::button(ui, crate::i18n::tr_label("Copy diagnostic information"), ui_kit::Button::Normal); + crate::scenario::publish_target("about:copy_diagnostics", copy.rect); + if copy.clicked() { + ctx.copy_text(diagnostics(app)); + } + egui::ScrollArea::vertical().max_height(crate::theme::Tokens::get().control_height * 15.0).show(ui, |ui| { + ui_kit::section(ui, "attributions", crate::i18n::tr("help.attributions"), false, |ui| { + ui_kit::text(ui, ATTRIBUTION, ui_kit::Text::Report("attributions", false)); + }); + ui_kit::section(ui, "fonts", crate::i18n::tr("help.fonts"), false, |ui| { + ui_kit::text(ui, crate::i18n::tr("help.font_details"), ui_kit::Text::Report("fonts", false)); + }); + ui_kit::section(ui, "licences", crate::i18n::tr("help.licences"), false, |ui| { + for (id, title, text) in + [("notice", "help.notice", NOTICE), ("mit", "help.mit", LICENSE_MIT), ("apache", "help.apache", LICENSE_APACHE)] + { + ui_kit::section(ui, id, crate::i18n::tr(title), false, |ui| { + ui_kit::text(ui, text, ui_kit::Text::Report(id, false)); }); + } + ui_kit::section(ui, "third_party", crate::i18n::tr("help.third_party"), false, |ui| { + if ui_kit::button(ui, crate::i18n::tr_label("Copy all licences"), ui_kit::Button::Normal).clicked() { + ctx.copy_text(solidcraft_engine::licences::all()); + } + ui_kit::text_lines(ui, "sc_third_party", THIRD_PARTY); }); }); }); + }); if closed || action == ui_kit::Action::Cancel { app.help.about = false; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6beed8a9f..c9b93a8ea 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -198,6 +198,7 @@ pub mod params_dialog; pub mod personal_sheet_rules; pub(crate) mod pick_index; pub(crate) mod place_gizmo; +pub mod platform; pub(crate) mod plugins; pub mod point_clouds; pub mod prefs; @@ -475,6 +476,7 @@ pub struct Services { pub browser_files: Option>, /// HTTP for the agent chat's API agents (OpenAI-compatible and Anthropic-compatible endpoints); None: no API agents. pub agent_http: Option, + pub browser_agent: Option, /// The system keychain, for API agents' keys; None: keys can't be stored. pub secrets: Option>, /// Upload a model to EasyPrint (Printables' slicer in the browser) and answer with the address @@ -514,6 +516,7 @@ pub struct SolveApp { pub(crate) viewport_status_fixture: viewport_status_fixture::Fixture, /// Compact browser embed: retain model panels and joint controls without application chrome. pub embedded: bool, + pub platform: platform::Platform, pub session: Session, pub ui: UiState, pub(crate) shell: shell::State, @@ -905,6 +908,7 @@ impl SolveApp { fit_waits: 0, flat_view: Default::default(), embedded: false, + platform: platform::Platform::default(), home: home::HomeState::default(), space_mouse: Default::default(), file_load: file_load::FileLoad::default(), @@ -1159,6 +1163,13 @@ impl SolveApp { /// Run a command programmatically (JSON parameters, no dialogs). pub fn run(&mut self, id: &str, params: Value) -> Result { + agent_chat::before_command(self, id); + if self.platform.enabled && platform::host_managed(id) { + return Err("HOST_MANAGED_DOCUMENT: use window.vibemakeCad".into()); + } + if self.platform.enabled && platform::unavailable(id) { + return Err("HOST_CAPABILITY_UNAVAILABLE".into()); + } if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() { return Err("a file operation is in progress".into()); } @@ -1550,6 +1561,23 @@ impl SolveApp { } fn start_with_variant_memory(&mut self, id: &str, remember_variant: bool, opener: Option, section_edit: bool) { + agent_chat::before_command(self, id); + if self.platform.enabled { + let intent = match id { + "file.new" => Some("new"), + "doc.open" => Some("open"), + "file.save" => Some("save"), + "file.save_as" => Some("saveAs"), + _ => None, + }; + if let Some(intent) = intent { + self.platform.intent = Some(intent); + return; + } + if platform::unavailable(id) || self.platform.is_locked() { + return; + } + } self.tree.clear_folder_pick(); if id == "timeline.play" { if let Err(why) = self.run(id, json!({})) { @@ -2894,6 +2922,11 @@ impl SolveApp { /// The frame's input before the app reads it: synthetic events, then what is typed while a /// capture hides the report waits for it (the control channel's typing too). pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) { + if self.platform.is_locked() { + raw.events.clear(); + raw.dropped_files.clear(); + return; + } self.synthetic_input(raw); issue_report::hold_input(self, raw); } @@ -2944,6 +2977,9 @@ impl SolveApp { /// Lay out the whole window. pub fn ui(&mut self, ui: &mut egui::Ui) { + if self.platform.is_locked() { + ui.disable(); + } let blur_source = !self.home.open && !render_workspace::result_active(self); let _blur_scope = self.blur.begin(ui.ctx(), blur_source); value_step::set_enabled(ui.ctx(), self.preferences.step_values); @@ -3006,7 +3042,11 @@ impl SolveApp { self.poll_deferred(ui.ctx()); self.poll_delete_check(ui.ctx()); timeline::tick_playback(self, ui.ctx()); - if !self.embedded { + if self.platform.enabled { + self.home.open = false; + agent_chat::show(self, ui); + platform::app_bar(self, ui); + } else if !self.embedded { toolbar::app_bar(self, ui); } issue_report::CadInput::block(self, ui, report_input); @@ -3045,7 +3085,7 @@ impl SolveApp { } theme::TabAccent::publish(self, ui.ctx()); browser::publish_row_prefs(self, ui.ctx()); - if !floating { + if !floating && !self.platform.enabled { agent_chat::show(self, ui); } if !floating && show_timeline && !left_timeline { @@ -3112,7 +3152,7 @@ impl SolveApp { if self.ui.show_browser && !render_ui::focused(self) { browser::browser(self, ui); } - if floating { + if floating && !self.platform.enabled { agent_chat::show(self, ui); } Container::new(ui.ctx(), Surface::Viewport) diff --git a/crates/ui-egui/src/platform.rs b/crates/ui-egui/src/platform.rs new file mode 100644 index 000000000..e43d0396c --- /dev/null +++ b/crates/ui-egui/src/platform.rs @@ -0,0 +1,146 @@ +//! Product-host policy. Opt-in only: standalone Web, CLI and desktop keep their own workflows. +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; + +use serde_json::Value; + +use crate::SolveApp; + +#[derive(Default)] +pub struct Platform { + pub enabled: bool, + pub agent_context: Option, + pub agent_capabilities: Option, + pub agent_document_session_code: Option, + pub agent_project_code: Option, + pub locked: Arc, + pub intent: Option<&'static str>, + pub menu_request: Option<&'static str>, +} + +pub fn host_managed(id: &str) -> bool { + matches!( + id, + "file.new" | "doc.open" | "doc.recover" | "file.save" | "file.save_as" | "file.close" | "doc.close" | "view.next_tab" | "view.previous_tab" + ) +} + +pub fn unavailable(id: &str) -> bool { + id.starts_with("assistant.") + || id.starts_with("plugin.") + || id.starts_with("agent.") + || id.starts_with("ai.") + || id.starts_with("mcp.") + || matches!( + id, + "file.send_to_slicer" + | "file.easyprint" + | "file.open_in_easyprint" + | "component.insert_design" + | "component.link" + | "component.update_link" + | "component.update_links" + | "component.break_link" + ) +} + +impl Platform { + pub fn is_locked(&self) -> bool { + self.enabled && self.locked.load(Ordering::Relaxed) + } +} + +impl SolveApp { + /// Replace a host-owned project after validation. No hidden document tabs or stale tool state. + pub fn adopt_platform_project(&mut self, session: solidcraft_engine::Session) { + crate::dialogs::cancel(self); + self.tool = None; + self.dialog = None; + self.params = None; + self.editing_state = None; + self.pending_feature_edit = None; + self.pre_sketch_cam = None; + self.pre_sketch_component = None; + self.tree.occurrence_move = None; + self.edit_in_place = Default::default(); + crate::design_properties::close_object(self); + crate::sketch_attachment_ui::clear(self); + self.session.replace_host_design(session); + self.docs = Default::default(); + crate::documents::reset_chat(self); + crate::render_workspace::reset_document(self); + self.home.open = false; + self.ui.ribbon_context = None; + self.ui.sketch_return_tab = None; + self.ui.tab = "MODEL".into(); + self.cam = Default::default(); + self.fit_view(); + } + + pub fn enable_vibemake(&mut self) { + self.platform.enabled = true; + self.platform.locked.store(true, Ordering::Relaxed); + self.home.open = false; + let locked = self.platform.locked.clone(); + self.session.set_command_check(Some(Arc::new(move |id, _, _| { + if host_managed(id) { + return Err("HOST_MANAGED_DOCUMENT: use window.vibemakeCad".into()); + } + if unavailable(id) { + return Err("HOST_CAPABILITY_UNAVAILABLE".into()); + } + if locked.load(Ordering::Relaxed) { + return Err("HOST_INTERACTION_LOCKED".into()); + } + Ok(()) + }))); + } + + /// Safe committed state only. A sketch's committed edits are serializable; a tool preview isn't. + pub fn platform_snapshot_available(&self) -> bool { + !self.file_picker_busy() + && !self.file_load.busy() + && self.saving.is_none() + && self.applying.is_none() + && self.dialog.is_none() + && self.params.is_none() + && self.tool.is_none() + && self.tree.occurrence_move.is_none() + && self.session.pending_moves.is_empty() + } +} + +/// Host chrome is measured in CSS pixels, independently of the CAD UI zoom preference. +pub(crate) fn app_bar_height(ctx: &egui::Context) -> f32 { + 42.0 / ctx.zoom_factor() +} + +/// The HTML product bar overlays the canvas's left column. Reserve its height in CAD too. +pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let host = crate::ui_kit::Container::new(&ctx, crate::ui_kit::Surface::ApplicationBar); + let bar = host.edge("sc_platform_appbar", crate::ui_kit::Edge::Top).exact_size(app_bar_height(&ctx)).resizable(false); + let response = host.show_edge(ui, bar, host.edge_frame(crate::theme::Tokens::get().app_bar), |_| {}); + crate::scenario::publish_rect("platform:appbar", response.response.rect); + if let Some(request) = app.platform.menu_request.take() { + match request { + "file" => { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| { + let id = egui::Id::new("sc_file_menu"); + let open = data.get_temp::(id).unwrap_or(false); + data.insert_temp(id, !open); + data.insert_temp(egui::Id::new("sc_file_menu_x"), 8.0_f32); + data.insert_temp(egui::Id::new("sc_file_menu_opened"), pass); + }); + } + "preferences" => crate::prefs::open_at(app, 0), + "help" => app.help.menu = !app.help.menu, + _ => {} + } + } + crate::toolbar::file_menu(app, &ctx); + crate::help::show(app, &ctx, egui::pos2(8.0, app_bar_height(&ctx))); +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index d8ad6d998..926ddacbb 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -2685,11 +2685,27 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { .actions("OK", "Cancel", Some("Apply")) .apply_enabled(pending); let window = if capturing { window.keep_open_on_escape() } else { window }; + // Platform hides unintegrated agent/plugin pages and keeps stable underlying page indices. + let platform_pages: Vec<_> = WINDOW_PAGES + .iter() + .take(PAGE_ASSISTANT) + .map(|page| ui_kit::WindowPage { + icon: page.icon, + label: page.label, + group: page.group, + handle: page.handle, + scroll: page.scroll, + draw: page.draw, + }) + .collect(); + if app.platform.enabled && app.prefs_window.section >= platform_pages.len() { + app.prefs_window.section = 0; + } let mut selected = app.prefs_window.section; let (closed, action) = window.show_pages_with_header( ctx, &mut selected, - WINDOW_PAGES, + if app.platform.enabled { &platform_pages } else { WINDOW_PAGES }, app, search_header, clear_search, @@ -2784,6 +2800,9 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { // agent list cannot draw on top of the setting that did match. let mut keep = vec![false; WINDOW_PAGES.len()]; for (index, _) in WINDOW_PAGES.iter().enumerate() { + if app.platform.enabled && index >= PAGE_ASSISTANT { + continue; + } crate::prefs_search::begin_page(ui, index, &page_path(index)); let before = crate::prefs_search::hits(ui); let mut probe = crate::prefs_search::detached_child(ui, ("prefs-search-probe", index), true); @@ -2792,6 +2811,9 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { } crate::prefs_search::rewind_search_layout(ui); for (index, _) in WINDOW_PAGES.iter().enumerate() { + if app.platform.enabled && index >= PAGE_ASSISTANT { + continue; + } if !keep.get(index).copied().unwrap_or(false) { continue; } diff --git a/crates/ui-egui/src/prefs/general.rs b/crates/ui-egui/src/prefs/general.rs index 89eda1fb1..b943a6a38 100644 --- a/crates/ui-egui/src/prefs/general.rs +++ b/crates/ui-egui/src/prefs/general.rs @@ -20,17 +20,21 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::i18n::Locale::for_language(&app.preferences.language).display_name().into_owned() }, |ui| { - if ui_kit::list_picker( - ui, - crate::i18n::SYSTEM, - app.tr("prefs.language_system"), - app.preferences.language == crate::i18n::SYSTEM, - ) - .clicked() + if !app.platform.enabled + && ui_kit::list_picker( + ui, + crate::i18n::SYSTEM, + app.tr("prefs.language_system"), + app.preferences.language == crate::i18n::SYSTEM, + ) + .clicked() { app.preferences.language = crate::i18n::SYSTEM.into(); } for locale in crate::i18n::LOCALES { + if app.platform.enabled && !matches!(locale.id, "zh" | "en") { + continue; + } if ui_kit::list_picker(ui, locale.id, &locale.display_name(), app.preferences.language == locale.id).clicked() { app.preferences.language = locale.id.into(); } @@ -41,30 +45,36 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); }); }); - ui_kit::settings_section(ui, "saving", app.tr("prefs.saving"), |ui| { - ui_kit::checkbox(ui, app.tr("Reopen the designs that were open when SolidCraft was last closed"), &mut app.preferences.reopen_designs); - ui_kit::settings_form(ui, labels, |ui| { - let shown = ui_kit::settings_row_help(ui, app.tr("ui.autosave_every"), crate::i18n::tr_label("0 turns it off"), |ui| { - let number = ui_kit::settings_number(ui, &mut app.autosave_minutes, 0.0..=120.0, 0.5); - number.widget_info(|| { - let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), app.autosave_minutes); - info.label = Some(app.tr("prefs.general.minutes").to_owned()); - info + if !app.platform.enabled { + ui_kit::settings_section(ui, "saving", app.tr("prefs.saving"), |ui| { + ui_kit::checkbox( + ui, + app.tr("Reopen the designs that were open when SolidCraft was last closed"), + &mut app.preferences.reopen_designs, + ); + ui_kit::settings_form(ui, labels, |ui| { + let shown = ui_kit::settings_row_help(ui, app.tr("ui.autosave_every"), crate::i18n::tr_label("0 turns it off"), |ui| { + let number = ui_kit::settings_number(ui, &mut app.autosave_minutes, 0.0..=120.0, 0.5); + number.widget_info(|| { + let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), app.autosave_minutes); + info.label = Some(app.tr("prefs.general.minutes").to_owned()); + info + }); + crate::scenario::publish_target("prefs:autosave_minutes", number.rect); + if number.changed() { + set_autosave(app); + } + ui_kit::settings_inline_note(ui, app.tr("prefs.minutes")); + ui.is_visible() }); - crate::scenario::publish_target("prefs:autosave_minutes", number.rect); - if number.changed() { - set_autosave(app); + if shown { + ui_kit::below_row_control(ui, app.tr("ui.autosave_every"), t.space_24 * 10.0 + t.space_16 + t.space_4, |ui| { + ui_kit::settings_autosave_timeline(ui, app.autosave_minutes) + }); } - ui_kit::settings_inline_note(ui, app.tr("prefs.minutes")); - ui.is_visible() }); - if shown { - ui_kit::below_row_control(ui, app.tr("ui.autosave_every"), t.space_24 * 10.0 + t.space_16 + t.space_4, |ui| { - ui_kit::settings_autosave_timeline(ui, app.autosave_minutes) - }); - } }); - }); + } ui_kit::settings_section(ui, "files", app.tr("FILES"), |ui| { file_size_rows(app, ui, labels); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs index b28584ce1..6bad37bba 100644 --- a/crates/ui-egui/src/shortcut_box.rs +++ b/crates/ui-egui/src/shortcut_box.rs @@ -204,6 +204,7 @@ pub fn search(app: &SolveApp, q: &str) -> Vec { let mut v: Vec<(u32, Row)> = command_specs() .into_iter() .filter(|c| !crate::workspace::AGENT_ONLY.contains(&c.id)) + .filter(|c| !app.platform.enabled || (!crate::platform::unavailable(c.id) && !crate::platform::host_managed(c.id))) .filter_map(|c| { let (home_tab, home_panel) = crate::workspace::destination(c).unwrap_or(("", "")); let info = crate::render_workspace::interactive_command_info(app, c); diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index 5bfd14f37..33f687255 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -2380,6 +2380,33 @@ mod tests { } } + #[test] + fn vibemake_brand_theme_keeps_engine_colours_and_viewport_background() { + let file = builtin().iter().find(|theme| theme.id == "vibemake-dark").expect("VibeMake theme is registered"); + let themed = resolve(file); + let original = Tokens::dark(); + assert_eq!(themed.accent, Color32::from_rgb(200, 255, 62)); + assert_eq!(themed.form_primary, themed.accent, "assistant and form actions use the VibeMake brand colour"); + assert_eq!(themed.form_primary_fill, themed.accent); + assert_eq!(themed.on_accent, Color32::from_rgb(13, 18, 3)); + assert_eq!(themed.panel, Color32::from_rgb(15, 17, 20)); + for (name, got, expected) in [ + ("viewport_top", themed.viewport_top, original.viewport_top), + ("viewport_bottom", themed.viewport_bottom, original.viewport_bottom), + ("grid", themed.grid, original.grid), + ("grid_major", themed.grid_major, original.grid_major), + ("axis_x", themed.axis_x, original.axis_x), + ("axis_y", themed.axis_y, original.axis_y), + ("axis_z", themed.axis_z, original.axis_z), + ("selection", themed.sel_face, original.sel_face), + ("warning", themed.warning, original.warning), + ("error", themed.error, original.error), + ("preview", themed.preview_add, original.preview_add), + ] { + assert_eq!(got, expected, "VibeMake must preserve the engine {name} colour"); + } + } + /// CGA uses only the 16 colours of the IBM Color Graphics Adapter (alpha only on translucent /// tokens) and sets every colour, so nothing falls back to Dark's palette. #[test] diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 90885755a..9d622c052 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -399,6 +399,10 @@ pub(crate) fn search_in_header(app: &SolveApp) -> bool { const HEADER_SEARCH_GAP: f32 = 4.0; pub fn app_bar(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.platform.enabled { + crate::platform::app_bar(app, ui); + return; + } let t = Tokens::get(); let app_bar = Container::new(ui.ctx(), Surface::ApplicationBar).edge("sc_appbar", Edge::Top); let frame = Container::new(ui.ctx(), Surface::ApplicationBar).edge_frame(t.app_bar); @@ -706,6 +710,21 @@ impl FileAction { /// Execute through the same document, save-job and preferences paths as the toolbar. pub fn run(&self, app: &mut SolveApp) { + if app.platform.enabled { + let intent = match self { + Self::New => Some("new"), + Self::Open => Some("open"), + Self::SaveAs => Some("saveAs"), + _ => None, + }; + if let Some(intent) = intent { + app.platform.intent = Some(intent); + return; + } + if matches!(self, Self::OpenRecent(_) | Self::ClearRecent | Self::SaveJson | Self::AgentChat | Self::Quit) { + return; + } + } if !self.enabled(app) { return; } @@ -740,7 +759,7 @@ impl FileAction { } } -fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { +pub(crate) fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { let id = egui::Id::new("sc_file_menu"); if !ctx.data(|d| d.get_temp::(id).unwrap_or(false)) { return; @@ -748,7 +767,10 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { let mut close = false; let resp = Container::new(ctx, Surface::Popup) .area(egui::Id::new("sc_file_area")) - .fixed_pos(pos2(ctx.data(|d| d.get_temp::(egui::Id::new("sc_file_menu_x"))).unwrap_or(100.0), APP_BAR_HEIGHT)) + .fixed_pos(pos2( + ctx.data(|d| d.get_temp::(egui::Id::new("sc_file_menu_x"))).unwrap_or(100.0), + if app.platform.enabled { crate::platform::app_bar_height(ctx) } else { APP_BAR_HEIGHT }, + )) .order(egui::Order::Foreground) .show(ctx, |ui| { crate::ui_kit::Menu::show_frame(ui, crate::ui_kit::Menu::frame(), |ui| { @@ -770,23 +792,25 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { FileAction::Open.run(app); close = true; } - crate::ui_kit::Menu::button(ui, app.tr("ui.open_recent"), |ui| { - for path in app.home.recent.clone() { - let missing = !crate::home::available(app, &path); - let label = format!("{path}{}", if missing { " (missing)" } else { "" }); - if crate::context_menu::button(ui, &label, "open").clicked() { - FileAction::OpenRecent(path).run(app); + if !app.platform.enabled { + crate::ui_kit::Menu::button(ui, app.tr("ui.open_recent"), |ui| { + for path in app.home.recent.clone() { + let missing = !crate::home::available(app, &path); + let label = format!("{path}{}", if missing { " (missing)" } else { "" }); + if crate::context_menu::button(ui, &label, "open").clicked() { + FileAction::OpenRecent(path).run(app); + close = true; + ui.close(); + } + } + ui.separator(); + if crate::context_menu::button(ui, app.tr("ui.clear_recent"), "delete").clicked() { + FileAction::ClearRecent.run(app); close = true; ui.close(); } - } - ui.separator(); - if crate::context_menu::button(ui, app.tr("ui.clear_recent"), "delete").clicked() { - FileAction::ClearRecent.run(app); - close = true; - ui.close(); - } - }); + }); + } if item_if(ui, "Insert STEP…", "", "import", shown) { FileAction::Command("file.insert_step").run(app); close = true; @@ -799,7 +823,7 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { app.start("pointcloud.insert"); close = true; } - if item_if(ui, &format!("{}…", app.tr_label("Insert Design")), "", "component", shown) { + if !app.platform.enabled && item_if(ui, &format!("{}…", app.tr_label("Insert Design")), "", "component", shown) { FileAction::Command("component.insert_design").run(app); close = true; } @@ -813,13 +837,17 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { FileAction::SaveAs.run(app); close = true; } - if item(ui, "Save As JSON…", "", "save") { + if !app.platform.enabled && item(ui, "Save As JSON…", "", "save") { FileAction::SaveJson.run(app); close = true; } // The browser build: a copy as a downloaded file, whatever Save does. if app.services.download_design.is_some() && item_if(ui, "Download design", "", "export", shown) { - download_design(app); + if app.platform.enabled { + app.platform.intent = Some("download"); + } else { + download_design(app); + } close = true; } if app.services.browser_files.is_some() && item(ui, "Files in this browser…", "", "open") { @@ -841,7 +869,7 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { FileAction::Command("file.export_3mf").run(app); close = true; } - if item_if(ui, "Send to Slicer", "", "mesh_export", shown && crate::dialogs_save_mesh::available(app)) { + if item_if(ui, "Send to Slicer", "", "mesh_export", shown && !app.platform.enabled && crate::dialogs_save_mesh::available(app)) { app.start("file.send_to_slicer"); close = true; } @@ -872,7 +900,8 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { } ui.separator(); // The browser can install SolidCraft as an app (`install`): only while it offers to. - if let Some(offer) = crate::install::offered(app) + if !app.platform.enabled + && let Some(offer) = crate::install::offered(app) && crate::context_menu::button(ui, crate::i18n::tr("install.menu"), "new") .on_hover_text(crate::i18n::tr("install.button_tip")) .clicked() @@ -888,7 +917,7 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { FileAction::Shortcuts.run(app); close = true; } - if item(ui, app.tr("ui.quit"), "", "close") { + if !app.platform.enabled && item(ui, app.tr("ui.quit"), "", "close") { FileAction::Quit.run(app); close = true; } @@ -911,6 +940,10 @@ pub fn save(app: &mut SolveApp) { app.tree.capture_prompt = Some(crate::browser::SAVE.into()); return; } + if app.platform.enabled { + app.platform.intent = Some("save"); + return; + } if app.session.path.is_some() { // Read-only, or changed on disk since it was opened: Save As, or a question, instead. if crate::open_elsewhere::check_save(app) { @@ -922,6 +955,10 @@ pub fn save(app: &mut SolveApp) { } pub(crate) fn save_as(app: &mut SolveApp) { + if app.platform.enabled { + app.platform.intent = Some("saveAs"); + return; + } save_as_with_extension(app, solidcraft_engine::io::DESIGN_EXT); } @@ -1648,6 +1685,9 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { if !app.preferences.sketch_construction_lines { cmds.retain(|c| solidcraft_engine::cmd::construction_line_mode(c.id).is_none()); } + if app.platform.enabled { + cmds.retain(|command| !crate::platform::unavailable(command.id) && !crate::platform::host_managed(command.id)); + } let mut shown = crate::toolbar_custom::buttons(app, &tab, panel, &cmds, promote); // Gallery cells are painted together after the large buttons, in reading order. if tab == "SKETCH" && panel == "CONSTRAIN" { diff --git a/crates/ui-egui/src/ui_kit/assistant.rs b/crates/ui-egui/src/ui_kit/assistant.rs index 8a9f28d89..5cc5bf8fc 100644 --- a/crates/ui-egui/src/ui_kit/assistant.rs +++ b/crates/ui-egui/src/ui_kit/assistant.rs @@ -67,7 +67,6 @@ pub(crate) fn assistant_header(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) - } /// Inset controls band beneath the header, aligned with the conversation body. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_controls(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); egui::Frame::NONE.inner_margin(egui::Margin::symmetric(t.space_12 as i8, t.space_8 as i8)).show(ui, |ui| { @@ -77,7 +76,6 @@ pub(crate) fn assistant_controls(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) } /// Right-aligned user message with a compact lower-right corner and 86% maximum width. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_bubble(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); let width = ui.available_width().max(0.0); @@ -106,7 +104,6 @@ pub(crate) fn assistant_bubble(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) - } /// Assistant prose remains unboxed and uses the shared readable body typography. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_prose(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { let t = Tokens::get(); ui.scope(|ui| { @@ -118,7 +115,6 @@ pub(crate) fn assistant_prose(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> .inner } -#[cfg(any(not(target_arch = "wasm32"), test))] #[derive(Clone, Copy)] pub(crate) enum AssistantToolState { Pending, @@ -128,7 +124,6 @@ pub(crate) enum AssistantToolState { } /// A 15 pt status mark with distinct shape and colour for every tool state. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_tool_status(ui: &mut Ui, state: AssistantToolState) -> Response { let t = Tokens::get(); let size = t.space_12 + t.space_3; @@ -162,7 +157,6 @@ pub(crate) fn assistant_tool_status(ui: &mut Ui, state: AssistantToolState) -> R } /// Bordered tool group; the caller retains expansion, status and automation identities. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_tool_frame(ui: &mut Ui, failed: bool, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); egui::Frame::NONE @@ -177,14 +171,12 @@ pub(crate) fn assistant_tool_frame(ui: &mut Ui, failed: bool, add: impl FnOnc } /// Individual tool-row surface, retaining a failed row's tint inside a shared group. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_tool_row(ui: &mut Ui, failed: bool, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); egui::Frame::NONE.fill(if failed { t.form_error_fill } else { t.dialog_body }).corner_radius(t.control_radius).show(ui, add) } /// Indented detail box using the same field surface as inline command parameters. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_tool_detail(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); egui::Frame::NONE @@ -196,7 +188,6 @@ pub(crate) fn assistant_tool_detail(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> } /// Approval frame with a tinted heading. Permission choices remain entirely caller-owned. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_approval(ui: &mut Ui, title: &str, body: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); let output = egui::Frame::NONE.fill(t.dialog_body).stroke(egui::Stroke::new(1.0, t.form_primary)).corner_radius(t.radius_xl).show(ui, |ui| { @@ -229,7 +220,6 @@ pub(crate) fn assistant_approval(ui: &mut Ui, title: &str, body: impl FnOnce( /// Unframed growing editor inside the composer. The caller retains focus ID and Enter routing. /// Tokens: font_label, control_height, space_8 and shared text_input alignment. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_input(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response { let t = Tokens::get(); // The hint is painted here, not by the TextEdit: a multiline edit wraps its hint onto @@ -255,7 +245,6 @@ pub(crate) fn assistant_input(ui: &mut Ui, id: egui::Id, value: &mut String, hin } /// The composer hint laid out on one row of at most `width`, cut with an ellipsis. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_hint_galley(ui: &Ui, hint: &str, width: f32) -> std::sync::Arc { let t = Tokens::get(); let mut job = egui::text::LayoutJob::simple_singleline(hint.to_owned(), egui::FontId::proportional(t.font_label), ui.visuals().weak_text_color()); @@ -264,7 +253,6 @@ pub(crate) fn assistant_hint_galley(ui: &Ui, hint: &str, width: f32) -> std::syn } /// Compact right-aligned approval actions; wrapping grows by control rows, not the remaining card height. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_actions(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); ui.allocate_ui_with_layout( @@ -275,14 +263,12 @@ pub(crate) fn assistant_actions(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) } /// Bottom corners follow the window; the top meets the footer rule square. -#[cfg(any(not(target_arch = "wasm32"), test))] fn composer_corners(t: &Tokens) -> egui::CornerRadius { let r = t.radius_xl.saturating_sub(1); egui::CornerRadius { nw: 0, ne: 0, sw: r, se: r } } /// Composer's rounded field surface with an accent border only while focused. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_composer(ui: &mut Ui, focused: bool, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); egui::Frame::NONE @@ -298,7 +284,6 @@ pub(crate) fn assistant_composer(ui: &mut Ui, focused: bool, add: impl FnOnce } /// Circular primary send or stop action. The caller retains queue and cancellation dispatch. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_send(ui: &mut Ui, enabled: bool, busy: bool, label: &str) -> Response { let t = Tokens::get(); ui.add_enabled_ui(enabled, |ui| { @@ -321,7 +306,6 @@ pub(crate) fn assistant_send(ui: &mut Ui, enabled: bool, busy: bool, label: &str } /// Pinned composer footer. The enclosing shell retains ownership of scrolling and sizing. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_composer_footer(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let t = Tokens::get(); let output = egui::Frame::NONE @@ -336,7 +320,6 @@ pub(crate) fn assistant_composer_footer(ui: &mut Ui, add: impl FnOnce(&mut Ui } /// Centred setup copy and caller-supplied action, bounded to a readable 300 pt column. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_empty(ui: &mut Ui, title: &str, body: &str, add: impl FnOnce(&mut Ui) -> R) -> R { let t = Tokens::get(); let width = ui.available_width().min(t.form_card_width + t.space_24 + t.space_12).max(0.0); @@ -355,7 +338,6 @@ pub(crate) fn assistant_empty(ui: &mut Ui, title: &str, body: &str, add: impl } /// Semantic warning/error/information band with caller-owned text and actions. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn assistant_banner(ui: &mut Ui, tone: AssistantTone, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse { banner(ui, tone, add) } diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index 3f7be6951..347a66046 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -1498,7 +1498,6 @@ fn relative_number(text: &str, now: f64) -> Option { /// Growing plain-text message editor; its parent owns scrolling and Enter routing. /// Tokens: control_fill, form_inset, font_label. Use text_area for bounded data input. -#[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn message_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response { let t = Tokens::get(); let mut response = ui.add( diff --git a/docs/vibemake/assistant-backend-handoff.md b/docs/vibemake/assistant-backend-handoff.md new file mode 100644 index 000000000..6ca419cdb --- /dev/null +++ b/docs/vibemake/assistant-backend-handoff.md @@ -0,0 +1,108 @@ +# Web 助手后端接入交接 + +本轮先恢复前端。当前生产路径仍是浏览器直连模型,不存在已上线的助手运行服务。下面的接口是待双方实现的接入约定,不能当作现有接口调用。接入时还需在 Web 引擎增加 `RemoteBackend`,由宿主取得会话凭证后注入;不要把模型密钥或平台 token 放到 URL。 + +## 保留的前端 + +- `crates/ui-egui/src/agent_chat/panel.rs`:原版面板、输入、消息、计划、审批、工具记录、停止、撤销、模型与配置选择。 +- `crates/ui-egui/src/agent_chat/backend.rs`:`ChatBackend` / `Event` / `PromptPart` 是行为契约;目前不是可直接传输的 JSON 协议,需要显式序列化映射。 +- `crates/ui-egui/src/agent_chat/gate.rs`:工具审批、权限、当前工程约束和操作限额。 +- `apps/solidcraft-web/src/agent_tools.rs`:原版 MCP schema / 工具调用到浏览器控制请求的适配。 +- `apps/solidcraft-web/src/agent.rs`:现有直连 `BrowserBackend`。新增远程适配器与它并存,不在 JS 中再做一套聊天面板或建模循环。 +- Vibemake `js/cad/app.js`:账号、工程 binding、页面生命周期。认证失效或换工程必须释放旧助手会话。 + +本轮恢复原版服务预设、连接类型位置、附件菜单、剪贴板图片、图片/文本拖入和模型列表。工具失败反馈及工具记录 ID 也与原版语义对齐。本机智能体/命令和独立系统窗口目前保留入口但置灰,不表示这些能力已经接通。Ask 初始权限、显式云保存和账号隔离继续保留。 + +## 运行边界 + +浏览器保有当前未保存工程,执行 CAD 命令、审批、撤销和文件序列化。新服务负责模型 HTTP、流式事件、ACP 进程和模型密钥。现有业务后端负责登录、项目归属和云保存。初期不在服务器另跑一份 CAD 桌面,也不以云端旧文件替代当前编辑状态。 + +云端 ACP 子进程属于服务端环境,不继承用户电脑的登录、文件或本地模型。需要本机智能体时另接本地连接程序。服务端进程、临时附件和凭据必须按账号/会话隔离;浏览器回传的工具结果才是当前工程的执行结果。 + +## 建议接口(待实现) + +| 接口 | 职责 | +| --- | --- | +| `POST /api/cad/assistant/sessions` | 沿用平台认证,校验 `cadProjectCode` 归属,创建绑定页面的会话,返回短期、单次使用凭证和服务能力 | +| `WSS /api/cad/assistant/sessions/{sessionId}/stream` | 双向命令、事件、工具往返和取消;建立后首条消息认证,不在查询参数携带凭证 | +| `DELETE /api/cad/assistant/sessions/{sessionId}` | 幂等释放;取消模型请求、待审批和进程任务 | + +会话请求应包含 `cadProjectCode`、`binding`、`clientInstanceId`、`engineBuildId`、协议版本、当前文档修订号、客户端工具能力。返回 `sessionId`、凭证有效期、能力和配置。`binding` 是防止旧页面操作新工程的关联标识,不代替后端授权。所有接口再次校验当前账号和会话归属;WS 校验站点 Origin。 + +不要要求前端把平台 token 转交模型厂商。模型密钥默认会话级使用;如提供服务端保存,需单独的凭据权限、加密存储和删除机制。 + +## 建议消息格式(待实现) + +```json +{ + "protocol": "vibemake.assistant.v1", + "sessionId": "opaque-session", + "clientInstanceId": "browser-instance", + "binding": "current-document-binding", + "turnId": "turn-unique-id", + "seq": 1, + "type": "prompt", + "payload": { "parts": [{ "type": "text", "text": "创建一个支架" }] } +} +``` + +`turnId` 在会话内唯一;`seq` 分方向递增。工具增加独立 `callId`,不能直接使用厂商可能重复的工具 ID。文档修订号及 u64 编号在 JSON 中用十进制字符串,避免 JS 数值精度问题。服务端和前端都拒绝旧 session / binding / turn 的消息。 + +客户端命令映射: + +| 消息 | 原版方法/语义 | +| --- | --- | +| `prompt` | `prompt(parts)`;图片带 MIME 和受限字节,文档按能力传输,不暴露任意本机路径 | +| `cancel` | `cancel()`;取消当前模型请求及未执行工具,并返回结束确认 | +| `new_session` | `new_session()`;先终止当前轮次,再清空模型会话 | +| `permission.answer` | `answer_permission(key, option)`;含取消答案 | +| `authenticate` | `authenticate(method)`;只能打开受控登录入口,不能把本机命令当浏览器链接执行 | +| `model.set` / `mode.set` | `set_model` / `set_mode`;拒绝时返回明确事件,不假装切换成功 | +| `timeout.set` / `reasoning.set` | 原版请求超时及推理强度设置,从下次请求生效 | +| `config.set` | `set_config_option(id, value)`;需要成功/失败确认 | +| `tool.result` | 工具结果、失败/拒绝、执行后修订号;保留原始 `callId` | + +服务端事件需要覆盖全部原版 `Event`: + +| 事件 | 必需数据 | +| --- | --- | +| `ready` / `capabilities` | 智能体名称/版本、图片、文档及 CAD 工具能力;未经验证不宣称支持 | +| `text` | 文本片段、原版 `thought` 显示标志 | +| `tool.activity` | 展示 ID、标题、种类、状态、参数和结果;仅显示,不能触发执行 | +| `tool.request` | 真正的 CAD 工具调用:`callId`、工具名、参数、预期文档修订号 | +| `plan` | 步骤列表及状态 | +| `permission` | 原版 ACP 审批 key、标题、种类、选项 | +| `auth.required` / `auth.status` | 登录方式、描述和状态;远程登录与本机登录分别处理 | +| `models` / `models.note` / `model.rejected` | 当前模型、完整可用列表、列表失败说明、切换拒绝原因 | +| `modes` | 当前模式及可用模式 | +| `config.options` / `config.finished` | 可配置项、当前值、可选值和设置结果 | +| `turn.ended` | 正常、取消或失败的结束原因 | +| `error` / `exited` | 可恢复错误与智能体退出分别处理;尾部日志先脱敏、截断 | + +能力协商未声明的设置在原版位置显示不可用原因。连接失败不能标为 ready。模型列表失败可保留手输模型继续连接,并显示原版列表警告。不得只实现文字 token 的转发。 + +## CAD 工具往返 + +1. 后端只下发工具请求。浏览器先校验会话、工程 binding、轮次和预期文档修订号。 +2. 浏览器调用既有工具适配和 gate;需审批时由原版面板展示。远程服务不能用 `tool.activity` 绕过审批。 +3. 通过原版命令执行,更新当前文档、dirty 和同一轮撤销分组。 +4. 浏览器返回结果或错误。失败、未知工具、非法参数及拒绝都反馈给模型;不把失败假装成成功,也不无条件中断模型解释。 +5. 后端继续模型循环。服务端工具记录只是展示,不执行第二次。 + +`callId` / 执行确认用于去重;重连不能盲目重放写操作。后端在结果不明时先查询执行状态,不以新 ID 自动重试相同修改。项目切换、账号失效、人工修改、Stop 和断开需使旧待执行请求失效。已经完成的几何修改保留且可撤销。 + +关闭页面后首期停止依赖浏览器的建模。后台建模另需版本化快照、无头引擎和冲突合并,不在本次前端恢复范围内。 + +## Web 文件适配 + +- 视口截图:浏览器生成图片字节,不传 native screenshot 的文件路径。 +- 图片/文本:前端已有选择、粘贴和拖入;继续保留类型、大小、图片解码和附件数限制。 +- PDF:仅在后端及当前模型明确声明文档能力后开放;实现字节/附件引用映射,不能假定浏览器 `file://` 可被远端访问。 +- CAD 导入、工程打开/新建、保存、导出:逐项接现有宿主文件/工作空间接口和确认流程。不能直接解除 `gate.rs` 的宿主限制。 +- 模型修改不会自动云保存。云保存继续使用现有 `expectedVersion` / `uploadCode` 协议。 + +## 联调验收 + +用相同提示词和可控模型响应对照原版,检查:模型列表与失败回退、重复厂商工具 ID、合法/非法参数、工具失败反馈、图片/文档能力、模型/模式/配置事件、ACP 登录与审批、Stop、断线重连、工具去重、工程切换、账号切换、人工编辑冲突、整轮撤销和显式云保存。 + +现有浏览器回归在 Vibemake 的 `tests/cad/assistant-browser.mjs`,本机可控模型在 `assistant-model.mjs`。它们仅用于测试,不能部署为生产模型服务。新增后端后应保留这些用例,并增加远程事件及会话测试;真实 HTTPS、真实服务与跨浏览器验收另做。 diff --git a/docs/vibemake/assistant-frontend-parity-2026-11-03.md b/docs/vibemake/assistant-frontend-parity-2026-11-03.md new file mode 100644 index 000000000..07e678801 --- /dev/null +++ b/docs/vibemake/assistant-frontend-parity-2026-11-03.md @@ -0,0 +1,63 @@ +# Web 助手前端还原验收记录 + +日期:2026-11-03(Asia/Shanghai)。本轮按“先恢复前端,再由后端同事实现服务”的范围修改,没有实现或部署助手后端。 + +## 本轮结果 + +继续复用 SolidCraft 的 Rust/egui 助手,不另写 HTML 聊天界面。恢复原版服务预设、三种连接类型的布局、附件菜单和连接后的模型列表;为浏览器补上剪贴板图片及图片/文本拖入。原版消息、计划、工具卡片、审批、停止、权限和整轮撤销继续使用已有实现。 + +修复三类行为差异:厂商重复工具 ID 不再覆盖旧卡片;工具失败、未知工具和非法参数以失败记录反馈给模型,允许其解释或修正;新建对话不再出现上一轮的取消提示。切换服务预设或协议时,不把旧服务密钥带到新地址。多附件读取仍受数量、文件大小和当前会话限制。 + +Web 无法直接提供的本机智能体、自定义命令、主机控制设置和独立系统窗口,保留原版位置并禁用,说明所需运行环境。左右停靠继续可用。本轮不宣称桌面能力已 100% 还原。 + +## 最终产物 + +- SMLib 引擎 build ID:`24bceec2a532eca13da1623c`。 +- 构建时间:2026-11-03 22:05:38(Asia/Shanghai)。 +- 引擎目录:`dist/vibemake-cad-engine/`;清单包含 8 个文件。 +- 原始产物及独立 staging 均通过 VibeMake `readCadEngine` 的文件、长度与 SHA-256 校验。 +- VibeMake `node scripts/build.mjs` 已更新主站 `dist.zip`。主站 ZIP 不包含独立 CAD 引擎,发布时必须按 [前端与引擎集成](frontend-implementation.md) 另外叠加引擎。 +- 未进行线上部署;本机测试使用隔离的模拟 API / 模型服务,不向真实项目或厂商发送请求。 + +## 已通过的检查 + +| 检查 | 结果 | +| --- | --- | +| 原版助手 Rust 回归:`cargo test --profile ci -p solidcraft-ui-egui --features solidcraft-engine/smlib --lib -- agent_chat` | 279 项通过 | +| VibeMake `npm run test:cad` | 35 项通过 | +| 最终引擎的助手浏览器专项 | 26 项通过,`errors: []` | +| 最终引擎的完整 CAD 浏览器集成:`npm run test:cad:browser` | 46 项通过(含 26 项助手专项),`errors: []` | +| Web 严格 Clippy:`cargo clippy -p solidcraft-web --target wasm32-unknown-unknown --release --no-deps -- -D warnings` | 通过 | +| `cargo fmt --all -- --check` | 通过 | +| 列表、UI 容器和技能检查 | 通过 | +| `cargo xtask web-offline-test` | 通过 | +| 最终 SMLib Web 构建 | 通过 | + +浏览器为本机 macOS 上的 Playwright Chromium,允许 SwiftShader。测试实际执行了剪贴板图片读取、SVG 文本文件选择、多文件拖入、完整模型列表、重复工具 ID、两种协议的错误反馈、审批、Stop、整轮撤销、刷新、账号和工程隔离。完整集成还验证了云保存、工程重开、上传回执丢失、版本冲突、草稿恢复和窄屏/登录限制。截图中的账号、Key 和模型响应均为测试数据。 + +新增消息已提供 de / en / ja / ko / zh 翻译;`i18n` 扫描仍列出仓库部分语言的缺译,不将其报告为所有语言完整。此轮没有重跑或宣称全仓库 CI 通过;先前已观察到的几何测试失败保留在 [上一轮验收记录](web-assistant-validation.md#全仓库-ci-的失败与未完成范围),没有通过修改几何基线掩盖。 + +## 证据 + +原始结果与截图归档在 `evidence/assistant-frontend-2026-11-03/`: + +- [助手专项结果](evidence/assistant-frontend-2026-11-03/assistant-browser-results.json) +- [完整 CAD 浏览器结果](evidence/assistant-frontend-2026-11-03/browser-results.json) +- [最终引擎清单](evidence/assistant-frontend-2026-11-03/engine.json) +- [原版连接布局与服务预设](evidence/assistant-frontend-2026-11-03/assistant-original-presets-zh.png) +- [附件菜单](evidence/assistant-frontend-2026-11-03/assistant-attachment-menu-zh.png) +- [剪贴板图片](evidence/assistant-frontend-2026-11-03/assistant-clipboard-picture-zh.png) +- [多文件拖入](evidence/assistant-frontend-2026-11-03/assistant-dropped-files-zh.png) +- [独立工具卡片](evidence/assistant-frontend-2026-11-03/assistant-tool-history.png) +- [中文设置](evidence/assistant-frontend-2026-11-03/assistant-settings-zh.png) / [英文设置](evidence/assistant-frontend-2026-11-03/assistant-settings-en.png) +- [英文面板](evidence/assistant-frontend-2026-11-03/assistant-en.png) + +已目视检查最终中英文设置、服务预设、附件菜单和工具记录,未见本轮新增控件遮挡。设置页的智能体列表仍通过原版滚动区域展示。 + +## 后续服务边界 + +当前仍是浏览器直连模型的非流式 JSON 请求。云端 ACP / 模型代理、流式事件、服务端凭据及会话管理尚未实现。需要用户电脑上的智能体或文件时,还需本地连接程序;云端后端不能直接获得这些能力。系统钥匙串、独立桌面窗口也不能简单靠新增 HTTP 服务等同恢复。 + +后端同事从 [Web 助手后端接入交接](assistant-backend-handoff.md) 开始:先确定会话与双向事件协议,再实现模型/ACP 运行服务,最后与前端 Rust `RemoteBackend` 联调。该适配器当前尚未实现,不能只部署建议接口就认为前端已接通。CAD 命令、审批和撤销继续在持有当前未保存工程的浏览器执行。 + +真实 HTTPS、真实模型服务、真实业务后端和跨浏览器支持范围仍需单独验收。 diff --git a/docs/vibemake/backend-implementation.md b/docs/vibemake/backend-implementation.md new file mode 100644 index 000000000..a8b75a30b --- /dev/null +++ b/docs/vibemake/backend-implementation.md @@ -0,0 +1,946 @@ +# VibeMake CAD 后端实施与接口契约 + +> 历史方案:当前前端对接以 [CAD 个人工作空间前端对接](workspace-api.md) 为准(2026-11-03 同步)。以下 v1.2 设计保留供参考,不作为当前实现或部署输入;其接口路径、capabilities、complete/状态查询、专用私有 Bucket 和临时下载签名已被新契约替代。 + +- 文档版本:v1.2,已按最终决定复用 VibeMake 登录弹窗。 +- 更新日期:2026-11-03。 +- 适用对象:VibeMake 后端开发、使用 Codex 实施的开发者、CAD 前端开发和测试。 +- 实施状态:需求与接口契约,尚未据此实现或部署后端。 +- 产品范围:基于 SolidCraft 的 VibeMake CAD Web 版本,权威源文件为 `.sc`。 + +> 本文可单独交给后端同事作为 Codex 实施输入,不依赖之前的聊天。项目现有技术栈、认证组件、数据库和 OSS 封装需要先检查再复用。不得把文档示例当作已经上线的能力或真实环境配置。 + +## 1. 已确定的产品决定 + +1. 产品名为 **VibeMake CAD**,浏览器编辑器基于 SolidCraft/Rust/WASM。 +2. CAD 页面未登录时打开 **VibeMake 统一登录弹窗**,登录完成后继续当前 CAD 页面或操作。 +3. **CAD 不新增登录页、注册、验证码、账号表、密码管理或 token 签发接口。** 统一账号系统继续负责登录;CAD API 必须复用现有认证并校验资源归属。 +4. 推荐 CAD 前端与主站同源部署:`/cad/` 为列表,`/cad/editor/?project=` 为编辑器。API 基址沿用现有业务系统,可以是独立 API 域名或同源反向代理。 +5. 一个 CAD 项目对应一个原生 `.sc` 工程。STEP、STL、GLB 等不是云端权威工程格式。 +6. CAD 数据独立建模,复用主站用户和基础设施,不直接复用社区/工作区项目记录,不建立隐式 projectCode 映射。 +7. 一期手动云保存;本机草稿由前端负责,不等于云保存。 +8. 文件直传私有 OSS 临时位置;后端固化、校验并原子提交后,才确认保存成功。 +9. 一期保留所有已确认快照,但不提供历史列表/恢复 UI。删除先做逻辑删除。 +10. 不自动覆盖并发保存;使用基于云端版本的比较并提交(CAS)。 + +### 1.1 一期不包含 + +- 多人实时协同、团队、分享、社区发布、CAD 管理后台。 +- 服务端建模、几何布尔、转换格式、渲染缩略图。 +- 工程目录、外部附件集合、任意 ZIP 上传、分片续传、差量同步。 +- 历史版本查询界面、历史恢复、物理删除入口。 +- 对主站和 PCB 数据模型或登录体系的重构。 + +缩略图一期允许为空,由列表显示占位图标。以后增加时,缩略图是绑定 revision 的派生资源,不能代替源文件。 + +### 1.2 核心不变量 + +- OSS 上传成功不代表云保存成功;只有 `COMMITTED` 才可显示“已保存到云端”。 +- 项目 head 永远只指向已经固化并校验通过的不可变文件。 +- 同一保存 operation 无论重试多少次,最多生成一个 revision。 +- 客户端提交的 owner、用户 ID、对象 key 不能决定实际权限。 +- 文件下载、副本导出、本机草稿都不能推进云端版本。 +- 失败、超时、冲突时不能清除用户当前未保存内容。 + +## 2. 后端 Codex 开始实施前的检查 + +先阅读目标后端仓库的 AGENTS.md、README、运行和测试说明,再检查: + +1. 当前语言、框架、项目分层和 API 路由习惯。 +2. 用户稳定标识、现有鉴权中间件、token/会话验证和账号禁用规则。 +3. 数据库、迁移工具、事务隔离和锁使用方式。 +4. OSS SDK、私有桶、签名上传下载、当前环境配置与 CORS。 +5. 统一 JSON 信封、异常处理、requestId、国际化和限流组件。 +6. 是否已经存在 CAD 模块、表、接口或历史工程数据。 +7. 后台任务、持久化队列、定时任务及测试基础设施。 + +实施要求: + +- 优先扩展现有业务后端,不因本文新建整套账号服务或不必要的微服务。 +- 如果 CAD 模块位于同一后端,直接复用认证中间件;如果独立部署,接入现有身份验证机制,不自行设计另一种 token。 +- 已有 CAD 功能先核对实际行为,补齐缺口,不重复建表、覆盖数据或删除旧实现。 +- 如果已有 OpenCADStudio/DWG/DXF 项目,保留原格式和引擎归属;不能把旧记录改标为 `.sc`。需要兼容时使用明确的 engineKind/格式区分和可回滚迁移。 +- 表和类可遵循现有命名习惯,但本文公共 API 字段、状态、错误码和语义需保持一致;必须变更时更新契约和测试,不能静默改动。 +- 不假设用户 ID 类型、桶名或 OSS 密钥;登录弹窗复用现有主站接口。优先从现有配置解析,缺少的环境值作为明确配置项交付。 +- 不部署正式环境,不执行破坏性数据迁移,不创建/修改生产用户,不把测试写请求发往生产。 + +## 3. 架构与职责 + +| 组件 | 职责 | +| --- | --- | +| 统一登录弹窗和账号后端 | 登录、凭据签发/失效、账号状态和退出 | +| CAD 平台前端 | 登录弹窗、列表、项目名称、上传调度、保存状态、草稿和冲突提示 | +| Rust/WASM 编辑器 | 几何、约束、参数、原生工程快照生成与加载 | +| CAD 业务模块 | 鉴权、CRUD、快照、上传事务、配额、幂等和提交 | +| 文件校验任务 | 固化源文件、检查实际字节与结构、提交或拒绝 | +| 数据库 | 项目、不可变 revision、对象引用、事务与幂等结果 | +| 私有 OSS | 临时上传、最终不可变文件、短期读取授权 | + +标准保存链路: + +```text +固定本次工程快照及字节 + -> 创建保存事务 + -> 直传 OSS 临时位置 + -> complete 请求 + -> 最终对象固化与校验 + -> 数据库原子提交 revision/head/事务回执 + -> 返回 COMMITTED +``` + +业务后端沿用现有技术栈。结构校验可使用受限的独立组件或复用兼容的原生读取组件,不要求服务端运行桌面 CAD,不执行建模重放或渲染。 + +## 4. 统一登录和鉴权边界 + +### 4.1 登录弹窗由主站统一系统负责 + +CAD 复用主站邮箱与图片验证码登录弹窗,继续调用现有 auth 接口,不新增 CAD 专用 captcha/login/register 接口。 + +前端流程: + +1. 用户访问列表或编辑器。 +2. 未登录时自动打开主站同款登录弹窗;关闭后停留在登录提示页,不加载私有项目或引擎。 +3. 登录成功后继续原 CAD 深链接或待执行操作。 +4. CAD 使用统一账号系统已有的凭据请求业务 API。 +5. 编辑中凭据失效时,先保护本机草稿,再引导重新登录。 + +当前主站已有 Bearer 请求方式和 `vm.auth` 前端身份存储。以实际统一账号契约为准复用,不为 CAD 强制迁移 Cookie、OIDC 或另发 token。 + +一期不新增 `/login/` 路由,不使用 returnTo 跳转登录。弹窗打开时锁定画布输入和键盘焦点;简体中文与英文共享当前 CAD 语言。 + +同源 `/cad/` 复用主站 `vm.auth` 和已有 Bearer。编辑中明确 401 时保护原账号草稿、锁定输入并打开登录弹窗;同账号续登先查未知事务,不同账号登录后释放原工程并进入新账号列表。跨标签页身份变化必须同步,旧账号回执不得更新新会话。 + +### 4.2 CAD 后端仍需验证身份和权限 + +所有本文业务接口,包括 capabilities,都要求现有认证。当前请求方式: + +```http +Authorization: Bearer <统一账号系统签发的凭据> +``` + +- 当前用户来自服务端认证上下文,不能来自请求 body、URL 参数或可伪造身份头。 +- 项目、revision、upload、签名授权都验证 owner 及关联关系。 +- 不存在和越权统一 `404 NOT_FOUND`,不泄漏他人数据是否存在。 +- 当前用户自己的已删除项目通常返回 `410 PROJECT_DELETED`;已确认事务回执查询见第 12 节例外。 +- 未登录、失效、被统一认证拒绝时返回 **JSON HTTP 401**,CAD API 不 302 跳转登录页。 +- 后端不读取或信任浏览器 `vm.auth` 内容;它只验证请求实际携带的凭据。 +- CORS 不是鉴权。知道 UUID、OSS key 或通过前端路由检查,都不构成访问权限。 + +退出或取消 HTTP 请求不会自动撤销已受理的保存。已受理操作即便最终完成,也只能属于原账号、原项目;前端切账号后不得应用旧回执。 + +## 5. 原生文件及版本约定 + +### 5.1 权威源文件 + +| 项目 | 一期约定 | +| --- | --- | +| 扩展名/sourceFormat | `.sc` / `sc` | +| MIME | `application/octet-stream` | +| 文件数 | 每次保存一个完整工程 | +| 容器 | 支持的 SolidCraft 原生容器,当前为 `solidcraft-container/1` | +| 参数化文档 | 容器中的 `document.json`,携带 `solidcraft/N` | +| 保存方式 | 原始二进制字节,不重写、不重新压缩、不转换 | + +原生容器采用 ZIP 结构,包含 `container.json`、`document.json`、必要的 `blobs/` 以及可选缓存。这不等于允许任意 ZIP、目录包或附加 gzip 封装。 + +- 旧 JSON、旧扩展名或导入格式由编辑器解析后生成支持的 `.sc` 再上传。 +- 内部 `solidcraft/N` 等格式标识不因产品更名改变。 +- 后端不生成空工程文件。项目初始可以没有快照。 +- 工程特征、约束、参数和必要资源由原生文件承载;不能用 STL/STEP/GLB 或截图替代。 +- 工程内缓存不是权威建模结果;是否可编辑由引擎和 round-trip 测试验证。 +- Undo/Redo 会话栈不要求上传;云端保存序号也不是操作历史。 + +### 5.2 四种版本不能混用 + +| 字段 | 含义 | +| --- | --- | +| headVersion | 云项目第几次确认保存,0、1、2…… | +| containerFormat | 容器编码版本 | +| documentFormat | 实际参数化文档结构版本 `solidcraft/N` | +| engineBuild | 生成工程的编辑器构建标识 | + +`N` 必须取自实际序列化文件及发布的校验器,不能用应用版本号猜测。本文 JSON 中 `solidcraft/` 是示例占位,生产响应必须是真实格式值。 + +前端支持、后端接受和校验器识别的格式范围需要建立发布清单。新版本不支持时明确拒绝,不能静默丢弃未知内容。 + +### 5.3 项目名称与工程内容 + +项目重命名只修改平台元数据,不改 `.sc` 原始字节、内部文档名、headVersion 或 lastSavedAt。下载名称可由平台安全生成,源文件的内部模型名称不要求与平台名每时每刻相同。 + +## 6. 数据模型 + +下面为逻辑模型,落地按现有 ORM/数据库习惯调整。ID 推荐 UUID;用户字段使用现有稳定用户标识。数值版本通过 JSON 返回时必须处于前端可精确表示的整数范围。 + +### 6.1 cad_projects + +| 字段 | 说明 | +| --- | --- | +| id | 项目 UUID | +| owner_user_code | 服务端身份,类型沿用主站 | +| name | 显示名,trim 后 1–120 个 Unicode 码点,UTF-8 不超过 512 字节 | +| engine_kind | 一期 `solidcraft` | +| source_format | 一期 `sc` | +| head_version | 非负整数,初始 0 | +| head_revision_id | 最新确认 revision,可空 | +| metadata_version | 初始 1;名称修改等元数据变更时递增 | +| last_saved_at | 仅确认工程保存时更新,可空 | +| created_at / updated_at | 创建/最近元数据或工程更新时间 | +| deleted_at | 逻辑删除时间,可空 | + +派生状态:EMPTY=head 为空;READY=head 非空;DELETED=deleted_at 非空。不要再维护一份容易漂移的 EMPTY/READY 持久化状态。 + +约束:headVersion=0 时 revision 为空;大于 0 时指向本项目已确认 revision。允许同用户同名项目。名称拒绝控制字符,作为纯文本展示。 + +### 6.2 cad_revisions + +| 字段 | 说明 | +| --- | --- | +| id / project_id | revision UUID 和所属项目 | +| version | 项目内保存序号 | +| blob_id | 已固化并校验通过的对象 | +| client_operation_id | 保存幂等键 | +| client_snapshot_id | 客户端固定快照标识,不授予权限 | +| created_by_user_code | 认证提交者 | +| container_format / document_format | 服务端检测值 | +| engine_build | 客户端构建标识,仅诊断信息 | +| created_at | 服务器确认时间 | + +唯一约束:`(project_id, version)`、`(project_id, client_operation_id)`。已确认 revision 不允许原地覆盖源文件。 + +### 6.3 cad_blobs + +| 字段 | 说明 | +| --- | --- | +| id | UUID | +| object_key | 私有最终对象 key,浏览器从无写权限 | +| object_version_id | 启用存储版本控制时记录具体版本 | +| size_bytes / sha256 | 服务端对最终字节实际校验的结果 | +| source_format / container_format / document_format | 检测结果 | +| created_at | 固化时间 | + +一期不做跨用户去重;不同显式保存可产生不同对象和 revision。同一幂等 operation 重试不能产生第二个 revision。 + +### 6.4 cad_uploads + +| 字段 | 说明 | +| --- | --- | +| id / project_id / owner_user_code | 事务 UUID 与归属 | +| client_operation_id / client_snapshot_id | 固定保存操作与快照 | +| request_fingerprint | 规范化后的请求摘要 | +| expected_version | 客户端读取并编辑所基于的云 head | +| expected_size / expected_sha256 | 声明的完整源字节信息 | +| declared_container_format / declared_document_format | 声明格式,不能取代实际检测 | +| file_name / engine_build | 固定文件显示名与构建标识 | +| temp_object_key | 唯一临时上传位置 | +| state | 第 12 节定义的状态 | +| error_code / error_details | 固定拒绝原因,不含敏感内部信息 | +| verifier_token / lease_until | 校验执行权及租约 | +| candidate_object_key | 本次校验尝试使用的独立固化位置 | +| committed_revision_id / committed_version / saved_at | 固定确认回执 | +| reserved_bytes | 预留配额 | +| expires_at / created_at / updated_at | 期限和时间 | + +唯一约束:`(project_id, client_operation_id)`。请求摘要至少包括 expectedVersion、snapshotId、文件名、大小、hash、格式和构建标识;规范化方式固定,后端计算,不信任客户端传入摘要。 + +### 6.5 创建项目幂等记录与配额 + +创建项目使用独立记录,键为 `(owner, action, Idempotency-Key)`,保存请求摘要和创建的 projectId。不得因网络重试重复创建项目。一期持久保存结果,若未来清理,需先明确重试期限和旧键拒绝策略。 + +复用或新增用户配额记录,用事务协调 used/reserved bytes,不能仅在前端计数或每个并发请求各自做无锁检查。 + +### 6.6 索引与事务 + +- 列表至少索引 owner、删除状态、排序时间、ID。 +- upload 索引项目/owner、幂等键、state、过期时间、租约。 +- revision 和 blob 使用外键或等价完整性检查,防止串项目引用。 +- 保存与删除按统一锁顺序协调;对象网络操作不放在持有行锁的长事务内。 +- 数据库迁移必须可审查并有回滚/兼容说明,不删除既有业务数据。 + +## 7. 通用 API 规则 + +统一前缀:`/api/cad`。本文示例省略真实域名。 + +```json +{ + "code": "OK", + "message": "", + "data": {}, + "requestId": "server-generated-request-id" +} +``` + +- 失败使用真实 HTTP 状态和稳定业务 code。前端不以 message 文本判断逻辑。 +- 时间统一 UTC ISO 8601,带 `Z`;大小为字节;SHA-256 为 64 位小写十六进制。 +- JSON 接口仅接收元数据,设置合理 body 限制;源文件直接去 OSS。 +- API 私有响应 `Cache-Control: no-store`,CDN/SW 不缓存。 +- 响应头 `X-Request-Id`,限流时 `Retry-After`。 +- 支持 `Accept-Language: zh-CN`/`en`,默认中文;error details 使用机器字段。 +- 不返回堆栈、存储密钥、未经脱敏对象地址等内部信息。 +- 不接受客户端覆盖 owner、head、revision 关联或对象 key。 + +成功查询到 REJECTED/EXPIRED 事务仍可是 HTTP 200 + code=OK;仅表示查询成功,前端必须判断 data.status。 + +## 8. 接口总览 + +| 方法 | 路径 | 用途 | +| --- | --- | --- | +| GET | /capabilities | 格式和限制 | +| GET | /projects | 当前用户项目列表 | +| POST | /projects | 幂等创建 EMPTY 项目 | +| GET | /projects/{projectId} | 项目元数据 | +| PATCH | /projects/{projectId} | 带元数据版本的重命名 | +| DELETE | /projects/{projectId} | 逻辑删除 | +| GET | /projects/{projectId}/snapshot | 确认快照和只读授权 | +| POST | /projects/{projectId}/uploads | 幂等初始化保存 | +| POST | /projects/{projectId}/uploads/{uploadId}/complete | 开始/继续确认 | +| GET | /projects/{projectId}/uploads/{uploadId} | 查询固定事务结果 | + +以下成功示例均为信封中的 data,不重复外层 code/message/requestId。 + +## 9. 能力和 CRUD 详细契约 + +### 9.1 GET /capabilities + +```json +{ + "apiVersion": 1, + "engineKind": "solidcraft", + "sourceFormats": ["sc"], + "preferredSourceFormat": "sc", + "containerFormats": ["solidcraft-container/1"], + "documentFormats": ["solidcraft/"], + "formatSupportId": "实际发布格式清单的标识", + "maxSourceBytes": 52428800, + "maxSourceFiles": 1, + "externalAttachments": false, + "saveProtocol": "signed-post-cas-v1", + "manualSave": true, + "cloudAutosave": false, + "historyUi": false, + "uploadAuthorizationTtlSeconds": 300, + "uploadTransactionTtlSeconds": 1800, + "downloadAuthorizationTtlSeconds": 300 +} +``` + +`documentFormats` 必须返回校验器实际接受的版本清单,不返回占位 ``。50 MiB 是建议初始配置,不是现有线上能力;完成浏览器和服务端峰值内存/重开测试后确定。不直接复用主站普通文件的 10 MiB 限制。 + +所有时间和容量由配置产生并与签名、校验实际行为一致。前端使用服务端和编辑器承载能力的较小上限。 + +### 9.2 GET /projects + +参数:q 可选,最多 200 个 Unicode 码点;page 从 1 开始;pageSize 默认 20,最大 100。名称搜索使用参数化查询并正确处理 LIKE 特殊字符,不拼 SQL。 + +仅查当前用户、未删除、engineKind=solidcraft 的项目。排序:`COALESCE(last_saved_at, created_at) DESC, id DESC`。重命名不伪装成保存;分页期间新保存可改变顺序,不承诺固定快照分页。 + +```json +{ + "items": [ + { + "id": "11111111-1111-4111-8111-111111111111", + "name": "机械臂支架", + "engineKind": "solidcraft", + "sourceFormat": "sc", + "state": "READY", + "headVersion": 3, + "headRevisionId": "33333333-3333-4333-8333-333333333333", + "metadataVersion": 1, + "createdAt": "2026-11-03T02:00:00Z", + "updatedAt": "2026-11-03T02:20:00Z", + "lastSavedAt": "2026-11-03T02:20:00Z", + "thumbnail": null + } + ], + "page": 1, + "pageSize": 20, + "total": 1 +} +``` + +列表不返回文件字节或签名源文件 URL,不触发渲染。 + +### 9.3 POST /projects + +必须携带 `Idempotency-Key: `。 + +```json +{ + "name": "机械臂支架" +} +``` + +首次返回 HTTP 201 和项目结构:EMPTY、headVersion=0、headRevisionId=null、metadataVersion=1、lastSavedAt=null。相同 owner/键/请求返回同一项目(HTTP 200);同键异内容 `409 IDEMPOTENCY_KEY_REUSED`。 + +格式、engineKind、owner 由服务端确定。创建不接工程字节。导入时可先在编辑器确认文件可读,再创建 EMPTY 项目并走标准保存。 + +### 9.4 GET /projects/{projectId} + +返回与列表条目一致的项目结构。不存在/越权 404;自己的已删除项目 410。 + +### 9.5 PATCH /projects/{projectId} + +```json +{ + "name": "机械臂支架 V2", + "expectedMetadataVersion": 1 +} +``` + +仅允许修改名称。使用 metadataVersion 条件更新并递增,返回更新后的项目。过期版本 `409 METADATA_CONFLICT`,details 包含 currentMetadataVersion。若响应丢失,前端重读元数据确认,不盲目重复覆盖。 + +不修改源字节、工程 headVersion 或 lastSavedAt。普通工程保存不修改 metadataVersion;updatedAt 可以更新。 + +### 9.6 DELETE /projects/{projectId} + +```json +{ + "id": "11111111-1111-4111-8111-111111111111", + "deleted": true +} +``` + +逻辑删除,与保存提交竞争同一项目锁。重复 owner 删除返回同样成功;越权/不存在 404。 + +删除后禁止新 init、新快照授权和未完成保存提交。已确认 revision 保留,不修改其他产品数据。已签发读取 URL 可能到期前仍可用,不承诺删除时即时撤销;读取授权短期有效。 + +## 10. 工程快照与下载 + +### 10.1 GET /projects/{projectId}/snapshot + +EMPTY: + +```json +{ + "projectId": "11111111-1111-4111-8111-111111111111", + "headVersion": 0, + "revisionId": null, + "savedAt": null, + "file": null +} +``` + +READY: + +```json +{ + "projectId": "11111111-1111-4111-8111-111111111111", + "headVersion": 3, + "revisionId": "33333333-3333-4333-8333-333333333333", + "savedAt": "2026-11-03T02:20:00Z", + "file": { + "name": "design.sc", + "sourceFormat": "sc", + "containerFormat": "solidcraft-container/1", + "documentFormat": "solidcraft/", + "size": 123456, + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "downloadUrl": "<短期只读、绑定不可变对象的签名 URL>", + "downloadExpiresAt": "2026-11-03T02:25:00Z" + } +} +``` + +强制约定: + +- headVersion/revision/file 来自一次一致性读取,不拼接不同时间的结果。 +- URL 固定到该 revision 的不可变对象或具体对象版本,不使用可覆盖的 latest.sc。 +- 下载期间云端 head 前进不改变已签发文件。 +- 前端校验 size/hash 后交给引擎,保存时使用该快照对应 expectedVersion。 +- 不能把新读取的 head 数字套到仍在编辑的旧文件上。 + +### 10.2 同一 revision 续签 + +支持 `GET /projects/{projectId}/snapshot?revisionId=<已知UUID>`。只允许该项目 owner 读取已确认且属于该项目的 revision,返回它自己的版本。用于下载过期续签,不新增历史列表 API。 + +下载禁止匿名永久地址。浏览器向 OSS 不携带业务 Bearer,使用短期只读授权;后端签名不接受任意外部 URL。 + +## 11. 初始化上传及直传 + +### 11.1 POST /projects/{projectId}/uploads + +```json +{ + "clientOperationId": "44444444-4444-4444-8444-444444444444", + "clientSnapshotId": "55555555-5555-4555-8555-555555555555", + "expectedVersion": 3, + "engineBuild": "实际编辑器构建标识", + "file": { + "name": "design.sc", + "sourceFormat": "sc", + "containerFormat": "solidcraft-container/1", + "documentFormat": "solidcraft/", + "size": 123456, + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } +} +``` + +要求: + +- expectedVersion 为非负整数;文件大小为正且不超过配置。 +- 文件名为安全 basename,UTF-8 建议不超过 255 字节,不能含目录、控制字符或被当作对象 key。 +- 同一 operationId 固定该次快照、基准版本、字节及请求字段;新内容用新 operationId。 +- 先鉴权并查同 operation 幂等记录,再检查新事务的 head;已提交的旧操作重试不能因当前 head 前进而变成冲突。 +- 新事务检查 owner、项目未删除、格式、大小、版本、频率、并发和额度;可以提前 409,但 complete 仍再次 CAS。 +- 初始化和预留配额原子处理,避免并发超额或重复预留。 + +### 11.2 初始化返回 + +首次新建 HTTP 201;同键重试 HTTP 200,返回原事务当前状态。 + +```json +{ + "uploadId": "66666666-6666-4666-8666-666666666666", + "projectId": "11111111-1111-4111-8111-111111111111", + "clientOperationId": "44444444-4444-4444-8444-444444444444", + "clientSnapshotId": "55555555-5555-4555-8555-555555555555", + "status": "PENDING_UPLOAD", + "expiresAt": "2026-11-03T02:50:00Z", + "upload": { + "method": "POST", + "url": "<当前环境 OSS 上传地址>", + "fields": { + "key": "<后端生成的精确临时 key>", + "policy": "", + "<签名相关字段>": "", + "success_action_status": "204" + }, + "fileField": "file", + "uploadExpiresAt": "2026-11-03T02:25:00Z" + } +} +``` + +fields 为完整不透明表单,由实际 OSS SDK/签名版本生成,不能把示例占位字段或某套旧签名字段写死在前端。策略限制精确 temp key、有效期和大小范围。浏览器不具备 final 目录写权限或列举权限。 + +已 COMMITTED 的重试返回原确认回执,不再签发上传;VERIFYING/REJECTED/EXPIRED 返回现有状态,不新建或复活事务。仅 PENDING 且未超过事务期限时允许同请求续签同 key。 + +### 11.3 浏览器直传 + +1. 构造 FormData,原样添加 fields。 +2. 最后附加 file 字段和完整原始字节。 +3. POST 到指定 OSS 地址,不带业务 Bearer,不手动设置 multipart boundary。 +4. OSS 成功后请求 complete。 + +此处 multipart/form-data 是单文件表单上传,不是 OSS 分片协议。不增加 Base64 JSON 工程上传通道。 + +OSS 响应丢失时可先调用 complete;文件不存在则收到 UPLOAD_NOT_READY 后继续同事务。签名过期但 PENDING 事务未过期,可相同 init 续签。 + +## 12. complete、状态查询与幂等回执 + +### 12.1 状态机 + +```text +PENDING_UPLOAD -> VERIFYING -> COMMITTED + | | + v v + EXPIRED REJECTED +``` + +- COMMITTED/REJECTED/EXPIRED 为不可逆终态。 +- PENDING 的 expiresAt 是允许开始确认的截止时间。 +- 已受理 VERIFYING 使用独立校验租约、超时和有限重试,不能由普通过期任务改成 EXPIRED。 +- 可恢复存储/数据库故障不直接变成永久拒绝;在重试预算内继续 VERIFYING。耗尽后明确终态错误,不无限处理中。 + +### 12.2 POST /projects/{projectId}/uploads/{uploadId}/complete + +请求 body 为 `{}`。不接受换 key/hash/文件/版本;以初始化记录为准。 + +PENDING 且对象尚未存在:`409 UPLOAD_NOT_READY`,仍保持 PENDING,可上传后重试。鉴权失败 401;越权事务 404。 + +已开始异步确认,HTTP 202: + +```json +{ + "uploadId": "66666666-6666-4666-8666-666666666666", + "projectId": "11111111-1111-4111-8111-111111111111", + "clientOperationId": "44444444-4444-4444-8444-444444444444", + "clientSnapshotId": "55555555-5555-4555-8555-555555555555", + "status": "VERIFYING", + "retryAfterMs": 1000 +} +``` + +已提交,HTTP 200: + +```json +{ + "uploadId": "66666666-6666-4666-8666-666666666666", + "projectId": "11111111-1111-4111-8111-111111111111", + "clientOperationId": "44444444-4444-4444-8444-444444444444", + "clientSnapshotId": "55555555-5555-4555-8555-555555555555", + "status": "COMMITTED", + "revisionId": "77777777-7777-4777-8777-777777777777", + "headVersion": 4, + "savedAt": "2026-11-03T02:21:00Z", + "file": { + "size": 123456, + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } +} +``` + +HTTP 202、OSS 204、单纯 code=OK 或 VERIFYING 均不能显示已保存。 + +### 12.3 GET /projects/{projectId}/uploads/{uploadId} + +所有状态包含 uploadId/projectId/clientOperationId/clientSnapshotId/status/expiresAt;VERIFYING 可带 retryAfterMs。COMMITTED 返回上述固定确认字段。 + +终态失败查询 HTTP 200,例如: + +```json +{ + "uploadId": "66666666-6666-4666-8666-666666666666", + "projectId": "11111111-1111-4111-8111-111111111111", + "clientOperationId": "44444444-4444-4444-8444-444444444444", + "clientSnapshotId": "55555555-5555-4555-8555-555555555555", + "status": "REJECTED", + "expiresAt": "2026-11-03T02:50:00Z", + "error": { + "code": "HEAD_CONFLICT", + "details": {"expectedVersion": 3, "currentHeadVersion": 4} + } +} +``` + +EXPIRED 同样返回状态及 UPLOAD_EXPIRED。查询成功不等于保存成功。complete 对 REJECTED/EXPIRED 返回对应 HTTP 错误和稳定原因;同 init 重试可以 200 返回原事务终态。 + +### 12.4 固定结果与删除例外 + +- 已 COMMITTED 的 complete/init/status 重试永远返回那笔固定结果,不因当前 head 后来前进变成冲突。 +- 项目后来被 owner 删除,仍允许该 owner 查询已发生的 COMMITTED 回执,可附 projectDeleted=true;不签发新的文件读取授权。 +- 未确认事务遇项目删除,拒绝为 PROJECT_DELETED;不能复活项目。 +- 查询仍需有效身份。其他用户无论项目是否删除都不能查回执。 +- 超时/断网/5xx 后先查同笔事务,不盲目换 operationId 重做。轮询按 retryAfterMs 退避并有前台等待上限;暂停轮询不等于后端取消。 + +## 13. 固化、校验、CAS 的实现要求 + +### 13.1 临时对象不可作为确认文件 + +临时 POST 授权有效期间可能重复写入。因此禁止“校验 temp 后直接引用 temp”,也禁止“先校验 temp,再假设稍后复制到的内容相同”。 + +推荐实现: + +1. complete 取得事务执行权,转 VERIFYING,持久化任务。 +2. 每次校验尝试生成独立 token 和候选 final key,先记录后执行复制。 +3. 将 temp 复制到仅后端可写的候选对象;可用源 version/条件复制固定来源。 +4. 对候选对象实际字节计算 size/hash,执行结构/版本/依赖校验。 +5. 验证执行 token 仍有效,才允许 CAS 提交该候选对象。 + +候选 key 不跨尝试复用。租约过期的旧任务即使晚到,也不能覆盖当前候选或提交。复制请求结果未知时,先查本次候选对象并验证,不能盲目覆盖已存在候选。 + +采用存储版本控制时,固定对象 versionId;不能仅依赖一个在目标桶配置下可能不起作用的防覆盖头。ETag 不能当作原始文件 SHA-256。 + +### 13.2 数据库原子提交 + +对象校验完成后,短事务中按统一顺序锁项目再锁 upload: + +```text +重新验证 owner / project / upload 关联 +若 upload 已 COMMITTED:返回原回执 +验证 upload 状态与 verifier token +检查项目未删除 +检查 head_version == expected_version +写入 blob 和 revision(version = expected_version + 1) +更新项目 head_revision_id / head_version / last_saved_at / updated_at +将 upload 标记 COMMITTED 并保存固定回执 +reserved 配额转为 used 配额 +提交 +``` + +CAS 失败时持久化 HEAD_CONFLICT 终态并释放预留额度,不推进 head。失败处理本身也需事务和幂等;不能依赖已经回滚事务里的错误状态更新。 + +对象读取、hash、解压和 OSS 复制在数据库长锁之外执行。revision/head/upload/配额必须原子一致。唯一约束是最后防线,不取代权限和版本检查。 + +### 13.3 故障恢复 + +对象存储与数据库不在同一事务: + +- 固化成功、DB 提交失败:原事务恢复重试,未引用候选可能成为孤儿。 +- DB 提交成功、响应丢失:重试返回固定 COMMITTED。 +- 校验任务崩溃:租约到期后由恢复任务接管,用新 token/候选,禁止旧任务提交。 +- 所有确认对象必须能从 revision 找到;孤儿允许晚回收,丢失已确认对象不可接受。 + +单体后端可用持久化任务表/现有队列,不要求额外引入消息中间件;只用进程内 Promise/线程而不持久化状态不合格。 + +## 14. 文件校验与依赖 + +校验最终将被引用的对象,而非信任文件名、Content-Type、客户端元数据或 OSS 自定义 metadata。 + +必须检查: + +1. 实际长度与声明相等,且不超过当前限制。 +2. 服务端计算 SHA-256 与声明一致。 +3. 原生容器签名、container.json、document.json 及真实格式版本。 +4. 条目数、压缩后/展开后预算、JSON 深度、解析时间和资源预算。 +5. 重复/歧义条目、路径穿越、绝对路径及不支持的归档特性。 +6. 必要源 blob 引用、实际长度、CRC/hash 及原生格式所要求的结构约束。 +7. 必要外部依赖是否已完整嵌入或被一期明确拒绝。 + +优先复用安全的原生读取组件或兼容的受限校验器,不自行猜测不完整文件结构。不能把“只读 ZIP 魔数”标为完整验证。校验器应能在资源限制下失败退出,业务服务保持可用。 + +允许把完整源文件作为受控临时单文件供 seek 读取,但不能按归档内路径解压到业务目录。不得让校验器访问任意服务器文件或主动抓取任意 URL。 + +### 14.1 结构校验不等于几何保证 + +不运行参数化建模、布尔、渲染作为保存前置条件。可选显示/模型缓存按原生读取规则处理:缓存无效可回退不等于必要源数据可损坏;缓存永远不代替权威源数据。 + +保证持久化的原始字节可重取,不承诺任意外来工程都能无错误求解。编辑续编能力必须通过真实编辑器 round-trip 验收。 + +### 14.2 外部依赖策略 + +- 已完整嵌入 `.sc` 的导入数据和图片等允许。 +- 必需但未包含的外部设计/组件文件一期阻断云保存,返回 EXTERNAL_DEPENDENCIES_UNSUPPORTED。 +- 按字段真实语义判断,不因任意 path 字段存在就误判必要依赖;仅作来源说明的路径不能与实际未解析依赖混为一谈。 +- 不假装已上传附件,不自动下载用户任意 URL。 +- 可选字体的回退与几何/必需依赖区分,明确兼容边界,不保证任意本机字体跨设备完全一致。 + +## 15. 并发、草稿和前端 ACK + +### 15.1 多窗口 + +A/B 都打开 head=3;A 提交成为 4;B 基于 3 的提交必须 HEAD_CONFLICT,不覆盖 A。不提供隐式 force=true。 + +冲突后前端保留草稿,可下载副本、另存新项目,或经用户确认重新加载云端。不能只刷新 head 版本号然后上传旧模型覆盖。 + +### 15.2 保存过程中继续编辑 + +快照 S7 上传时用户继续编辑出 S8:确认只属于 S7,S8 仍未保存。服务端回显 snapshotId/operationId/file hash,前端匹配 user/project/document binding 后才能推进对应云基线。 + +现有引擎本地保存可能直接标记 saved,云适配必须拆分“取得快照”和“服务器确认此快照”。下载副本不能清云 dirty。 + +### 15.3 本机恢复与身份 + +前端将固定快照、原 init 参数、operationId/uploadId 和草稿按用户/项目隔离持久化。刷新后先查询未知事务,再决定是否新建保存。 + +切账号、切项目或关闭文档,旧请求回执不能写入新 binding。401 后停止新写入并保护草稿;已经受理的原事务可能完成,不能宣称取消浏览器请求就撤销了提交。 + +## 16. 错误码 + +| HTTP | code | 语义/前端处理 | +| --- | --- | --- | +| 400 | INVALID_ARGUMENT | 参数或受保护字段不合法,显示错误 | +| 401 | UNAUTHORIZED | JSON;保护草稿,引导统一登录 | +| 403 | QUOTA_EXCEEDED | 当前用户容量/项目额度不足 | +| 404 | NOT_FOUND | 不存在或越权,不泄漏资源 | +| 409 | HEAD_CONFLICT | 保留草稿,处理工程并发 | +| 409 | METADATA_CONFLICT | 重读元数据,由用户决定 | +| 409 | IDEMPOTENCY_KEY_REUSED | 同键异内容,协议错误 | +| 409 | UPLOAD_NOT_READY | 临时文件尚未就绪,可同事务重试 | +| 410 | PROJECT_DELETED | 阻止保存,不自动复活 | +| 410 | UPLOAD_EXPIRED | 保留字节,重试需新 operation | +| 413 | SOURCE_TOO_LARGE | 返回实际 maxSourceBytes | +| 422 | INVALID_SOURCE_FILE | 原生工程结构无效 | +| 422 | UNSUPPORTED_FORMAT_VERSION | 部署不支持实际文件版本 | +| 422 | CHECKSUM_MISMATCH | 实际大小/hash 不符,本事务拒绝 | +| 422 | EXTERNAL_DEPENDENCIES_UNSUPPORTED | 处理必要外部依赖 | +| 429 | RATE_LIMITED | 返回 Retry-After,有界退避 | +| 503 | SAVE_UNAVAILABLE | 结果可能未知,先查同笔事务 | + +失败示例: + +```json +{ + "code": "HEAD_CONFLICT", + "message": "云端已有更新版本", + "data": { + "uploadId": "66666666-6666-4666-8666-666666666666", + "expectedVersion": 3, + "currentHeadVersion": 4 + }, + "requestId": "server-generated-request-id" +} +``` + +错误不清除未保存状态。无 upload 的初始化提前拒绝不伪造 uploadId。持久事务拒绝结果必须可查询;5xx 不能让客户端猜测是否已提交。 + +## 17. OSS、CORS、配额与清理 + +### 17.1 私有存储 + +示例 key 结构,仅为后端内部约定: + +```text +cad//tmp////source +cad//objects/////source.sc +``` + +- 环境隔离,私有读写;不为浏览器暴露长期密钥。 +- 显示名称不决定 key。 +- 最终 key 不覆盖、不跨校验尝试复用;有版本控制时固定版本。 +- 临时授权只允许本次精确位置和合理大小/期限。 +- 下载短期只读,正确设置附件文件名,不能注入响应头。 +- 不记录 token、完整签名 URL 或上传签名表单到普通日志。 + +### 17.2 CORS 和缓存 + +业务 API 精确允许实际开发/生产前端 origin: + +```text +Methods: GET, POST, PATCH, DELETE, OPTIONS +Request headers: Authorization, Content-Type, Accept, Accept-Language, Idempotency-Key +Exposed response headers: X-Request-Id, Retry-After +``` + +OSS 独立配置 POST/GET/HEAD 和实际预检,允许必要请求头并暴露实际读取的 ETag/请求标识。OSS CORS 和业务 API CORS 不能只配其中一处。 + +私有 API、snapshot、事务状态、身份和源文件不进入公共 CDN/SW 缓存。CAD 静态入口和 WASM 资源策略由前端发布处理,不能让静态 fallback 返回 HTML 冒充 API/文件。 + +### 17.3 建议初始参数 + +| 配置 | 建议起点 | +| --- | --- | +| 单源文件 | 50 MiB,测试通过后启用 | +| 上传授权 | 5 分钟 | +| PENDING 事务 | 30 分钟 | +| 下载授权 | 5 分钟 | +| 每用户同时 PENDING/VERIFYING | 建议 3,按实际容量调整 | +| 临时回收宽限 | 建议过期后至少 24 小时,再验证引用/租约 | +| 历史确认快照自动清理 | 一期不启用 | + +用户项目数、总存储、初始化频率、校验并发/内存/耗时和重试上限必须可配置。对外开放前确定具体值,不能隐式无限制。 + +### 17.4 配额一致性 + +init 原子预留 expected bytes;COMMITTED 转 used;REJECTED/EXPIRED 仅释放一次。校验重试不重复记费/预留。存储容量按保留版本计,软删除且仍留存对象不能假装已释放实际容量。 + +临时与重复校验候选的物理开销另外受并发/任务/清理限制,不以逻辑 quota 代替存储运维预算。 + +### 17.5 回收安全条件 + +可回收:过期临时对象、被拒绝/失效尝试的候选、无 revision 引用且无有效任务租约的孤儿。 + +禁止:全前缀无差别生命周期删除、删除 VERIFYING 有效候选、删除已确认引用、项目软删除立即清空历史。 + +清理与任务接管需防竞争,重新核对引用/状态/租约并使用安全宽限。对象存储中存在但 DB 无记录的异常候选也要能按受控前缀识别回收。 + +## 18. 后台恢复、监控和部署 + +至少三个逻辑任务:校验、租约恢复、过期/孤儿清理。可部署在同一服务,但任务状态必须持久化,进程重启后可继续。 + +日志关联字段:requestId、userCode、projectId、uploadId、operationId、状态、大小、校验/提交耗时、拒绝码。日志脱敏。 + +指标:成功保存率、确认耗时、积压、长时间 VERIFYING、校验失败、冲突、存储/DB 错误、额度预留异常和孤儿增长。 + +部署顺序: + +1. 核对/迁移数据库,部署向后兼容的 API 和任务。 +2. 配置私有存储、CORS、额度和实际格式校验器。 +3. 开发环境联调统一登录、CRUD、直传、确认、跨浏览器重开。 +4. 确认编辑器构建与格式支持清单兼容,再切前端入口。 +5. 保留回滚能力,不回删已经保存的工程或新版本数据。 + +备份必须同时考虑数据库引用和不可变对象。上线前完成恢复演练,恢复后的 head 必须能找到正确文件。RPO/RTO 沿用平台既有要求,缺少时由部署方明确,而非文档虚构 SLA。 + +## 19. 前后端分工及配套交付 + +| 工作 | 后端 | 前端/编辑器 | +| --- | --- | --- | +| 统一登录弹窗 | 复用账号系统,不新增 CAD 登录接口 | 弹窗、继续原操作、过期时保护草稿与锁输入 | +| 身份和资源权限 | 每次服务端验证 | 携带现有凭据,不决定 owner | +| 项目列表/CRUD | 十接口中的相关 API | 页面、双语、交互 | +| 工程字节 | 原样存储、校验 | 生成固定快照、读写原生 `.sc` | +| 云保存 | 事务、CAS、幂等、固定回执 | 上传、查询、快照 ACK、dirty | +| 恢复 | 任务接管、查询未知提交 | 用户/项目分区本机草稿 | +| 格式兼容 | 发布真实校验支持清单 | 提供真实样例及构建/格式信息 | +| 并发 | 防覆盖和删除竞争 | 冲突提示、另存、重新加载 | + +前端 API 封装需支持 Idempotency-Key 等自定义请求头;OSS 上传使用独立直传逻辑,不强塞进只接受 JSON 成功信封的业务 request 函数。 + +工程字节使用二进制桥/Uint8Array/Blob,不通过普通 JSON 命令传 Base64。当前编辑器命令桥不等于完整云工程桥;需补齐序列化、打开、文档绑定和快照确认。 + +## 20. Codex 实施顺序和交付要求 + +### 阶段 A:检查和基础模块 + +- 识别现有认证、表、OSS、配置和任务设施,记录复用点。 +- 提交可审查迁移,接入现有认证和通用错误信封。 +- 完成 capabilities、CRUD、创建幂等和权限测试。 + +### 阶段 B:源文件和保存协议 + +- 完成私有读取授权、不可变 snapshot。 +- 完成 upload 初始化、预留额度、签名直传契约。 +- 完成固化/校验任务、CAS、固定回执和状态查询。 +- 完成重启恢复、过期与孤儿清理。 + +### 阶段 C:联调和交付 + +- 先用测试身份、私有测试桶和真实 `.sc` 样例联调,再用真实浏览器编辑器验收。 +- 故障/并发测试通过后提供配置、部署和回滚说明。 +- 运行目标仓库适当的检查,不靠 mock 通过宣称真实 OSS/账号/数据库已经联通。 +- 不将占位格式、无效签名、内存任务或模拟存储作为生产完成实现。 + +最终交付物: + +1. 业务代码、数据库迁移、任务和配置模板。 +2. OpenAPI 或等效机器可读接口定义,覆盖状态、错误和 HTTP 202。 +3. 单元/集成/并发及故障恢复测试结果。 +4. `.sc` 真实样例、校验器格式范围、大小/展开预算说明。 +5. 测试环境 API 基址、允许 origin、OSS 实际行为和限制参数。 +6. 账号接入说明,明确没有新增 CAD 登录体系。 +7. 运维、清理、监控、备份恢复和回滚说明。 +8. 实际完成/未完成列表,明确哪些仅模拟验证,哪些真实服务联调。 + +## 21. 必须通过的验收矩阵 + +| 编号 | 场景 | 预期结果 | +| --- | --- | --- | +| T01 | 未登录调用 CAD API | JSON 401,不返回登录页 HTML 或 302 | +| T02 | 登录后访问 CAD | 接受统一凭据,不需要 CAD 再登录 | +| T03 | A 访问 B 的项目/事务/revision | 404,不签发任何授权 | +| T04 | 同用户创建两个同名项目 | ID/文件独立 | +| T05 | create 响应丢失后重试 | 同一项目,无重复创建 | +| T06 | 同幂等键换请求内容 | 409,不替换原操作 | +| T07 | EMPTY snapshot | head=0,revision/file=null | +| T08 | 重命名并发 | 过期 metadataVersion 冲突,不改变工程 head | +| T09 | 连续三次保存 | 三份不可变确认记录,head 指向第三次 | +| T10 | init/complete 多次重试 | 同操作至多一个 revision | +| T11 | COMMITTED 响应丢失 | 查询返回固定原回执 | +| T12 | head 前进后重试旧成功操作 | 仍返回旧成功,不误报冲突 | +| T13 | 双窗口基于同一 head | 一笔成功,另一笔冲突,不覆盖 | +| T14 | S7 上传期间继续编辑 S8 | 仅确认 S7,S8 仍未保存 | +| T15 | 未上传就 complete | UPLOAD_NOT_READY,可同事务继续 | +| T16 | 签名过期、事务未过期 | 仅 PENDING 可同请求续签 | +| T17 | PENDING 过期 | EXPIRED,不能复活或重复释放额度 | +| T18 | 校验时覆盖 temp | 只提交已固化并验证的最终字节 | +| T19 | 提交后旧临时授权继续写 | 不改变已确认 revision | +| T20 | 大小/hash/格式声明不符 | 拒绝,不推进 head | +| T21 | 非法 ZIP、路径、超大展开、损坏 blob | 受限安全失败,业务服务不崩溃 | +| T22 | 必要外部依赖未嵌入 | 明确拒绝,不假保存 | +| T23 | 校验任务退出/租约接管 | 新旧任务不竞争提交,无重复版本 | +| T24 | 对象固化后 DB 故障 | 可恢复同操作,孤儿可安全回收 | +| T25 | 保存与删除并发 | 不复活项目;已发生提交可查固定回执 | +| T26 | 下载授权过期续签 | 仍绑定正确 revision/字节 | +| T27 | 换账号/项目后旧回执晚到 | 不串数据、不更新新页面状态 | +| T28 | 并发上传和配额释放 | 不超额、不重复扣费/释放 | +| T29 | 清理与有效校验并发 | 不删有效候选或已引用对象 | +| T30 | 跨浏览器下载 | 原始 size/hash 相同 | +| T31 | 真实编辑器跨浏览器重开续编 | 特征/约束/参数可继续修改并再次保存 | +| T32 | 备份恢复 | head 可读取正确不可变文件 | +| T33 | 主站/PCB 回归 | 原登录和项目功能保持正常 | + +完成定义:浏览器 A 登录主站账号,新建 CAD 项目并进行草图/三维编辑,确认云保存后关闭;浏览器 B 同账号从列表打开,修改既有参数后再次保存;A 重新打开获得新结果。失败、并发、删除、重试和换账号时没有假保存、串写或已确认文件被覆盖。真实后端/OSS/编辑器联调未完成前不得宣称线上可用。 + +## 22. 可直接交给后端 Codex 的任务说明 + +```text +请在当前 VibeMake 业务后端仓库实施《VibeMake CAD 后端实施与接口契约 v1.2》。 + +先阅读当前仓库规则,检查已有账号鉴权、API 信封、数据库迁移、OSS、任务和测试体系, +然后按文档完成独立 CAD 模块。已有能力优先复用,不覆盖现有 CAD 或其他业务数据。 + +用户已经决定:CAD 复用主站统一登录弹窗;后端仍须鉴权和 owner 校验,不新增 CAD 登录/注册/验证码/账号/token 签发。 +CAD API 复用统一认证,逐请求校验项目、revision 和 upload 的 owner。 + +源文件是 SolidCraft 原生 .sc,不能套用 DWG/DXF 或将 STEP/STL/GLB 当权威工程。 +严格实现不可变快照、受限 OSS 临时直传、最终固化校验、幂等事务、CAS 和固定 COMMITTED 回执。 +上传成功、HTTP 202 和本机草稿不能当作云保存成功。 + +按文档顺序实现数据库、十个 API、任务恢复/清理、额度、错误码和验收测试。 +环境差异从现有配置识别;无法确认的登录地址/身份验证/桶权限/格式校验器要列明, +不能编造已联通能力,也不能用 mock/内存存储冒充生产实现。 + +只在本地和测试环境验证,不部署生产或执行破坏性迁移。 +交付机器可读接口定义、配置模板、测试结果、部署回滚说明及真实未完成项。 +``` diff --git a/docs/vibemake/frontend-implementation.md b/docs/vibemake/frontend-implementation.md new file mode 100644 index 000000000..e33712ea4 --- /dev/null +++ b/docs/vibemake/frontend-implementation.md @@ -0,0 +1,152 @@ +# VibeMake CAD 前端与引擎集成 + +本文记录 VibeMake 主站与 SolidCraft WASM 引擎的前端集成边界、构建步骤、运行配置和发布验收。云项目 API 与上传协议以同目录的 [CAD 个人工作空间前端对接](workspace-api.md) 为准(2026-11-05 同步)。`backend-implementation.md` v1.2 是历史方案,其中的旧接口、私有 Bucket 和下载签名约定不再作为当前对接依据。 + +## 产品结构 + +| 路径 | 用途 | 加载 CAD WASM | +| --- | --- | --- | +| `/cad/` | VibeMake CAD 项目列表 | 否 | +| `/cad/editor/?project=` | 单项目编辑器 | 是 | + +VibeMake 原生 ES 模块负责账号复用、登录弹窗、项目 CRUD、路由、设备检查、二进制下载、IndexedDB 草稿和云保存协调。SolidCraft Rust/WASM 负责文档解析、参数化建模、模型视图、原生格式序列化、快照和精确保存基线。浏览器中的 `window.vibemakeCad` 是平台宿主桥;既有 `window.solidcraft` 建模 API 仍由引擎提供。 + +登录沿用主站 `vm.auth` 和邮箱图片验证码弹窗。进入列表或编辑页时先验证身份,再读取私有数据。取消弹窗不加载项目或引擎。CAD 本身不签发凭据;CAD API 每次仍需校验当前身份和项目 owner。 + +## 源码位置 + +VibeMake: + +- `js/cad/` 页面控制器、文案、接口、快照保存协调器、本机草稿和引擎加载。 +- `js/auth-dialog.js` 主站与 CAD 共用的登录表单;`js/auth.js` 保留既有导出接口。 +- `cad.html` 列表入口;`cad/editor/index.html` 编辑器壳层;`css/cad.css` 产品样式。 +- `scripts/cad-engine.mjs` 校验并组合独立引擎;`scripts/server.mjs` 提供本地深链接、API 代理和引擎资源。 + +SolidCraft: + +- `crates/ui-egui/src/platform.rs` 平台策略与单文档约束。 +- `apps/solidcraft-web/src/platform.rs` WASM 二进制宿主桥。 +- `crates/engine/src/lib.rs` 快照 ACK 的文档基线,以及宿主项目替换时的旧检查点隔离。 +- `assets/styles/ui/themes/vibemake-dark.json` VibeMake Dark UI token;视口底色、坐标轴、选择、警告、错误与预览颜色继续由原工程主题提供。 +- `assets/locales/pending/vibemake-platform.json` 与 `attribution/pending/vibemake-platform.md` 按上游目录规则保留新主题及消息。 + +## 前端行为约束 + +- 编辑页固定 42px HTML CAD 应用栏,VibeMake Logo 返回 CAD 项目列表,文件/保存/撤销/重做靠左,助手/首选项/帮助/保存状态/账号靠右;不显示主页图标或独立产品标题。WASM 画布使用其余视口。单页只绑定一个项目;多个项目由多个浏览器标签页承载。 +- 初始设备检查在引擎加载之前执行。手机、平板或宽度不大于 820px 时显示桌面提示;编辑时窗口变窄则锁住画布并保留当前页面和文档。 +- 品牌色、产品名、帮助目标和外部链接集中维护。对外只开放简体中文与英文,语言偏好键为 `vm.cad.locale`,新账号首次进入默认中文。 +- Rust 平台模式独立于旧 `embed`。它隐藏不能接入的桌面进程、ACP、本机工具发现和插件功能,过滤菜单、命令搜索和命令执行入口。原版助手通过浏览器模型连接运行,详见 [Web 助手说明](web-assistant.md)。宿主接管的文档重绑命令明确拒绝调用。 +- Native `.sc` 打开先在临时会话校验,再创建云项目。坏文件、格式不兼容或权限失败不会替换当前文档。插入 STEP、Mesh、Point Cloud 和实际可用的导出仍走已有 Rust 命令。 +- 项目列表展示接口返回的 `coverUrl`,只接受完整 HTTPS 地址;图片延迟解码、按需加载并完整展示,缺少封面或加载失败时显示既有占位。列表不加载 CAD 引擎。 +- 云保存和另存通过 `createSnapshot({includeCover:true})` 同时获取原生文件和 640×400 PNG。封面复用缓存显示网格、实体颜色和独立等轴测相机,不读取或修改编辑相机,不包含平台 UI、网格或选择高亮;空模型、未就绪缓存或超出绘制预算时保留原封面并提示预览不可用。普通草稿不额外生成云封面,原生容器内缩略图规格不变。 +- 原生文件确认并 ACK 后,复用 `/uploads/project-covers/signature` 签名、匿名 OSS FormData 上传,再以 `PATCH {coverUrl}` 绑定到 CAD 项目。封面任务单独保存在账号和项目隔离的 IndexedDB 日志,失败显示工程已保存,重试不重复上传工程或增加版本;PATCH 失败可重用已上传的普通图片地址。页面重新打开后可恢复同版本的封面任务。 +- 封面 PATCH 按当前接口没有版本条件参数。前端在上传前和绑定前检查远端文件版本,放弃已知过期的任务;这不等于服务端原子版本校验,最后一次 GET 与 PATCH 之间的跨客户端竞态仍需后端条件更新协议解决。封面上传需要 `OSS_ENABLED`,独立于工程的 `CAD_OSS_ENABLED`。 +- 保存只传固定的原生工程快照。单个 `SaveCoordinator` 串行执行申请签名、OSS 表单直传和 `PUT document` 确认;确认回执的 `cadProjectCode`、下一版本号和 `savedAt` 校验成功后,才 ACK 对应 binding 下的快照。快照 ACK 不修改随后发生的更改、项目名或视图。 +- 上传响应丢失或上传失败时,先用原 `uploadCode` 确认;确认仍不明确时保留批次和原生文件。仅后端明确返回文件缺失、大小不符或批次过期时才申请新批次。确认超时重试原批次,不重复创建项目或版本。 +- IndexedDB 数据库存于 `vm.cad`,按账号、项目、标签页会话分区;草稿是二进制原生工程,保存事务日志不含认证 token、签名地址或 OSS 凭据。不可用时明确告警。草稿不等于云端保存。 +- 离开保护、`Ctrl/⌘+S`、另存和下载都由宿主统一协调。冲突时保留当前内容并提供另存、下载或用户确认重载;不会自动更新 head 后覆盖远端。 +- UI 更新使用同源 `/cad/sw.js`,worker 只认识当前 engine manifest 中列出的无查询参数静态资源路径,不拦截 API、身份响应、私有文件或签名 URL。它不调用 `skipWaiting`,更新通过“保存后刷新”提示交给用户。 + +## Web 助手边界 + +助手复用 Rust/egui 面板、对话、权限、工具记录与撤销分组,不加载社区 Maker AI。服务预设、连接类型布局、附件菜单及模型列表沿用原版;图片/文本可选择或拖入,剪贴板图片由浏览器授权后读取。需要本机进程的连接类型和独立系统窗口保留原版位置并显示不可用原因。 + +浏览器直接访问用户自行配置的模型服务;VibeMake 业务 API 不转发模型请求。协议支持 OpenAI 兼容和 Anthropic 兼容的非流式 JSON 响应,界面异步等待。请求可取消并有超时及响应大小限制。服务必须允许浏览器访问,协议兼容性由一次真实模型请求和无副作用的工具探针确认。工具失败反馈给模型以便解释或修正,后续操作仍通过原版审批和当前工程校验。 + +下一阶段服务边界、完整事件映射和 CAD 工具往返见 [Web 助手后端接入交接](assistant-backend-handoff.md)。这是待实现协议;接入时仍需实现 Rust `RemoteBackend`,当前没有已连接的远程助手运行服务。 + +`window.vibemakeCad.ready()` 的 `capabilities.assistant` 表示引擎实现了助手。VibeMake 编辑页绑定工程后助手自动显示在右侧全高分栏,网页菜单栏与助手共用分隔线和栏宽;平台分隔线拖动也会同步更新菜单栏宽度。宿主在工程绑定后调用 `setAgentContext({userId, projectId, binding, sessionId})`,身份失效或退出时调用 `setAgentContext(null)`;`showMenu("assistant")` 确保常驻助手可见,不会关闭它。`getState()` 与订阅的 `assistant` 仅包含能力、开关、连接、运行、待审批计数及公开的栏宽,不含密钥、消息或平台 token。新外壳使用旧引擎时隐藏助手入口并提示更新。 + +普通助手配置、权限与授权记录保存在账号独立的 `vm.cad.agent.profile.`;共享 `vm.cad.engine.prefs` 不保存这些内容。密钥默认只保存在页面内存,主动勾选后才写入独立 IndexedDB `vm.cad.agent.credentials.v1`。该存储不是系统钥匙串,同源脚本可访问。退出或切换账号取消请求并清理内存,对话刷新后不恢复。 + +AI 工具仍执行 Rust 命令;Web 适配层复用 MCP 的工具 schema 和调用校验,不运行本机进程、任意 JavaScript 或终端。权限不能解除宿主工程绑定和输入锁定。工具发起、审批与实际执行时检查当前轮次和文档修订;用户在轮次中修改模型会取消旧审批。AI 修改只更新工程 dirty,不自动云保存。 + +## 引擎产物 + +保持 SolidCraft 默认 SMLib WASM 构建开启,不发布不含内核的空壳。先在 SolidCraft 仓库根目录执行: + +```sh +node scripts/build-vibemake-cad.mjs +``` + +产物默认写入 `dist/vibemake-cad-engine/`,也可使用 `VIBEMAKE_CAD_ENGINE_OUT` 指定输出目录。`engine.json` 含 `bridgeVersion`、`engineKind`、kernel、build id,以及每个 JS/WASM/字体/许可证文件的路径、大小和 SHA-256。产物目录包含匹配的 `_assets//`。 + +当前主站 `scripts/build.mjs` 已采用独立引擎发布:主站包不会自动复制引擎,也不会把引擎放进主站 ZIP。发布时必须另外校验并发布上述产物,不能只上传主站包。可复用主站已有的 `readCadEngine` / `copyCadEngine`,生成专用于叠加发布的目录: + +```sh +VIBEMAKE_CAD_ENGINE_DIST="/path/to/solidcraft/dist/vibemake-cad-engine" \ +VM_CAD_STAGING="/absolute/path/to/cad-release" node --input-type=module <<'JS' +import { readCadEngine, copyCadEngine } from './scripts/cad-engine.mjs'; +if (!process.env.VM_CAD_STAGING) throw new Error('VM_CAD_STAGING is required'); +copyCadEngine(readCadEngine(process.env.VIBEMAKE_CAD_ENGINE_DIST), process.env.VM_CAD_STAGING); +JS +``` + +命令在 VibeMake 仓库运行。缺少清单、缺少文件、哈希不匹配、引擎版本不兼容或资源不在 build id 路径下都会失败。将 staging 的 `cad/` 叠加发布到网站根目录,保留线上旧 `_assets//`;最后更新 `engine.json`。主站构建会重建自己的 `dist/`,不能依靠它保留旧引擎目录。不会回退旧 iframe。 + +本地开发服务从 VibeMake 仓库启动: + +```sh +PORT=8091 VIBEMAKE_CAD_ENGINE_DIST="/path/to/solidcraft/dist/vibemake-cad-engine" npm run dev +``` + +开发环境 `/api` 由此同源服务代理;部署仍沿用主站现有 `API_BASE`、域名选择和后端 CORS 配置。真实开发和生产环境不得将测试 mock 后端作为默认目标。 + +静态主站需要为两条 CAD URL 配置 SPA/目录索引回退;`/cad/_assets//...` 使用一年 immutable 缓存,`/cad/engine.json`、页面、worker 不做长缓存。WASM 返回 `application/wasm`,页面通过绝对 `/cad/` 资源 URL 载入。不要在部署清理时删除仍被已打开页面引用的旧 build-id 资源。发布新版本不改变 PCB 路由;回滚时恢复页面和 `engine.json`,保留所有 engine asset 目录。 + +## API 与错误边界 + +云接口前缀为 `/api/cad/workspace/projects`,字段、幂等回执、版本冲突、错误语义和容量上限由 `workspace-api.md` 定义。当前接口不提供 capabilities、complete 或上传状态查询端点。读取文件和原生工程快照受编辑器 256 MiB 上限约束;下载内容在解析前校验实际长度,草稿和事务日志使用本机 SHA-256 校验。 + +对象存储上传将签名中的 `formFields` 原样加入 FormData,最后追加名为 `file` 的原生 `.sc`;不注入 private ACL,不手写 multipart Content-Type。上传和文件读取均不带平台 Bearer token。文件读取使用普通 OSS/CDN 地址,允许 `expiresAt=null`,不做签名续期。403 提示管理员检查 OSS/CDN 访问权限和跨域配置,不触发平台退出登录或自动重新获取地址。编辑基础版本始终来自同次读取的 `document.version`。 + +后端 CAD 存储复用主站 `vibemake.oss` 的连接参数和 `OSS_PUBLIC_BASE_URL`,由 `CAD_OSS_ENABLED` 独立开启;不要求专用私有 Bucket。`CAD_STORAGE_UNAVAILABLE` / `CAD_STORAGE_UNSAFE` 提示管理员检查开关和连接配置。前端不接收或保存 RAM 密钥。删除项目不会撤销已发出的普通文件直链。 + +前端只依稳定错误 `code` 选择双语文案;平台 API 的 HTTP 401 表示身份失效并打开共用登录弹窗,普通超时、离线和 5xx 不会清除登录态。收到账号切换时先锁画布、保护旧账号草稿并释放旧项目;过期写入回执不得确认新文档。`CAD_VERSION_CONFLICT`、项目 404、上传结果未知与本机草稿损坏都保留本地工程并明确给出恢复动作。 + +## 验证 + +VibeMake 定向自动测试: + +```sh +npm run test:cad +npm run test:downloads +npm run test:experiences +``` + +真实 WASM 浏览器集成使用测试专用 API/对象存储模拟器,不写真实云端: + +```sh +node tests/cad/mock-server.mjs +PORT=8091 API_TARGET=http://127.0.0.1:8092 \ + VIBEMAKE_CAD_ENGINE_DIST="/path/to/solidcraft/dist/vibemake-cad-engine" npm run dev +``` + +另一个终端执行 `npx playwright install chromium`(首次运行)和 `npm run test:cad:browser`。可设置 `VM_CAD_BASE_URL`、`PLAYWRIGHT_CHROMIUM_EXECUTABLE`、`VM_CAD_ARTIFACT_DIR`;浏览器记录和截图只写到指定的本机验收目录。 + +SolidCraft 定向检查: + +```sh +cargo fmt --all --check +cargo check -p solidcraft-ui-egui +cargo check -p solidcraft-web --target wasm32-unknown-unknown +cargo test -p solidcraft-engine --lib cloud_snapshot --profile release +cargo test -p solidcraft-ui-egui --lib vibemake_platform --profile release +cargo xtask lists +cargo xtask assets +cargo xtask ui-containers +cargo xtask layers +cargo xtask skills +``` + +发布前还需运行各仓库完整 CI,在真实后端和对象存储完成端到端及受支持浏览器矩阵。真实 API、OSS、Windows/Edge、Safari 降级、服务端最大工程容量和生产部署回滚在本机 mock 环境中无法证明,发布记录不得把这些标成已验收。 + +### 封面专项验证(2026-11-05) + +- `npm run test:cad` 57 项、下载测试 7 项、体验资源测试 40 项通过;覆盖封面签名与匿名直传、同快照绑定、封面失败单独重试、重新打开后的任务恢复、账号隔离和过期版本检查。 +- macOS 安全校验进程恢复后,`node scripts/build-vibemake-cad.mjs` 完整通过(包含 release WASM 编译、Trunk 优化与资源打包)。新引擎构建号为 `25c0c2b8b7c9a5235ac69ae0`,构建时间为 2026-11-05 17:17:51(Asia/Shanghai),8 个资源均通过 `readCadEngine` 的大小与 SHA-256 校验。 +- `cargo fmt --all --check` 以及 `cargo test -p solidcraft-engine --lib --features smlib --profile ci cmd::file::thumbnail::tests -- --test-threads=1` 通过(4 项),确认固定封面尺寸、保存基线不变及原生缩略图行为。 +- 使用上述实际发布版 WASM 的 `createSnapshot({includeCover:true})`,未注入测试图片:确认 640×400 PNG、切换实时相机后封面字节不变、截图不移动当前相机。实际页面连接测试专用 API/OSS,验证签名、匿名上传、封面 PATCH 不增加文件版本、列表显示且不加载引擎、图片 404 回退;模拟封面签名失败后,真实保存按钮仍完成原生工程保存,刷新后补传不再增加版本。5 项专项检查通过,页面脚本错误为 0,记录位于 `target/cad-cover-verification/actual-engine-browser-results.json`,截图为同目录 `fixed-camera-cover.png` 和 `project-list-with-cover-zh.png`。 +- `npm run test:cad:browser` 完整回归未通过:现有菜单断言仍要求 `assistant` 按钮,而当前页面仅有 `file`、`preferences`、`help`。测试在封面步骤前停止;未将上述封面专项结果写成完整回归通过。 +- `npm run build` 已生成配套主站 `vibemake/dist.zip`。独立引擎部署包为 `solidcraft-main/dist/vibemake-cad-engine-25c0c2b8b7c9a5235ac69ae0.zip`,根目录为 `cad/`,只包含本次构建及部署说明;两个 ZIP 均通过完整性检查。主站 ZIP 不包含引擎,发布时按独立引擎说明叠加,并最后切换 `engine.json`。 +- 发布时必须同时更新主站前端和对应的新 WASM 引擎。使用旧引擎或取不到预览时,原生工程仍能保存,界面提示封面预览不可用并保留旧图。真实账号与 OSS 联调尚未执行。 diff --git a/docs/vibemake/web-assistant-validation.md b/docs/vibemake/web-assistant-validation.md new file mode 100644 index 000000000..2b563294d --- /dev/null +++ b/docs/vibemake/web-assistant-validation.md @@ -0,0 +1,90 @@ +# VibeMake CAD Web 助手验收记录 + +日期:2026-11-03。此次交付仅修改 Rust/WASM、VibeMake 编辑器外壳、测试及文档,没有新增业务后端或模型代理。 + +## 产物与运行环境 + +- 独立引擎 build ID:`d269c0e2629dce707e7048a4`。 +- 构建时间:2026-11-03 20:06:12(Asia/Shanghai)。 +- 引擎:默认 SMLib;未使用无内核构建。 +- 产物:`dist/vibemake-cad-engine/engine.json` 及对应 `_assets//`,清单含 8 个文件。 +- `readCadEngine` 校验原产物后,通过 `copyCadEngine` 复制至独立 staging,再重新校验成功。 +- 浏览器:本机 macOS Google Chrome,经 Playwright 驱动;WebGPU 测试允许 SwiftShader。不能据此宣称硬件 GPU、Windows、Edge 或 Safari 已全部验收。 +- 本机站点:`http://localhost:8094`;测试专用 API / 模型接口:`http://127.0.0.1:8092`。该模型接口仅属于测试,不是产品后端,不应发布成公共代理。 + +## 已通过的检查 + +| 检查 | 结果 | +| --- | --- | +| `npm run test:cad` | 35 项通过 | +| 最终 SMLib 引擎的 `npm run test:cad:browser` | 38 项通过,`errors: []`;其中 18 项为助手专项,其余为 CAD / 登录 / 设备回归 | +| 原版助手核心回归,复用 workspace CI 编译的 UI 测试二进制,过滤 `agent_chat` | 275 项通过 | +| VibeMake 主题回归 | 1 项通过;视口背景、网格、坐标轴、工程选择色、警告、错误及预览色不变 | +| Web 宿主测试 | 28 项通过,包含 2 项无子进程 MCP 适配测试 | +| 原版 MCP 测试 | 95 项通过 | +| 当前源码 native workspace Clippy | `cargo clippy --workspace --all-targets --profile ci -- -D warnings` 通过 | +| 当前源码 Web 宿主 Clippy | `cargo clippy -p solidcraft-web --target wasm32-unknown-unknown --no-deps -- -D warnings` 通过 | +| WASM 检查 | 14 个 crate 通过 | +| Rust 格式 | `cargo fmt --all --check` 通过 | +| 资源、图标、许可证、列表、技能、分层、UI 容器、mesh-decisions | 全仓库 CI 的静态阶段通过 | +| 中英文及 complete locale 覆盖 | `cargo xtask i18n --check` 通过;德语、韩语仍是上游部分翻译 | +| 离线与更新 | `cargo xtask web-offline-test` 通过 | +| 最终 SMLib Web 构建 | `node scripts/build-vibemake-cad.mjs` 通过 | + +原版助手核心回归包含新增的短消息高度与复制按钮测试、Stop 后旧工具不得进入下一轮测试,以及已有的权限、消息队列、工具、快捷键和撤销回归。 + +## 浏览器回归与截图证据 + +本轮使用上面记录的最终 build ID。完整结果保存在 [browser-results.json](evidence/web-assistant-2026-11-03/browser-results.json),包含 38 项检查名称和空错误列表。 + +归档截图时修正了测试对设置页切换的等待方式,并确认实际助手设置页已显示、语言状态已同步;随后单独重跑 18 项助手检查,全部通过,记录见 [assistant-browser-results.json](evidence/web-assistant-2026-11-03/assistant-browser-results.json)。本次补跑未修改产品代码或引擎产物。 + +助手专项覆盖: + +- 原版面板与初始 Ask;未批准、拒绝和人工修改期间的旧审批都不能执行建模。 +- OpenAI / Anthropic 兼容请求;请求不携带主站身份凭据;仅聊天模型不能执行 CAD 工具。 +- AI 多步建模的一次撤销;AI 修改后正常云保存、重开及原生工程可编辑性。 +- 内存 Key 刷新后清空;主动记住后恢复;更换服务地址不继承旧 Key;IndexedDB 失败明确提示且内存 Key 可用。 +- 模型服务 401、429、无效 JSON、重定向、实际 CORS 拒绝、离线与 30 秒超时;均不退出主站账号。 +- All 权限下仍拒绝云项目重绑;Stop、人工修改及账号上下文切换取消旧操作,晚到响应不修改新会话。 + +其余 CAD 用例覆盖项目列表导航与搜索、真实 WASM 和中文字体、单行应用栏、撤销状态、原子打开损坏工程、快照 ACK 与后续 dirty、手动云保存、丢失回执查询、文件 403、公共文件地址、跨上下文重开、版本冲突、本机草稿、双语,以及窄屏、移动设备和取消登录时的引擎加载限制。 + +截图由自动化实际运行的编辑器捕获。模型接口、账号、提示词与 Key 均为测试数据,不能据此宣称真实厂商验收通过。 + +| 截图 | 检查内容 | +| --- | --- | +| [中文审批](evidence/web-assistant-2026-11-03/assistant-approval-zh.png) | 审批前无新实体;操作名称、拒绝、始终允许和允许一次可见 | +| [中文建模结果](evidence/web-assistant-2026-11-03/assistant-result-zh.png) | 原版工具活动记录、模型修改和手动保存状态 | +| [中文助手设置](evidence/web-assistant-2026-11-03/assistant-settings-zh.png) | 原版设置页、API 智能体、模型、权限和请求超时 | +| [英文助手设置](evidence/web-assistant-2026-11-03/assistant-settings-en.png) | 同一设置页的英文布局 | +| [英文助手面板](evidence/web-assistant-2026-11-03/assistant-en.png) | 原版面板、停靠、输入区和绿色发送按钮 | +| [浏览器密钥表单](evidence/web-assistant-2026-11-03/assistant-key-setup.png) | 浏览器内存 / 主动记住的表单;不包含真实服务凭据 | + +已目视检查上面的中英文页面、审批和结果:未发现本轮助手新增控件的遮挡或文字截断,3D 背景及实体材质表现保持。少量复用的上游启动说明和面板介绍仍出现 SolidCraft 名称,尚未全部统一为 VibeMake 称谓。 + +## 全仓库 CI 的失败与未完成范围 + +执行了 `SOLIDCRAFT_TEST_JOBS=2 CARGO_BUILD_JOBS=2 cargo xtask ci`。静态检查、WASM 检查和 doc tests 通过,测试阶段实际观察到以下失败: + +- `kernel / boolean_props`:`edge_only_box_join_is_refused_in_both_orders`、`translation_invariant`。前者使用同一已编译的测试二进制单独运行仍失败,报告 edge-only join 产生非流形结果。 +- `solidcraft-cli / naming_corpus`:`oracle/83-boundary-loop-thicken` 的 `surface.thicken` 返回 SMLib status 1001。 +- `solidcraft-cli / action_matrix`:`action_matrix_sample` 的既有 shell 基线失败。 + +命名 corpus 和 action matrix 的对应失败已列在仓库 `tests/KNOWN_FAILING_TESTS`。上述几何、命名与测试期望代码没有在本次助手适配中修改,也未通过忽略测试或修改基线掩盖失败。布尔测试的两个失败不在该基线清单中,仍需独立排查。 + +确认这些失败后停止了尚未完成的全仓库几何测试。**完整 CI 没有通过;停止时剩余测试不计为通过。** 助手核心、主题、MCP 和 Web 宿主测试分别验证。一次更早的全仓库构建还曾因磁盘不足失败;清理的仅是可重建的编译缓存,此后独立引擎构建完成。 + +额外尝试的全依赖 WASM Clippy 被未修改的 `crates/io/src/safe_write.rs` 中 `drop_non_drop` 阻断。Web 宿主自身的严格 Clippy 已通过;这不等于全依赖 WASM Clippy 通过。 + +## 实际支持边界 + +- 浏览器直连 OpenAI 兼容 / Anthropic 兼容的非流式 JSON 请求;UI 与网络异步运行,支持停止、超时和响应大小限制。 +- 工具能力依真实模型请求探针判定;仅聊天的服务不执行 CAD 工具。 +- API Key 默认在内存,主动勾选后才使用账号分区的 IndexedDB;同源脚本仍可能读取浏览器存储。 +- 不支持原生程序、ACP 子进程、终端、本地连接服务、系统钥匙串或独立桌面窗口。 +- 不新增自动云保存;AI 改动仍需用户手动保存,是否逐次审批由所选权限决定。 +- 未提供真实商业模型服务的地址 / Key,未部署真实 HTTPS 验收站点,因此**没有任何具体模型厂商被标记为实测支持**。 +- 真实后端与 OSS、浏览器本机网络权限、硬件 GPU 及跨浏览器矩阵仍需发布前实测。本机可控接口测试不能代替这些验收。 + +使用和连接排错参见 [Web 助手说明](web-assistant.md),引擎发布方式参见 [前端与引擎集成](frontend-implementation.md)。 diff --git a/docs/vibemake/web-assistant.md b/docs/vibemake/web-assistant.md new file mode 100644 index 000000000..6cb813437 --- /dev/null +++ b/docs/vibemake/web-assistant.md @@ -0,0 +1,96 @@ +# VibeMake CAD Web 助手 + +## 使用方式 + +1. 在桌面浏览器登录 VibeMake,打开一个 CAD 云项目。 +2. 点击顶部右侧的助手图标,或使用原版助手快捷键。 +3. 在“首选项 → 助手”添加智能体,选择 OpenAI 兼容或 Anthropic 兼容协议,填写名称、服务地址和模型名称。没有模型列表也可以手动填写模型。 +4. 按服务要求填写 API Key,点击测试连接。测试会调用一次模型,并请求一个不修改工程的工具。测试可能产生模型服务费用。 +5. 使用“每次询问”模式开始对话。读取工程可直接执行;修改工程需先批准。也可在原版权限设置中选择“自动允许模型编辑”或“全部”。 +6. 检查修改结果,需要时撤销;确认后使用正常云保存。助手不会自动把模型修改保存到云端。 + +服务地址填写 API 基址,例如服务文档定义的 `/v1`,不要填写单个 `/chat/completions` 或 `/messages` 请求地址。界面沿用原版服务预设,也支持自定义地址;预设仅帮助填写,不能视为已经通过浏览器认证。“兼容协议”表示请求形状,不能保证任意服务支持浏览器、图片或全部工具。修改协议或服务预设时,旧密钥不会随之发送到新地址。 + +“已安装”和“自定义命令”保留原版位置,当前置灰并说明需要助手服务或本地连接程序。独立系统窗口入口同样说明 Web 限制;左右停靠、调整宽度、最小化和新建对话继续使用原版交互。 + +输入区“+”恢复原版菜单:添加文件或粘贴图片。剪贴板图片需浏览器授权,不可用时可改用文件选择。选择器支持原版图片和文本扩展名(含 SVG 源码、TSV、日志等);图片/文本也可拖入助手。PDF、CAD 文件及任意本机路径不在当前聊天附件能力内。连接时自动读取模型列表,失败时显示警告并保留手输模型。 + +## 数据与凭据 + +- 浏览器直接请求该模型服务,不经过 VibeMake 模型代理,也不发送 VibeMake token 或 Cookie。 +- 对话会按需包含当前工程摘要、选择与工具查询结果。视图截图和图片/文本文件由用户主动附加;不默认上传完整 `.sc`。 +- CAD 文件继续使用文件菜单导入,不能在聊天中绕过工程绑定和导入确认。 +- 对话仅在当前页面会话内存在;刷新后清空。普通智能体配置、默认项、权限和授权记录按账号保存。 +- API Key 默认仅存在当前页面内存,刷新后需重新填写。勾选“在本浏览器记住”才保存到账号独立的 IndexedDB。 +- 取消记住、删除密钥或清除本账号已记住密钥,会删除持久化副本。浏览器存储失败时提示“未记住”,当前页面仍可使用内存中的密钥。 +- 浏览器存储不是系统钥匙串;同源脚本可访问。更换服务地址时必须重新填写密钥,不自动传递旧密钥。 +- 退出或换账号清空内存中的凭据和任务;主动记住的凭据仍属于原账号。多个设备或浏览器不会同步密钥。 + +## 权限和取消 + +| 设置 | 规则 | +| --- | --- | +| 每次询问(初始值) | 读取直接执行,修改先审批 | +| 自动允许模型编辑 | 普通建模修改直接执行,其他原版需确认操作继续询问 | +| 全部 | 当前 Web 平台允许的工具自动执行 | + +单智能体覆盖和“允许一次 / 始终允许 / 拒绝”沿用原版。所有模式都禁止助手替换当前云项目、访问本机文件、执行终端、退出账号或绕过平台锁定。用户在轮次中修改模型会使旧审批失效,需要基于最新模型继续。 + +停止会取消网络和尚未执行的工具,已经完成的修改保留并可撤销。正在运行的同步几何计算不能保证立即中断。登录失效、宿主锁定、项目释放和上下文切换同样取消未完成任务。工具失败、拒绝或参数无效时,以失败状态保留工具记录并将错误反馈给模型,供其解释或修正;后续工具仍逐项通过相同审批和工程检查。 + +## 连接排错 + +| 现象 | 检查方法 | +| --- | --- | +| 401 / 403 | 检查模型服务自己的 Key、权限和配额;这不会退出 VibeMake | +| 429 | 模型服务限流或额度限制,稍后重试并检查服务控制台 | +| 网络失败 | 检查服务地址、HTTPS、网络、服务状态、浏览器本机网络权限与跨域配置;不能只凭浏览器的通用错误断定是 CORS | +| CORS 拒绝 | 模型服务必须允许当前网站源、所需请求方法和请求头;前端不能绕过服务端拒绝 | +| 跳转失败 | 带 Key 的请求不自动跟随重定向,请填写最终 API 基址 | +| 请求超时 | 检查服务状态,或调整智能体请求超时;停止可取消请求与响应读取 | +| 响应无效 | 检查所选协议、服务基址及非流式 JSON 兼容性;超出 16 MiB 的响应会被拒绝 | +| 仅支持聊天 | 模型能回答但未通过工具调用探针;不会标记为可操作 CAD,需更换支持工具调用的模型 | +| 模型列表失败 | 可以手动输入模型名称,再测试真实模型请求 | +| 密钥未记住 | 检查浏览器 IndexedDB、隐私模式、配额和网站存储权限;不等于密钥无效 | +| 助手要求引擎更新 | 主站和独立引擎版本不匹配,需发布含助手能力的新引擎 | + +默认允许 HTTPS;本机地址遵循已有严格 loopback 规则。HTTP localhost 能否从线上网站访问仍由浏览器安全策略决定,不能保证所有浏览器可用。 + +## 实现位置 + +- `crates/ui-egui/src/agent_chat/`:原版 UI、共享协议、权限、轮次和文档检查。 +- `apps/solidcraft-web/src/agent.rs`:Fetch、AbortController、模型探针、双协议回合及浏览器附件。 +- `apps/solidcraft-web/src/agent_tools.rs`:无子进程的 MCP 工具适配;只派发尚未执行的控制请求。 +- `apps/solidcraft-web/src/agent_storage.rs`:账号配置、内存密钥和可选 IndexedDB。 +- `apps/solidcraft-web/src/platform.rs`:能力声明、上下文、锁定与生命周期。 +- VibeMake 的 `js/cad/app.js`:应用栏入口、账号/工程上下文同步与取消。 + +## 自动化验证 + +生产代码没有新增模型代理。`vibemake/tests/cad/assistant-model.mjs` 仅为自动化测试提供可控的本机模型接口,不能部署成公共服务。 + +在 VibeMake 仓库启动测试 API,再使用已构建的 SMLib 引擎启动站点: + +```sh +node tests/cad/mock-server.mjs +``` + +```sh +PORT=8094 API_TARGET=http://127.0.0.1:8092 \ +VIBEMAKE_CAD_ENGINE_DIST="/path/to/solidcraft-main/dist/vibemake-cad-engine" \ +node scripts/server.mjs +``` + +另一个终端: + +```sh +VM_CAD_BASE_URL=http://localhost:8094 \ +VM_CAD_ARTIFACT_DIR=/absolute/path/to/artifacts \ +npm run test:cad:assistant +``` + +`npm run test:cad:browser` 还会执行已有 CAD 集成回归和助手用例。真实 HTTPS 部署、实际模型服务及不同浏览器的兼容范围必须另外实测;本机可控接口通过不能当作商业模型服务已认证。 + +最新一轮前端还原、最终构建、46 项 CAD 浏览器回归(含 26 项助手专项)及截图,参见 [前端还原验收记录](assistant-frontend-parity-2026-11-03.md)。此前的 38 项浏览器回归、完整 CI 的失败及未验收边界保留在 [上一轮 Web 助手验收记录](web-assistant-validation.md)。 + +下一阶段服务接口和原版事件映射,参见 [后端接入交接](assistant-backend-handoff.md)。该文档描述待实现服务,不代表当前已接入后端。 diff --git a/docs/vibemake/workspace-api.md b/docs/vibemake/workspace-api.md new file mode 100644 index 000000000..b9822e89f --- /dev/null +++ b/docs/vibemake/workspace-api.md @@ -0,0 +1,159 @@ +# CAD 个人工作空间前端对接 + +网页 AI 助手使用独立的 `/api/cad/ai` 接口,复用平台登录,工具由浏览器执行;接口、工具循环、停止及撤销适配见 [CAD Web AI Agent 对接](frontend-cad-ai-agent.md)。AI 修改仍通过本文的原生 `.sc` 流程手动保存。 + +CAD 与 Vibemake 共用 `/api/auth/login`、`/api/auth/logout` 和 `/api/users/me`,使用同一个 `Authorization: Bearer <平台 token>`。CAD 工作空间独立于现有 `/api/workspace/projects`,不创建 Git 仓库、不自动发布社区。只支持当前用户的单个自包含原生 `.sc` 设计文件,不管理外部引用的多文件装配。 + +文件沿用现有 OSS 资源规则:上传继承 Bucket 权限,读取使用 `OSS_PUBLIC_BASE_URL` 对应的普通 OSS/CDN 地址。工作空间和平台接口按用户隔离,文件直链的访问权限由现有 Bucket/CDN 配置决定;公开配置下,拿到直链即可读取文件。 + +数据库的当前文件和上传批次只保存 `/cad-projects/{项目编码}/{批次编码}/design.sc`,不含环境前缀;上传签名的 `formFields.key` 和实际访问地址仍包含当前环境根目录,前端原样使用。所有资源的存储规范及历史数据转换 SQL 见 [OSS 引用规范](oss-storage-paths.md)。 + +通用响应、上海时间格式、分页和跨域规则沿用 [Vibemake 接入约定](vibemake-api.md#接入约定)。CAD 所有接口返回 `Cache-Control: no-store`。业务编码为不透明字符串,不使用数据库 ID。 + +## 接口与数据 + +下表前缀为 `/api/cad/workspace/projects`。全部需要登录,成功均为 HTTP 200,JSON 为 `{code,message,data,requestId}`。 + +| 方法 | 相对路径 | 请求 | 成功 data | +| --- | --- | --- | --- | +| GET | 空 | `page=1&size=20&keyword=名称` | 项目分页 | +| POST | 空 | `{name,description?,coverUrl?}` | 项目 | +| GET | `/{cadProjectCode}` | 无 | 项目 | +| PATCH | `/{cadProjectCode}` | `{name?,description?,coverUrl?}` | 项目 | +| DELETE | `/{cadProjectCode}` | 无 | null | +| POST | `/{cadProjectCode}/uploads/signature` | `{fileName,sizeBytes,expectedVersion}` | 上传签名 | +| PUT | `/{cadProjectCode}/document` | `{uploadCode}` | 保存回执 | +| GET | `/{cadProjectCode}/document` | 无 | 文件读取信息 | + +名称必填,去除首尾空白后 1~100 字符;描述最多 2000 字符,新建时默认空字符串。`coverUrl` 可选,传完整 HTTPS 地址,最多 2048 字符;新建省略、null 或空白表示没有封面。PATCH 省略或 null 表示保留,描述或封面传 `""` 可清空,至少提供一个非 null 字段。 + +项目: + +```ts +interface CadProject { + cadProjectCode: string; + name: string; + description: string; + coverUrl: string | null; // 完整 OSS/CDN 地址,无封面为 null + hasDocument: boolean; + version: number; + fileName: string; + sizeBytes: number; + savedAt: string | null; + createdAt: string; + updatedAt: string; +} +interface CadUploadSignature { + uploadCode: string; + uploadUrl: string; + formFields: Record; + expiresAt: string; +} +interface CadSaveResult { + cadProjectCode: string; + version: number; + savedAt: string; +} +interface CadDocument { + downloadUrl: string; + expiresAt: null; + version: number; + fileName: string; + sizeBytes: number; +} +``` + +新项目 `hasDocument=false、version=0、fileName=""、sizeBytes=0、savedAt=null`,未提供封面时 `coverUrl=null`。列表和详情均包含封面。列表只包含本人未删除项目,按最近更新时间倒序;支持名称包含搜索。`page` 为 1~100000,`size` 为 1~100,默认 20,返回 `{items,page,size,total}`。同名项目允许存在。改名、描述和封面修改不改变文件保存版本或 savedAt。 + +## 项目封面 + +复用 [已有封面上传](vibemake-api.md#项目封面与-oss-直传) 的 `POST /api/uploads/project-covers/signature`,无需 CAD 项目编码,也不会创建 Git 项目。请求 `{contentType,fileSize}`,支持 JPG、PNG、WebP,最大 5 MiB;使用同一平台 Token 申请签名,取得 `uploadUrl、formFields、coverUrl`。 + +将全部 formFields 和图片通过 FormData 直传 OSS,不携带平台 Token。上传成功后,将签名返回的完整 `coverUrl` 放入新建请求,或提交 `PATCH /api/cad/workspace/projects/{cadProjectCode}`: + +```json +{"coverUrl":"https://你的OSS或CDN域名/vibemake_dev/project-covers/用户编码/日期/文件名.png"} +``` + +封面上传遵循现有 `OSS_ENABLED` 开关和 OSS 规则;CAD 的 `.sc` 独立存储开关不代替封面上传开关。可以由前端截取 CAD 画布生成图片,后台不自动生成或更新封面。 + +平台托管封面在数据库 `cad_project.cover_url` 中保存 `/project-covers/...` 等无环境前缀的未编码路径;列表、详情和创建/修改结果中的 coverUrl 自动补当前环境前缀及 OSS/CDN 地址。沿用现有封面规则接受外部 HTTPS 图片链接并原样保存,不接受直接提交数据库相对路径。 + +只修改封面不更新 `.sc` 文件或版本,保存 `.sc` 也不会清空封面。换图、清空封面和删除 CAD 项目均不删除旧 OSS 图片。已有数据库部署前先执行 [CAD 封面增量 SQL](cad-database.md#已有数据库增加-cad-项目封面)。 + +## 保存和重新打开 + +1. 新设计首次保存先创建项目,保留返回的 `cadProjectCode` 和 `version=0`。 +2. 使用 SolidCraft 原生序列化生成完整 `.sc`,不能仅上传 STL、STEP、GLB 或显示网格;原生文件保留参数及可编辑设计。需要由前端接通原生文件导出和导入桥接,当前本机/浏览器保存不等于云端保存。 +3. 文件名须为不含路径和控制字符的 `.sc` 名称,最多 255 字符。文件非空,默认上限 268435456 字节(256 MiB)。`sizeBytes` 和 `expectedVersion` 必须是 JSON 整数,不接受字符串或小数。 +4. 申请签名,将 `formFields` 全部原样写入 FormData,最后追加 `file`,POST 到 `uploadUrl`。不携带平台 Authorization,不手写 multipart Content-Type。OSS 成功为 HTTP 200,无需解析 JSON。 +5. 上传完成后提交原 `uploadCode` 确认。后端核验对象大小、批次归属、截止时间和基础版本,成功才更新当前设计引用,并返回新版本。 +6. 只有确认成功才显示云端已保存;序列化期间及上传期间又产生的修改仍应标为未保存。每个项目前端串行执行云端保存。 +7. 打开项目先读详情;空项目进入新设计,否则 GET `document`,fetch `downloadUrl` 得到原始文件字节并交给 SolidCraft 打开。**本次编辑基础版本使用 `document.version`**,文件与版本来自同一快照,不混用先前详情中的版本。 + +上传签名默认 15 分钟,未确认批次同一时刻过期;文件上传完成但确认已过期时,重新申请批次。`downloadUrl` 为普通 OSS/CDN 文件地址,不附加临时下载签名,`expiresAt` 为兼容前端保留且固定返回 null;前端直接读取地址,不做下载签名续期。业务时间为上海时间字符串,无时区后缀,解析时补 `+08:00`。 + +相同 `uploadCode` 重复确认返回首次保存回执,不重复增加版本。即使之后已有更新版本,重试旧批次也不会恢复旧文件;回执版本可能小于最新项目版本,需要时重新读取详情。网络超时先保留原批次并重试确认,不直接创建新项目或新批次。上传使用现有 `signObject` 策略及其禁止覆盖参数,每次申请使用新的批次对象键;OSS 上传超时先尝试确认,缺文件再处理上传,不无条件重复上传。 + +两个标签页使用相同基础版本保存时,只有一个成功,另一个收到 `CAD_VERSION_CONFLICT`。保留本地修改并提供重新打开最新设计、下载本地副本或另存新项目的处理入口;不能只换成最新版本号后自动覆盖。 + +离开、切换项目、退出登录前提示未保存修改。401 后保留设计并引导重新登录,重新登录后核对当前账号和项目归属再继续保存。推荐部署同源的可编辑 SolidCraft 构建;iframe 跨源集成如使用 postMessage,须校验 source 和精确 origin,平台 Token 不放 URL。现有 `?embed` 会关闭浏览器持久化等能力,不能直接充当云端保存桥接。 + +## 错误处理 + +| HTTP / code | 处理 | +| --- | --- | +| 400 `BAD_REQUEST` / `CAD_INVALID_FILE` | 校验名称、描述、文件和整数参数 | +| 401 `UNAUTHORIZED` | 保留本地修改,恢复登录 | +| 404 `NOT_FOUND` | 非本人、不存在或已删除的项目/批次,停止对此项目保存 | +| 404 `CAD_DOCUMENT_NOT_FOUND` | 空项目尚未保存文件 | +| 409 `CAD_VERSION_CONFLICT` | 保留修改,处理并发冲突 | +| 409 `CAD_FILE_MISSING` | 尚未上传完整,检查 OSS 上传结果后重试确认 | +| 409 `CAD_FILE_SIZE_MISMATCH` | 当前文件不变,重新申请并上传正确文件 | +| 409 `CAD_UPLOAD_EXPIRED` | 重新申请上传批次 | +| 413 `CAD_FILE_TOO_LARGE` / `REQUEST_TOO_LARGE` | 文件超限或 JSON 超限,调整请求 | +| 429 `RATE_LIMITED` | 按 Retry-After 等待后重试 | +| 502 `CAD_OSS_ERROR` | 保留当前设计及批次,稍后重试 | +| 503 `CAD_STORAGE_UNAVAILABLE` / `CAD_STORAGE_UNSAFE` | 存储未开启或本地 OSS 连接参数不完整,联系管理员 | +| 503 `CAD_CODE_BUSY` / `REDIS_UNAVAILABLE` | 暂时无法处理,保留输入后重试 | + +删除为逻辑删除,之后列表、详情、文件地址获取、编辑及保存确认均不可访问,不提供恢复。上传失败、替换、删除均保留旧 OSS 对象,已有文件直链仍按 Bucket/CDN 规则访问,删除项目不会撤销已有直链。首期没有历史恢复和对象自动清理。 + +## 部署配置 + +先手工执行 [CAD 建表 SQL](cad-database.md),再部署后端。CAD 与现有资源共用 `vibemake.oss` 的 Bucket、地域、Endpoint、AccessKey 和各环境根目录;`vibemake.cad.oss` 仅保留独立的 `enabled` 开关,文件存储默认关闭。 + +```yaml +vibemake: + cad: + oss: + enabled: ${CAD_OSS_ENABLED:false} +``` + +| 配置项 | 默认值 / 要求 | +| --- | --- | +| `CAD_OSS_ENABLED` | false,配置齐全后设为 true | +| `OSS_REGION` | 与现有 OSS 共用,默认 cn-beijing | +| `OSS_ENDPOINT` | 与现有 OSS 共用,可选 HTTPS Endpoint;不填写时按地域生成 | +| `OSS_BUCKET` | 与现有资源共用同一个 Bucket | +| `OSS_ACCESS_KEY_ID` / `OSS_ACCESS_KEY_SECRET` | 与现有 OSS 共用,通过部署环境注入 | +| `OSS_PUBLIC_BASE_URL` | 与现有资源共用普通 OSS/CDN 访问基础地址,配置为空时使用 Bucket 域名 | +| `vibemake.oss.root-directory` | CAD 直接使用各环境根目录:test 为 vibemake_dev,prod 为 vibemake | +| `CAD_MAX_FILE_BYTES` | 268435456;配置范围为 1 字节至 OSS 表单上限 5 GiB,需同时兼容编辑器读取上限 | +| `CAD_UPLOAD_VALIDITY` | 默认 15m;范围 1 秒至 7 天 | +| `RATE_CAD_CREATE_PER_MINUTE` / `RATE_CAD_SIGN_PER_MINUTE` | 5 / 20,按当前用户独立限流 | +| `RATE_CAD_SAVE_PER_MINUTE` / `RATE_CAD_READ_PER_MINUTE` | 30 / 60,保存确认和文件地址读取尝试次数 | + +CAD 独立开关与 `OSS_ENABLED` 分开控制:公共资源上传关闭时,只要共用连接参数完整,CAD 仍可独立开启。只有 `CAD_OSS_ENABLED` 继续生效;旧的 `CAD_OSS_BUCKET`、`CAD_OSS_REGION`、`CAD_OSS_ENDPOINT`、`CAD_OSS_ACCESS_KEY_ID`、`CAD_OSS_ACCESS_KEY_SECRET` 和 `CAD_OSS_ROOT_DIRECTORY` 均不再读取,可从 `.env` 移除。 + +上传签名仅在本地生成,保存确认只通过 HEAD 核验对象存在和大小;文件地址沿用现有 `OssResourcePaths.publicUrl` 规则生成。后端不查询 Bucket ACL、公共访问策略、版本控制状态或对象 ACL,不修改 Bucket 配置,也不为 CAD 单独强制 private ACL。 + +共用 RAM 凭据只需覆盖当前环境 `cad-projects/*` 的 `oss:PutObject`、`oss:GetObject`,分别用于普通文件上传和 HEAD 元数据读取。不额外要求 CAD 的 ACL 或 Bucket 配置读取/修改权限。不要给前端 RAM 密钥。 + +上传策略与原有 STEP 等资源相同,精确绑定对象键、大小、MIME、Content-Disposition 和禁止覆盖参数,不设置 `x-oss-object-acl`。文件是否公开、CDN 是否需要鉴权、同名对象覆盖行为均遵循已有 OSS/CDN 配置,应用不增加 CAD 专属限制;数据库仍校验归属、基础版本、批次截止时间和幂等回执。 + +旧的 `CAD_DOWNLOAD_VALIDITY` 不再读取。前端如曾按下载签名过期时间续期,需调整为直接读取普通地址,允许 `expiresAt=null`。 + +若此前使用独立 CAD Bucket 保存过文件,切换前需按原对象键复制到 `OSS_BUCKET`。若旧文件曾单独设为 private,且现有普通地址无法读取,需按已有资源访问方式调整为继承 Bucket(default)或配置相应的 CDN 回源授权;代码不会自动迁移文件或修改历史对象 ACL。 + +OSS/CDN 沿用现有 CORS 规则,允许真实编辑器来源的 POST、GET 和 Content-Type;需要时暴露 Content-Length 和 Content-Disposition。直传和文件读取不携带平台 Token。联调验证上传、确认保存、通过配置的普通 OSS/CDN 地址读取,以及原生设计重新打开后可继续编辑。API 自动化使用存储替身,不替代真实 OSS/CDN 和编辑器联调。 diff --git a/scripts/build-vibemake-cad.mjs b/scripts/build-vibemake-cad.mjs new file mode 100644 index 000000000..3d8147ba3 --- /dev/null +++ b/scripts/build-vibemake-cad.mjs @@ -0,0 +1,27 @@ +#!/usr/bin/env node +// Independent Rust/WASM artifact. No fallback or alternate geometry kernel. +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, readdirSync, cpSync, writeFileSync, existsSync } from 'node:fs'; +import { resolve, relative, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { execFileSync } from 'node:child_process'; +const root = resolve(fileURLToPath(new URL('..', import.meta.url))); +const raw = join(root, 'target/vibemake-cad-raw'); +const destination = resolve(process.env.VIBEMAKE_CAD_ENGINE_OUT || join(root, 'dist/vibemake-cad-engine')); +execFileSync('trunk', ['build', '--release', '--dist', raw], { cwd: join(root, 'apps/solidcraft-web'), stdio: 'inherit' }); +const walk = (directory) => readdirSync(directory, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? walk(join(directory, entry.name)) : [join(directory, entry.name)]); +const selected = walk(raw).filter((file) => /\.(js|wasm|ttf|otf|txt)$/i.test(file) && !file.endsWith('/sw.js')).sort(); +const js = selected.find((file) => /solidcraft-web.*\.js$/.test(file)); +const wasm = selected.find((file) => /solidcraft-web.*_bg\.wasm$/.test(file)); +const font = selected.find((file) => file.endsWith('/CraftUI-SC.otf')); +if (!js || !wasm || !font) throw new Error('Engine JS, WASM or Chinese font is missing'); +const digest = (file) => createHash('sha256').update(readFileSync(file)).digest('hex'); +const buildId = createHash('sha256').update(selected.map((file) => `${relative(raw, file)}:${digest(file)}`).join('\n')).digest('hex').slice(0, 24); +const prefix = `/cad/_assets/${buildId}/`; +const files = selected.map((file) => ({ path: prefix + relative(raw, file).replaceAll('\\', '/'), size: readFileSync(file).length, sha256: digest(file) })); +for (const file of selected) { const out = join(destination, '_assets', buildId, relative(raw, file)); mkdirSync(resolve(out, '..'), { recursive: true }); cpSync(file, out); } +const manifest = { bridgeVersion: 1, engineKind: 'solidcraft', buildId, builtAt: new Date().toISOString(), kernel: 'smlib', + js: prefix + relative(raw, js), wasm: prefix + relative(raw, wasm), chineseFont: prefix + relative(raw, font), files }; +mkdirSync(destination, { recursive: true }); writeFileSync(join(destination, 'engine.json'), JSON.stringify(manifest, null, 2) + '\n'); +if (!existsSync(join(destination, '_assets', buildId))) throw new Error('Engine output failed'); +console.log(`VIBEMAKE_CAD_ENGINE_DIST=${destination}`);