ec622d1088
Recover the ZIP snapshot baseline at 147b4049cf from 6616 matching files and the archive timestamp. Preserve the existing browser assistant, host workspace bridge, theme, translations, and integration documents before updating upstream.
Generated validation media and logs remain in a local backup. The initial cargo xtask ci run stopped at those local media files lacking attribution; the integrated source tree will be checked after the upstream merge.
443 lines
20 KiB
Rust
443 lines
20 KiB
Rust
//! 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<RefCell<Vec<Request>>>,
|
|
listeners: Rc<RefCell<BTreeMap<u64, Function>>>,
|
|
next_listener: Rc<std::cell::Cell<u64>>,
|
|
context_generation: Rc<std::cell::Cell<u64>>,
|
|
ctx: egui::Context,
|
|
binding: Option<String>,
|
|
project: Option<String>,
|
|
snapshots: Rc<RefCell<BTreeMap<String, Snapshot>>>,
|
|
last_state: String,
|
|
pub font_failed: bool,
|
|
pub retry_font: bool,
|
|
}
|
|
|
|
pub fn config(name: &str) -> Option<String> {
|
|
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<String> {
|
|
field(args, name).as_string()
|
|
}
|
|
fn js(value: Value) -> Result<JsValue, JsValue> {
|
|
js_sys::JSON::parse(&value.to_string())
|
|
}
|
|
fn value(value: JsValue) -> Result<Option<Value>, 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<String, JsValue> {
|
|
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<Vec<u8>, JsValue> {
|
|
if !value.is_instance_of::<Uint8Array>() {
|
|
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<Session, JsValue> {
|
|
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<Self, JsValue> {
|
|
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::<dyn Fn(JsValue) -> Promise>::new(move |args| queue.request(method, args)).into_js_value();
|
|
Reflect::set(&object, &method.into(), &function)?;
|
|
}
|
|
let subscribed = bridge.clone();
|
|
let subscribe = Closure::<dyn Fn(Function) -> 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::<dyn Fn()>::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<JsValue, JsValue> {
|
|
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();
|
|
}
|
|
}
|
|
}
|