修改cad、pcb

This commit is contained in:
2026-11-06 15:54:55 +08:00
parent 7a792bfc7f
commit f8868d27a6
27 changed files with 1196 additions and 103 deletions
+4
View File
@@ -9,3 +9,7 @@ sandbox/node_modules/
# Generated simulation bundles and local upload/preview exports.
/play/
/deliverables/
# Generated CAD engine files installed from the SolidCraft Web package.
/cad/_assets/
/cad/engine.json
/cad/sw.js
+19
View File
@@ -18,6 +18,23 @@ npm run build:walking
生成 `/play/robots/index.html`(Robot Package 通用运行器)和 `/play/microduck/index.html`(旧版 Microduck 包)。两者由本站提供,按详情接口选择;关闭弹窗会释放仿真。修改沙盒后再次执行 `npm run build:walking`;`npm run build` 会自动构建并收录。默认暂停,点击开始后按住键盘 / 触摸方向键运动,松开停止。来源记录见 `sandbox/NOTICE`。
### CAD Web engine
Build the engine with `./build.sh` in the SolidCraft repository. Then run these commands from the VibeMake project root:
```bash
unzip -o ../solidcraft-main/dist/vibemake-cad-engine.zip -d .
npm run dev
```
The archive already contains a `cad/` directory. Merge it into the project root so that `cad/engine.json`, `cad/sw.js` and `cad/_assets/<buildId>/` sit beside the existing `cad/editor/`. Do not extract it into `cad/cad/` or replace the whole existing `cad/` directory. No CAD engine path environment variable is needed. Restart the development server after installing a new engine.
`npm run build` and `npm run build:dev` validate the engine installed in `cad/` and include its current assets in the site ZIP. If no engine is installed, the build reports that the engine must be deployed separately. Engine binaries are generated files and are not committed to this repository.
The site registers `/cad/worker.js`, which imports the engine package's `/cad/sw.js` and supplies the update activation protocol, including for older engine packages. The refresh action first runs the unsaved-changes guard, activates the waiting worker, and then reloads. Update notices compare the published engine build with the running build, rather than treating every waiting worker as a new editor version. Login state, IndexedDB drafts, and other applications' caches are retained.
Deploy the site changes (including `cad/worker.js` and `js/cad/`) once with this fix; replacing only the engine ZIP cannot repair the old site's refresh handler. Serve `/cad/engine.json`, `/cad/sw.js`, `/cad/worker.js`, the editor HTML, and `js/cad/` with `Cache-Control: no-cache` (or `no-store`). Only `/cad/_assets/<buildId>/` should use long-lived immutable caching. The development server already applies these cache policies. Update regressions: `node --test tests/cad/engine-updates.browser.mjs`.
### 项目装配与行走资源
社区详情读取后端实际上传绑定:
@@ -53,6 +70,8 @@ node scripts/server.mjs
# http://localhost:8091 后端接口数据(/api 转发到 dev 后端;线上也用这个服务器,按域名自动选 dev / 正式后端)
# http://127.0.0.1:8091 本地演示数据(最早的完整样子,作参考)
# /pcb/ 同源代理到相邻的 ziro-designer-main/designer,默认使用真实后端,无需手动打开 5173 端口
# AI 自动绘板默认连接本机 127.0.0.1:8000:先在相邻仓库 backend/.env.local 配置 DeepSeek 密钥与 KiCad 路径,再运行 backend/start.sh
# PCB_API_TARGET=http://其他服务器:8000 node scripts/server.mjs 可覆盖 AI 绘板后台地址
# PCB_API_MODE=mock node scripts/server.mjs 显式启用开发模拟(独立存储,不共用主站账号)
```
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 95.3697 24" role="img" aria-labelledby="title">
<title id="title">make CAD</title>
<g>
<path fill="#3088e9" transform="translate(0.0000 18) scale(0.00976562 -0.00976562)" d="M1049 510V147Q1049 61 1010.0 18.0Q971 -25 907 -25Q845 -25 806.5 18.0Q768 61 768 147V582Q768 685 761.0 742.0Q754 799 723.0 835.5Q692 872 625 872Q491 872 448.5 780.0Q406 688 406 516V147Q406 62 367.5 18.5Q329 -25 266 -25Q204 -25 164.5 18.5Q125 62 125 147V928Q125 1005 160.5 1045.0Q196 1085 254 1085Q310 1085 347.5 1047.5Q385 1010 385 944V918Q456 1003 537.0 1043.0Q618 1083 717 1083Q820 1083 894.0 1042.0Q968 1001 1016 918Q1085 1002 1164.0 1042.5Q1243 1083 1339 1083Q1451 1083 1532.0 1039.0Q1613 995 1653 913Q1688 839 1688 680V147Q1688 61 1649.0 18.0Q1610 -25 1546 -25Q1484 -25 1444.5 18.5Q1405 62 1405 147V606Q1405 694 1397.5 747.0Q1390 800 1357.0 836.0Q1324 872 1257 872Q1203 872 1154.5 840.0Q1106 808 1079 754Q1049 685 1049 510Z"/>
<path fill="#f24c38" transform="translate(16.9953 18) scale(0.00976562 -0.00976562)" d="M831 129Q732 52 639.5 13.5Q547 -25 432 -25Q327 -25 247.5 16.5Q168 58 125.0 129.0Q82 200 82 283Q82 395 153.0 474.0Q224 553 348 580Q374 586 477.0 607.0Q580 628 653.5 645.5Q727 663 813 688Q808 796 769.5 846.5Q731 897 610 897Q506 897 453.5 868.0Q401 839 363.5 781.0Q326 723 310.5 704.5Q295 686 244 686Q198 686 164.5 715.5Q131 745 131 791Q131 863 182.0 931.0Q233 999 341.0 1043.0Q449 1087 610 1087Q790 1087 893.0 1044.5Q996 1002 1038.5 910.0Q1081 818 1081 666Q1081 570 1080.5 503.0Q1080 436 1079 354Q1079 277 1104.5 193.5Q1130 110 1130 86Q1130 44 1090.5 9.5Q1051 -25 1001 -25Q959 -25 918.0 14.5Q877 54 831 129ZM813 524Q753 502 638.5 477.5Q524 453 480.0 441.5Q436 430 396.0 396.5Q356 363 356 303Q356 241 403.0 197.5Q450 154 526 154Q607 154 675.5 189.5Q744 225 776 281Q813 343 813 485Z"/>
<path fill="#41b4a0" transform="translate(28.1801 18) scale(0.00976562 -0.00976562)" d="M821 100 580 496 432 356V139Q432 60 390.5 17.5Q349 -25 295 -25Q232 -25 196.0 17.0Q160 59 160 141V1305Q160 1396 195.0 1443.5Q230 1491 295 1491Q358 1491 395.0 1448.0Q432 1405 432 1321V659L739 981Q796 1041 826.0 1063.0Q856 1085 899 1085Q950 1085 984.0 1052.5Q1018 1020 1018 971Q1018 911 907 811L762 678L1042 238Q1073 189 1086.5 163.5Q1100 138 1100 115Q1100 50 1064.5 12.5Q1029 -25 971 -25Q921 -25 894.0 2.0Q867 29 821 100Z"/>
<path fill="#f4801d" transform="translate(38.9449 18) scale(0.00976562 -0.00976562)" d="M903 463H369Q370 370 406.5 299.0Q443 228 503.5 192.0Q564 156 637 156Q686 156 726.5 167.5Q767 179 805.0 203.5Q843 228 875.0 256.0Q907 284 958 332Q979 350 1018 350Q1060 350 1086.0 327.0Q1112 304 1112 262Q1112 225 1083.0 175.5Q1054 126 995.5 80.5Q937 35 848.5 5.0Q760 -25 645 -25Q382 -25 236.0 125.0Q90 275 90 532Q90 653 126.0 756.5Q162 860 231.0 934.0Q300 1008 401.0 1047.5Q502 1087 625 1087Q785 1087 899.5 1019.5Q1014 952 1071.0 845.0Q1128 738 1128 627Q1128 524 1069.0 493.5Q1010 463 903 463ZM369 618H864Q854 758 788.5 827.5Q723 897 616 897Q514 897 448.5 826.5Q383 756 369 618Z"/>
<path fill="#ffffff" transform="translate(54.1297 18) scale(0.02000000 -0.02000000)" d="M545 474H697Q690 536 663.0 584.0Q636 632 594.5 664.5Q553 697 500.5 714.0Q448 731 389 731Q307 731 241.5 702.0Q176 673 131.0 622.0Q86 571 62.0 502.5Q38 434 38 354Q38 276 62.0 208.5Q86 141 131.0 91.0Q176 41 241.5 12.5Q307 -16 389 -16Q455 -16 510.0 4.0Q565 24 606.0 62.0Q647 100 672.0 154.0Q697 208 703 275H551Q542 203 501.5 159.0Q461 115 389 115Q336 115 299.0 135.5Q262 156 239.0 190.0Q216 224 205.5 266.5Q195 309 195 354Q195 401 205.5 445.0Q216 489 239.0 523.5Q262 558 299.0 578.5Q336 599 389 599Q418 599 444.5 589.5Q471 580 492.0 563.0Q513 546 527.0 523.5Q541 501 545 474Z"/>
<path fill="#ffffff" transform="translate(68.2497 18) scale(0.02000000 -0.02000000)" d="M249 276 342 538H344L434 276ZM264 714 -6 0H152L208 159H475L529 0H692L425 714Z"/>
<path fill="#ffffff" transform="translate(81.2497 18) scale(0.02000000 -0.02000000)" d="M226 132V582H338Q396 582 435.5 565.5Q475 549 499.0 518.0Q523 487 533.5 443.5Q544 400 544 346Q544 287 529.0 246.0Q514 205 489.0 179.5Q464 154 432.0 143.0Q400 132 366 132ZM69 714V0H377Q459 0 519.5 27.5Q580 55 620.5 103.0Q661 151 681.0 217.0Q701 283 701 361Q701 450 676.5 516.0Q652 582 608.5 626.0Q565 670 505.5 692.0Q446 714 377 714Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.2 KiB

+2
View File
@@ -1,6 +1,8 @@
<!doctype html>
<html lang="zh-CN"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<!-- Opt in before external styles load so incoming navigation can join the transition. -->
<style>@view-transition { navigation: auto; }</style>
<title>我的 CAD 项目 — VibeMake CAD</title><meta name="description" content="VibeMake CAD:在线参数化建模、草图、材质与渲染,安全管理你的设计项目。">
<meta property="og:title" content="VibeMake CAD"><meta property="og:description" content="在线参数化建模与项目管理"><meta name="theme-color" content="#07080a">
<link rel="icon" href="/favicon.ico" sizes="any"><link rel="icon" type="image/svg+xml" href="/favicon.svg"><link rel="apple-touch-icon" href="/apple-touch-icon.png">
+2
View File
@@ -1,6 +1,8 @@
<!doctype html>
<html lang="zh-CN"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<!-- Opt in before external styles load so incoming navigation can join the transition. -->
<style>@view-transition { navigation: auto; }</style>
<title>VibeMake CAD</title><meta name="description" content="VibeMake CAD 参数化设计编辑器"><meta property="og:title" content="VibeMake CAD"><meta name="theme-color" content="#07080a">
<link rel="icon" href="/favicon.ico" sizes="any"><link rel="icon" type="image/svg+xml" href="/favicon.svg"><link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/cad/manifest.webmanifest"><link rel="stylesheet" href="/css/fonts.css"><link rel="stylesheet" href="/css/style.css"><link rel="stylesheet" href="/css/cad.css">
+7
View File
@@ -0,0 +1,7 @@
// The site owns the activation protocol; engine packages own the asset allowlist.
// Imported-script changes are checked with updateViaCache: 'none'.
importScripts('/cad/sw.js');
self.addEventListener('message', (event) => {
if (event.data?.type === 'SKIP_WAITING') event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
+36 -10
View File
@@ -1,5 +1,6 @@
import { auth, API_BASE, ApiError } from '../api.js';
import { locale } from './i18n.js';
import { CAD, validStepFilename, validNativeFilename } from './config.js';
import { cadAgentRateLimiter } from './agent-rate-limit.js';
export { auth, ApiError };
@@ -34,9 +35,17 @@ function shanghaiTime(value) {
function projectRecord(value) {
const record = value?.project ?? value;
if (!record || typeof record.cadProjectCode !== 'string' || !record.cadProjectCode) throw cadError('BAD_RESPONSE');
if (!record || typeof record.cadProjectCode !== 'string' || !record.cadProjectCode
|| typeof record.hasDocument !== 'boolean' || !Number.isSafeInteger(record.version) || record.version < 0
|| (!record.hasDocument && record.version !== 0) || (record.hasDocument && record.version === 0)
|| (record.workspaceProjectCode != null && (typeof record.workspaceProjectCode !== 'string' || !record.workspaceProjectCode))) throw cadError('BAD_RESPONSE');
if (record.initialStep != null && (typeof record.initialStep !== 'object' || Array.isArray(record.initialStep)
|| typeof record.initialStep.downloadUrl !== 'string' || typeof record.initialStep.fileName !== 'string'
|| !Number.isSafeInteger(record.initialStep.sizeBytes))) throw cadError('BAD_RESPONSE');
return {
...record,
workspaceProjectCode: record.workspaceProjectCode ?? null,
initialStep: record.initialStep ?? null,
coverUrl: projectCoverUrl(record.coverUrl),
id: record.cadProjectCode,
cadProjectCode: record.cadProjectCode,
@@ -164,13 +173,20 @@ export class CadApi {
return { ...result, items: result.items.map(projectRecord), page: result.page, size: result.size };
}
async openWorkspaceProject(projectCode, signal) {
if (typeof projectCode !== 'string' || !projectCode || projectCode.length > 128) throw cadError('BAD_PROJECT');
const project = projectRecord(await this.call('/workspace/projects/' + id(projectCode) + '/cad-project', { method: 'POST', signal }));
if (project.workspaceProjectCode !== projectCode) throw cadError('BAD_RESPONSE');
return project;
}
async create(name, description = '', coverUrl) {
if (coverUrl != null && coverUrl !== '' && !projectCoverUrl(coverUrl)) throw cadError('BAD_COVER');
return projectRecord(await this.call(PROJECTS, { method: 'POST', body: { name, description, ...(coverUrl === undefined ? {} : { coverUrl }) } }));
}
async get(project) {
return projectRecord(await this.call(PROJECTS + '/' + id(project)));
async get(project, signal) {
return projectRecord(await this.call(PROJECTS + '/' + id(project), { signal }));
}
async rename(project, name) {
@@ -208,10 +224,10 @@ export class CadApi {
return this.call(PROJECTS + '/' + id(project), { method: 'DELETE' });
}
async document(project) {
const value = await this.call(PROJECTS + '/' + id(project) + '/document');
if (!value || !Number.isSafeInteger(value.version) || !Number.isSafeInteger(value.sizeBytes)
|| typeof value.downloadUrl !== 'string' || typeof value.fileName !== 'string') throw cadError('BAD_RESPONSE');
async document(project, signal) {
const value = await this.call(PROJECTS + '/' + id(project) + '/document', { signal });
if (!value || !Number.isSafeInteger(value.version) || value.version <= 0 || !Number.isSafeInteger(value.sizeBytes)
|| typeof value.downloadUrl !== 'string' || !validNativeFilename(value.fileName)) throw cadError('BAD_RESPONSE');
return { ...value, savedAt: shanghaiTime(value.savedAt) };
}
@@ -257,7 +273,8 @@ export async function downloadSource(file, maxBytes, progress = () => {}, signal
if (!response.ok) throw cadError(response.status === 403 ? 'DOWNLOAD_FORBIDDEN' : 'DOWNLOAD_FAILED');
if (!response.body) {
const bytes = new Uint8Array(await response.arrayBuffer());
if (bytes.byteLength !== size || bytes.byteLength > maxBytes) throw cadError('BAD_DESIGN');
if (bytes.byteLength > maxBytes) throw cadError('SOURCE_TOO_LARGE');
if (bytes.byteLength !== size) throw cadError('BAD_DESIGN');
progress(bytes.byteLength, size);
return bytes;
}
@@ -269,7 +286,8 @@ export async function downloadSource(file, maxBytes, progress = () => {}, signal
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > size || total > maxBytes) throw cadError('SOURCE_TOO_LARGE');
if (total > maxBytes) throw cadError('SOURCE_TOO_LARGE');
if (total > size) throw cadError('BAD_DESIGN');
chunks.push(value);
progress(total, size);
}
@@ -289,7 +307,7 @@ export async function downloadSource(file, maxBytes, progress = () => {}, signal
export async function uploadSource(signature, bytes, fileName, signal) {
const authorization = signatureRecord(signature);
if (typeof fileName !== 'string' || !/^[^\\/:\u0000-\u001f\u007f]+\.sc$/i.test(fileName)) throw cadError('BAD_FILE_NAME');
if (!validNativeFilename(fileName)) throw cadError('BAD_FILE_NAME');
const body = new FormData();
for (const [key, value] of Object.entries(authorization.formFields)) body.append(key, value);
body.append('file', new Blob([bytes], { type: 'application/octet-stream' }), fileName);
@@ -303,3 +321,11 @@ export async function uploadSource(signature, bytes, fileName, signal) {
});
if (!response.ok) throw cadError('UPLOAD_FAILED');
}
export function initialStepSource(value) {
if (!value || !validStepFilename(value.fileName)) throw cadError('BAD_STEP_FILE');
if (!Number.isSafeInteger(value.sizeBytes) || value.sizeBytes <= 0 || value.sizeBytes > CAD.maxStepSourceBytes) throw cadError('STEP_TOO_LARGE');
if (typeof value.downloadUrl !== 'string' || !value.downloadUrl.trim()) throw cadError('BAD_STEP_FILE');
storageUrl(value.downloadUrl);
return value;
}
+129 -56
View File
@@ -5,9 +5,10 @@ import { CAD, desktopAllowed, projectUrl, filename } from './config.js';
import { locale, setLocale, t, errorText, LOCALE_KEY } from './i18n.js';
import { CadApi, userId, cadError, downloadSource, sha256 } from './api.js';
import { DraftStore } from './drafts.js';
import { openProjectSource } from './opening.js';
import { SaveCoordinator } from './save.js';
import { choose, nameDialog } from './dialog.js';
import { loadEngine, downloadBytes } from './engine.js';
import { loadEngine, prepareEngineRefresh, downloadBytes } from './engine.js';
const editor = document.body.dataset.cadPage === 'editor';
renderShell('cad', { footer: false, assistant: false, search: !editor });
const main = document.querySelector('#cad-main'), header = document.querySelector('body > header.nav'), viewport = document.querySelector('#cad-viewport');
@@ -16,6 +17,7 @@ let api, bridge, project, binding, saver, boundUser = null, state = {}, epoch =
let request, booting = false, restartBoot = false, modalCount = 0, authLocked = true, viewportReady = false, saveState = 'never', draftTask = null, unsubscribe;
let leaving = false, signingOut = false, authToken = null, lastDraftRevision = null, draftWarning = false, recovering = false, recoveryPending = false, copying = false;
let discardedDraft = null;
let refreshingEngine = false, openingProject = false, importWarnings = [];
let assistantAvailable = false;
let assistantRequest;
const projectId = new URLSearchParams(location.search).get('project');
@@ -30,7 +32,15 @@ function assertContext(value, document = false) {
value.client?.assertIdentity();
if (value.epoch !== epoch || value.owner !== boundUser || (document && value.binding !== binding)) throw cadError('STALE_BINDING');
}
function notice(text) { const el = document.querySelector('#cad-notice'); el.textContent = text; el.hidden = !text; }
function notice(text) {
const el = document.querySelector('#cad-notice'); el.textContent = text; el.hidden = !text && !importWarnings.length;
if (importWarnings.length) {
const details = document.createElement('details'), summary = document.createElement('summary'), list = document.createElement('ul');
details.dataset.importWarnings = ''; summary.textContent = t('stepWarnings');
for (const warning of importWarnings) { const item = document.createElement('li'); item.textContent = String(warning); list.append(item); }
details.append(summary, list); el.append(details);
}
}
function storageWarning() { draftWarning = true; notice(t('storage')); }
function initEditorHeader() {
if (!editor || !header) return;
@@ -73,7 +83,7 @@ function initEditorHeader() {
saveButton.innerHTML = icon('save', 18);
saveButton.setAttribute('aria-label', t('save'));
saveButton.title = t('save');
saveButton.disabled = !binding || authLocked;
saveButton.disabled = !binding || authLocked || openingProject || recovering || recoveryPending;
if (authSlot) {
actions.insertBefore(saveStatus, authSlot);
} else {
@@ -108,11 +118,11 @@ function drawHeader() {
const saveStatus = header.querySelector('.cad-save-state');
const saveButton = header.querySelector('[data-save]');
if (saveStatus) { saveStatus.dataset.state = saveState; saveStatus.textContent = t(saveState); }
if (saveButton) { saveButton.disabled = !binding || authLocked; saveButton.title = t('save'); saveButton.setAttribute('aria-label', t('save')); }
if (saveButton) { saveButton.disabled = !binding || authLocked || openingProject || recovering || recoveryPending; saveButton.title = t('save'); saveButton.setAttribute('aria-label', t('save')); }
header.querySelector('[data-engine-menu="file"]').textContent = t('file');
const undo = header.querySelector('[data-history="undo"]'), redo = header.querySelector('[data-history="redo"]');
if (undo) { undo.disabled = authLocked || !state.canUndo; undo.title = t('undo'); undo.setAttribute('aria-label', t('undo')); }
if (redo) { redo.disabled = authLocked || !state.canRedo; redo.title = t('redo'); redo.setAttribute('aria-label', t('redo')); }
if (undo) { undo.disabled = authLocked || openingProject || recovering || recoveryPending || !state.canUndo; undo.title = t('undo'); undo.setAttribute('aria-label', t('undo')); }
if (redo) { redo.disabled = authLocked || openingProject || recovering || recoveryPending || !state.canRedo; redo.title = t('redo'); redo.setAttribute('aria-label', t('redo')); }
for (const key of ['assistant', 'preferences', 'help']) {
const button = header.querySelector('[data-engine-menu="' + key + '"]');
if (button) { button.title = t(key); button.setAttribute('aria-label', t(key)); }
@@ -141,7 +151,7 @@ function status(key, error) {
if (error && error.code !== 'STALE_IDENTITY' && error.code !== 'STALE_BINDING') showError(error);
}
function showError(error) {
if (['STALE_IDENTITY', 'STALE_BINDING', 'AbortError'].includes(error?.code || error?.name)) return;
if (['STALE_IDENTITY', 'STALE_BINDING', 'OPEN_CANCELLED', 'AbortError'].includes(error?.code || error?.name)) return;
notice(errorText(error));
if (['HEAD_CONFLICT', 'CAD_VERSION_CONFLICT'].includes(error.code)) conflictDialog();
if ([403, 404, 410].includes(error.status)) { status('unavailable'); authLocked = true; updateLock(); draft(); }
@@ -151,7 +161,15 @@ function message(key, hint, action, actionLabel = 'retry') {
main.innerHTML = `<section class="cad-state">${icon('cube', 48)}<h1>${esc(t(key))}</h1>${hint ? `<p>${esc(t(hint))}</p>` : ''}${action ? `<button class="btn btn-primary" data-action>${esc(t(actionLabel))}</button>` : ''}</section>`;
main.querySelector('[data-action]')?.addEventListener('click', action);
}
function stage(key, progress) { message(key); const p = main.querySelector('h1'); if (progress) p.textContent += ` ${progress}`; }
function stage(key, progress) {
message(key, null, openingProject ? cancelOpening : null, 'cancel');
const p = main.querySelector('h1'); if (progress) p.textContent += ` ${progress}`;
}
async function cancelOpening() {
++epoch; request?.abort();
await bridge?.cancelOpenProject?.().catch(() => {});
openingProject = false; updateLock(); message('openCancelled', null, boot);
}
async function signIn() { await openLogin({ locale: locale() }); if (!authLocked && !binding && editor) boot(); }
async function signOut() {
if (!(await guard())) return;
@@ -161,7 +179,7 @@ async function signOut() {
if (editor) location.assign('/cad/'); else { authLocked = true; drawHeader(); message('loginRequired', 'loginHint', signIn, 'signIn'); }
}
function updateLock() {
const locked = authLocked || recovering || recoveryPending || modalCount > 0 || !desktopAllowed() || !viewportReady;
const locked = authLocked || openingProject || recovering || recoveryPending || refreshingEngine || modalCount > 0 || !desktopAllowed() || !viewportReady;
if (viewport) { viewport.inert = locked; viewport.style.pointerEvents = locked ? 'none' : ''; }
bridge?.setInteractionLocked(locked).catch(() => {});
const blocker = document.querySelector('#cad-blocker');
@@ -260,7 +278,7 @@ async function boot() {
if (error.status === 401) { authLocked = true; message('loginRequired', 'loginHint', signIn, 'signIn'); setTimeout(signIn, 0); return; }
if (binding) showError(error);
else if (error.code === 'FONT_UNAVAILABLE') showFontError(error); else { message('error', null, boot); showError(error); }
} finally { booting = false; drawHeader(); updateLock(); if (restartBoot) { restartBoot = false; setTimeout(boot, 0); } }
} finally { openingProject = false; booting = false; drawHeader(); updateLock(); if (restartBoot) { restartBoot = false; setTimeout(boot, 0); } }
}
async function loadList() {
if (!api || authLocked) return;
@@ -316,36 +334,50 @@ async function newProject() {
}
async function openEditor(current) {
if (typeof projectId !== 'string' || !projectId || projectId.length > 128) throw cadError('NOT_FOUND');
openingProject = true; updateLock(); importWarnings = []; notice('');
request?.abort(); request = new AbortController(); const control = request, client = api;
const check = () => { client.assertIdentity(); if (current !== epoch || control.signal.aborted) throw cadError('STALE_BINDING'); };
stage('metadata');
project = await api.get(projectId);
let source = null;
try { source = await api.document(projectId); }
catch (error) { if (error.code !== 'CAD_DOCUMENT_NOT_FOUND') throw error; }
if (current !== epoch) return;
project.version = source?.version ?? project.version ?? 0;
project.headVersion = project.version;
project = await client.get(projectId, control.signal); check();
stage('engine'); viewport.hidden = false; viewport.style.visibility = 'hidden';
try { bridge = await loadEngine(); } catch (error) { if (error.code === 'FONT_UNAVAILABLE') { bridge = window.vibemakeCad; showFontError(error); } throw error; }
if (current !== epoch) return;
const engineReady = await bridge.ready();
check();
const engineReady = await bridge.ready(); check();
assistantAvailable = engineReady.capabilities?.assistant === true && typeof bridge.setAgentContext === 'function';
if (!assistantAvailable) notice(t('assistantUpdate'));
let bytes = null;
if (source) {
stage('download');
bytes = await downloadSource(source, CAD.maxSourceBytes, (received, size) => stage('download', Math.round(received / size * 100) + '%'));
const progress = bridge.subscribe((next) => {
if (current !== epoch || !next.opening) return;
const key = next.opening.phase === 'preparing' ? 'stepPreparing' : 'stepImport';
const { done, total } = next.opening;
stage(key, total > 0 ? `${Math.min(done, total)} / ${total}` : null);
});
let result;
try {
result = await openProjectSource({ api: client, bridge, project, signal: control.signal, assertCurrent: check,
onStage: stage, recover: () => restoreLocal({ preflight: true }) });
} finally { progress(); }
check();
if (result.blocked && !binding) return;
if (result.opened) {
saver?.dispose(); binding = result.opened.binding; project.version = result.version; project.headVersion = result.version;
saver = makeSaver();
}
if (current !== epoch) return;
stage('rebuild');
const result = await bridge.openProject({ projectId, bytes, saved: !!source });
if (current !== epoch) { await bridge.releaseProject(); return; }
binding = result.binding; recovering = true; viewportReady = true; viewport.style.visibility = ''; main.hidden = true;
recovering = true; viewportReady = true; viewport.style.visibility = ''; main.hidden = true;
unsubscribe?.(); unsubscribe = bridge.subscribe(onEngineState);
saver = makeSaver(); state = await bridge.getState(); saveState = source ? 'saved' : 'never'; drawHeader(); updateLock();
await restoreLocal();
await saver.restoreCover();
await bindAssistant(); state = await bridge.getState(); drawHeader();
state = await bridge.getState(); check();
saveState = recoveryPending ? 'pending' : saver?.conflicted ? 'conflict' : project.version ? (state.dirty ? 'dirty' : 'saved') : 'never';
if (result.kind !== 'recovery') importWarnings = result.warnings || [];
if (!result.blocked) notice(draftWarning ? t('storage') : '');
drawHeader(); updateLock();
if (result.kind === 'native') await restoreLocal();
else recovering = false;
if (importWarnings.length && !recoveryPending) notice('');
check();
if (result.kind === 'step') await draft();
await saver.restoreCover(); check();
await bindAssistant(); check(); state = await bridge.getState(); drawHeader();
}
function makeSaver() { return new SaveCoordinator({ api, bridge, store, user: boundUser, project, binding, session, onState: status, onStorageError: storageWarning }); }
function onEngineState(next) {
if (next.binding !== binding) return;
@@ -358,7 +390,7 @@ function onEngineState(next) {
if (next.locale && next.locale !== locale() && !next.fontFailed && !recovering) { setLocale(next.locale); drawHeader(); }
}
async function save() {
if (authLocked || !saver) throw cadError('UNAUTHORIZED');
if (authLocked || openingProject || recovering || !saver) throw cadError('UNAUTHORIZED');
if (copying) throw cadError('SAVE_IN_PROGRESS');
if (recoveryPending) throw cadError('PENDING_SAVE');
const ctx = context(); let result;
@@ -376,28 +408,32 @@ function draft() {
if (leaving || recovering || !bridge || !binding || !boundUser || draftTask || !state.dirty || !state.snapshotAvailable || state.revision === lastDraftRevision) return draftTask;
if (discardedDraft?.binding === binding && (discardedDraft.pending || discardedDraft.revision === state.revision)) return;
const engine = bridge, oldBinding = binding, owner = boundUser, target = project.id, version = project.version, revision = state.revision;
const origin = project.initialStep && version === 0 ? 'step-import' : undefined, warnings = [...importWarnings];
draftTask = (async () => {
let snapshot;
try {
snapshot = await engine.createSnapshot();
if (snapshot.binding !== oldBinding) return;
await store.put(owner, target, session, 'draft', { snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: version, revision: snapshot.revision, binding: oldBinding });
await store.put(owner, target, session, 'draft', { snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: version, revision: snapshot.revision, binding: oldBinding, origin, importWarnings: warnings });
if (oldBinding === binding) lastDraftRevision = revision;
} catch (error) { if (error.code !== 'SNAPSHOT_BUSY') storageWarning(); }
finally { if (snapshot) await engine.releaseSnapshot(snapshot.snapshotId); }
})().finally(() => { draftTask = null; });
return draftTask;
}
async function restoreLocal() {
if (recovering && recoveryPending) return;
async function restoreLocal({ preflight = false } = {}) {
if (recovering && recoveryPending) return { blocked: true };
const originalBinding = binding; let blocked = false;
recovering = true; recoveryPending = false; const ctx = context(); updateLock();
const decide = (...args) => choose(...args, { signal: request?.signal });
const pending = () => {
recoveryPending = true; status('pending'); notice(t('pending'));
blocked = true; recoveryPending = true; status('pending'); notice(t('pending'));
const button = document.createElement('button'); button.className = 'btn'; button.textContent = t('retry');
button.onclick = () => restoreLocal().catch(showError);
button.onclick = () => (binding ? restoreLocal() : boot()).catch(showError);
document.querySelector('#cad-notice').append(button);
if (!binding) message('pending', null, boot);
};
let resolvingJournal = true, showConflict = false;
let resolvingJournal = true, readingDrafts = false, showConflict = false;
try {
const journals = await store.list(boundUser, project.id, 'operation');
assertContext(ctx, true);
@@ -414,10 +450,11 @@ async function restoreLocal() {
await store.remove(journal.key, journal.snapshotId);
continue;
}
if (await choose(t('pending'), t('draftHint'), [['restore', t('restore'), true], ['cancel', t('stay')]]) === 'restore') {
assertContext(ctx, true);
const decision = await decide(t('pending'), t('draftHint'), [['restore', t('restore'), true], ['cancel', t('stay')]]);
assertContext(ctx, true);
if (decision === 'restore') {
const opened = await bridge.openProject({ projectId: project.id, bytes: journal.bytes, saved: false });
saver.dispose(); binding = opened.binding; ctx.binding = binding;
saver?.dispose(); binding = opened.binding; ctx.binding = binding;
project.version = journal.request.expectedVersion; project.headVersion = project.version;
saver = makeSaver();
main.hidden = true; updateLock();
@@ -431,37 +468,55 @@ async function restoreLocal() {
const latest = await api.get(project.id);
project.version = latest.version; project.headVersion = latest.version;
state = await bridge.getState(); showConflict = true;
return;
return { restored: true };
}
if (saver.operation) { pending(); return; }
if (saver.operation) { pending(); return { restored: true, blocked: true }; }
}
} else {
pending(); return;
pending(); return { blocked: true };
}
}
resolvingJournal = false;
readingDrafts = true;
const drafts = await store.list(boundUser, project.id, 'draft');
readingDrafts = false;
assertContext(ctx, true);
if (drafts.length) {
const value = drafts[0];
const decision = value.origin === 'native-import' && project.version === 0 ? 'restore'
: await choose(t('draft'), t('draftHint'), [['restore', t('restore'), true], ['discard', t('discard')], ['cancel', t('stay')]]);
: await decide(t('draft'), t('draftHint'), [['restore', t('restore'), true], ['discard', t('discard')], ['cancel', t('stay')]]);
assertContext(ctx, true);
if (decision === 'restore') {
const opened = await bridge.openProject({ projectId: project.id, bytes: value.bytes, saved: false });
saver.dispose(); binding = opened.binding; ctx.binding = binding; saver = makeSaver();
saver?.dispose(); binding = opened.binding; ctx.binding = binding; saver = makeSaver();
if (value.baseVersion !== project.version) { saver.conflicted = true; status('conflict'); } else status('dirty');
importWarnings = Array.isArray(value.importWarnings) ? value.importWarnings : [];
lastDraftRevision = null; state = await bridge.getState();
assertContext(ctx, true);
try { await store.rebindDraft(value.key, value.snapshotId, { binding, revision: state.revision }); }
catch { storageWarning(); }
} else if (decision === 'discard') for (const d of drafts) await store.remove(d.key);
else if (preflight) { blocked = true; recoveryPending = true; message('draft', null, boot, 'restore'); }
}
state = await bridge.getState();
} catch (error) {
if (resolvingJournal) { showError(error); if (!['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) pending(); }
else storageWarning();
else {
storageWarning();
if (preflight) {
// A known pending save is always blocking. Only an unreadable draft list,
// after pending saves were resolved, may be explicitly skipped.
const proceed = readingDrafts && await decide(t('storage'), t('draftReadFailed'),
[['retry', t('retry'), true], ['continue', t('continueWithoutDrafts')]]) === 'continue';
assertContext(ctx, true);
if (!proceed) { blocked = true; recoveryPending = true; message('draft', 'storage', boot); }
}
}
} finally {
recovering = false; updateLock();
if (showConflict) setTimeout(() => conflictDialog(), 0);
}
return { restored: !!binding && binding !== originalBinding, blocked };
}
async function renameCurrent() {
if (!project) return;
@@ -500,8 +555,9 @@ async function guard() {
}
async function navigate(url) { if (await guard()) { leaving = true; location.assign(url); } }
async function downloadCopy() {
const snapshot = await bridge.createSnapshot();
try { downloadBytes(snapshot.bytes, filename(project.name)); } finally { await bridge.releaseSnapshot(snapshot.snapshotId); }
const ctx = context(), engine = bridge, name = filename(project.name);
const snapshot = await engine.createSnapshot({ forLocalDownload: true });
try { assertContext(ctx, true); downloadBytes(snapshot.bytes, name); } finally { await engine.releaseSnapshot(snapshot.snapshotId); }
}
async function saveAs() {
if (copying || saver?.active) { notice(t('verifying')); return; }
@@ -558,6 +614,7 @@ function showFontError(error) {
button.onclick = async () => { setLocale('en', false); if (bridge) await bridge.setLocale('en'); await boot(); }; main.querySelector('section').append(button);
}
async function releaseAccount() {
request?.abort(); await bridge?.cancelOpenProject?.().catch(() => {});
await clearAssistant();
await draft(); saver?.dispose(); unsubscribe?.(); binding = null; viewportReady = false;
await bridge?.releaseProject(); project = null; state = {}; recoveryPending = false; updateLock();
@@ -565,11 +622,11 @@ async function releaseAccount() {
async function authChanged() {
if (signingOut) return;
if (booting) {
if (api && (api.token !== auth.token || api.user !== userId())) { ++epoch; authLocked = true; restartBoot = true; updateLock(); await clearAssistant(); }
if (api && (api.token !== auth.token || api.user !== userId())) { ++epoch; request?.abort(); authLocked = true; restartBoot = true; updateLock(); await bridge?.cancelOpenProject?.().catch(() => {}); if (!binding) await bridge?.releaseProject(); await clearAssistant(); }
return;
}
if (auth.token === authToken && userId() === boundUser) return;
++epoch; request?.abort();
++epoch; request?.abort(); await bridge?.cancelOpenProject?.().catch(() => {});
if (!auth.token) {
authToken = null; authLocked = true; updateLock(); status('expired');
await clearAssistant();
@@ -598,15 +655,31 @@ window.addEventListener('beforeunload', (event) => { if (!leaving && binding &&
window.addEventListener('offline', () => { if (editor && binding) status('offline'); });
window.addEventListener('online', () => { if (binding && saveState === 'offline') status(state.dirty ? 'dirty' : project.version ? 'saved' : 'never'); });
window.addEventListener('vm:cad:update', () => {
const banner = document.querySelector('#cad-notice'); banner.textContent = '';
if (refreshingEngine) return;
notice('');
const banner = document.querySelector('#cad-notice');
const label = document.createElement('span'); label.textContent = t('update');
const refresh = document.createElement('button'); refresh.className = 'btn'; refresh.textContent = t('refresh');
refresh.addEventListener('click', async () => { if (await guard()) { leaving = true; location.reload(); } });
banner.append(label, refresh); banner.hidden = false;
refresh.addEventListener('click', async () => {
if (refresh.disabled) return;
refresh.disabled = true;
try {
if (!(await guard())) return;
refreshingEngine = true; updateLock(); refresh.textContent = t('preparing');
await prepareEngineRefresh();
leaving = true; location.reload();
} catch {
label.textContent = t('updateFailed'); banner.replaceChildren(label, refresh); banner.hidden = false;
}
finally {
if (!leaving) { refreshingEngine = false; updateLock(); refresh.disabled = false; refresh.textContent = t('refresh'); }
}
});
banner.prepend(label, refresh); banner.hidden = false;
});
document.addEventListener('visibilitychange', () => { if (document.hidden) draft(); });
setInterval(draft, 30000);
setInterval(() => { if (authToken && !auth.token) authChanged(); }, 5000);
matchMedia('(max-width: 820px)').addEventListener('change', () => { updateLock(); if (!viewportReady && !desktopAllowed()) { ++epoch; message('desktop', 'desktopHint', () => location.assign('/'), 'home'); } });
matchMedia('(max-width: 820px)').addEventListener('change', () => { updateLock(); if (!viewportReady && !desktopAllowed()) { ++epoch; request?.abort(); bridge?.cancelOpenProject?.().catch(() => {}); message('desktop', 'desktopHint', () => location.assign('/'), 'home'); } });
initEditorHeader();
setLocale(locale(), false); drawHeader(); boot();
+12 -1
View File
@@ -1,4 +1,4 @@
export const CAD = Object.freeze({ product: 'VibeMake CAD', list: '/cad/', editor: '/cad/editor/', bridgeVersion: 1, maxSourceBytes: 256 * 1024 * 1024,
export const CAD = Object.freeze({ product: 'VibeMake CAD', list: '/cad/', editor: '/cad/editor/', bridgeVersion: 1, maxSourceBytes: 256 * 1024 * 1024, maxStepSourceBytes: 500 * 1024 * 1024,
links: Object.freeze({ home: '/', help: null, feedback: null, releases: null }), engineManifest: '/cad/engine.json' });
export const projectUrl = (id) => `${CAD.editor}?project=${encodeURIComponent(id)}`;
export function desktopAllowed() {
@@ -8,3 +8,14 @@ export function desktopAllowed() {
}
export function validName(value) { const s = value.trim(); return [...s].length >= 1 && [...s].length <= 100 && !/[\u0000-\u001f\u007f]/.test(s); }
export function filename(name) { return (name.replace(/[\\/:*?"<>|\u0000-\u001f\u007f]/g, '_').slice(0, 100).replace(/^\.+/, '') || 'design') + '.sc'; }
export function validNativeFilename(value) {
return typeof value === 'string' && value.length > 3 && [...value].length <= 255 && /\.sc$/i.test(value)
&& !/[\\/:\u0000-\u001f\u007f-\u009f]/.test(value);
}
export function validStepFilename(value) {
return typeof value === 'string' && [...value].length <= 1024 && /\.(step|stp)$/i.test(value)
&& !/[\\/\u0000-\u001f\u007f-\u009f]/.test(value);
}
export const workspaceCadEditable = (project, sha = null) => project?.repoStatus === 'READY'
&& typeof project.stepMainUrl === 'string' && !!project.stepMainUrl.trim() && !sha;
+5 -2
View File
@@ -2,11 +2,14 @@ import { openModal } from '../auth-dialog.js';
import { esc } from '../layout.js';
import { t } from './i18n.js';
import { validName } from './config.js';
export function choose(title, description, choices) {
export function choose(title, description, choices, { signal } = {}) {
if (signal?.aborted) return Promise.resolve(null);
return new Promise((resolve) => {
const m = openModal({ title, closeLabel: t('cancel'), body: `<p>${esc(description)}</p><div class="cad-dialog-actions">${choices.map(([id, label, primary]) => `<button class="btn${primary ? ' btn-primary' : ''}" data-choice="${esc(id)}">${esc(label)}</button>`).join('')}</div>` });
let answer = null;
m.onClose = () => resolve(answer);
const abort = () => m.close();
m.onClose = () => { signal?.removeEventListener('abort', abort); resolve(answer); };
signal?.addEventListener('abort', abort, { once: true });
m.el.querySelectorAll('[data-choice]').forEach((button) => button.addEventListener('click', () => { answer = button.dataset.choice; m.close(); }));
queueMicrotask(() => m.el.querySelector('button[data-choice]')?.focus());
});
+23 -3
View File
@@ -1,6 +1,15 @@
// Binary drafts and save journals never contain tokens or signed URLs.
function coveredRevision(revision, saved) {
if (typeof revision !== 'string' || typeof saved !== 'string' || !revision || !saved) return false;
if (revision === saved) return true;
const before = typeof revision === 'string' && /^(\d{1,20}):/.exec(revision);
const after = typeof saved === 'string' && /^(\d{1,20}):/.exec(saved);
// Revision counters only order changes within one binding. Equal counters with
// different visibility state may represent a later change and must survive.
return !!before && !!after && BigInt(before[1]) < BigInt(after[1]);
}
export class DraftStore {
constructor(indexed = globalThis.indexedDB) { this.indexed = indexed; }
constructor(indexed = globalThis.indexedDB) { this.indexed = indexed; this.acknowledged = new Map(); }
async database() {
if (!this.indexed) throw new Error('IndexedDB unavailable');
this.db ??= new Promise((resolve, reject) => {
@@ -20,7 +29,11 @@ export class DraftStore {
}
key(user, project, session, kind) { return JSON.stringify([user, project, session, kind]); }
put(user, project, session, kind, value) {
return this.transaction('readwrite', (store) => store.put({ key: this.key(user, project, session, kind), user, project, session, kind, updatedAt: Date.now(), ...value }));
return this.transaction('readwrite', (store) => {
const saved = value.binding && this.acknowledged.get(JSON.stringify([user, project, value.binding]));
if (kind === 'draft' && saved && coveredRevision(value.revision, saved)) return;
store.put({ key: this.key(user, project, session, kind), user, project, session, kind, updatedAt: Date.now(), ...value });
});
}
async list(user, project, kind) {
return this.transaction('readonly', (store, done) => { const req = store.getAll(); req.onsuccess = () => done(req.result.filter((r) => r.user === user && r.project === project && (!kind || r.kind === kind)).sort((a, b) => b.updatedAt - a.updatedAt)); });
@@ -28,9 +41,16 @@ export class DraftStore {
remove(key, snapshotId) {
return this.transaction('readwrite', (store) => { const request = store.get(key); request.onsuccess = () => { if (request.result && (!snapshotId || request.result.snapshotId === snapshotId)) store.delete(key); }; });
}
rebindDraft(key, snapshotId, baseline) {
return this.transaction('readwrite', (store) => { const request = store.get(key); request.onsuccess = () => {
const record = request.result;
if (record?.kind === 'draft' && record.snapshotId === snapshotId) store.put({ ...record, ...baseline });
}; });
}
clearAcknowledged(user, project, snapshotId, baseline) {
if (baseline?.binding && baseline.revision) this.acknowledged.set(JSON.stringify([user, project, baseline.binding]), baseline.revision);
return this.transaction('readwrite', (store) => { const request = store.openCursor(); request.onsuccess = () => { const cursor = request.result; if (!cursor) return;
const r = cursor.value;
if (r.user === user && r.project === project && (r.snapshotId === snapshotId || (r.kind === 'draft' && baseline?.binding && r.binding === baseline.binding && r.revision === baseline.revision))) cursor.delete(); cursor.continue(); }; });
if (r.user === user && r.project === project && (r.snapshotId === snapshotId || (r.kind === 'draft' && baseline?.binding && r.binding === baseline.binding && coveredRevision(r.revision, baseline.revision)))) cursor.delete(); cursor.continue(); }; });
}
}
+52 -7
View File
@@ -1,7 +1,7 @@
import { CAD } from './config.js';
import { cadError } from './api.js';
import { locale } from './i18n.js';
let engine;
let engine, workerRegistration;
export function loadEngine() {
return engine ??= start().catch((error) => { engine = null; throw error; });
}
@@ -20,17 +20,62 @@ async function start() {
while (!window.vibemakeCad) { if (performance.now() > deadline) throw cadError('ENGINE_TIMEOUT'); await new Promise((r) => setTimeout(r, 30)); }
await window.vibemakeCad.ready();
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/cad/sw.js', { scope: '/cad/', updateViaCache: 'none' }).then((registration) => {
const notify = () => window.dispatchEvent(new CustomEvent('vm:cad:update'));
workerRegistration = navigator.serviceWorker.register('/cad/worker.js', { scope: '/cad/', updateViaCache: 'none' }).then((registration) => {
let notifiedBuild;
const notify = async () => {
try {
const response = await fetch(CAD.engineManifest, { cache: 'no-store' });
if (!response.ok) return;
const latest = await response.json();
// A waiting cache worker does not mean the running engine is outdated.
if (typeof latest.buildId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(latest.buildId) || latest.buildId === manifest.buildId || latest.buildId === notifiedBuild) return;
notifiedBuild = latest.buildId;
window.dispatchEvent(new CustomEvent('vm:cad:update'));
} catch { /* An unavailable update check must not interrupt editing. */ }
};
if (registration.waiting) notify();
registration.addEventListener('updatefound', () => {
const worker = registration.installing;
const watch = (worker) => {
worker?.addEventListener('statechange', () => { if (worker.state === 'installed' && navigator.serviceWorker.controller) notify(); });
});
}).catch(() => { /* Editor remains usable when static caching is unavailable. */ });
};
watch(registration.installing);
registration.addEventListener('updatefound', () => watch(registration.installing));
return registration;
}).catch(() => null); // Editor remains usable when static caching is unavailable.
}
return window.vibemakeCad;
}
function waitForWorker(worker, states, timeout) {
return new Promise((resolve) => {
const finish = (result) => {
clearTimeout(timer);
worker.removeEventListener('statechange', changed);
resolve(result);
};
const changed = () => {
if (states.includes(worker.state)) finish(true);
else if (worker.state === 'redundant') finish(false);
};
const timer = setTimeout(() => finish(false), timeout);
worker.addEventListener('statechange', changed);
changed();
});
}
// Called only after the editor has completed its unsaved-changes guard.
export async function prepareEngineRefresh() {
if (!('serviceWorker' in navigator)) return;
const registration = await (workerRegistration || navigator.serviceWorker.getRegistration('/cad/'));
if (!registration || registration.scope !== new URL('/cad/', location.href).href) return;
await registration.update();
if (registration.installing && !await waitForWorker(registration.installing, ['installed', 'activated'], 10000)) throw cadError('ENGINE_UPDATE_FAILED');
const worker = registration.waiting;
if (!worker) return;
const activated = waitForWorker(worker, ['activated'], 2000);
worker.postMessage({ type: 'SKIP_WAITING' });
if (!await activated) throw cadError('ENGINE_UPDATE_FAILED');
}
export function downloadBytes(bytes, name) {
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
+11 -1
View File
@@ -1,6 +1,12 @@
// Product strings live here, separate from engine message IDs.
const messages = {
assistant: ['助手', 'Assistant'], assistantUpdate: ['当前编辑器引擎未包含助手,请更新引擎后刷新。', 'This editor engine does not include the assistant. Update the engine, then refresh.'],
stepDownload: ['下载初始 STEP…', 'Downloading initial STEP…'], stepImport: ['导入 STEP…', 'Importing STEP…'],
stepPreparing: ['准备模型视图…', 'Preparing model view…'], openCancelled: ['已取消打开项目', 'Project opening cancelled'],
stepWarnings: ['STEP 导入存在警告,请检查模型后再保存(展开详情)', 'STEP import has warnings. Check the model before saving (show details)'],
stepInvalid: ['STEP 文件无法导入或没有可用模型,请重试或检查源文件。', 'STEP could not be imported or contains no usable model. Retry or check the source file.'],
stepTooLarge: ['初始 STEP 超过 500 MiB 上限。', 'Initial STEP exceeds the 500 MiB limit.'],
stepEngineUpdate: ['当前引擎不支持云端 STEP 导入,请检查并刷新编辑器。', 'This engine does not support cloud STEP import. Check for updates and refresh the editor.'],
projects: ['我的 CAD 项目', 'My CAD projects'], new: ['新建项目', 'New project'], search: ['搜索项目名称', 'Search project names'],
untitled: ['未命名项目', 'Untitled project'], open: ['打开', 'Open'], rename: ['重命名', 'Rename'], delete: ['删除', 'Delete'],
deleteAsk: ['删除这个项目?此操作不能从列表中撤销。', 'Delete this project? This cannot be undone from the list.'],
@@ -22,7 +28,7 @@ const messages = {
unavailable: ['项目已删除或无权限', 'Project deleted or access denied'], error: ['暂时无法完成,请重试。', 'Unable to complete. Please retry.'],
incompatible: ['工程格式或后端能力不兼容,请联系管理员。', 'Design format or backend capability is incompatible. Contact your administrator.'],
quota: ['项目容量已达上限,请联系管理员。', 'Project storage quota reached. Contact your administrator.'],
tooLarge: ['工程超过允许的大小。请下载本地副本。', 'Design exceeds the size limit. Download a local copy.'],
tooLarge: ['工程超过 256 MiB 云端上限,当前设计已保留。请通过文件菜单下载工程副本。', 'Design exceeds the 256 MiB cloud limit. Your design is preserved. Download a design copy from the File menu.'],
invalidFile: ['工程损坏、包含外部依赖或格式不受支持,原工程已保留。', 'Invalid or unsupported design or external dependencies. Your current design is intact.'],
desktop: ['请在电脑端使用 VibeMake CAD', 'Use VibeMake CAD on a desktop'], desktopHint: ['CAD 需要鼠标、键盘及宽于 820px 的窗口。', 'CAD needs a mouse, keyboard and a window wider than 820px.'],
expand: ['请扩大窗口以继续编辑', 'Widen the window to continue editing'], protected: ['你的编辑会话已保留。', 'Your editing session is preserved.'],
@@ -32,6 +38,8 @@ const messages = {
conflictHint: ['另一窗口已更新云端版本。保留当前设计,另存新项目或下载副本;重新加载会丢弃当前修改。', 'Another window updated the cloud version. Save a new project or download your current design. Reloading discards your changes.'],
draft: ['发现本机草稿', 'Local draft found'], draftHint: ['恢复此设备上的未保存设计?云端更新过时,恢复后会保留冲突保护。', 'Restore this device’s unsaved design? A newer cloud version will keep conflict protection.'],
restore: ['恢复草稿', 'Restore draft'], discard: ['放弃草稿', 'Discard draft'], storage: ['本机草稿不可用,请及时保存或下载副本。', 'Local drafts unavailable. Save or download a copy regularly.'],
draftReadFailed: ['未完成保存事务已检查,但无法读取本机草稿。重试,或继续导入初始模型;继续不会删除已有草稿。', 'Pending saves were checked, but local drafts could not be read. Retry, or continue loading the initial model. Existing drafts will not be deleted.'],
continueWithoutDrafts: ['继续加载模型', 'Continue loading model'],
snapshotBusy: ['请先完成当前交互,或在文件菜单选择保存以处理组件移动。', 'Finish the current interaction, or use File > Save to resolve component moves.'],
pending: ['上次保存结果未知。重试会确认同一上传批次,不会创建重复版本。', 'The previous save result is unknown. Retrying confirms the same upload batch without creating a duplicate version.'],
font: ['中文字体加载失败。请重试,或临时使用英文。', 'Chinese font failed to load. Retry, or temporarily use English.'],
@@ -40,6 +48,7 @@ const messages = {
metadataConflict: ['名称已在另一窗口修改,请刷新后重试。', 'The name changed in another window. Refresh and retry.'],
update: ['编辑器有新版本。请保存后刷新。', 'An editor update is available. Save before refreshing.'],
refresh: ['检查并刷新', 'Refresh'],
updateFailed: ['更新检查失败,当前设计已保留,请重试。', 'The update check failed. Your current design is preserved. Please retry.'],
engineMissing: ['编辑器资源缺失,请联系管理员或重试。', 'Editor resources are missing. Contact your administrator or retry.'],
uploadExpired: ['保存事务已过期,当前设计已保留,请重新保存。', 'The save transaction expired. Your design is preserved. Save again.'],
downloadForbidden: ['无法读取工程文件,请联系管理员检查 OSS/CDN 访问权限和跨域配置。', 'Cannot read the design file. Ask your administrator to check OSS/CDN access and CORS settings.'],
@@ -60,6 +69,7 @@ export function errorText(error) {
const keys = { HEAD_CONFLICT: 'conflict', CAD_VERSION_CONFLICT: 'conflict', METADATA_CONFLICT: 'metadataConflict', PROJECT_DELETED: 'unavailable', NOT_FOUND: 'unavailable', FORBIDDEN: 'unavailable',
UNAUTHORIZED: 'expired', FORMAT_UNSUPPORTED: 'incompatible', UNSUPPORTED_FORMAT: 'incompatible', SOURCE_TOO_LARGE: 'tooLarge',
TOO_LARGE: 'tooLarge', SNAPSHOT_BUSY: 'snapshotBusy', BAD_DESIGN: 'invalidFile', RATE_LIMITED: 'rateLimit', PENDING_SAVE: 'pending', FONT_UNAVAILABLE: 'font',
BAD_STEP_FILE: 'stepInvalid', STEP_IMPORT_FAILED: 'stepInvalid', STEP_EMPTY_MODEL: 'stepInvalid', STEP_TOO_LARGE: 'stepTooLarge', STEP_ENGINE_UPDATE: 'stepEngineUpdate',
ENGINE_MISSING: 'engineMissing', UPLOAD_EXPIRED: 'uploadExpired', SAVE_IN_PROGRESS: 'verifying', QUOTA_EXCEEDED: 'quota',
INVALID_SOURCE_FILE: 'invalidFile', CHECKSUM_MISMATCH: 'invalidFile', EXTERNAL_DEPENDENCIES_UNSUPPORTED: 'invalidFile', UNSUPPORTED_FORMAT_VERSION: 'incompatible',
SAVE_UNAVAILABLE: 'pending', UPLOAD_NOT_READY: 'pending', UPLOAD_AUTH_EXPIRED: 'uploadExpired',
+49
View File
@@ -0,0 +1,49 @@
// The cloud document is authoritative; initial STEP is only an unsaved bootstrap source.
import { CAD } from './config.js';
import { cadError, downloadSource, initialStepSource } from './api.js';
export async function openProjectSource({ api, bridge, project, signal, onStage = () => {}, assertCurrent = () => {},
recover = async () => ({}), downloader = downloadSource }) {
const check = () => { signal?.throwIfAborted(); assertCurrent(); };
const download = async (source, maxBytes, stage) => {
check(); onStage(stage);
let bytes;
try {
bytes = await downloader(source, maxBytes, (done, total) => {
check(); onStage(stage, Math.round(done / total * 100) + '%');
}, signal);
} catch (error) {
if (stage === 'stepDownload' && error.code === 'SOURCE_TOO_LARGE') throw cadError('STEP_TOO_LARGE');
throw error;
}
check(); return bytes;
};
check();
if (project.hasDocument) {
const source = await api.document(project.id, signal);
check();
const bytes = await download(source, CAD.maxSourceBytes, 'download');
onStage('rebuild');
const opened = await bridge.openProject({ projectId: project.id, bytes, saved: true });
check();
return { opened, version: source.version, kind: 'native' };
}
const recovery = await recover();
check();
if (recovery.restored || recovery.blocked) return { ...recovery, kind: 'recovery' };
if (project.initialStep) {
const source = initialStepSource(project.initialStep);
const capabilities = await bridge.ready();
check();
if (capabilities.capabilities?.stepImport !== true || typeof bridge.openProjectFromStep !== 'function'
|| typeof bridge.cancelOpenProject !== 'function') throw cadError('STEP_ENGINE_UPDATE');
const bytes = await download(source, CAD.maxStepSourceBytes, 'stepDownload');
onStage('stepImport');
const opened = await bridge.openProjectFromStep({ projectId: project.id, bytes, fileName: source.fileName });
check();
return { opened, version: 0, kind: 'step', warnings: opened.warnings || [] };
}
const opened = await bridge.openProject({ projectId: project.id, bytes: null, saved: false });
check();
return { opened, version: 0, kind: 'empty' };
}
+4 -1
View File
@@ -96,11 +96,14 @@ export function renderShell(active, { overlay = false, footer = true, assistant
if (existing) return bindShell(existing, overlay, footer, assistant, search);
const nav = document.createElement('header');
nav.className = `nav${overlay ? ' overlay' : ''}`;
const logoImage = active === 'cad' && document.body.dataset.cadPage === 'editor'
? '<img src="/assets/brand/make-cad.svg" alt="make CAD" width="92" height="34">'
: '<img src="/assets/brand/make-web-384.png" srcset="/assets/brand/make-web-256.png 256w, /assets/brand/make-web-384.png 384w, /assets/brand/make-web-512.png 512w, /assets/brand/make-web-768.png 768w" sizes="(max-width: 820px) 96px, 112px" alt="make" width="112" height="42">';
// 工作台(studio)页面不滚动、没有滚动条,其他页面有。给导航补上滚动条宽度,切换页面时 logo 和按钮不会左右跳
if (overlay) nav.style.paddingRight = `${scrollbarWidth()}px`;
nav.innerHTML = `
<div class="nav-inner">
<a class="nav-logo" href="/" aria-label="make 首页"><img src="/assets/brand/make-web-384.png" srcset="/assets/brand/make-web-256.png 256w, /assets/brand/make-web-384.png 384w, /assets/brand/make-web-512.png 512w, /assets/brand/make-web-768.png 768w" sizes="(max-width: 820px) 96px, 112px" alt="make" width="112" height="42"></a>
<a class="nav-logo" href="/" aria-label="make 首页">${logoImage}</a>
<nav class="nav-links">${NAV.map((n) => navLink(n, active)).join('')}</nav>
<div class="nav-actions">
<button class="nav-search" data-palette>${icon('search', 15)}<span>搜索</span><kbd>⌘K</kbd></button>
+4 -1
View File
@@ -11,6 +11,9 @@
{ id: 'workspace', label: '我的', href: '/workspace/' },
];
var p = location.pathname;
var logoImage = /^\/cad\/editor(?:\/|$)/.test(p)
? '<img src="/assets/brand/make-cad.svg" alt="make CAD" width="92" height="34">'
: '<img src="/assets/brand/make-web-384.png" srcset="/assets/brand/make-web-256.png 256w, /assets/brand/make-web-384.png 384w, /assets/brand/make-web-512.png 512w, /assets/brand/make-web-768.png 768w" sizes="(max-width: 820px) 96px, 112px" alt="make" width="112" height="42">';
var active = /^\/(explore|project)/.test(p) ? 'explore' : /^\/studio/.test(p) ? 'studio' : /^\/cad/.test(p) ? 'cad' : /^\/pcb/.test(p) ? 'pcb' : /^\/workspace/.test(p) ? 'workspace' : 'home';
var overlay = active === 'studio';
var svg = function (path, size) {
@@ -42,7 +45,7 @@
nav.dataset.active = active;
nav.innerHTML =
'<div class="nav-inner">' +
'<a class="nav-logo" href="/" aria-label="make 首页"><img src="/assets/brand/make-web-384.png" srcset="/assets/brand/make-web-256.png 256w, /assets/brand/make-web-384.png 384w, /assets/brand/make-web-512.png 512w, /assets/brand/make-web-768.png 768w" sizes="(max-width: 820px) 96px, 112px" alt="make" width="112" height="42"></a>' +
'<a class="nav-logo" href="/" aria-label="make 首页">' + logoImage + '</a>' +
'<nav class="nav-links">' + links + '</nav>' +
'<div class="nav-actions">' +
'<button class="nav-search" data-palette>' + svg('<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>', 15) + '<span>搜索</span><kbd>⌘K</kbd></button>' +
+41
View File
@@ -12,6 +12,8 @@ import DOMPurify from 'dompurify';
import { renderShell, esc, icon, timeAgo, toast } from './layout.js';
import { dataMode, typeName } from './source.js';
import * as api from './api.js';
import { CadApi } from './cad/api.js';
import { desktopAllowed, projectUrl, workspaceCadEditable } from './cad/config.js';
import { openModal, openLogin, splitBatches } from './auth.js';
renderShell('workspace');
@@ -232,6 +234,8 @@ function syncUrl(push = false) {
if (url.href !== location.href) history[push ? 'pushState' : 'replaceState'](null, '', url);
}
let cadOpening = false, cadRetryAfter = 0;
// ---------- 头部:名称、状态、发布 ----------
async function renderHeader() {
const p = repo.project;
@@ -245,9 +249,11 @@ async function renderHeader() {
${p.urdfMainUrl ? `<span class="ws-badge ok">${icon('cube', 12)}3D 模型</span>` : ''}
${p.sourceProjectCode ? `<a class="ws-badge" href="/project/?id=${encodeURIComponent(p.sourceProjectCode)}">${icon('fork', 12)}Fork 自原项目</a>` : ''}`;
$('ws-actions').innerHTML = !ready() ? '' : `
${workspaceCadEditable(p, repo.sha) ? `<button class="btn" data-ws-cad ${cadOpening ? 'disabled' : ''}>${icon('edit', 14)}${cadOpening ? '正在打开…' : '编辑'}</button>` : ''}
${published ? `<a class="btn" href="/project/?id=${encodeURIComponent(code)}" target="_blank">${icon('globe', 14)}在社区查看</a>` : ''}
${!published ? `<button class="btn btn-primary" data-ws-publish>${icon('upload', 14)}发布到社区</button>` : ''}
${outdated ? `<button class="btn btn-primary" data-ws-publish>${icon('upload', 14)}更新社区版本</button>` : ''}`;
$('ws-actions').querySelector('[data-ws-cad]')?.addEventListener('click', openCadProject);
$('ws-actions').querySelectorAll('[data-ws-publish]').forEach((b) => b.addEventListener('click', openPublishDialog));
const banner = !ready()
? `<div class="ws-banner warn">${p.repoStatus === 'FAILED' ? `仓库初始化失败(状态 ${esc(p.repoStatus)}),不能编辑文件。可以在「设置」里删除这个项目重新建,或者把项目编码 <code>${esc(code)}</code> 发给后端核对。` : `仓库还在准备中(状态 ${esc(p.repoStatus)}),暂时不能读取和编辑文件。稍后刷新看看;一直这样请把项目编码 <code>${esc(code)}</code> 发给后端核对。`}</div>`
@@ -259,6 +265,40 @@ async function renderHeader() {
`<button data-tab="${k}" class="${repo.tab === k ? 'active' : ''}">${icon(ic, 15)}${label}</button>`).join('');
}
async function openCadProject() {
if (cadOpening || !workspaceCadEditable(repo.project, repo.sha)) return;
if (!desktopAllowed()) { toast('请在电脑端使用 CAD 编辑器,窗口宽度需大于 820px'); return; }
if (Date.now() < cadRetryAfter) { toast('操作频繁,请稍后重试'); return; }
// Keep dirty state until navigation actually succeeds, including request failures.
const client = new CadApi(), control = new AbortController();
const timer = setTimeout(() => control.abort(), 30000);
cadOpening = true; renderHeader();
try {
const target = await client.openWorkspaceProject(code, control.signal);
client.assertIdentity();
if (!workspaceCadEditable(repo.project, repo.sha)) return;
// Browser beforeunload remains the final guard if edits were made during the request.
location.assign(projectUrl(target.id));
} catch (error) {
if (error.code === 'STALE_IDENTITY') return;
if (error.status === 401) { await openLogin(); return; }
if (error.status === 429) {
const seconds = Number(error.retryAfter);
cadRetryAfter = Date.now() + (Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : Math.max(1000, Date.parse(error.retryAfter) - Date.now() || 1000));
}
const text = error.code === 'PROJECT_STEP_NOT_FOUND' ? '当前项目的 STEP 已不可用,请刷新后重试'
: error.code === 'CONFLICT' ? '项目仓库尚未准备好,请刷新后重试'
: error.status === 404 ? '项目不存在或无权访问'
: error.name === 'AbortError' ? '打开 CAD 超时,请重试;将复用同一个关联项目'
: error.status === 429 ? '操作频繁,请稍后重试' : api.errorText(error);
toast(text);
if (['PROJECT_STEP_NOT_FOUND', 'CONFLICT'].includes(error.code)) {
try { const latest = await api.getMyProject(code); client.assertIdentity(); repo.project = latest; }
catch { /* Keep the current page and its unsaved changes if refresh fails. */ }
}
} finally { clearTimeout(timer); cadOpening = false; renderHeader(); }
}
function renderRepo() {
closeArchiveMenu();
urdfViewer?.dispose(); // 离开设置页时释放 3D 预览
@@ -376,6 +416,7 @@ function go(next, push = true) {
if (!confirmLeave()) return;
Object.assign(repo, next);
syncUrl(push);
renderHeader();
renderRepo();
scrollTo({ top: Math.min(scrollY, $('ws-main').offsetTop - 120) });
}
+7 -1
View File
@@ -6,9 +6,11 @@ import { join, resolve } from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { compressRobot } from './meshes.mjs';
import { readCadEngine, copyCadEngine } from './cad-engine.mjs';
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const DIST = join(ROOT, 'dist');
const CAD_ENGINE = existsSync(join(ROOT, 'cad/engine.json')) ? readCadEngine(join(ROOT, 'cad')) : null;
const BUILD_ENV = process.argv.find((arg) => arg.startsWith('--env='))?.slice(6) || 'auto';
if (!['auto', 'dev'].includes(BUILD_ENV)) throw new Error(`不支持的打包环境:${BUILD_ENV}`);
const PCB_DIST = resolve(process.env.PCB_DIST || join(ROOT, '../ziro-designer-main/designer/dist'));
@@ -17,7 +19,7 @@ if (!existsSync(join(PCB_DIST, 'index.html')))
const SKIP = /(^|\/)(\.DS_Store|Thumbs\.db)$/;
const copy = (rel) => cpSync(join(ROOT, rel), join(DIST, rel), { recursive: true, filter: (src) => !SKIP.test(src) });
// Rebuild the site package from scratch; the CAD engine is built and deployed separately.
// Rebuild the site package and include the CAD engine installed in the project.
mkdirSync(DIST, { recursive: true });
for (const name of readdirSync(DIST)) rmSync(join(DIST, name), { recursive: true, force: true });
@@ -37,6 +39,8 @@ cpSync(PCB_DIST, join(DIST, 'pcb'), { recursive: true });
cpSync(join(ROOT, 'cad/editor'), join(DIST, 'cad/editor'), { recursive: true });
cpSync(join(ROOT, 'cad/manifest.webmanifest'), join(DIST, 'cad/manifest.webmanifest'));
cpSync(join(ROOT, 'cad/worker.js'), join(DIST, 'cad/worker.js'));
if (CAD_ENGINE) copyCadEngine(CAD_ENGINE, DIST);
// 只带 robots.json 里用到的模型目录(demo-* 是早期示例,不上线)
mkdirSync(join(DIST, 'robots'));
@@ -74,6 +78,7 @@ ${BUILD_ENV === 'dev' ? `本包仅用于 dev 环境,接口固定为 https://de
- 页面地址:\`/\`、\`/explore/\`、\`/studio/\`、\`/cad/\`、\`/pcb/\`、\`/project/?id=<编号>\`、\`/workspace/\`、\`/workspace/?code=<编号>\`
- PCB:与主站同源部署在 /pcb/,由独立 PCB 仓库构建;项目列表和工程深链接由 PCB 单页应用处理。站点包将 PCB_DIST 指定的独立构建复制到 dist/pcb,无需合并两份源码。
- CAD:/cad/ 为同源项目列表,/cad/editor/?project=<UUID> 直接加载 Rust/WASM;CAD / PCB 仅电脑端开放。
- CAD engine: ${CAD_ENGINE ? `included from cad/ (build ${CAD_ENGINE.manifest.buildId}).` : 'not installed in this build; extract the SolidCraft Web package into the website root before using the CAD editor.'}
- Nginx 等静态服务器需让 PCB 无扩展名深链接回退到 /pcb/index.html,例如:location ^~ /pcb/ { try_files $uri $uri/ /pcb/index.html; }。
- 接口:${BUILD_ENV === 'dev' ? '固定连接 https://dev-vibemake-api.robotquan.com/api。' : '浏览器按访问的域名直接请求后端(js/api.js 的 API_HOSTS):dev-vibemake.robotquan.com → https://dev-vibemake-api.robotquan.com/api;vibemake.robotquan.com → https://vibemake-api.robotquan.com/api。'}
- **后端需要允许前端域名跨域**(CORS:允许来源 ${BUILD_ENV === 'dev' ? 'https://dev-vibemake.robotquan.com' : 'https://dev-vibemake.robotquan.com、https://vibemake.robotquan.com'};
@@ -107,5 +112,6 @@ try {
}
console.log(`dist:${DIST}`);
console.log(`PCB:${join(DIST, 'pcb')} ← ${PCB_DIST}`);
console.log(CAD_ENGINE ? `CAD: ${join(DIST, 'cad')} (build ${CAD_ENGINE.manifest.buildId})` : 'CAD: no local engine installed; deploy the SolidCraft Web package separately.');
console.log(`模型:${dirs.join('、')}`);
if (!existsSync(join(DIST, 'robots/so101/so101.urdf'))) throw new Error('模型文件没有复制成功');
+1 -1
View File
@@ -2,7 +2,7 @@ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync }
import { createHash } from 'node:crypto';
import { join, resolve, sep } from 'node:path';
export function readCadEngine(source) {
if (!source) throw new Error('VIBEMAKE_CAD_ENGINE_DIST is required. Build the SolidCraft VibeMake engine first.');
if (!source) throw new Error('A CAD engine directory is required. Extract the SolidCraft Web package into the VibeMake project root first.');
const root = resolve(source), manifest = JSON.parse(readFileSync(join(root, 'engine.json'), 'utf8'));
if (manifest.bridgeVersion !== 1 || manifest.engineKind !== 'solidcraft' || manifest.kernel !== 'smlib' || !/^[a-zA-Z0-9_-]+$/.test(manifest.buildId) || !Array.isArray(manifest.files)) throw new Error('Incompatible CAD engine manifest');
const prefix = `/cad/_assets/${manifest.buildId}/`, names = new Set();
+6 -1
View File
@@ -22,7 +22,8 @@ import { readCadEngine, cadWorker } from './cad-engine.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(process.env.SITE_ROOT || (basename(HERE) === 'scripts' ? join(HERE, '..') : HERE));
const CAD_ENGINE = process.env.VIBEMAKE_CAD_ENGINE_DIST ? readCadEngine(process.env.VIBEMAKE_CAD_ENGINE_DIST) : null;
const CAD_ENGINE_SOURCE = process.env.VIBEMAKE_CAD_ENGINE_DIST || (existsSync(join(ROOT, 'cad/engine.json')) ? join(ROOT, 'cad') : null);
const CAD_ENGINE = CAD_ENGINE_SOURCE ? readCadEngine(CAD_ENGINE_SOURCE) : null;
const PORT = Number(process.env.PORT || 8091);
const PCB_APP_ROOT = resolve(process.env.PCB_APP_ROOT || join(ROOT, '../ziro-designer-main/designer'));
const PCB_DEV_TARGET = process.env.PCB_DEV_TARGET === 'off'
@@ -226,12 +227,16 @@ server.on('upgrade', (req, socket, head) => {
if (upstreamHead.length) socket.write(upstreamHead);
upstreamSocket.pipe(socket);
socket.pipe(upstreamSocket);
upstreamSocket.on('error', () => socket.destroy());
upstreamSocket.on('close', () => socket.destroy());
socket.on('error', () => upstreamSocket.destroy());
socket.on('close', () => upstreamSocket.destroy());
});
upstream.on('response', (response) => {
socket.end(`HTTP/${response.httpVersion} ${response.statusCode} ${response.statusMessage}\r\n\r\n`);
});
upstream.on('error', () => socket.destroy());
socket.on('error', () => upstream.destroy());
socket.on('close', () => upstream.destroy());
upstream.end();
});
+164 -3
View File
@@ -44,7 +44,7 @@ test('CAD metadata accepts, displays and clears HTTPS covers without changing do
const api = new CadApi({ fetcher: async (path, options) => {
calls.push({ path, options });
const body = JSON.parse(options.body);
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad/a', version: 4, savedAt: '2026-11-05 10:00:00', coverUrl: body.coverUrl || null } });
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad/a', hasDocument: true, version: 4, savedAt: '2026-11-05 10:00:00', coverUrl: body.coverUrl || null } });
} });
assert.equal((await api.create('Plate', '', url)).coverUrl, url);
assert.deepEqual(JSON.parse(calls[0].options.body), { name: 'Plate', description: '', coverUrl: url });
@@ -328,9 +328,9 @@ test('create, rename, signature and commit use their exact request fields and HT
uploadCode: 'upload-code', uploadUrl: 'https://oss.example/post', formFields: { key: 'fixed', policy: 'signed' },
expiresAt: '2026-11-03 12:15:00',
} });
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', name: 'Plate', description: '', version: 0 } });
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', name: 'Plate', description: '', hasDocument: false, version: 0 } });
}
if (options.method === 'PATCH') return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', name: 'New', description: '', version: 0 } });
if (options.method === 'PATCH') return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', name: 'New', description: '', hasDocument: false, version: 0 } });
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-code', version: 1, savedAt: '2026-11-03 12:00:00' } });
} });
await api.create('Plate');
@@ -419,6 +419,18 @@ test('downloads validate the exact byte count and omit bearer credentials', asyn
const result = await downloadSource({ sizeBytes: 3, downloadUrl: 'https://oss.example/immutable' }, 10);
assert.deepEqual(result, bytes);
await assert.rejects(downloadSource({ sizeBytes: 4, downloadUrl: 'https://oss.example/immutable' }, 10), { code: 'BAD_DESIGN' });
await assert.rejects(downloadSource({ sizeBytes: 2, downloadUrl: 'https://oss.example/immutable' }, 10), { code: 'BAD_DESIGN' });
});
test('streamed and buffered downloads enforce the size cap before reporting length mismatch', async (t) => {
const original = globalThis.fetch, bytes = new Uint8Array([1, 2, 3]);
t.after(() => { globalThis.fetch = original; });
const source = { sizeBytes: 2, downloadUrl: 'https://oss.example/immutable' };
globalThis.fetch = async () => new Response(bytes);
await assert.rejects(downloadSource(source, 2), { code: 'SOURCE_TOO_LARGE' });
globalThis.fetch = async () => ({ ok: true, body: null, arrayBuffer: async () => bytes.buffer });
await assert.rejects(downloadSource(source, 2), { code: 'SOURCE_TOO_LARGE' });
await assert.rejects(downloadSource(source, 10), { code: 'BAD_DESIGN' });
});
test('OSS POST preserves signed fields and appends the raw .sc file last', async (t) => {
@@ -468,3 +480,152 @@ test('project names and 256 MiB limit match the workspace contract', () => {
assert.equal(filename('../../机械臂'), '_.._机械臂.sc');
assert.equal(sha256 instanceof Function, true);
});
test('workspace association uses the current fork code and a bodyless identity-bound POST', async () => {
const calls = [], source = { downloadUrl: 'https://cdn.example/a.STP', fileName: '装配.STP', sizeBytes: 32 };
const api = new CadApi({ fetcher: async (url, options) => {
calls.push({ url, options });
return Response.json({ code: 'OK', data: { cadProjectCode: 'cad-linked', workspaceProjectCode: 'fork/a', initialStep: source, hasDocument: false, version: 0 } });
} });
for (let i = 0; i < 2; i++) {
const result = await api.openWorkspaceProject('fork/a');
assert.equal(result.id, 'cad-linked'); assert.deepEqual(result.initialStep, source);
}
assert.equal(calls.length, 2);
assert.equal(calls[0].url, '/api/workspace/projects/fork%2Fa/cad-project');
assert.equal(calls[0].options.method, 'POST'); assert.equal(calls[0].options.body, undefined);
assert.equal(calls[0].options.headers['Content-Type'], undefined);
assert.equal(calls[0].options.cache, 'no-store'); assert.equal(calls[0].options.headers.Authorization, 'Bearer token-a');
});
test('association responses from another identity are discarded', async () => {
const api = new CadApi({ fetcher: async () => {
auth.set({ token: 'other', user: { userCode: 'other' } });
return Response.json({ code: 'OK', data: { cadProjectCode: 'old', hasDocument: false, version: 0 } });
} });
await assert.rejects(api.openWorkspaceProject('fork'), { code: 'STALE_IDENTITY' });
});
test('association responses must refer to the requested current workspace project', async () => {
for (const workspaceProjectCode of [null, 'upstream']) {
const api = new CadApi({ fetcher: async () => Response.json({ data: {
cadProjectCode: 'cad', hasDocument: false, version: 0, workspaceProjectCode,
} }) });
await assert.rejects(api.openWorkspaceProject('current-fork'), { code: 'BAD_RESPONSE' });
}
});
test('project and native metadata reads use the opening abort signal', async () => {
const signals = [], control = new AbortController();
const api = new CadApi({ fetcher: async (url, options) => {
signals.push(options.signal);
return Response.json({ data: url.endsWith('/document')
? { version: 1, sizeBytes: 3, fileName: 'a.sc', downloadUrl: 'https://cdn.example/a.sc' }
: { cadProjectCode: 'p', hasDocument: false, version: 0 } });
} });
await api.get('p', control.signal); await api.document('p', control.signal);
assert.deepEqual(signals, [control.signal, control.signal]);
});
test('CAD metadata rejects ambiguous document state and invalid versions', async () => {
for (const record of [{ version: 0 }, { hasDocument: 'false', version: 0 }, { hasDocument: false, version: 2 }, { hasDocument: true, version: -1 }, { hasDocument: true, version: 1.5 }]) {
const api = new CadApi({ fetcher: async () => Response.json({ data: { cadProjectCode: 'p', ...record } }) });
await assert.rejects(api.get('p'), { code: 'BAD_RESPONSE' });
}
});
const { openProjectSource } = await import('../../js/cad/opening.js');
const { initialStepSource } = await import('../../js/cad/api.js');
const { validStepFilename, validNativeFilename, workspaceCadEditable } = await import('../../js/cad/config.js');
const initialStep = { downloadUrl: 'https://cdn.example/assembly', fileName: '装配.STP', sizeBytes: 3 };
function openingHarness(overrides = {}) {
const calls = [], bytes = new Uint8Array([1, 2, 3]);
const options = {
api: { document: async () => { calls.push('document'); return { ...initialStep, fileName: 'design.sc', version: 7 }; } },
bridge: {
ready: async () => ({ capabilities: { stepImport: true } }), cancelOpenProject: async () => {},
openProject: async (args) => { calls.push(['native', args]); return { binding: 'native' }; },
openProjectFromStep: async (args) => { calls.push(['step', args]); return { binding: 'step', warnings: ['partial support'] }; },
},
project: { id: 'p', hasDocument: false, version: 0, initialStep },
downloader: async (source, cap) => { calls.push(['download', source, cap]); return bytes; },
recover: async () => { calls.push('recover'); return {}; }, ...overrides,
};
return { options, calls, bytes };
}
test('cloud native documents take precedence and use document snapshot version', async () => {
const h = openingHarness({ project: { id: 'p', hasDocument: true, initialStep } });
const result = await openProjectSource(h.options);
assert.equal(result.version, 7); assert.equal(result.kind, 'native');
assert.equal(h.calls.includes('recover'), false);
assert.equal(h.calls[1][2], CAD.maxSourceBytes); assert.equal(h.calls[2][0], 'native'); assert.equal(h.calls[2][1].saved, true);
});
test('a missing cloud document never falls back to STEP or an empty design', async () => {
const h = openingHarness({ project: { id: 'p', hasDocument: true, initialStep }, api: { document: async () => { throw Object.assign(new Error(), { code: 'CAD_DOCUMENT_NOT_FOUND' }); } } });
await assert.rejects(openProjectSource(h.options), { code: 'CAD_DOCUMENT_NOT_FOUND' }); assert.deepEqual(h.calls, []);
});
test('initial STEP imports raw bytes and original filename after local recovery preflight', async () => {
const h = openingHarness(), result = await openProjectSource(h.options);
assert.equal(result.kind, 'step'); assert.equal(result.version, 0); assert.deepEqual(result.warnings, ['partial support']);
assert.equal(h.calls[0], 'recover'); assert.equal(h.calls[1][2], CAD.maxStepSourceBytes);
assert.deepEqual(h.calls[2], ['step', { projectId: 'p', fileName: '装配.STP', bytes: h.bytes }]);
});
test('restored drafts and unresolved transactions bypass STEP downloading', async () => {
for (const recovery of [{ restored: true }, { blocked: true }]) {
const h = openingHarness({ recover: async () => recovery });
assert.equal((await openProjectSource(h.options)).kind, 'recovery'); assert.deepEqual(h.calls, []);
}
});
test('empty independent projects open empty without requesting a document', async () => {
const h = openingHarness({ project: { id: 'p', hasDocument: false, initialStep: null } });
assert.equal((await openProjectSource(h.options)).kind, 'empty');
assert.deepEqual(h.calls, ['recover', ['native', { projectId: 'p', bytes: null, saved: false }]]);
});
test('older engines remain compatible with native projects but refuse initial STEP', async () => {
const h = openingHarness(); h.options.bridge.ready = async () => ({ capabilities: {} });
await assert.rejects(openProjectSource(h.options), { code: 'STEP_ENGINE_UPDATE' });
assert.deepEqual(h.calls, ['recover']);
h.options.project.hasDocument = true;
assert.equal((await openProjectSource(h.options)).kind, 'native');
});
test('cancelled or obsolete downloads cannot adopt their imported model', async () => {
for (const abort of [true, false]) {
const controller = new AbortController(); let stale = false;
const h = openingHarness({ signal: controller.signal, assertCurrent: () => { if (stale) throw Object.assign(new Error(), { code: 'STALE_BINDING' }); },
downloader: async () => { if (abort) controller.abort(); else stale = true; return new Uint8Array([1]); } });
await assert.rejects(openProjectSource(h.options)); assert.deepEqual(h.calls, ['recover']);
}
});
test('STEP and native limits and filename rules stay independent', () => {
assert.equal(CAD.maxStepSourceBytes, 524288000); assert.equal(CAD.maxSourceBytes, 268435456);
for (const name of ['A.step', '零件.STP', '长'.repeat(1019) + '.step']) assert.equal(validStepFilename(name), true);
for (const name of ['a.sc', '../a.step', 'a\\b.stp', '长'.repeat(1020) + '.step']) assert.equal(validStepFilename(name), false);
assert.equal(validNativeFilename('长'.repeat(252) + '.sc'), true);
assert.equal(validNativeFilename('长'.repeat(253) + '.sc'), false);
assert.equal(validNativeFilename('长'.repeat(300) + '.step'), false);
assert.equal(initialStepSource({ ...initialStep, sizeBytes: CAD.maxSourceBytes + 1 }).sizeBytes, CAD.maxSourceBytes + 1);
assert.throws(() => initialStepSource({ ...initialStep, sizeBytes: CAD.maxStepSourceBytes + 1 }), { code: 'STEP_TOO_LARGE' });
});
test('STEP download errors report the STEP limit without changing native errors', async () => {
const h = openingHarness({ downloader: async () => { throw Object.assign(new Error(), { code: 'SOURCE_TOO_LARGE' }); } });
await assert.rejects(openProjectSource(h.options), { code: 'STEP_TOO_LARGE' });
h.options.project.hasDocument = true;
await assert.rejects(openProjectSource(h.options), { code: 'SOURCE_TOO_LARGE' });
});
test('workspace CAD entry is limited to latest ready projects with a STEP', () => {
const project = { repoStatus: 'READY', stepMainUrl: 'https://cdn.example/a.step', sourceProjectCode: 'upstream' };
assert.equal(workspaceCadEditable(project), true); assert.equal(workspaceCadEditable(project, 'historical-sha'), false);
assert.equal(workspaceCadEditable({ ...project, stepMainUrl: '' }), false);
assert.equal(workspaceCadEditable({ ...project, repoStatus: 'PENDING' }), false);
});
+232 -9
View File
@@ -9,10 +9,19 @@ const artifactDir = process.env.VM_CAD_ARTIFACT_DIR ? resolve(process.env.VM_CAD
const browserOptions = { headless: true, args: ['--enable-unsafe-webgpu', '--use-angle=swiftshader', '--enable-webgl'] };
if (process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE) browserOptions.executablePath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE;
const browser = await chromium.launch(browserOptions), checks = [], errors = [];
function recordPageError(page, error) {
errors.push(String(error));
console.error(JSON.stringify({ pageError: String(error), stack: error.stack, url: page.url() }));
}
const auth = { token: 'cad-browser-test-token', user: { userCode: 'cad-browser-test-user', nickname: 'CAD Browser Test', email: 'cad-test@example.test' } };
async function authenticatedContext(viewport = { width: 1440, height: 1000 }) {
const context = await browser.newContext({ viewport });
await context.addInitScript((value) => localStorage.setItem('vm.auth', JSON.stringify(value)), auth);
if (artifactDir) await context.route('**/js/cad/app.js', async (route) => {
const response = await route.fetch(), body = await response.text();
await route.fulfill({ response, body: body.replace('function showError(error) {',
'function showError(error) { (window.__cadTestErrors ??= []).push({ code: error.code, status: error.status, message: error.message });') });
});
await context.route('https://cad-covers.example.test/**', async (route) => {
const response = await fetch(`${base}/api/cad/mock-cover-source/${new URL(route.request().url()).pathname.split('/').at(-1)}`);
await route.fulfill({ status: response.status, contentType: 'image/png', body: Buffer.from(await response.arrayBuffer()) });
@@ -21,8 +30,9 @@ async function authenticatedContext(viewport = { width: 1440, height: 1000 }) {
}
async function ready(page) {
await page.waitForFunction(() => window.vibemakeCad && typeof window.solidcraft?.execute === 'function', null, { timeout: 180000 });
let stable = 0;
for (let i = 0; i < 900; i++) {
let stable = 0; const deadline = Date.now() + 180000;
while (Date.now() < deadline) {
assert.equal(await page.locator('.modal.open [data-choice]').count(), 0, 'Unexpected recovery or conflict dialog while opening');
const state = await page.evaluate(() => window.vibemakeCad.getState());
const hostReady = await page.evaluate(() => document.querySelector('#cad-main')?.hidden && !document.querySelector('#cad-viewport')?.inert);
stable = state.binding && !state.locked && hostReady ? stable + 1 : 0;
@@ -35,13 +45,206 @@ const execute = (page, command, params) => page.evaluate(([id, value]) => window
const apiHeaders = { Authorization: `Bearer ${auth.token}`, 'Content-Type': 'application/json' };
if (artifactDir) await mkdir(artifactDir, { recursive: true });
async function workspaceIntegrationChecks() {
console.log('Checking workspace STEP integration');
const request = async (path, method = 'GET', body) => {
const response = await fetch(base + path, { method, headers: apiHeaders, body: body === undefined ? undefined : JSON.stringify(body) });
const result = await response.json(); assert.equal(result.code, 'OK', JSON.stringify(result)); return result.data;
};
const workspace = await request('/api/cad/mock-workspace', 'POST', {});
const linked = await Promise.all(Array.from({ length: 8 }, () => request(`/api/workspace/projects/${workspace.projectCode}/cad-project`, 'POST')));
const id = linked[0].cadProjectCode;
assert.equal(new Set(linked.map((p) => p.cadProjectCode)).size, 1); checks.push('workspace-association-is-idempotent');
const context = await authenticatedContext(), page = await context.newPage(), sourceRequests = [], signatures = [], confirmations = [];
page.on('pageerror', (error) => recordPageError(page, error));
page.on('dialog', (dialog) => dialog.accept());
page.on('request', (request) => {
if (request.url().includes('/api/cad/mock-source/step-')) sourceRequests.push(request.url());
if (request.url().endsWith('/uploads/signature')) signatures.push(JSON.parse(request.postData()));
if (request.method() === 'PUT' && request.url().endsWith('/document')) confirmations.push(request.postDataJSON());
});
await page.goto(`${base}/workspace/?code=${workspace.projectCode}&sha=history`);
await page.locator('#ws-title h1').waitFor(); assert.equal(await page.locator('[data-ws-cad]').count(), 0);
await page.goto(`${base}/workspace/?code=${workspace.projectCode}`);
await page.locator('[data-ws-cad]').click(); await page.waitForURL(`**/cad/editor/?project=${id}`); await ready(page);
const imported = await page.evaluate(() => window.solidcraft.inspect({}));
assert.ok(imported.bodies.length > 0);
assert.equal((await page.evaluate(() => window.vibemakeCad.getState())).dirty, true);
assert.equal((await request(`/api/cad/workspace/projects/${id}`)).hasDocument, false);
assert.equal(sourceRequests.length, 1); checks.push('workspace-entry-imports-step-without-cloud-saving');
const warningDetails = page.locator('[data-import-warnings]');
await warningDetails.waitFor();
const importWarnings = await warningDetails.locator('li').allTextContents();
assert.ok(importWarnings.length > 0);
await page.evaluate(() => dispatchEvent(new Event('vm:cad:update')));
assert.deepEqual(await warningDetails.locator('li').allTextContents(), importWarnings);
checks.push('usable-step-import-keeps-warnings-visible-including-engine-update-notices');
if (artifactDir) await page.screenshot({ path: resolve(artifactDir, 'workspace-step-import.png') });
const stepBytes = await page.evaluate(async (source) => Array.from(new Uint8Array(await (await fetch(source)).arrayBuffer())), linked[0].initialStep.downloadUrl);
const atomic = await page.evaluate(async (bytes) => {
const bridge = window.vibemakeCad, before = await bridge.getState();
let invalid, cancelled;
try { await bridge.openProjectFromStep({ projectId: 'bad', fileName: 'broken.step', bytes: new Uint8Array([1, 2, 3]) }); }
catch (error) { invalid = error.code; }
const pending = bridge.openProjectFromStep({ projectId: 'cancelled', fileName: 'cancel.STP', bytes: new Uint8Array(bytes) }).catch((e) => { cancelled = e.code; });
await bridge.cancelOpenProject(); await pending;
const after = await bridge.getState();
return { invalid, cancelled, same: before.binding === after.binding && before.revision === after.revision };
}, stepBytes);
assert.deepEqual(atomic, { invalid: 'STEP_IMPORT_FAILED', cancelled: 'OPEN_CANCELLED', same: true });
checks.push('step-import-failure-and-cancellation-are-atomic');
await execute(page, 'solid.box', { length: 5, width: 6, height: 7, corner: [40, 0, 0] });
const draftBytes = await page.evaluate(async () => {
const bridge = window.vibemakeCad, snapshot = await bridge.createSnapshot({ forLocalDownload: true });
const result = Array.from(snapshot.bytes); await bridge.releaseSnapshot(snapshot.snapshotId); return result;
});
assert.ok(draftBytes.length > 0); checks.push('local-download-snapshot-remains-unsaved');
await page.locator('[data-save]').click();
await page.waitForFunction(() => document.querySelector('.cad-save-state')?.dataset.state === 'saved', null, { timeout: 60000 });
assert.equal(signatures[0].expectedVersion, 0);
const saved = await request(`/api/cad/workspace/projects/${id}`); assert.equal(saved.version, 1); assert.equal(saved.hasDocument, true);
const stepCount = sourceRequests.length;
await page.reload(); await ready(page);
assert.equal(sourceRequests.length, stepCount);
assert.equal((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length, imported.bodies.length + 1);
checks.push('linked-project-saves-native-and-reopens-without-reimporting-step');
const broken = await request('/api/cad/mock-workspace', 'POST', { invalidStep: true });
const recoverable = await request(`/api/workspace/projects/${broken.projectCode}/cad-project`, 'POST');
await page.evaluate(async ({ projectId, bytes, owner, importWarnings }) => {
const { DraftStore } = await import('/js/cad/drafts.js');
await new DraftStore().put(owner, projectId, 'seed', 'draft', { snapshotId: crypto.randomUUID(), bytes: new Uint8Array(bytes), baseVersion: 0, origin: 'step-import', importWarnings });
}, { projectId: recoverable.cadProjectCode, bytes: draftBytes, owner: auth.user.userCode, importWarnings });
const beforeRecovery = sourceRequests.length;
await page.goto(`${base}/cad/editor/?project=${recoverable.cadProjectCode}`);
await page.locator('[data-choice="cancel"]').click({ timeout: 180000 });
assert.equal(await page.locator('[data-save]').isDisabled(), true); assert.equal(sourceRequests.length, beforeRecovery);
await page.locator('#cad-main [data-action]').click();
await page.locator('[data-choice="restore"]').click(); await ready(page);
assert.equal(sourceRequests.length, beforeRecovery);
assert.equal((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length, imported.bodies.length + 1);
assert.deepEqual(await warningDetails.locator('li').allTextContents(), importWarnings);
checks.push('local-draft-stay-and-restore-precede-unavailable-step-source');
const unfinishedSource = await request('/api/cad/mock-workspace', 'POST', { invalidStep: true });
const unfinished = await request(`/api/workspace/projects/${unfinishedSource.projectCode}/cad-project`, 'POST');
const originalUpload = await page.evaluate(async ({ projectId, bytes, owner }) => {
const { CadApi, uploadSource } = await import('/js/cad/api.js');
const { DraftStore } = await import('/js/cad/drafts.js');
const request = { fileName: 'recovery.sc', sizeBytes: bytes.length, expectedVersion: 0 };
const signature = await new CadApi().signUpload(projectId, request);
const binary = new Uint8Array(bytes);
await uploadSource(signature, binary, request.fileName);
const store = new DraftStore(), session = 'interrupted-save';
await store.put(owner, projectId, session, 'operation', { user: owner, projectId, request,
bytes: binary, snapshotId: crypto.randomUUID(), uploadCode: signature.uploadCode,
journalKey: store.key(owner, projectId, session, 'operation') });
return signature.uploadCode;
}, { projectId: unfinished.cadProjectCode, bytes: draftBytes, owner: auth.user.userCode });
const signaturesBeforeRecovery = signatures.length, confirmationsBeforeRecovery = confirmations.length;
await page.goto(`${base}/cad/editor/?project=${unfinished.cadProjectCode}`);
await page.locator('[data-choice="cancel"]').click({ timeout: 180000 });
assert.equal(await page.locator('[data-save]').isDisabled(), true);
assert.equal(confirmations.length, confirmationsBeforeRecovery); assert.equal(sourceRequests.length, beforeRecovery);
await page.locator('#cad-main [data-action]').click();
await page.locator('[data-choice="restore"]').click(); await ready(page);
assert.equal(signatures.length, signaturesBeforeRecovery);
assert.deepEqual(confirmations.at(-1), { uploadCode: originalUpload });
assert.equal(sourceRequests.length, beforeRecovery);
assert.equal((await request(`/api/cad/workspace/projects/${unfinished.cadProjectCode}`)).version, 1);
checks.push('pending-first-save-blocks-step-and-confirms-original-upload-batch');
await page.goto(`${base}/cad/`);
await context.route(`**/api/cad/workspace/projects/${id}/document`, (route) => route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ code: 'CAD_DOCUMENT_NOT_FOUND', data: null }) }));
await page.goto(`${base}/cad/editor/?project=${id}`);
await page.locator('#cad-main [data-action]').waitFor();
assert.equal(sourceRequests.length, beforeRecovery); assert.equal(await page.locator('[data-save]').isDisabled(), true);
checks.push('cloud-document-read-error-never-reimports-step');
await context.unroute(`**/api/cad/workspace/projects/${id}/document`);
await request(`/api/workspace/projects/${workspace.projectCode}`, 'PATCH', { stepMainUrl: '' });
await page.goto(`${base}/workspace/?code=${workspace.projectCode}`); await page.locator('#ws-title h1').waitFor();
assert.equal(await page.locator('[data-ws-cad]').count(), 0);
assert.equal((await request(`/api/workspace/projects/${workspace.projectCode}/cad-project`, 'POST')).cadProjectCode, id);
await request(`/api/workspace/projects/${workspace.projectCode}`, 'DELETE');
await page.goto(`${base}/cad/editor/?project=${id}`); await ready(page);
checks.push('workspace-step-removal-and-deletion-preserve-linked-cad');
const unreadable = await request('/api/cad/mock-workspace', 'POST', {});
const withoutDrafts = await request(`/api/workspace/projects/${unreadable.projectCode}/cad-project`, 'POST');
await context.route('**/js/cad/drafts.js', async (route) => {
const response = await route.fetch();
const body = await response.text();
await route.fulfill({ response, body: body + '\nconst originalList = DraftStore.prototype.list; DraftStore.prototype.list = function(user, project, kind) { if (kind === "draft") throw new Error("Unreadable test drafts"); return originalList.call(this, user, project, kind); };' });
});
const beforeUnreadable = sourceRequests.length;
await page.goto(`${base}/cad/editor/?project=${withoutDrafts.cadProjectCode}`);
await page.locator('[data-choice="continue"]').waitFor({ timeout: 180000 });
assert.equal(await page.locator('[data-save]').isDisabled(), true);
assert.equal(sourceRequests.length, beforeUnreadable);
await page.locator('[data-choice="continue"]').click(); await ready(page);
assert.ok((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length > 0);
assert.equal((await request(`/api/cad/workspace/projects/${withoutDrafts.cadProjectCode}`)).hasDocument, false);
checks.push('unreadable-drafts-require-explicit-choice-before-step-import');
await context.unroute('**/js/cad/drafts.js');
await request(`/api/workspace/projects/${unreadable.projectCode}`, 'DELETE');
const beforeDeletedSource = sourceRequests.length;
await page.reload();
await page.locator('.modal.open [data-choice="discard"]').click({ timeout: 180000 });
await ready(page);
assert.equal(sourceRequests.length, beforeDeletedSource + 1);
assert.ok((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length > 0);
assert.equal((await request(`/api/cad/workspace/projects/${withoutDrafts.cadProjectCode}`)).hasDocument, false);
checks.push('unsaved-cad-retains-its-initial-step-after-workspace-deletion');
const recreatedSource = await request('/api/cad/mock-workspace', 'POST', {});
const removedCad = await request(`/api/workspace/projects/${recreatedSource.projectCode}/cad-project`, 'POST');
await request(`/api/cad/workspace/projects/${removedCad.cadProjectCode}`, 'DELETE');
assert.equal((await fetch(`${base}/api/cad/workspace/projects/${removedCad.cadProjectCode}`, { headers: apiHeaders })).status, 404);
const replacementCad = await request(`/api/workspace/projects/${recreatedSource.projectCode}/cad-project`, 'POST');
assert.notEqual(replacementCad.cadProjectCode, removedCad.cadProjectCode);
await page.goto(`${base}/workspace/?code=${recreatedSource.projectCode}`);
await page.locator('[data-ws-cad]').click();
await page.waitForURL(`**/cad/editor/?project=${replacementCad.cadProjectCode}`);
await ready(page);
assert.ok((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length > 0);
assert.equal((await request(`/api/cad/workspace/projects/${replacementCad.cadProjectCode}`)).hasDocument, false);
checks.push('deleting-cad-releases-the-association-and-the-workspace-opens-a-new-cad');
const logoutSource = await request('/api/cad/mock-workspace', 'POST', { invalidStep: true });
const logoutProject = await request(`/api/workspace/projects/${logoutSource.projectCode}/cad-project`, 'POST');
await page.evaluate(async ({ projectId, bytes, owner }) => {
const { DraftStore } = await import('/js/cad/drafts.js');
await new DraftStore().put(owner, projectId, 'logout-seed', 'draft', { snapshotId: crypto.randomUUID(),
bytes: new Uint8Array(bytes), baseVersion: 0, origin: 'step-import' });
}, { projectId: logoutProject.cadProjectCode, bytes: draftBytes, owner: auth.user.userCode });
const requestsBeforeLogout = sourceRequests.length;
await page.goto(`${base}/cad/editor/?project=${logoutProject.cadProjectCode}`);
await page.locator('.modal.open [data-choice="restore"]').waitFor({ timeout: 180000 });
await page.evaluate(async () => (await import('/js/api.js')).auth.clear());
await page.getByRole('heading', { name: '登录后管理你的 CAD 项目' }).waitFor();
assert.equal(await page.locator('.modal.open [data-choice]').count(), 0);
assert.equal(sourceRequests.length, requestsBeforeLogout);
assert.equal((await page.evaluate(() => window.vibemakeCad.getState())).binding, null);
checks.push('logout-cancels-pending-recovery-before-step-or-document-adoption');
await context.close();
}
try {
if (process.env.VM_CAD_BROWSER_SUITE === 'workspace') {
await workspaceIntegrationChecks();
assert.deepEqual(errors, []);
if (artifactDir) await writeFile(resolve(artifactDir, 'workspace-results.json'), JSON.stringify({ checks, errors }, null, 2));
console.log(JSON.stringify({ checks, errors }));
} else {
const projectName = `CAD browser integration ${Date.now()}`;
const created = await (await fetch(`${base}/api/cad/workspace/projects`, { method: 'POST', headers: apiHeaders, body: JSON.stringify({ name: projectName, description: '' }) })).json();
assert.equal(created.code, 'OK');
const project = created.data, url = `${base}/cad/editor/?project=${project.cadProjectCode}`;
const firstContext = await authenticatedContext(), first = await firstContext.newPage();
first.on('pageerror', (error) => errors.push(String(error)));
first.on('pageerror', (error) => recordPageError(first, error));
first.on('dialog', (dialog) => dialog.accept());
await first.goto(`${base}/`);
const navLayout = (page) => page.locator('body > header.nav .nav-inner').evaluate((element) => {
@@ -73,7 +276,8 @@ try {
await projectCard.getByRole('link', { name: '打开' }).click();
await ready(first); checks.push('actual-wasm-and-font-ready');
assert.equal(await first.locator('body > header.nav').count(), 1);
assert.deepEqual(await first.locator('.cad-engine-menus button').evaluateAll((buttons) => buttons.map((button) => button.dataset.engineMenu)), ['file', 'assistant', 'preferences', 'help']);
assert.deepEqual(await first.locator('.cad-engine-menus button').evaluateAll((buttons) => buttons.map((button) => button.dataset.engineMenu)), ['file', 'preferences', 'help']);
const editorHostState = await first.evaluate(() => window.vibemakeCad.getState());
const editorBar = await first.locator('body > header.nav').evaluate((header) => {
const logo = header.querySelector('.nav-logo').getBoundingClientRect();
const left = header.querySelector('.cad-appbar-left').getBoundingClientRect();
@@ -83,7 +287,9 @@ try {
});
assert.equal(editorBar.height, 42);
assert.ok(editorBar.logoLeft < editorBar.controlsLeft);
assert.ok(editorBar.actionsRight >= editorBar.viewportWidth - 20);
const menuRight = editorHostState.assistant?.fullHeight && editorHostState.assistant.open
? editorBar.viewportWidth * (1 - editorHostState.assistant.panelFraction) : editorBar.viewportWidth;
assert.ok(editorBar.actionsRight >= menuRight - 20 && editorBar.actionsRight <= menuRight + 1);
assert.equal(await first.locator('body > header.nav a[href="/"]').count(), 0);
assert.equal((await first.locator('[data-save]').innerText()).trim(), '');
assert.equal(await first.locator('[data-save]').getAttribute('aria-label'), '保存');
@@ -193,7 +399,8 @@ try {
if (artifactDir) await first.screenshot({ path: resolve(artifactDir, 'editor-zh.png') });
const secondContext = await authenticatedContext(), second = await secondContext.newPage();
second.on('pageerror', (error) => errors.push(String(error)));
console.log('Checking public document reads and concurrent saves');
second.on('pageerror', (error) => recordPageError(second, error));
second.on('dialog', (dialog) => dialog.accept());
let documentReads = 0, sourceReads = 0, saveBase;
second.on('request', (request) => {
@@ -211,7 +418,8 @@ try {
});
await second.route('**/api/cad/mock-source/*', (route) => route.fulfill({ status: 403 }));
await second.goto(url);
await second.locator('#cad-notice').filter({ hasText: 'OSS/CDN' }).waitFor();
await second.locator('#cad-notice').waitFor({ timeout: 180000 });
assert.match(await second.locator('#cad-notice').innerText(), /OSS\/CDN/);
assert.equal(documentReads, 1);
assert.equal(sourceReads, 1);
assert.equal((await second.evaluate(() => JSON.parse(localStorage.getItem('vm.auth')))).token, auth.token);
@@ -249,8 +457,9 @@ try {
await Promise.all([firstContext.close(), secondContext.close()]);
const draftProject = (await (await fetch(`${base}/api/cad/workspace/projects`, { method: 'POST', headers: apiHeaders, body: JSON.stringify({ name: 'IndexedDB draft recovery', description: '' }) })).json()).data;
console.log('Checking native draft recovery');
const draftContext = await authenticatedContext(), draftPage = await draftContext.newPage();
draftPage.on('pageerror', (error) => errors.push(String(error)));
draftPage.on('pageerror', (error) => recordPageError(draftPage, error));
await draftPage.goto(`${base}/cad/editor/?project=${draftProject.cadProjectCode}`); await ready(draftPage);
await draftPage.locator('[data-save]').click();
await draftPage.waitForFunction(() => document.querySelector('[data-state]')?.dataset.state === 'coverUnavailable', null, { timeout: 90000 });
@@ -329,6 +538,7 @@ try {
assert.deepEqual(await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode), []);
checks.push('discarded-draft-does-not-return-when-project-reopens');
if (artifactDir) await draftPage.screenshot({ path: resolve(artifactDir, 'discard-reopened-zh.png') });
await draftContext.close();
const platformAgentResult = await runPlatformAgentBrowserChecks(browser); checks.push(...platformAgentResult.checks); errors.push(...platformAgentResult.errors);
@@ -343,13 +553,26 @@ try {
assert.deepEqual(privateRequests, []); assert.equal(await signedOut.evaluate(() => window.vibemakeCad), undefined);
checks.push('cancel-login-does-not-load-private-data-or-engine');
await workspaceIntegrationChecks();
if (artifactDir) {
await mkdir(artifactDir, { recursive: true });
await writeFile(resolve(artifactDir, 'browser-results.json'), JSON.stringify({ checks, errors, url }, null, 2));
}
assert.deepEqual(errors, []);
console.log(JSON.stringify({ checks, errors }));
await Promise.all([draftContext.close(), mobileContext.close(), signedOutContext.close()]);
await Promise.all([mobileContext.close(), signedOutContext.close()]);
}
} catch (error) {
if (artifactDir) {
const pages = browser.contexts().flatMap((context) => context.pages());
for (const [index, page] of pages.entries()) {
await page.screenshot({ path: resolve(artifactDir, `failure-${index}.png`) }).catch(() => {});
console.error(JSON.stringify(await page.evaluate(() => ({ url: location.href,
main: document.querySelector('#cad-main')?.innerText,
notice: document.querySelector('#cad-notice')?.innerText, errors: window.__cadTestErrors, engine: !!window.vibemakeCad })).catch(() => ({ url: page.url() }))));
}
}
throw error;
} finally {
await browser.close();
}
+27 -2
View File
@@ -3,23 +3,32 @@ import assert from 'node:assert/strict';
import 'fake-indexeddb/auto';
import { DraftStore } from '../../js/cad/drafts.js';
test('drafts stay partitioned and acknowledgement clears only the matching saved baseline', async () => {
test('acknowledgement clears covered drafts while preserving later changes and other bindings', async () => {
const store = new DraftStore(indexedDB), bytes = new Uint8Array([1, 2, 3]);
const baseline = { binding: 'binding-a', revision: '7:visible' };
await store.put('user-a', 'project-a', 'tab-a', 'draft', { snapshotId: 'draft-s7', bytes, baseVersion: 3, ...baseline });
await store.put('user-a', 'project-a', 'tab-a', 'draft', { snapshotId: 'draft-s8', bytes, baseVersion: 3, binding: baseline.binding, revision: '8:visible' });
await store.put('user-a', 'project-a', 'older-tab', 'draft', { snapshotId: 'draft-s6', bytes, baseVersion: 3, binding: baseline.binding, revision: '6:visible' });
await store.put('user-a', 'project-a', 'visibility-tab', 'draft', { snapshotId: 'changed-visibility', bytes, binding: baseline.binding, revision: '7:other' });
await store.put('user-a', 'project-a', 'other-binding-tab', 'draft', { snapshotId: 'other-binding', bytes, binding: 'binding-b', revision: '1:visible' });
await store.put('user-a', 'project-a', 'covered-tab', 'draft', { snapshotId: 'covered', bytes, ...baseline });
await store.put('user-b', 'project-a', 'tab-a', 'draft', { snapshotId: 'other-user', bytes, baseVersion: 3, ...baseline });
await store.put('user-a', 'project-b', 'tab-a', 'draft', { snapshotId: 'other-project', bytes, baseVersion: 3, ...baseline });
await store.put('user-a', 'project-a', 'tab-a', 'operation', { snapshotId: 'op-s7', bytes, baseVersion: 3 });
await store.clearAcknowledged('user-a', 'project-a', 'op-s7', baseline);
// A snapshot started before ACK may finish its IndexedDB write afterwards.
await store.put('user-a', 'project-a', 'late-write', 'draft', { snapshotId: 'late-covered', bytes, binding: baseline.binding, revision: '6:visible' });
const drafts = await store.list('user-a', 'project-a', 'draft');
assert.deepEqual(drafts.map((draft) => draft.snapshotId), ['draft-s8']);
assert.deepEqual(new Set(drafts.map((draft) => draft.snapshotId)), new Set(['draft-s8', 'changed-visibility', 'other-binding']));
assert.deepEqual(new Uint8Array(drafts[0].bytes), bytes);
assert.equal((await store.list('user-b', 'project-a', 'draft')).length, 1);
assert.equal((await store.list('user-a', 'project-b', 'draft')).length, 1);
assert.equal((await store.list('user-a', 'project-a', 'operation')).length, 0);
await store.put('user-a', 'project-a', 'unknown-revision', 'draft', { snapshotId: 'unknown', bytes, binding: baseline.binding });
await store.clearAcknowledged('user-a', 'project-a', 'no-match', { binding: baseline.binding });
assert.ok((await store.list('user-a', 'project-a', 'draft')).some((draft) => draft.snapshotId === 'unknown'));
(await store.database()).close();
await new Promise((resolve, reject) => {
@@ -27,3 +36,19 @@ test('drafts stay partitioned and acknowledgement clears only the matching saved
request.onsuccess = resolve; request.onerror = () => reject(request.error);
});
});
test('restored draft binding is updated only if its snapshot has not changed', async () => {
const store = new DraftStore(indexedDB), bytes = new Uint8Array([1]);
const key = store.key('user', 'project', 'source-tab', 'draft');
await store.put('user', 'project', 'source-tab', 'draft', { snapshotId: 'original', bytes, binding: 'old', revision: '99:old' });
await store.rebindDraft(key, 'original', { binding: 'new', revision: '2:visible' });
assert.equal((await store.list('user', 'project', 'draft'))[0].binding, 'new');
await store.put('user', 'project', 'source-tab', 'draft', { snapshotId: 'later', bytes, binding: 'other', revision: '3:visible' });
await store.rebindDraft(key, 'original', { binding: 'new', revision: '2:visible' });
assert.equal((await store.list('user', 'project', 'draft'))[0].binding, 'other');
(await store.database()).close();
await new Promise((resolve, reject) => {
const request = indexedDB.deleteDatabase('vm.cad');
request.onsuccess = resolve; request.onerror = () => reject(request.error);
});
});
+176
View File
@@ -0,0 +1,176 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { chromium } from 'playwright';
import { cadWorker } from '../../scripts/cad-engine.mjs';
const root = new URL('../../', import.meta.url);
const html = `<!doctype html><button hidden>Refresh</button><script type="module">
import { loadEngine, prepareEngineRefresh } from '/js/cad/engine.js';
window.notices = 0;
window.manifestChecks = 0;
const nativeFetch = window.fetch;
window.fetch = async (...args) => {
const response = await nativeFetch(...args);
if (args[0] === '/cad/engine.json') {
const json = response.json.bind(response);
response.json = async () => { const value = await json(); window.manifestChecks++; return value; };
}
return response;
};
const button = document.querySelector('button');
addEventListener('vm:cad:update', () => { window.notices++; button.hidden = false; });
button.onclick = async () => {
button.disabled = true;
try { await prepareEngineRefresh(); location.reload(); }
catch { window.refreshFailed = true; button.disabled = false; }
};
await loadEngine(); window.engineReady = true;
</script>`;
// Exact lifecycle behaviour of packages shipped before explicit activation existed.
const legacyWorker = (manifest) => `
const FILES=new Set(${JSON.stringify(manifest.files.map((f) => f.path))});
const CACHE='vm.cad.static.${manifest.buildId}';
self.addEventListener('install',()=>{});
self.addEventListener('activate',()=>{});
self.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;})());});
`;
test('CAD engine updates complete without clearing browser data', async (t) => {
let buildId = 'v1', legacy = false, workerUnavailable = false;
const manifest = () => ({
bridgeVersion: 1, buildId,
js: `/cad/_assets/${buildId}/engine.js`, wasm: `/cad/_assets/${buildId}/engine.wasm`, chineseFont: `/cad/_assets/${buildId}/font.otf`,
files: ['engine.js', 'engine.wasm', 'font.otf'].map((name) => ({ path: `/cad/_assets/${buildId}/${name}` })),
});
const server = createServer(async (req, res) => {
const path = new URL(req.url, 'http://localhost').pathname;
res.setHeader('Cache-Control', 'no-store');
if (path === '/cad/editor/') res.writeHead(200, { 'Content-Type': 'text/html' }).end(html);
else if (path === '/cad/seed/') res.writeHead(200, { 'Content-Type': 'text/html' }).end('<!doctype html><title>Previous editor</title>');
else if (path === '/cad/worker.js') res.writeHead(workerUnavailable ? 503 : 200, { 'Content-Type': 'text/javascript' }).end(await readFile(new URL('cad/worker.js', root)));
else if (path === '/cad/engine.json') res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(manifest()));
else if (path === '/cad/sw.js') res.writeHead(workerUnavailable ? 503 : 200, { 'Content-Type': 'text/javascript' }).end(legacy ? legacyWorker(manifest()) : cadWorker(manifest()));
else if (path === '/other/sw.js') res.writeHead(200, { 'Content-Type': 'text/javascript' }).end("self.addEventListener('install',()=>{});");
else if (/^\/cad\/_assets\/[^/]+\/engine.js$/.test(path)) {
const version = path.split('/')[3];
res.writeHead(200, { 'Content-Type': 'text/javascript' }).end(`export default async function() { window.engineBuild=${JSON.stringify(version)}; window.vibemakeCad={ready:async()=>({})}; }`);
} else if (path.startsWith('/cad/_assets/')) res.writeHead(200).end('asset');
else if (path.startsWith('/js/')) {
try { res.writeHead(200, { 'Content-Type': 'text/javascript' }).end(await readFile(new URL(path.slice(1), root))); }
catch { res.writeHead(404).end(); }
} else res.writeHead(404).end();
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({ headless: true });
t.after(async () => { await browser.close(); server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); });
const loaded = (page, expected) => page.waitForFunction((version) => window.engineReady && window.engineBuild === version, expected);
const open = async (context) => {
const page = await context.newPage();
await page.goto(`${base}/cad/editor/`);
await loaded(page, buildId);
await page.evaluate(() => navigator.serviceWorker.ready);
await page.reload();
await loaded(page, buildId);
await page.waitForFunction(() => !!navigator.serviceWorker.controller);
return page;
};
const publish = async (page) => {
await page.evaluate(async () => { await (await navigator.serviceWorker.getRegistration('/cad/')).update(); });
await page.waitForFunction(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting);
};
const preserveData = async (page) => page.evaluate(async () => {
localStorage.setItem('vm.auth', 'preserved-login');
const { DraftStore } = await import('/js/cad/drafts.js');
const store = new DraftStore();
await store.put('owner', 'project', 'session', 'draft', { snapshotId: 'keep-draft', bytes: new Uint8Array([1, 2, 3]) });
await (await caches.open('unrelated-cache')).put('/keep', new Response('keep'));
await navigator.serviceWorker.register('/other/sw.js', { scope: '/other/' });
});
const assertData = async (page) => {
const data = await page.evaluate(async () => {
const { DraftStore } = await import('/js/cad/drafts.js');
const drafts = await new DraftStore().list('owner', 'project', 'draft');
return { auth: localStorage.getItem('vm.auth'), draft: [...drafts[0].bytes], cache: await (await caches.match('/keep')).text(), otherWorker: !!await navigator.serviceWorker.getRegistration('/other/') };
});
assert.deepEqual(data, { auth: 'preserved-login', draft: [1, 2, 3], cache: 'keep', otherWorker: true });
};
await t.test('activates the new worker before refresh and leaves other editor tabs intact', async () => {
buildId = 'v1'; legacy = false;
const context = await browser.newContext();
try {
const first = await open(context), second = await open(context);
await second.evaluate(() => { window.unsavedDesign = 'keep editing'; });
await preserveData(first);
buildId = 'v2';
await publish(first);
await first.waitForFunction(() => window.notices === 1);
assert.equal(await first.evaluate(() => window.engineBuild), 'v1');
await first.getByRole('button', { name: 'Refresh' }).click();
await loaded(first, 'v2');
assert.equal(await first.evaluate(() => window.notices), 0);
assert.equal(await first.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting), false);
assert.deepEqual(await second.evaluate(() => ({ build: window.engineBuild, design: window.unsavedDesign })), { build: 'v1', design: 'keep editing' });
await assertData(first);
await first.reload(); await loaded(first, 'v2');
assert.equal(await first.evaluate(() => window.notices), 0);
} finally { await context.close(); }
});
await t.test('recovers from a legacy waiting worker without clearing auth, drafts or other scopes', async () => {
buildId = 'legacy-v1'; legacy = true;
const context = await browser.newContext();
try {
const previous = await context.newPage();
await previous.goto(`${base}/cad/seed/`);
await previous.evaluate(async () => {
await navigator.serviceWorker.register('/cad/sw.js', { scope: '/cad/', updateViaCache: 'none' });
await navigator.serviceWorker.ready;
});
const page = await open(context), other = await open(context);
await preserveData(page);
buildId = 'legacy-v2'; await publish(page);
await page.waitForFunction(() => window.notices === 1);
await page.getByRole('button', { name: 'Refresh' }).click();
await loaded(page, 'legacy-v2');
await page.evaluate(() => navigator.serviceWorker.ready);
assert.equal(await page.evaluate(() => window.notices), 0);
assert.equal(await page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting), false);
assert.equal(await other.evaluate(() => window.engineBuild), 'legacy-v1');
await assertData(page);
} finally { await context.close(); }
});
await t.test('a fresh engine does not show an update merely because a cache worker is waiting', async () => {
buildId = 'same-v1'; legacy = true;
const context = await browser.newContext();
try {
const page = await open(context), other = await open(context);
buildId = 'same-v2'; await publish(page);
await page.reload(); await loaded(page, 'same-v2');
await page.waitForFunction(() => window.manifestChecks === 2);
assert.equal(await page.evaluate(() => window.notices), 0);
assert.equal(await page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting), true);
assert.equal(await other.evaluate(() => window.engineBuild), 'same-v1');
} finally { await context.close(); }
});
await t.test('failed worker checks keep the editor open for retry', async () => {
buildId = 'offline-v1'; legacy = false;
const context = await browser.newContext();
try {
const page = await open(context);
buildId = 'offline-v2'; await publish(page);
await page.waitForFunction(() => window.notices === 1);
workerUnavailable = true;
await page.getByRole('button', { name: 'Refresh' }).click();
await page.waitForFunction(() => window.refreshFailed);
assert.equal(await page.evaluate(() => window.engineBuild), 'offline-v1');
assert.equal(await page.getByRole('button', { name: 'Refresh' }).isEnabled(), true);
} finally { workerUnavailable = false; await context.close(); }
});
});
+108
View File
@@ -0,0 +1,108 @@
ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('step-conformance generated part'),'2;1');
FILE_NAME('cylinder_twice.step','2026-10-12T00:00:00',(''),(''),'step-conformance generate','step-conformance generate','');
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
ENDSEC;
DATA;
#1=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );
#2=( NAMED_UNIT(*) PLANE_ANGLE_UNIT() SI_UNIT($,.RADIAN.) );
#3=( NAMED_UNIT(*) SI_UNIT($,.STERADIAN.) SOLID_ANGLE_UNIT() );
#4=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-7),#1,'distance_accuracy_value','confusion accuracy');
#5=( GEOMETRIC_REPRESENTATION_CONTEXT(3) GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#4)) GLOBAL_UNIT_ASSIGNED_CONTEXT((#1,#2,#3)) REPRESENTATION_CONTEXT('','3D') );
#6=APPLICATION_CONTEXT('automotive design');
#7=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#6);
#8=PRODUCT_CONTEXT('',#6,'mechanical');
#9=PRODUCT_DEFINITION_CONTEXT('part definition',#6,'design');
#10=PRODUCT('cylinder_twice assembly','cylinder_twice assembly','',(#8));
#11=PRODUCT_DEFINITION_FORMATION('','',#10);
#12=PRODUCT_DEFINITION('design','',#11,#9);
#13=PRODUCT_DEFINITION_SHAPE('','',#12);
#14=APPLICATION_CONTEXT('automotive design');
#15=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#14);
#16=PRODUCT_CONTEXT('',#14,'mechanical');
#17=PRODUCT_DEFINITION_CONTEXT('part definition',#14,'design');
#18=PRODUCT('cylinder_twice','cylinder_twice','',(#16));
#19=PRODUCT_DEFINITION_FORMATION('','',#18);
#20=PRODUCT_DEFINITION('design','',#19,#17);
#21=PRODUCT_DEFINITION_SHAPE('','',#20);
#22=CARTESIAN_POINT('',(0.0,0.0,0.0));
#23=DIRECTION('',(0.0,0.0,1.0));
#24=DIRECTION('',(1.0,0.0,0.0));
#25=AXIS2_PLACEMENT_3D('',#22,#23,#24);
#26=CARTESIAN_POINT('',(0.0,0.0,0.0));
#27=DIRECTION('',(0.0,0.0,1.0));
#28=DIRECTION('',(1.0,0.0,0.0));
#29=AXIS2_PLACEMENT_3D('',#26,#27,#28);
#30=CIRCLE('',#29,10.0);
#31=CARTESIAN_POINT('',(10.0,0.0,0.0));
#32=VERTEX_POINT('',#31);
#33=EDGE_CURVE('',#32,#32,#30,.T.);
#34=CARTESIAN_POINT('',(0.0,0.0,30.0));
#35=DIRECTION('',(0.0,0.0,1.0));
#36=DIRECTION('',(1.0,0.0,0.0));
#37=AXIS2_PLACEMENT_3D('',#34,#35,#36);
#38=CIRCLE('',#37,10.0);
#39=CARTESIAN_POINT('',(10.0,0.0,30.0));
#40=VERTEX_POINT('',#39);
#41=EDGE_CURVE('',#40,#40,#38,.T.);
#42=CARTESIAN_POINT('',(0.0,0.0,0.0));
#43=DIRECTION('',(0.0,0.0,1.0));
#44=DIRECTION('',(1.0,0.0,0.0));
#45=AXIS2_PLACEMENT_3D('',#42,#43,#44);
#46=PLANE('',#45);
#47=ORIENTED_EDGE('',*,*,#33,.F.);
#48=EDGE_LOOP('',(#47));
#49=FACE_OUTER_BOUND('',#48,.T.);
#50=ADVANCED_FACE('',(#49),#46,.F.);
#51=CARTESIAN_POINT('',(0.0,0.0,0.0));
#52=DIRECTION('',(0.0,0.0,1.0));
#53=DIRECTION('',(1.0,0.0,0.0));
#54=AXIS2_PLACEMENT_3D('',#51,#52,#53);
#55=CYLINDRICAL_SURFACE('',#54,10.0);
#56=ORIENTED_EDGE('',*,*,#33,.T.);
#57=EDGE_LOOP('',(#56));
#58=ORIENTED_EDGE('',*,*,#41,.F.);
#59=EDGE_LOOP('',(#58));
#60=FACE_OUTER_BOUND('',#57,.T.);
#61=FACE_BOUND('',#59,.T.);
#62=ADVANCED_FACE('',(#60,#61),#55,.T.);
#63=CARTESIAN_POINT('',(0.0,0.0,30.0));
#64=DIRECTION('',(0.0,0.0,1.0));
#65=DIRECTION('',(1.0,0.0,0.0));
#66=AXIS2_PLACEMENT_3D('',#63,#64,#65);
#67=PLANE('',#66);
#68=ORIENTED_EDGE('',*,*,#41,.T.);
#69=EDGE_LOOP('',(#68));
#70=FACE_OUTER_BOUND('',#69,.T.);
#71=ADVANCED_FACE('',(#70),#67,.T.);
#72=CLOSED_SHELL('',(#50,#62,#71));
#73=MANIFOLD_SOLID_BREP('',#72);
#74=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#73,#25),#5);
#75=SHAPE_DEFINITION_REPRESENTATION(#21,#74);
#76=CARTESIAN_POINT('',(0.0,0.0,0.0));
#77=DIRECTION('',(0.0,0.0,1.0));
#78=DIRECTION('',(1.0,0.0,0.0));
#79=AXIS2_PLACEMENT_3D('',#76,#77,#78);
#80=CARTESIAN_POINT('',(0.0,0.0,0.0));
#81=DIRECTION('',(0.0,0.0,1.0));
#82=DIRECTION('',(1.0,0.0,0.0));
#83=AXIS2_PLACEMENT_3D('',#80,#81,#82);
#84=CARTESIAN_POINT('',(60.0,0.0,10.0));
#85=DIRECTION('',(1.0,0.0,0.0));
#86=DIRECTION('',(0.0,1.0,0.0));
#87=AXIS2_PLACEMENT_3D('',#84,#85,#86);
#88=SHAPE_REPRESENTATION('',(#79,#83,#87),#5);
#89=SHAPE_DEFINITION_REPRESENTATION(#13,#88);
#90=NEXT_ASSEMBLY_USAGE_OCCURRENCE('1','cylinder_twice','',#12,#20,$);
#91=PRODUCT_DEFINITION_SHAPE('','',#90);
#92=ITEM_DEFINED_TRANSFORMATION('','',#25,#83);
#93=( REPRESENTATION_RELATIONSHIP('','',#74,#88) REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#92) SHAPE_REPRESENTATION_RELATIONSHIP() );
#94=CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#93,#91);
#95=NEXT_ASSEMBLY_USAGE_OCCURRENCE('2','cylinder_twice','',#12,#20,$);
#96=PRODUCT_DEFINITION_SHAPE('','',#95);
#97=ITEM_DEFINED_TRANSFORMATION('','',#25,#87);
#98=( REPRESENTATION_RELATIONSHIP('','',#74,#88) REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#97) SHAPE_REPRESENTATION_RELATIONSHIP() );
#99=CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#98,#96);
ENDSEC;
END-ISO-10303-21;
+39
View File
@@ -1,8 +1,11 @@
import http from 'node:http';
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { assistantModel } from './assistant-model.mjs';
const projects = new Map(), uploads = new Map(), objects = new Map();
const workspaces = new Map();
const stepBytes = readFileSync(new URL('./fixtures/assembly.step', import.meta.url));
const owner = 'cad-browser-test-user', token = 'cad-browser-test-token';
const json = (res, data, status = 200, code = 'OK') => {
res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
@@ -17,6 +20,8 @@ const timestamp = () => new Date().toISOString();
function projectData(project) {
return {
cadProjectCode: project.cadProjectCode,
workspaceProjectCode: project.workspaceProjectCode || null,
initialStep: project.initialStep || null,
name: project.name,
description: project.description,
coverUrl: project.coverUrl || null,
@@ -92,6 +97,40 @@ const server = http.createServer(async (req, res) => {
}
if (req.headers.authorization !== 'Bearer ' + token) return json(res, null, 401, 'UNAUTHORIZED');
if (url.pathname === '/project-types') return json(res, [{ code: 'robot', name: 'Robot' }]);
// Test-only workspace seeding. Immutable source bytes outlive workspace changes/deletion.
if (url.pathname === '/cad/mock-workspace' && req.method === 'POST') {
const input = JSON.parse(body || '{}'), projectCode = 'fork-' + randomUUID(), key = 'step-' + randomUUID();
objects.set(key, input.invalidStep ? Buffer.from('not a STEP') : stepBytes);
const source = { downloadUrl: '/api/cad/mock-source/' + key, fileName: input.fileName || '装配.STP', sizeBytes: objects.get(key).length };
const workspace = { projectCode, name: input.name || 'Forked assembly', description: 'STEP source', projectType: 'robot',
repoStatus: input.repoStatus || 'READY', publishStatus: 'UNPUBLISHED', sourceProjectCode: 'upstream-project', stepMainUrl: source.downloadUrl, initialStep: source };
workspaces.set(projectCode, workspace); return json(res, workspace);
}
const workspaceMatch = url.pathname.match(/^\/workspace\/projects\/([^/]+)(?:\/(.*))?$/);
if (workspaceMatch) {
const workspace = workspaces.get(decodeURIComponent(workspaceMatch[1])), tail = workspaceMatch[2];
if (!workspace || workspace.deleted) return json(res, null, 404, 'NOT_FOUND');
if (!tail) {
if (req.method === 'DELETE') { workspace.deleted = true; return json(res, null); }
if (req.method === 'PATCH') Object.assign(workspace, JSON.parse(body));
return json(res, workspace);
}
if (tail === 'cad-project' && req.method === 'POST') {
if (body.length) return json(res, null, 400, 'BAD_REQUEST');
if (workspace.repoStatus !== 'READY') return json(res, null, 409, 'CONFLICT');
let project = [...projects.values()].find((p) => !p.deleted && p.workspaceProjectCode === workspace.projectCode);
if (!project) {
if (!workspace.stepMainUrl) return json(res, null, 409, 'PROJECT_STEP_NOT_FOUND');
project = createProject(workspace.name, workspace.description);
project.workspaceProjectCode = workspace.projectCode; project.initialStep = { ...workspace.initialStep };
}
return json(res, projectData(project));
}
if (tail === 'tree') return json(res, { commitSha: 'mock-head', path: '', entries: [] });
if (tail === 'commits') return json(res, { items: [], total: 0, page: 1, size: 20 });
return json(res, null, 404, 'NOT_FOUND');
}
if (url.pathname === '/uploads/project-covers/signature' && req.method === 'POST') {
const input = JSON.parse(body);
if (!['image/png', 'image/jpeg', 'image/webp'].includes(input.contentType) || !Number.isSafeInteger(input.fileSize)
+24 -4
View File
@@ -146,6 +146,8 @@ async function run(browser) {
// Real browser IME events: the hidden text bridge must retain its native caret after
// each commit, while the visible egui editor still supports insertion in the middle.
await page.bringToFront();
await page.waitForFunction(() => document.hasFocus());
await clickHandle(page, 'agent_chat:input');
await page.keyboard.type('vm-test:read ', { delay: 35 });
const cdp = await context.newCDPSession(page);
@@ -161,14 +163,31 @@ async function run(browser) {
await page.keyboard.press('End');
await page.keyboard.press('Shift+Enter');
await page.keyboard.type('ok', { delay: 50 });
// Let egui consume the browser text event before sending the next key.
await page.waitForTimeout(150);
await page.keyboard.press('Backspace');
await page.waitForTimeout(150);
// Wait for actual engine frames; software rendering can exceed a fixed delay.
const flushInput = () => page.evaluate(async () => {
for (let frame = 0; frame < 2; frame++) await window.solidcraft.request('ui.handles', { prefix: 'agent_chat:input' });
});
await flushInput();
await page.waitForFunction(() => {
const input = document.activeElement;
return input instanceof HTMLInputElement && input.value.endsWith('ok')
&& input.selectionStart === input.value.length && input.selectionEnd === input.value.length;
});
// Release only after the engine consumes key-down; software rendering can
// take longer than a fixed key-press duration when several editors are open.
await page.keyboard.down('Backspace');
await flushInput();
await page.keyboard.up('Backspace');
await page.waitForFunction(() => document.activeElement instanceof HTMLInputElement && document.activeElement.value === '');
await flushInput();
await page.keyboard.press('Enter');
await until(page, (state) => !state.turn && state.items.some((item) => item.user), 'typed prompt did not finish');
assert.equal((await chat(page)).items.find((item) => item.user).user, 'vm-test:read 你好X世界\no');
checks.push('chinese-ime-commits-preserve-order-and-middle-editing-newlines-and-backspace');
if (process.env.VM_CAD_AGENT_BROWSER_SUITE === 'input') {
assert.deepEqual(errors, []);
return { checks, errors, url: page.url() };
}
await chat(page, { new_chat: true });
const empty = await inspect(page);
@@ -531,6 +550,7 @@ async function run(browser) {
const waiting = await chat(page);
assert.ok(waiting.turn, 'reaching the rate limit must wait instead of ending the turn');
const pacedCalls = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat'
&& call.body.cadProjectCode === pacedProject.data.cadProjectCode
&& call.body.history.some((item) => item.content?.some((part) => part.text?.includes('paced-cancel'))));
assert.equal(pacedCalls.length, 1, 'no continuation may be sent above the rate limit');
await chat(page, { cancel: true });