修改ai助手
CI / Select checks (push) Has been cancelled
CI / Format and repository checks (push) Has been cancelled
CI / Compile RISC-V (manual) (push) Has been cancelled
Docker / image (push) Has been cancelled
Generated files / Regenerate and commit (push) Has been cancelled
Lists / Design format changes merge cleanly (push) Has been cancelled
Lists / Lists are sorted one item per line (push) Has been cancelled
Packaging lint / lint (push) Has been cancelled
Pages / build (push) Has been cancelled
CI / Dependency advisories (push) Has been cancelled
CI / Quick compile (push) Has been cancelled
CI / Native Linux Clippy (push) Has been cancelled
CI / Build tests (push) Has been cancelled
CI / Native Linux tests (push) Has been cancelled
CI / GPU path tests (1/4) (push) Has been cancelled
CI / GPU path tests (2/4) (push) Has been cancelled
CI / GPU path tests (3/4) (push) Has been cancelled
CI / GPU path tests (4/4) (push) Has been cancelled
CI / Action matrix (1/16) (push) Has been cancelled
CI / Action matrix (10/16) (push) Has been cancelled
CI / Action matrix (11/16) (push) Has been cancelled
CI / Action matrix (12/16) (push) Has been cancelled
CI / Action matrix (13/16) (push) Has been cancelled
CI / Action matrix (14/16) (push) Has been cancelled
CI / Action matrix (15/16) (push) Has been cancelled
CI / Action matrix (16/16) (push) Has been cancelled
CI / Action matrix (2/16) (push) Has been cancelled
CI / Action matrix (3/16) (push) Has been cancelled
CI / Action matrix (4/16) (push) Has been cancelled
CI / Action matrix (5/16) (push) Has been cancelled
CI / Action matrix (6/16) (push) Has been cancelled
CI / Action matrix (7/16) (push) Has been cancelled
CI / Action matrix (8/16) (push) Has been cancelled
CI / Action matrix (9/16) (push) Has been cancelled
CI / Action matrix determinism (push) Has been cancelled
CI / Property tests (many cases) (push) Has been cancelled
CI / Doc tests (push) Has been cancelled
CI / Reference tests (push) Has been cancelled
CI / Windows D3D12 FXC shaders (push) Has been cancelled
CI / Windows app startup (push) Has been cancelled
CI / ci (push) Has been cancelled
CI / Compile WebAssembly (push) Has been cancelled
CI / Nightly alert (push) Has been cancelled
Pages / deploy (push) Has been cancelled
CI / Select checks (push) Has been cancelled
CI / Format and repository checks (push) Has been cancelled
CI / Compile RISC-V (manual) (push) Has been cancelled
Docker / image (push) Has been cancelled
Generated files / Regenerate and commit (push) Has been cancelled
Lists / Design format changes merge cleanly (push) Has been cancelled
Lists / Lists are sorted one item per line (push) Has been cancelled
Packaging lint / lint (push) Has been cancelled
Pages / build (push) Has been cancelled
CI / Dependency advisories (push) Has been cancelled
CI / Quick compile (push) Has been cancelled
CI / Native Linux Clippy (push) Has been cancelled
CI / Build tests (push) Has been cancelled
CI / Native Linux tests (push) Has been cancelled
CI / GPU path tests (1/4) (push) Has been cancelled
CI / GPU path tests (2/4) (push) Has been cancelled
CI / GPU path tests (3/4) (push) Has been cancelled
CI / GPU path tests (4/4) (push) Has been cancelled
CI / Action matrix (1/16) (push) Has been cancelled
CI / Action matrix (10/16) (push) Has been cancelled
CI / Action matrix (11/16) (push) Has been cancelled
CI / Action matrix (12/16) (push) Has been cancelled
CI / Action matrix (13/16) (push) Has been cancelled
CI / Action matrix (14/16) (push) Has been cancelled
CI / Action matrix (15/16) (push) Has been cancelled
CI / Action matrix (16/16) (push) Has been cancelled
CI / Action matrix (2/16) (push) Has been cancelled
CI / Action matrix (3/16) (push) Has been cancelled
CI / Action matrix (4/16) (push) Has been cancelled
CI / Action matrix (5/16) (push) Has been cancelled
CI / Action matrix (6/16) (push) Has been cancelled
CI / Action matrix (7/16) (push) Has been cancelled
CI / Action matrix (8/16) (push) Has been cancelled
CI / Action matrix (9/16) (push) Has been cancelled
CI / Action matrix determinism (push) Has been cancelled
CI / Property tests (many cases) (push) Has been cancelled
CI / Doc tests (push) Has been cancelled
CI / Reference tests (push) Has been cancelled
CI / Windows D3D12 FXC shaders (push) Has been cancelled
CI / Windows app startup (push) Has been cancelled
CI / ci (push) Has been cancelled
CI / Compile WebAssembly (push) Has been cancelled
CI / Nightly alert (push) Has been cancelled
Pages / deploy (push) Has been cancelled
This commit is contained in:
@@ -447,7 +447,7 @@ fn base64_size(data: &str) -> usize {
|
||||
}
|
||||
|
||||
fn platform_image(mime: &str, data: &str, limits: &Value) -> Result<(Value, u32, u32), String> {
|
||||
if !matches!(mime, "image/png" | "image/jpeg") {
|
||||
if !matches!(mime, "image/png" | "image/jpeg" | "image/gif" | "image/webp") {
|
||||
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)?;
|
||||
@@ -460,7 +460,10 @@ fn platform_image(mime: &str, data: &str, limits: &Value) -> Result<(Value, u32,
|
||||
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()) {
|
||||
if matches!(mime, "image/png" | "image/jpeg")
|
||||
&& 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 {
|
||||
|
||||
@@ -10,6 +10,7 @@ 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;
|
||||
const MAX_STEP_BYTES: usize = 500 * 1024 * 1024;
|
||||
|
||||
struct Request {
|
||||
method: &'static str,
|
||||
@@ -17,18 +18,33 @@ struct Request {
|
||||
resolve: Function,
|
||||
reject: Function,
|
||||
context_generation: u64,
|
||||
open_generation: u64,
|
||||
}
|
||||
struct Snapshot {
|
||||
binding: String,
|
||||
baseline: SaveBaseline,
|
||||
}
|
||||
|
||||
struct PendingOpen {
|
||||
request: Request,
|
||||
path: String,
|
||||
project: String,
|
||||
reply: std::sync::mpsc::Receiver<Result<solidcraft_ui_egui::platform::PreparedProject, String>>,
|
||||
}
|
||||
impl Drop for PendingOpen {
|
||||
fn drop(&mut self) {
|
||||
let _ = io::vfs::remove(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[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>>,
|
||||
open_generation: Rc<std::cell::Cell<u64>>,
|
||||
pending_open: Rc<RefCell<Option<PendingOpen>>>,
|
||||
ctx: egui::Context,
|
||||
binding: Option<String>,
|
||||
project: Option<String>,
|
||||
@@ -76,11 +92,14 @@ fn uuid() -> Result<String, JsValue> {
|
||||
function.call0(&crypto)?.as_string().ok_or_else(|| error("UUID_UNAVAILABLE"))
|
||||
}
|
||||
fn bytes(value: JsValue) -> Result<Vec<u8>, JsValue> {
|
||||
limited_bytes(value, MAX_BYTES)
|
||||
}
|
||||
fn limited_bytes(value: JsValue, max: usize) -> 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 {
|
||||
if array.length() == 0 || array.length() as usize > max {
|
||||
return Err(error("SOURCE_TOO_LARGE"));
|
||||
}
|
||||
Ok(array.to_vec())
|
||||
@@ -106,6 +125,8 @@ impl Bridge {
|
||||
listeners: Rc::default(),
|
||||
next_listener: Rc::new(std::cell::Cell::new(0)),
|
||||
context_generation: Rc::default(),
|
||||
open_generation: Rc::default(),
|
||||
pending_open: Rc::default(),
|
||||
ctx,
|
||||
binding: None,
|
||||
project: None,
|
||||
@@ -118,6 +139,8 @@ impl Bridge {
|
||||
for method in [
|
||||
"ready",
|
||||
"openProject",
|
||||
"openProjectFromStep",
|
||||
"cancelOpenProject",
|
||||
"validateProject",
|
||||
"createSnapshot",
|
||||
"acknowledgeSave",
|
||||
@@ -161,9 +184,13 @@ impl Bridge {
|
||||
if method == "setAgentContext" {
|
||||
self.context_generation.set(self.context_generation.get().wrapping_add(1));
|
||||
}
|
||||
if matches!(method, "openProject" | "openProjectFromStep" | "cancelOpenProject" | "releaseProject") {
|
||||
self.open_generation.set(self.open_generation.get().wrapping_add(1));
|
||||
}
|
||||
let open_generation = self.open_generation.get();
|
||||
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.requests.borrow_mut().push(Request { method, args: args.clone(), resolve, reject, context_generation, open_generation });
|
||||
self.ctx.request_repaint();
|
||||
})
|
||||
}
|
||||
@@ -171,6 +198,20 @@ impl Bridge {
|
||||
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 matches!(request.method, "openProject" | "openProjectFromStep") && request.open_generation != self.open_generation.get() {
|
||||
let _ = request.reject.call1(&JsValue::UNDEFINED, &error("OPEN_CANCELLED"));
|
||||
continue;
|
||||
}
|
||||
if request.method == "openProjectFromStep" {
|
||||
self.cancel_open(app);
|
||||
match self.begin_step(app, request) {
|
||||
Ok(()) => {}
|
||||
Err((request, reason)) => {
|
||||
let _ = request.reject.call1(&JsValue::UNDEFINED, &reason);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if request.method == "setAgentContext" && request.context_generation != self.context_generation.get() {
|
||||
let _ = request.reject.call1(&JsValue::UNDEFINED, &error("STALE_AGENT_CONTEXT"));
|
||||
continue;
|
||||
@@ -204,6 +245,7 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.poll_open(app);
|
||||
if !app.platform.enabled && app.platform.agent_context.is_some() {
|
||||
crate::agent_storage::save_profile(app);
|
||||
}
|
||||
@@ -227,7 +269,7 @@ impl Bridge {
|
||||
}
|
||||
|
||||
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),
|
||||
json!({"opening":app.platform_open_progress(), "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})
|
||||
}
|
||||
|
||||
@@ -238,7 +280,7 @@ impl Bridge {
|
||||
Err(error("FONT_UNAVAILABLE"))
|
||||
} else {
|
||||
js(
|
||||
json!({"bridgeVersion":1, "engineBuild":config("buildId"), "capabilities":{"assistant":app.services.browser_agent.is_some(), "projectCover":true}}),
|
||||
json!({"bridgeVersion":1, "engineBuild":config("buildId"), "capabilities":{"assistant":app.services.browser_agent.is_some(), "projectCover":true, "stepImport":true}}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -305,7 +347,12 @@ impl Bridge {
|
||||
let _ = open(&bytes(args)?)?;
|
||||
Ok(JsValue::TRUE)
|
||||
}
|
||||
"cancelOpenProject" => {
|
||||
self.cancel_open(app);
|
||||
Ok(JsValue::UNDEFINED)
|
||||
}
|
||||
"openProject" => {
|
||||
self.cancel_open(app);
|
||||
let project = text(&args, "projectId").ok_or_else(|| error("BAD_PROJECT"))?;
|
||||
if project.len() > 128 || project.is_empty() {
|
||||
return Err(error("BAD_PROJECT"));
|
||||
@@ -326,6 +373,7 @@ impl Bridge {
|
||||
js(json!({"binding":binding}))
|
||||
}
|
||||
"releaseProject" => {
|
||||
self.cancel_open(app);
|
||||
self.clear_agent(app);
|
||||
let mut session = Session::default();
|
||||
session.set_command_check(app.session.command_check());
|
||||
@@ -376,7 +424,9 @@ impl Bridge {
|
||||
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 {
|
||||
// Local downloads remain available for designs too large for cloud storage.
|
||||
// Cloud snapshots retain the native upload limit by default.
|
||||
if bytes.len() > MAX_BYTES && field(&args, "forLocalDownload").as_bool() != Some(true) {
|
||||
return Err(error("SOURCE_TOO_LARGE"));
|
||||
}
|
||||
let result = js(
|
||||
@@ -425,6 +475,94 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_open(&mut self, app: &mut SolveApp) {
|
||||
let pending = self.pending_open.borrow_mut().take();
|
||||
if let Some(pending) = pending {
|
||||
app.file_load.cancel();
|
||||
let _ = pending.request.reject.call1(&JsValue::UNDEFINED, &error("OPEN_CANCELLED"));
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_step(&mut self, app: &mut SolveApp, mut request: Request) -> Result<(), (Request, JsValue)> {
|
||||
let prepared = (|| {
|
||||
let project = text(&request.args, "projectId").filter(|p| !p.is_empty() && p.len() <= 128).ok_or_else(|| error("BAD_PROJECT"))?;
|
||||
let name = text(&request.args, "fileName").ok_or_else(|| error("BAD_STEP_FILE"))?;
|
||||
if name.chars().count() > 1024
|
||||
|| name.chars().any(|c| c.is_control() || c == '/' || c == '\\')
|
||||
|| !(name.to_ascii_lowercase().ends_with(".step") || name.to_ascii_lowercase().ends_with(".stp"))
|
||||
{
|
||||
return Err(error("BAD_STEP_FILE"));
|
||||
}
|
||||
let data = limited_bytes(field(&request.args, "bytes"), MAX_STEP_BYTES)?;
|
||||
let path = format!("/vibemake-step/{}.step", uuid()?);
|
||||
io::vfs::insert(&path, data);
|
||||
let stem = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem);
|
||||
match app.prepare_platform_step(&path, stem) {
|
||||
Ok(reply) => Ok((project, path, reply)),
|
||||
Err(_) => {
|
||||
let _ = io::vfs::remove(&path);
|
||||
Err(error("STEP_IMPORT_FAILED"))
|
||||
}
|
||||
}
|
||||
})();
|
||||
match prepared {
|
||||
Ok((project, path, reply)) => {
|
||||
// The VFS now owns the source bytes; do not retain the JavaScript input
|
||||
// throughout staged conversion and view preparation.
|
||||
request.args = JsValue::UNDEFINED;
|
||||
*self.pending_open.borrow_mut() = Some(PendingOpen { request, project, path, reply });
|
||||
Ok(())
|
||||
}
|
||||
Err(reason) => Err((request, reason)),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_open(&mut self, app: &mut SolveApp) {
|
||||
use std::sync::mpsc::TryRecvError;
|
||||
let result = {
|
||||
let pending = self.pending_open.borrow();
|
||||
let Some(pending) = pending.as_ref() else { return };
|
||||
match pending.reply.try_recv() {
|
||||
Ok(result) => result,
|
||||
Err(TryRecvError::Empty) => return,
|
||||
Err(TryRecvError::Disconnected) => Err("the import stopped".into()),
|
||||
}
|
||||
};
|
||||
let Some(pending) = self.pending_open.borrow_mut().take() else { return };
|
||||
let result = (|| {
|
||||
if pending.request.open_generation != self.open_generation.get() {
|
||||
return Err(error("OPEN_CANCELLED"));
|
||||
}
|
||||
let mut prepared = result.map_err(|reason| {
|
||||
let e = error("STEP_IMPORT_FAILED");
|
||||
let _ = Reflect::set(&e, &"message".into(), &reason.into());
|
||||
e
|
||||
})?;
|
||||
if prepared.session.model.state().bodies.is_empty() {
|
||||
return Err(error("STEP_EMPTY_MODEL"));
|
||||
}
|
||||
let warnings = prepared.result.get("warnings").cloned().unwrap_or_else(|| json!([]));
|
||||
let binding = uuid()?;
|
||||
let response = js(json!({"binding":binding, "warnings":warnings}))?;
|
||||
prepared.session.mark_unsaved();
|
||||
prepared.session.set_command_check(app.session.command_check());
|
||||
self.clear_agent(app);
|
||||
app.adopt_platform_project(prepared.session);
|
||||
self.binding = Some(binding);
|
||||
self.project = Some(pending.project.clone());
|
||||
self.snapshots.borrow_mut().clear();
|
||||
Ok(response)
|
||||
})();
|
||||
match result {
|
||||
Ok(value) => {
|
||||
let _ = pending.request.resolve.call1(&JsValue::UNDEFINED, &value);
|
||||
}
|
||||
Err(reason) => {
|
||||
let _ = pending.request.reject.call1(&JsValue::UNDEFINED, &reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_agent(&mut self, app: &mut SolveApp) {
|
||||
if !app.platform.enabled {
|
||||
crate::agent_storage::save_profile(app);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"ar": {
|
||||
"ui.agent_chat_upload_attachment": "رفع مرفق",
|
||||
"ui.agent_chat_upload_attachment_tip": "أرفق صورًا أو ملفات نصية برسالتك التالية. حتى 8 ملفات؛ الصور حتى 40 MB والنص بترميز UTF-8 حتى 256 KB."
|
||||
},
|
||||
"de": {
|
||||
"ui.agent_chat_upload_attachment": "Anhang hinzufügen",
|
||||
"ui.agent_chat_upload_attachment_tip": "Bilder oder Textdateien an die nächste Nachricht anhängen. Bis zu 8 Dateien; Bilder bis 40 MB, UTF-8-Text bis 256 KB."
|
||||
},
|
||||
"en": {
|
||||
"ui.agent_chat_upload_attachment": "Upload attachment",
|
||||
"ui.agent_chat_upload_attachment_tip": "Attach images or text files to your next message. Up to 8 files; images up to 40 MB, UTF-8 text up to 256 KB."
|
||||
},
|
||||
"he": {
|
||||
"ui.agent_chat_upload_attachment": "העלאת קובץ מצורף",
|
||||
"ui.agent_chat_upload_attachment_tip": "צירוף תמונות או קובצי טקסט להודעה הבאה. עד 8 קבצים; תמונות עד 40 MB וטקסט UTF-8 עד 256 KB."
|
||||
},
|
||||
"ja": {
|
||||
"ui.agent_chat_upload_attachment": "添付ファイルを追加",
|
||||
"ui.agent_chat_upload_attachment_tip": "次のメッセージに画像やテキストファイルを添付します。最大8ファイル。画像は40 MB、UTF-8テキストは256 KBまで。"
|
||||
},
|
||||
"ko": {
|
||||
"ui.agent_chat_upload_attachment": "첨부 파일 업로드",
|
||||
"ui.agent_chat_upload_attachment_tip": "다음 메시지에 이미지나 텍스트 파일을 첨부합니다. 최대 8개 파일, 이미지 40 MB, UTF-8 텍스트 256 KB까지 지원합니다."
|
||||
},
|
||||
"vi": {
|
||||
"ui.agent_chat_upload_attachment": "Tải tệp đính kèm",
|
||||
"ui.agent_chat_upload_attachment_tip": "Đính kèm ảnh hoặc tệp văn bản vào tin nhắn tiếp theo. Tối đa 8 tệp; ảnh tối đa 40 MB, văn bản UTF-8 tối đa 256 KB."
|
||||
},
|
||||
"zh": {
|
||||
"ui.agent_chat_upload_attachment": "上传附件",
|
||||
"ui.agent_chat_upload_attachment_tip": "为下一条消息附加图片或文本文件。最多 8 个文件;图片最大 40 MB,UTF-8 文本最大 256 KB。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build a complete CAD website package and a separate engine-only update archive.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
for tool in node cargo rustc trunk zip unzip; do
|
||||
if ! command -v "$tool" >/dev/null 2>&1; then
|
||||
printf 'Error: required build tool is missing: %s\n' "$tool" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# The platform frontend is maintained in VibeMake; publishing it never builds the main site.
|
||||
SITE_ROOT="$(node -p "require('node:path').resolve(process.env.VIBEMAKE_SITE_ROOT || '../vibemake')")"
|
||||
for file in scripts/build-cad.mjs cad.html cad/editor/index.html js/cad/app.js css/cad.css; do
|
||||
if [[ ! -f "$SITE_ROOT/$file" ]]; then
|
||||
printf 'Error: CAD frontend input is missing: %s/%s\n' "$SITE_ROOT" "$file" >&2
|
||||
printf 'Set VIBEMAKE_SITE_ROOT to the VibeMake source directory.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if ! node --input-type=module - "$SITE_ROOT/scripts/lib/version-site-assets.mjs" <<'NODE'
|
||||
import { pathToFileURL } from 'node:url';
|
||||
await import(pathToFileURL(process.argv[2]).href);
|
||||
NODE
|
||||
then
|
||||
printf 'Error: install the CAD frontend packaging dependencies with npm ci in %s.\n' "$SITE_ROOT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
WASM_LIB_DIR="$(rustc --print target-libdir --target wasm32-unknown-unknown)"
|
||||
if [[ ! -d "$WASM_LIB_DIR" ]]; then
|
||||
printf 'Error: install the WebAssembly target first:\n rustup target add wasm32-unknown-unknown\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-"$ROOT_DIR/target"}"
|
||||
ENGINE_DIR="$(node -p "require('node:path').resolve(process.env.VIBEMAKE_CAD_ENGINE_OUT || 'dist/vibemake-cad-engine')")"
|
||||
export VIBEMAKE_CAD_ENGINE_OUT="$ENGINE_DIR"
|
||||
ARCHIVE="$ROOT_DIR/dist/vibemake-cad-engine.zip"
|
||||
SITE_ARCHIVE="$ROOT_DIR/dist/vibemake-cad.zip"
|
||||
|
||||
printf 'Building the release Web engine...\n'
|
||||
if command -v nice >/dev/null 2>&1; then
|
||||
nice node "$ROOT_DIR/scripts/build-vibemake-cad.mjs"
|
||||
else
|
||||
node "$ROOT_DIR/scripts/build-vibemake-cad.mjs"
|
||||
fi
|
||||
|
||||
mkdir -p "$ROOT_DIR/dist"
|
||||
STAGING_DIR="$(mktemp -d "$ROOT_DIR/dist/.web-package.XXXXXX")"
|
||||
trap 'rm -rf -- "$STAGING_DIR"' EXIT
|
||||
|
||||
node --input-type=module - "$ENGINE_DIR" "$STAGING_DIR" <<'NODE'
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve, sep } from 'node:path';
|
||||
|
||||
const output = resolve(process.argv[2]);
|
||||
const stage = resolve(process.argv[3]);
|
||||
const manifestBytes = readFileSync(join(output, 'engine.json'));
|
||||
const manifest = JSON.parse(manifestBytes);
|
||||
if (!/^[a-f0-9]{24}$/.test(manifest.buildId)
|
||||
|| !Array.isArray(manifest.files) || manifest.files.length === 0) {
|
||||
throw new Error('The Web engine manifest is invalid');
|
||||
}
|
||||
const prefix = `/cad/_assets/${manifest.buildId}/`;
|
||||
const assetRoot = resolve(output, '_assets', manifest.buildId) + sep;
|
||||
for (const file of manifest.files) {
|
||||
if (typeof file.path !== 'string' || !file.path.startsWith(prefix)) {
|
||||
throw new Error('An engine asset is outside the current build');
|
||||
}
|
||||
const relativePath = file.path.slice('/cad/'.length);
|
||||
const source = resolve(output, relativePath);
|
||||
if (!source.startsWith(assetRoot)) {
|
||||
throw new Error('An engine asset has an invalid path');
|
||||
}
|
||||
const bytes = readFileSync(source);
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex');
|
||||
if (bytes.length !== file.size || sha256 !== file.sha256) {
|
||||
throw new Error(`Engine asset verification failed: ${file.path}`);
|
||||
}
|
||||
const target = join(stage, 'cad', relativePath);
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, bytes);
|
||||
}
|
||||
writeFileSync(join(stage, 'cad', 'engine.json'), manifestBytes);
|
||||
writeFileSync(join(stage, 'cad', 'sw.js'), readFileSync(join(output, 'sw.js')));
|
||||
writeFileSync(join(stage, 'cad', 'ENGINE-ONLY.txt'), 'Engine update only: this archive contains no HTML pages. For a complete CAD deployment, use vibemake-cad.zip from the same build.\n');
|
||||
console.log(`Verified ${manifest.files.length} assets for build ${manifest.buildId}`);
|
||||
NODE
|
||||
|
||||
(cd "$STAGING_DIR" && zip -q -r vibemake-cad-engine.zip cad)
|
||||
mv -f "$STAGING_DIR/vibemake-cad-engine.zip" "$ARCHIVE"
|
||||
|
||||
printf '\nPackaging CAD HTML, scripts, styles and the freshly built engine...\n'
|
||||
VIBEMAKE_CAD_ENGINE_DIST="$ENGINE_DIR" \
|
||||
VIBEMAKE_CAD_PACKAGE_DIR="$ROOT_DIR/dist/vibemake-cad" \
|
||||
VIBEMAKE_CAD_PACKAGE_ZIP="$SITE_ARCHIVE" \
|
||||
node "$SITE_ROOT/scripts/build-cad.mjs"
|
||||
|
||||
printf '\nWeb build completed successfully.\n'
|
||||
printf 'Engine directory: %s\n' "$ENGINE_DIR"
|
||||
printf 'Engine manifest: %s/engine.json\n' "$ENGINE_DIR"
|
||||
printf 'DEPLOY THIS COMPLETE CAD ZIP: %s\n' "$SITE_ARCHIVE"
|
||||
printf 'Engine-only update ZIP (no HTML): %s\n' "$ARCHIVE"
|
||||
printf '\nExtract the complete CAD ZIP directly into <website-root>/cad/.\n'
|
||||
printf 'Its root contains index.html, editor/, js/, css/, vendor/ and the current engine.\n'
|
||||
printf 'Preserve the main site, PCB and existing CAD asset directories. Do not extract into cad/cad/.\n'
|
||||
printf 'The engine-only ZIP has a different layout: merge it into the website root.\n'
|
||||
printf 'No main-site build or deployment is required.\n'
|
||||
@@ -1066,6 +1066,13 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
Layout::left_to_right(Align::Center).with_main_wrap(true),
|
||||
|ui| {
|
||||
ui.set_min_height(Tokens::get().control_height);
|
||||
let upload =
|
||||
ui_kit::button(ui, tr("ui.agent_chat_upload_attachment"), ui_kit::Button::Enabled(attachment_picker_enabled(app)))
|
||||
.backing_on_hover_text(tr("ui.agent_chat_upload_attachment_tip"));
|
||||
crate::scenario::publish_target("agent_chat:upload_attachment", upload.rect);
|
||||
if upload.clicked() {
|
||||
choose_attachment_file(app, ui.ctx());
|
||||
}
|
||||
// A picture of the view goes with the message to agents that take pictures.
|
||||
let images = app.agent_chat.images || !state.running();
|
||||
let attach = ui
|
||||
@@ -2252,9 +2259,34 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap<u64, egui::Tex
|
||||
clicked
|
||||
}
|
||||
|
||||
/// The + button: choose a file with the app's picker (pictures, text and CAD files), or paste
|
||||
/// the clipboard's picture.
|
||||
/// Both attachment entry points share the same quota and picker.
|
||||
fn attachment_picker_enabled(app: &SolveApp) -> bool {
|
||||
let available = app.agent_chat.browser_attachment.is_none() && app.agent_chat.files() < attach::MAX_FILES;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let available = available && app.services.browser_agent.is_some();
|
||||
available
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn choose_attachment_file(app: &mut SolveApp, _ctx: &egui::Context) {
|
||||
app.pick_file(tr("ui.agent_chat_attachable"), &attach::extensions(), |app, path| {
|
||||
if let Some(path) = path
|
||||
&& let Err(e) = attach_path(app, &path)
|
||||
{
|
||||
app.agent_chat.notice(e, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn choose_attachment_file(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if let Some(service) = &app.services.browser_agent {
|
||||
app.agent_chat.browser_attachment = Some((service.attach)(ctx.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The + menu also offers the clipboard's picture.
|
||||
fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let (mut choose, mut paste) = (false, false);
|
||||
let r = ui_kit::action_menu(ui, "+", |ui| {
|
||||
@@ -2274,13 +2306,7 @@ fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
crate::scenario::publish_handle("agent_chat:add", r.response.rect.center());
|
||||
r.response.backing_on_hover_text(tr("ui.agent_chat_add"));
|
||||
if choose {
|
||||
app.pick_file(tr("ui.agent_chat_attachable"), &attach::extensions(), |app, path| {
|
||||
if let Some(path) = path
|
||||
&& let Err(e) = attach_path(app, &path)
|
||||
{
|
||||
app.agent_chat.notice(e, true);
|
||||
}
|
||||
});
|
||||
choose_attachment_file(app, ui.ctx());
|
||||
}
|
||||
if paste && let Err(e) = paste_picture(app) {
|
||||
app.agent_chat.notice(e, true);
|
||||
@@ -2656,7 +2682,7 @@ fn agent_list(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
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 enabled = attachment_picker_enabled(app);
|
||||
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));
|
||||
@@ -2672,12 +2698,10 @@ fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
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()));
|
||||
}
|
||||
if choose {
|
||||
choose_attachment_file(app, ui.ctx());
|
||||
}
|
||||
if paste && let Some(service) = &app.services.browser_agent {
|
||||
app.agent_chat.browser_attachment = Some((service.paste_picture)(ui.ctx().clone()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3334,11 +3334,11 @@ fn each_file_has_its_own_id_and_thumbnail() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// The + button: "Choose a file…" asks the app's file picker for the types that can be attached
|
||||
/// Upload attachment and the + menu ask the same picker for the types that can be attached
|
||||
/// (not the design types Open shows) and attaches what it answers; "Paste a picture" attaches
|
||||
/// the clipboard's picture (here given as RGBA, as the system does).
|
||||
#[test]
|
||||
fn the_plus_button_attaches_a_chosen_file_or_a_pasted_picture() {
|
||||
fn the_upload_button_and_plus_menu_attach_a_chosen_file_or_a_pasted_picture() {
|
||||
use crate::scenario::handle_at;
|
||||
let d = attachable("plus");
|
||||
let mut h = narrow_chat();
|
||||
@@ -3351,6 +3351,14 @@ fn the_plus_button_attaches_a_chosen_file_or_a_pasted_picture() {
|
||||
Box::pin(async move { Some(p) })
|
||||
}));
|
||||
h.frames(2);
|
||||
let upload = handle_at("agent_chat:upload_attachment").expect("upload is visible without opening a menu");
|
||||
let panel = h.app.agent_chat.panel_rect.expect("the chat panel");
|
||||
assert!(panel.contains(upload), "upload stays inside a narrow chat");
|
||||
h.call("ui.click", json!({"x": upload.x, "y": upload.y}));
|
||||
h.frames(4);
|
||||
assert_eq!(status(&h.app)["attachments"], json!(["brief.md"]));
|
||||
h.call("ui.agent_chat", json!({"remove_file": 0}));
|
||||
h.frames(2);
|
||||
let plus = handle_at("agent_chat:add").expect("a + button");
|
||||
h.call("ui.click", json!({"x": plus.x, "y": plus.y}));
|
||||
h.frames(2);
|
||||
|
||||
@@ -32,6 +32,8 @@ use crate::ui_kit;
|
||||
pub enum Kind {
|
||||
/// Open the design (or a CAD, mesh or drawing file as a new design) in a tab of its own.
|
||||
Open,
|
||||
/// Prepare a STEP in an isolated session for a product host; never adopt a tab.
|
||||
PlatformStep,
|
||||
/// Insert CAD bodies, meshes or sketch drawing geometry into the active design.
|
||||
Insert,
|
||||
/// Open a design an earlier run autosaved before it closed.
|
||||
@@ -49,6 +51,7 @@ pub struct Request {
|
||||
pub kind: Kind,
|
||||
/// A control-channel caller waiting for the command's reply.
|
||||
pub reply: Option<Sender<ControlResponse>>,
|
||||
pub(crate) prepared: Option<Sender<Result<crate::platform::PreparedProject, String>>>,
|
||||
/// The folders that caller's agent may use: the worker reads the file inside them.
|
||||
pub scope: Option<solidcraft_engine::io::vfs::PathScope>,
|
||||
/// What that caller asked of an open or import besides its path (`up`, `names`, `matrix`,
|
||||
@@ -69,6 +72,7 @@ impl Request {
|
||||
path: path.into(),
|
||||
kind,
|
||||
reply: None,
|
||||
prepared: None,
|
||||
scope: solidcraft_engine::io::vfs::current_scope(),
|
||||
options: Default::default(),
|
||||
allow_hosts: Vec::new(),
|
||||
@@ -88,6 +92,7 @@ impl Request {
|
||||
fn command(&self) -> (&'static str, Value) {
|
||||
match &self.kind {
|
||||
Kind::Open => ("doc.open", self.params()),
|
||||
Kind::PlatformStep => ("file.insert_step", self.params()),
|
||||
Kind::Insert if solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", self.params()),
|
||||
Kind::Insert if solidcraft_engine::io::is_point_cloud_path(&self.path) => ("pointcloud.insert", self.params()),
|
||||
Kind::Insert => (insert_command(&self.path), self.params()),
|
||||
@@ -97,6 +102,9 @@ impl Request {
|
||||
}
|
||||
}
|
||||
fn answer(&self, r: Result<Value, String>) {
|
||||
if let (Some(reply), Err(error)) = (&self.prepared, &r) {
|
||||
let _ = reply.send(Err(error.clone()));
|
||||
}
|
||||
if let Some(reply) = &self.reply {
|
||||
if crate::control::chat_turn_cancelled(self.chat_turn.as_deref()) {
|
||||
let _ = reply.send(crate::control::cancelled_chat_response());
|
||||
@@ -187,7 +195,7 @@ const STAGED_FRAME_MS: f64 = 30.0;
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
fn staged_kind(request: &Request) -> bool {
|
||||
let p = &request.path;
|
||||
let step = matches!(request.kind, Kind::Insert | Kind::Open)
|
||||
let step = matches!(request.kind, Kind::Insert | Kind::Open | Kind::PlatformStep)
|
||||
&& solidcraft_engine::io::is_step_path(p)
|
||||
&& !solidcraft_engine::io::is_iges_path(p)
|
||||
&& !solidcraft_engine::io::is_native_cad_path(p);
|
||||
@@ -285,6 +293,7 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String>
|
||||
return Ok(());
|
||||
}
|
||||
let r = match &request.kind {
|
||||
Kind::PlatformStep => Err("unsupported platform import".into()),
|
||||
Kind::Insert => {
|
||||
app.insert_path(&request.path);
|
||||
Ok(Value::Null)
|
||||
@@ -408,6 +417,7 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio
|
||||
path: path.into(),
|
||||
kind,
|
||||
reply: Some(req.reply.clone()),
|
||||
prepared: None,
|
||||
scope,
|
||||
options,
|
||||
allow_hosts: Vec::new(),
|
||||
@@ -476,7 +486,9 @@ fn start(app: &mut SolveApp) {
|
||||
let mut scratch = if insert || update || request.kind == Kind::ExportDxf { app.session.scratch() } else { Session::default() };
|
||||
// A design opened or recovered here is run through the host's pre-command check too, and
|
||||
// evaluated under the user's validation mode.
|
||||
scratch.set_command_check(app.session.command_check());
|
||||
if request.kind != Kind::PlatformStep {
|
||||
scratch.set_command_check(app.session.command_check());
|
||||
}
|
||||
scratch.set_validation(app.preferences.validation);
|
||||
if insert {
|
||||
scratch.selection = app.session.selection.clone();
|
||||
@@ -604,7 +616,9 @@ fn start_staged(app: &mut SolveApp) {
|
||||
let insert = request.insert();
|
||||
let before = if insert { crate::open_meshing::session_world(&app.session).bodies.iter().map(|b| b.name.clone()).collect() } else { Vec::new() };
|
||||
let mut session = if insert { app.session.scratch() } else { Session::default() };
|
||||
session.set_command_check(app.session.command_check());
|
||||
if request.kind != Kind::PlatformStep {
|
||||
session.set_command_check(app.session.command_check());
|
||||
}
|
||||
session.set_validation(app.preferences.validation);
|
||||
if insert {
|
||||
session.selection = app.session.selection.clone();
|
||||
@@ -1068,6 +1082,11 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
request.answer(r);
|
||||
}
|
||||
Ok(made) if request.kind == Kind::PlatformStep && running.matches(&app.session) => {
|
||||
if let Some(reply) = &request.prepared {
|
||||
let _ = reply.send(Ok(crate::platform::PreparedProject { session: made.session, result: made.result }));
|
||||
}
|
||||
}
|
||||
Ok(_) if reuse_open(app, request) => {}
|
||||
Ok(made) if running.matches(&app.session) => 'open: {
|
||||
// Not meshed yet: framing it while it goes in must not mesh it here.
|
||||
@@ -1183,6 +1202,27 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
/// its window buttons and the window's resize edges stay live; the design underneath takes no
|
||||
/// pointer input until the file is in.
|
||||
/// What a file operation under way is doing (for the frame watch), if one is.
|
||||
pub(crate) fn platform_progress(app: &SolveApp) -> Option<Value> {
|
||||
let running = app.file_load.running.as_ref()?;
|
||||
if running.request.kind != Kind::PlatformStep {
|
||||
return None;
|
||||
}
|
||||
let work = running.work();
|
||||
let phase = if running.phase.load(Ordering::Relaxed) > 0 {
|
||||
"preparing"
|
||||
} else if work.is_some_and(|(name, _, _)| name != "reading") {
|
||||
"importing"
|
||||
} else {
|
||||
"reading"
|
||||
};
|
||||
let mut result = json!({"phase": phase});
|
||||
if let Some((_, done, total)) = work.filter(|(_, _, total)| *total > 0) {
|
||||
result["done"] = json!(done);
|
||||
result["total"] = json!(total);
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn phase(app: &SolveApp) -> Option<&'static str> {
|
||||
let r = app.file_load.running.as_ref()?;
|
||||
Some(match (r.staged.is_some(), r.phase.load(Ordering::Relaxed)) {
|
||||
@@ -1280,7 +1320,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
crate::i18n::tr("file_load.waiting")
|
||||
} else {
|
||||
crate::i18n::tr(match r.request.kind {
|
||||
Kind::Insert => "file_load.inserting",
|
||||
Kind::Insert | Kind::PlatformStep => "file_load.inserting",
|
||||
Kind::Open => "file_load.opening",
|
||||
Kind::Recover { .. } => "file_load.recovering",
|
||||
Kind::ExportDxf => "dxf.exporting",
|
||||
@@ -1288,7 +1328,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
})
|
||||
};
|
||||
let icon = match r.request.kind {
|
||||
Kind::Insert => "import",
|
||||
Kind::Insert | Kind::PlatformStep => "import",
|
||||
Kind::Open => "open",
|
||||
Kind::Recover { .. } => "restore",
|
||||
Kind::ExportDxf => "export",
|
||||
@@ -1415,6 +1455,39 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_step_prepares_without_replacing_the_host_document() {
|
||||
let mut app = SolveApp::new(Session::default(), Default::default());
|
||||
app.enable_vibemake();
|
||||
let before = app.session.doc.clone();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut request = Request::new("/host/part.step", Kind::PlatformStep);
|
||||
request.prepared = Some(tx);
|
||||
let mut incoming = Session::default();
|
||||
incoming.execute("solid.box", &json!({"length": 2, "width": 3, "height": 4})).unwrap();
|
||||
completed_open(&mut app, request, incoming);
|
||||
tick(&mut app, &egui::Context::default());
|
||||
let prepared = rx.try_recv().unwrap().unwrap();
|
||||
assert!(!prepared.session.doc.features.is_empty());
|
||||
assert!(Arc::ptr_eq(&before, &app.session.doc));
|
||||
assert!(app.platform.is_locked());
|
||||
assert_eq!(app.docs.count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_platform_step_never_publishes_its_prepared_session() {
|
||||
let mut app = SolveApp::new(Session::default(), Default::default());
|
||||
let before = app.session.doc.clone();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut request = Request::new("/host/part.step", Kind::PlatformStep);
|
||||
request.prepared = Some(tx);
|
||||
completed_open(&mut app, request, Session::default());
|
||||
app.file_load.cancel();
|
||||
tick(&mut app, &egui::Context::default());
|
||||
assert!(rx.try_recv().unwrap().is_err());
|
||||
assert!(Arc::ptr_eq(&before, &app.session.doc));
|
||||
}
|
||||
|
||||
/// An Open says which design it brought in, by the name its tab shows, and whether it took
|
||||
/// a tab of its own or replaced the blank design.
|
||||
#[test]
|
||||
|
||||
@@ -8,6 +8,12 @@ use serde_json::Value;
|
||||
|
||||
use crate::SolveApp;
|
||||
|
||||
/// An isolated import returned to a host after loading and preparing its display meshes.
|
||||
pub struct PreparedProject {
|
||||
pub session: solidcraft_engine::Session,
|
||||
pub result: Value,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Platform {
|
||||
pub enabled: bool,
|
||||
@@ -53,6 +59,23 @@ impl Platform {
|
||||
}
|
||||
|
||||
impl SolveApp {
|
||||
/// Load a host-supplied STEP without changing this app's active document or command policy.
|
||||
pub fn prepare_platform_step(&mut self, path: &str, name: &str) -> Result<std::sync::mpsc::Receiver<Result<PreparedProject, String>>, String> {
|
||||
if self.file_load.busy() {
|
||||
return Err("a file operation is already running".into());
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut request = crate::file_load::Request::new(path, crate::file_load::Kind::PlatformStep);
|
||||
request.options.insert("name".into(), serde_json::json!(name));
|
||||
request.prepared = Some(tx);
|
||||
crate::file_load::begin_request(self, request)?;
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
pub fn platform_open_progress(&self) -> Option<Value> {
|
||||
crate::file_load::platform_progress(self)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# VibeMake CAD 前端与引擎集成
|
||||
|
||||
Workspace STEP integration uses the bodyless association POST and the additive `stepImport` bridge capability. See [Workspace STEP integration](workspace-step-integration.md). Initial STEP files have a separate 500 MiB input limit; native cloud designs retain their 256 MiB limit.
|
||||
|
||||
本文记录 VibeMake 主站与 SolidCraft WASM 引擎的前端集成边界、构建步骤、运行配置和发布验收。云项目 API 与上传协议以同目录的 [CAD 个人工作空间前端对接](workspace-api.md) 为准(2026-11-05 同步)。`backend-implementation.md` v1.2 是历史方案,其中的旧接口、私有 Bucket 和下载签名约定不再作为当前对接依据。
|
||||
|
||||
## 产品结构
|
||||
@@ -63,34 +65,46 @@ AI 工具仍执行 Rust 命令;Web 适配层复用 MCP 的工具 schema 和调
|
||||
|
||||
## 引擎产物
|
||||
|
||||
保持 SolidCraft 默认 SMLib WASM 构建开启,不发布不含内核的空壳。先在 SolidCraft 仓库根目录执行:
|
||||
Keep the default SolidCraft SMLib WASM build enabled. The CAD page sources still live in the adjacent VibeMake checkout. Run `npm ci` in that checkout once to install its packaging dependency, then run this command from the SolidCraft repository root:
|
||||
|
||||
```sh
|
||||
node scripts/build-vibemake-cad.mjs
|
||||
./build.sh
|
||||
```
|
||||
|
||||
产物默认写入 `dist/vibemake-cad-engine/`,也可使用 `VIBEMAKE_CAD_ENGINE_OUT` 指定输出目录。`engine.json` 含 `bridgeVersion`、`engineKind`、kernel、build id,以及每个 JS/WASM/字体/许可证文件的路径、大小和 SHA-256。产物目录包含匹配的 `_assets/<buildId>/`。
|
||||
The script builds the current engine and produces two separate archives:
|
||||
|
||||
当前主站 `scripts/build.mjs` 已采用独立引擎发布:主站包不会自动复制引擎,也不会把引擎放进主站 ZIP。发布时必须另外校验并发布上述产物,不能只上传主站包。可复用主站已有的 `readCadEngine` / `copyCadEngine`,生成专用于叠加发布的目录:
|
||||
- `dist/vibemake-cad.zip` is the complete CAD deployment package. Its ZIP root contains `index.html`, `editor/index.html`, `engine.json`, workers, the manifest, current `_assets/<buildId>/`, CAD and shared dependency modules under `js/`, common and CAD styles under `css/`, fonts and libraries under `vendor/`, required brand and environment assets, icons, and robot indexes under `data/` and `robots/`. It has no enclosing `cad/` directory. Publish this archive for a first CAD deployment or a combined page and engine update. Its unpacked output is `dist/vibemake-cad/`.
|
||||
- `dist/vibemake-cad-engine.zip` contains only `cad/engine.json`, `cad/sw.js` and the current `cad/_assets/<buildId>/`. It has no HTML pages and is only for updating an already deployed CAD application. It is not sufficient for a first deployment.
|
||||
|
||||
Extract the complete archive directly into the website's `cad/` directory:
|
||||
|
||||
```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
|
||||
unzip -o /path/to/solidcraft-main/dist/vibemake-cad.zip -d /path/to/vibemake/cad
|
||||
```
|
||||
|
||||
命令在 VibeMake 仓库运行。缺少清单、缺少文件、哈希不匹配、引擎版本不兼容或资源不在 build id 路径下都会失败。将 staging 的 `cad/` 叠加发布到网站根目录,保留线上旧 `_assets/<buildId>/`;最后更新 `engine.json`。主站构建会重建自己的 `dist/`,不能依靠它保留旧引擎目录。不会回退旧 iframe。
|
||||
The result must include `<website-root>/cad/index.html` and `<website-root>/cad/editor/index.html`. Extract the archive itself; copying a ZIP into the directory does not publish its contents. Do not extract the complete package into the website root or add an extra enclosing directory. All CAD frontend dependencies are contained under `cad/`; it does not depend on the website root's shared JS, CSS, fonts or vendor files. Preserve the main site, PCB, server configuration and older `cad/_assets/<buildId>/` directories used by open editors. Do not clear the website or CAD directory before extraction.
|
||||
|
||||
本地开发服务从 VibeMake 仓库启动:
|
||||
The default frontend checkout is `../vibemake`. Set `VIBEMAKE_SITE_ROOT=/absolute/path/to/vibemake` when it lives elsewhere. The script passes the freshly built engine directory to `scripts/build-cad.mjs`, so the complete archive cannot silently use an older engine installed in the frontend checkout. The engine itself remains in `dist/vibemake-cad-engine/`; its manifest records the bridge version, engine kind, kernel, build ID, sizes and SHA-256 digests.
|
||||
|
||||
For local development, install only the engine archive from the VibeMake repository root:
|
||||
|
||||
```sh
|
||||
PORT=8091 VIBEMAKE_CAD_ENGINE_DIST="/path/to/solidcraft/dist/vibemake-cad-engine" npm run dev
|
||||
unzip -o ../solidcraft-main/dist/vibemake-cad-engine.zip -d .
|
||||
```
|
||||
|
||||
开发环境 `/api` 由此同源服务代理;部署仍沿用主站现有 `API_BASE`、域名选择和后端 CORS 配置。真实开发和生产环境不得将测试 mock 后端作为默认目标。
|
||||
Unlike the complete package, the engine-only archive already contains a top-level `cad/` directory. Extract that archive into the website or VibeMake project root, not into its `cad/` directory. Preserve the pages and other CAD frontend files. Do not create a nested `cad/cad/` directory. Engine binaries installed here are ignored by Git.
|
||||
|
||||
Start the local server from VibeMake without a CAD engine path setting:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Restart the development server after installing a new engine. Local startup validates `cad/engine.json` and its assets. The former external-directory environment setting remains an optional development override for compatibility; the normal workflow uses the files in `cad/`.
|
||||
|
||||
VibeMake's `npm run build` and `npm run build:dev` exclude `cad/`, `pcb/`, `js/cad/` and `css/cad.css`. They do not require CAD or PCB sources or engine files, and never publish those independent modules. The optional compatibility command `npm run build:cad` packages the engine already installed in VibeMake with the CAD pages and frontend dependencies as `dist-cad.zip`. Extract this complete package directly into the website's `cad/` directory as well. It is not required after SolidCraft's `./build.sh`, which produces the complete deployment archive directly.
|
||||
|
||||
Development `/api` requests use the existing same-origin proxy. Deployment retains the site's API base selection and backend CORS configuration. Mock APIs are for isolated tests only.
|
||||
|
||||
静态主站需要为两条 CAD URL 配置 SPA/目录索引回退;`/cad/_assets/<buildId>/...` 使用一年 immutable 缓存,`/cad/engine.json`、页面、worker 不做长缓存。WASM 返回 `application/wasm`,页面通过绝对 `/cad/` 资源 URL 载入。不要在部署清理时删除仍被已打开页面引用的旧 build-id 资源。发布新版本不改变 PCB 路由;回滚时恢复页面和 `engine.json`,保留所有 engine asset 目录。
|
||||
|
||||
@@ -118,8 +132,7 @@ npm run test:experiences
|
||||
|
||||
```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
|
||||
PORT=8091 API_TARGET=http://127.0.0.1:8092 npm run dev
|
||||
```
|
||||
|
||||
另一个终端执行 `npx playwright install chromium`(首次运行)和 `npm run test:cad:browser`。可设置 `VM_CAD_BASE_URL`、`PLAYWRIGHT_CHROMIUM_EXECUTABLE`、`VM_CAD_ARTIFACT_DIR`;浏览器记录和截图只写到指定的本机验收目录。
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
“已安装”和“自定义命令”保留原版位置,当前置灰并说明需要助手服务或本地连接程序。独立系统窗口入口同样说明 Web 限制;左右停靠、调整宽度、最小化和新建对话继续使用原版交互。
|
||||
|
||||
输入区“+”恢复原版菜单:添加文件或粘贴图片。剪贴板图片需浏览器授权,不可用时可改用文件选择。选择器支持原版图片和文本扩展名(含 SVG 源码、TSV、日志等);图片/文本也可拖入助手。PDF、CAD 文件及任意本机路径不在当前聊天附件能力内。连接时自动读取模型列表,失败时显示警告并保留手输模型。
|
||||
The composer has an **Upload attachment** button beside Attach view, Attach selection and Pick context. The existing **+** menu also offers a file picker and clipboard pictures; clipboard access requires browser permission. Files can also be dropped onto the assistant. Supported images are PNG, JPG/JPEG, GIF, WebP, BMP and TIF/TIFF. Hosted CAD AI converts GIF/WebP/BMP/TIFF to PNG; animated images use the first frame when converted. Supported UTF-8 text files are SVG source, TXT, MD/Markdown, JSON, CSV/TSV, YAML/YML, TOML, XML, LOG, INI and CFG. A message accepts up to eight files, each image up to 40 MiB and each text file up to 256 KiB. Images are resized to a longest edge of at most 2048 pixels; backend limits may reduce them further. Attachments are sent with the next message. PDF, Office documents, CAD files, audio, video and local path references are unavailable as web chat attachments; use File import for CAD files.
|
||||
|
||||
## 数据与凭据
|
||||
|
||||
@@ -76,9 +76,7 @@ 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
|
||||
PORT=8094 API_TARGET=http://127.0.0.1:8092 node scripts/server.mjs
|
||||
```
|
||||
|
||||
另一个终端:
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# CAD 个人工作空间前端对接
|
||||
|
||||
> Workspace STEP integration was added on 2026-11-06. See [Workspace STEP integration](workspace-step-integration.md) for the current association contract, opening order and deployment checklist. STEP is an initial import source only; CAD saves never write back to a workspace repository.
|
||||
|
||||
网页 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` 设计文件,不管理外部引用的多文件装配。
|
||||
@@ -32,6 +34,8 @@ CAD 与 Vibemake 共用 `/api/auth/login`、`/api/auth/logout` 和 `/api/users/m
|
||||
```ts
|
||||
interface CadProject {
|
||||
cadProjectCode: string;
|
||||
workspaceProjectCode: string | null;
|
||||
initialStep: { downloadUrl: string; fileName: string; sizeBytes: number } | null;
|
||||
name: string;
|
||||
description: string;
|
||||
coverUrl: string | null; // 完整 OSS/CDN 地址,无封面为 null
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Workspace STEP integration
|
||||
|
||||
VibeMake workspace projects may bootstrap one associated CAD project. This integration is one-way: the first import reads STEP, while subsequent cloud saves and opens use the native `.sc` document. Neither saving nor Save As changes workspace STEP, Git, or community publication.
|
||||
|
||||
## Entry and API
|
||||
|
||||
The current owner's workspace detail shows Edit only for a READY repository with a nonempty `stepMainUrl`, outside Git historical views. The existing desktop check runs before creating an association. Use the current fork's `projectCode`, never its `sourceProjectCode`.
|
||||
|
||||
`POST /api/workspace/projects/{projectCode}/cad-project` has no body, uses the platform Bearer token, and returns a `CadProject` in the standard envelope. The server atomically returns or creates one active association, including under retries and concurrent tabs. The editor URL contains only the returned CAD code.
|
||||
|
||||
All CAD records include `workspaceProjectCode: string | null` and `initialStep: {downloadUrl, fileName, sizeBytes} | null`. An associated source is a creation-time snapshot and remains after native saves. A standalone project has null association fields. Unsaved projects have `hasDocument=false` and `version=0`.
|
||||
|
||||
## Opening and recovery
|
||||
|
||||
1. Fetch latest CAD metadata.
|
||||
2. With `hasDocument=true`, read document metadata and open its `.sc` using `document.version`. Failure never falls back to STEP or an empty design.
|
||||
3. Without a cloud document, offer pending transaction and local draft recovery before downloading the source. Unresolved transactions or a deferred draft block fresh initialization.
|
||||
4. With no recovered document, import `initialStep`; without a source, open an empty design.
|
||||
5. STEP import is unsaved and starts at version zero. Preserve import warnings, offer details, and reject an import with no usable bodies. Capture a local native draft before normal editing continues.
|
||||
|
||||
A source STEP accepts at most 524288000 bytes and a filename of 1024 Unicode characters, preserving original case and Unicode. Native cloud documents retain their 268435456-byte and 255-character limits. The source limit is not a guarantee of successful geometry import or native serialization size. All downloads use returned public URLs without platform credentials and validate the actual byte count.
|
||||
|
||||
## Binary bridge
|
||||
|
||||
Bridge version 1 adds `ready().capabilities.stepImport=true`, `openProjectFromStep({projectId,fileName,bytes:Uint8Array})`, and `cancelOpenProject()`. Successful imports return `{binding,warnings}`. `getState()` and subscriptions report `opening` with a phase and available work counts. Native `openProject` stays compatible; a host only requires STEP capability when it needs to import a source.
|
||||
|
||||
`createSnapshot({forLocalDownload:true})` permits a local native download above the 256 MiB cloud limit. Ordinary snapshots, native uploads, and native opens retain their existing limit. The host uses this option only for Download design copy; it does not acknowledge a cloud save. If the draft list cannot be read after pending transactions were checked, the user can explicitly retry or continue without restoring a draft. Unresolved transactions always remain blocking.
|
||||
|
||||
The bridge stages bytes under a private temporary VFS key, passes the original name separately, and uses `file_load` to prepare an isolated session through the existing STEP reader and `file.insert_step`. The prepare-only completion path does not adopt tabs or relax the active document's host command checks. Only a current request may atomically adopt its result and bind a project. Failure, cancellation, release, and stale completion clean up staged bytes. An import keeps its component, Import feature, assembly structure, and existing rigid assembly semantics.
|
||||
|
||||
Cancelling an open preserves the current document. Releasing a project also cancels its pending import. Account changes abort downloads and invalidate pending opens before they can adopt a session or bind an assistant.
|
||||
|
||||
Recovery prompts close when their opening request is aborted. Restored drafts are rebound to the new native binding only if the stored snapshot has not changed. Successful save acknowledgements clear earlier drafts covered by the same binding's monotonic revision counter, while preserving later revisions, differing visibility at the same counter, and every other binding. A draft write finishing after acknowledgement cannot recreate a covered draft.
|
||||
|
||||
## Saving
|
||||
|
||||
Use the existing native snapshot, signature, anonymous OSS POST, uploadCode confirmation and exact-baseline ACK. First save uses expectedVersion zero. Preserve journals, conflict handling, later edits, covers, and account isolation. Save As creates a standalone CAD project. Cover failure remains nonfatal to native saving.
|
||||
|
||||
## Backend and release checks
|
||||
|
||||
- Apply association and initial-STEP database increments and verify cover migrations.
|
||||
- Verify owner isolation, active association uniqueness, idempotent retries, quota accounting and documented errors.
|
||||
- Keep referenced STEP object bytes immutable and retained while a CAD project needs them, including after workspace replacement or deletion.
|
||||
- Workspace deletion must not delete CAD. CAD deletion releases its association; a later workspace edit can create a fresh CAD code.
|
||||
- Enable CAD native uploads with `CAD_OSS_ENABLED` and existing shared OSS settings. Creating an association does not depend on this switch.
|
||||
- Check real frontend-origin CORS for both STEP reads and native uploads/reads. Object-store 403 does not expire platform authentication.
|
||||
- Deploy backend, engine assets/manifest, then host code. Retain previous build-id assets for open tabs and rollback; do not clear drafts, auth, CAD data or associations.
|
||||
|
||||
The local workspace contains no backend service implementation. The mock exercises this contract; it does not verify deployed database transactions, resource retention or production CORS.
|
||||
|
||||
## Validation
|
||||
|
||||
`npm run test:cad` covers metadata, association transport, opening precedence, recovery, stale requests and limits. `npm run test:cad:browser` adds the real WASM STEP import/save/reopen path, draft recovery without the source, atomic failure/cancellation, and workspace removal/deletion behavior against the mock. Existing cover, assistant, save, browser, and engine-update checks remain relevant. Rust loader tests verify prepare-only completion and cancellation without changing the active host document. Run WASM checks and the required repository gates before committing.
|
||||
|
||||
For focused integration checks, set `VM_CAD_BROWSER_SUITE=workspace` when running the browser suite. `VM_CAD_BASE_URL` points at the local frontend proxy and `VM_CAD_ARTIFACT_DIR` enables screenshots and JSON results. Tests must use the local mock backend, not a production account or project.
|
||||
@@ -24,4 +24,7 @@ const manifest = { bridgeVersion: 1, engineKind: 'solidcraft', buildId, builtAt:
|
||||
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}`);
|
||||
const publicFiles = files.map((file) => file.path);
|
||||
// Cache only this build's public assets, never API requests or signed URLs.
|
||||
writeFileSync(join(destination, 'sw.js'), `const FILES=new Set(${JSON.stringify(publicFiles)});\nconst CACHE='vm.cad.static.${buildId}';\nself.addEventListener('install',()=>{});\nself.addEventListener('activate',()=>{});\nself.addEventListener('fetch',event=>{const u=new URL(event.request.url);if(event.request.method!=='GET'||u.origin!==self.location.origin||u.search||!FILES.has(u.pathname))return;event.respondWith((async()=>{const cache=await caches.open(CACHE);const hit=await cache.match(event.request);if(hit)return hit;const response=await fetch(event.request);if(response.ok)await cache.put(event.request,response.clone());return response;})());});\n`);
|
||||
console.log(`Engine directory: ${destination}`);
|
||||
|
||||
Reference in New Issue
Block a user