diff --git a/README.md b/README.md index 51886b0..9691011 100644 --- a/README.md +++ b/README.md @@ -50,14 +50,16 @@ npm run build:walking ```bash cd ~/vibemake-site node scripts/server.mjs -# http://localhost:8090 后端接口数据(/api 转发到 dev 后端;线上也用这个服务器,按域名自动选 dev / 正式后端) -# http://127.0.0.1:8090 本地演示数据(最早的完整样子,作参考) +# http://localhost:8091 后端接口数据(/api 转发到 dev 后端;线上也用这个服务器,按域名自动选 dev / 正式后端) +# http://127.0.0.1:8091 本地演示数据(最早的完整样子,作参考) +# /pcb/ 同源代理到相邻的 ziro-designer-main/designer,默认使用真实后端,无需手动打开 5173 端口 +# PCB_API_MODE=mock node scripts/server.mjs 显式启用开发模拟(独立存储,不共用主站账号) ``` -手机与电脑连接同一 Wi-Fi 后,用 `http://<电脑局域网 IP>:8090` 访问。本地 / 局域网下,社区 URDF、网格和贴图统一通过 `/__model_assets/` 同源读取,避免 OSS 仅允许 localhost 跨域时手机加载失败。代理仅允许 linkerbot bucket 的 URDF、experiences 与 project-resources 数据资源目录,保留缓存与流式传输,不修改模型文件;线上域名继续使用原 OSS 地址。回归检查:`node --test scripts/model-assets.test.mjs`。 +手机与电脑连接同一 Wi-Fi 后,用 `http://<电脑局域网 IP>:8091` 访问。本地 / 局域网下,社区 URDF、网格和贴图统一通过 `/__model_assets/` 同源读取,避免 OSS 仅允许 localhost 跨域时手机加载失败。代理仅允许 linkerbot bucket 的 URDF、experiences 与 project-resources 数据资源目录,保留缓存与流式传输,不修改模型文件;线上域名继续使用原 OSS 地址。回归检查:`node --test scripts/model-assets.test.mjs`。 -页面路由(不带 .html):`/`、`/explore`、`/studio?robot=`、`/cad`、`/pcb`、`/project/<编号>`、`/workspace`、`/workspace/<编号>`;旧的 `xxx.html` 地址会 301 跳到新地址。`/cad` 和 `/pcb` 分别全屏嵌入 `https://cadworld-studio.robotquan.com/cad` 与 `https://cadworld-studio.robotquan.com/pcb`。 -CAD / PCB 仅电脑端开放:手机、平板及 820px 以下(含)的窄屏隐藏导航、菜单与页脚入口,直接访问时用 `location.replace('/')` 返回首页;通过检测后才加载编辑器 iframe。手机横屏仍按移动设备处理。 +页面路由(不带 .html):`/`、`/explore`、`/studio?robot=`、`/cad`、`/pcb`、`/project/<编号>`、`/workspace`、`/workspace/<编号>`;旧的 `xxx.html` 地址会 301 跳到新地址。`/cad` 继续复用独立 CAD 部署;`/pcb/` 由独立 PCB 前端应用在主站同源提供,不再嵌入旧 PCB iframe。 +CAD / PCB 仅电脑端开放:手机、平板及 820px 以下(含)的窄屏隐藏主站导航入口。CAD 仍由主站的桌面检测保护;PCB 前端自行显示电脑端提示。手机横屏仍按移动设备处理。 线上部署使用构建后的静态文件,不需要启动 Node 服务;具体配置见 dist/DEPLOY.md。 ## 目录 @@ -165,17 +167,23 @@ robots/demo-*/ 早期用基础几何体生成的演示 URDF(已不在 ```bash npm install # 第一次打包前装一次(只是打包工具:模型压缩) -npm run build # 构建行走演示并生成 dist/ 和 dist.zip;STL 网格会转成 Draco 压缩的 GLB(47 MB → 3 MB) -npm run build:dev # 生成 dist/ 和 dist-dev.zip,固定 dev 接口并禁用本地演示数据模式 +pnpm -C ../ziro-designer-main/designer build # 独立构建 PCB 应用 +npm run build # 收录相邻 PCB designer/dist,构建主站并生成 dist.zip +npm run build:dev # 同样收录 PCB 应用,生成固定 dev 接口的 dist-dev.zip +PCB_DIST=/path/to/designer/dist node scripts/build.mjs # PCB 仓库不在默认相邻目录时指定构建产物 SITE_ROOT=dist PORT=8093 node scripts/server.mjs # 本地预览打包结果 ``` -dist 里附带 `nginx.conf.example`(/api 转发、页面路由、缓存、gzip)和 `DEPLOY.md`。 +两套源代码和构建仍独立;网站打包时将 PCB 的 Vite 静态产物复制到 `dist/pcb/`。线上服务器需将无扩展名 PCB 工程地址回退到 `/pcb/index.html`,静态资源则按原路径返回。部署检查见 `dist/DEPLOY.md`。 + +CAD 平台助手的容量、截图、超时和请求频率读取 `/api/cad/ai/capabilities` 的实际 `limits`,缺失或为 0 的字段不增加前端业务上限。每次续调都会向模型补充当前限额、已用容量和剩余图片数;图片自动缩小并重新编码,过大的工具文字结果返回明确错误,要求缩小查询,禁止将残缺 JSON 当成结果或重做已执行修改。旧历史只按完整用户轮次裁剪。按照复杂建模需求,当前前端继续取消单轮 12 次模型调用和 24 条修改的限制;这些整轮限额若要恢复,需要前后端先统一产品配置。 + +`/api/cad/ai/chat` 必须按 SSE 透传:禁止缓存,Nginx 设置 `proxy_buffering off`、`proxy_cache off`,网关、负载均衡及代理的请求/读取超时至少 90 秒,覆盖当前 60 秒模型请求超时。4 MiB JSON 配额只配置在 chat 路径;实例并发数、Redis 用户限流、断连取消和日志脱敏由后端保证,浏览器排队不能代替服务端限制。 ## 接入后端(Community API) ```bash -node scripts/server.mjs # http://localhost:8090,/api 代理到 https://dev-vibemake-api.robotquan.com +node scripts/server.mjs # http://localhost:8091,/api 代理到 https://dev-vibemake-api.robotquan.com API_TARGET=http://localhost:8993 node scripts/server.mjs # 换成本机后端 ``` diff --git a/css/cad.css b/css/cad.css index 250ff4e..2a5b8e6 100644 --- a/css/cad.css +++ b/css/cad.css @@ -10,6 +10,8 @@ @media(prefers-reduced-motion:reduce){.cad-page *{scroll-behavior:auto!important;transition:none!important;animation-duration:.01ms!important}} .cad-page .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .cad-page .cad-card{border-radius:8px} +.cad-card-art img{display:block;width:100%;height:100%;min-height:0;object-fit:contain} +.cad-editor .cad-save-state[data-state=coverFailed],.cad-editor .cad-save-state[data-state=coverUnavailable]{color:#ffb870} .cad-eyebrow{letter-spacing:0} .cad-editor .nav{position:fixed;inset:0 0 auto;height:var(--nav)} .cad-editor .nav-inner{height:100%} @@ -25,3 +27,25 @@ .cad-editor .cad-blocker{inset:var(--nav) 0 0} @media(max-width:1100px){.cad-editor .cad-save-state{max-width:130px}} .cad-page .nav .btn{min-height:34px} +.cad-editor{--nav:42px} +.cad-editor .nav-inner{width:100%;max-width:none;margin:0;padding:0 12px;gap:12px} +.cad-editor .nav-logo{min-height:0} +.cad-editor .nav-logo img{width:92px;height:34px} +.cad-appbar-left{display:flex;align-items:center;gap:2px;flex:0 0 auto} +.cad-appbar-divider{height:24px;border-left:1px solid var(--border);margin:0 6px 0 2px} +.cad-appbar-left .cad-engine-menus{margin-right:0} +.cad-editor .cad-engine-menus button{padding:4px 9px;border-radius:3px} +.cad-editor .cad-engine-menus button:hover{background:rgba(255,255,255,.06)} +.cad-appbar-icon{width:32px!important;height:32px!important;flex:0 0 32px;border-radius:3px!important} +.cad-appbar-icon:hover{background:rgba(255,255,255,.08)} +.cad-appbar-icon:disabled{opacity:.35;cursor:default} +.cad-appbar-icon:disabled:hover{background:transparent} +.cad-editor .cad-editor-utility{display:flex;align-items:center;gap:2px;margin-right:0} +.cad-editor .cad-editor-utility button{padding:0} +.cad-editor .nav-actions{gap:8px;margin-left:auto} +.cad-editor .nav-actions .cad-editor-utility{margin-right:8px} +.cad-editor .cad-engine-menus button:focus-visible,.cad-editor .cad-appbar-icon:focus-visible{outline:2px solid var(--accent);outline-offset:2px} +.cad-editor.cad-full-height .cad-viewport{inset:0} +.cad-editor.cad-full-height .nav{right:var(--cad-assistant-width,0%);width:auto;background:var(--cad-bg2);border-bottom:1px solid var(--cad-border);backdrop-filter:none;container-type:inline-size} +@container(max-width:680px){.cad-editor.cad-full-height .cad-save-state{display:none}.cad-editor.cad-full-height .nav-inner{gap:6px}.cad-editor.cad-full-height .nav-actions{gap:4px}.cad-editor.cad-full-height .nav-actions .cad-editor-utility{margin-right:0}} +@container(max-width:520px){.cad-editor.cad-full-height .nav-logo img{width:72px}.cad-editor.cad-full-height .cad-appbar-divider{margin:0 2px}.cad-editor.cad-full-height [data-engine-menu="assistant"]{display:none}.cad-editor.cad-full-height .nav-user{width:36px;padding:0;justify-content:center}.cad-editor.cad-full-height .nav-user>span:not(.avatar){display:none}} diff --git a/js/cad/agent-rate-limit.js b/js/cad/agent-rate-limit.js new file mode 100644 index 0000000..7af7cab --- /dev/null +++ b/js/cad/agent-rate-limit.js @@ -0,0 +1,88 @@ +// Account-wide transport pacing, including tool continuations and newly opened documents. +const WINDOW_MS = 60_500; + +function delay(ms, signal) { + signal?.throwIfAborted(); + return new Promise((resolve, reject) => { + const finish = () => { signal?.removeEventListener('abort', abort); resolve(); }; + const timer = setTimeout(finish, ms); + const abort = () => { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + reject(signal.reason); + }; + signal?.addEventListener('abort', abort, { once: true }); + }); +} + +export class CadAgentRateLimiter { + constructor({ now = Date.now, sleep = delay, storage, locks = globalThis.navigator?.locks } = {}) { + this.now = now; + this.sleep = sleep; + this.locks = locks; + this.memory = new Map(); + try { this.storage = storage ?? globalThis.localStorage; } catch { this.storage = null; } + } + + read(key, now) { + let state = this.memory.get(key); + if (this.storage) { + try { state = JSON.parse(this.storage.getItem(key) || 'null'); } catch (error) { + if (error instanceof SyntaxError) state = null; + else this.storage = null; + } + } + const sent = Array.isArray(state?.sent) ? state.sent.filter((time) => Number.isFinite(time) + && time > now - WINDOW_MS && time <= now + WINDOW_MS).sort((a, b) => a - b) : []; + return { sent, blockedUntil: Number.isFinite(state?.blockedUntil) ? state.blockedUntil : 0 }; + } + + write(key, state) { + this.memory.set(key, state); + try { this.storage?.setItem(key, JSON.stringify(state)); } catch { this.storage = null; } + } + + locked(key, signal, action) { + signal?.throwIfAborted(); + return this.locks?.request + ? this.locks.request(key, signal ? { signal } : {}, action) + : Promise.resolve().then(action); + } + + async run(key, limit, send, signal, assertIdentity) { + limit = Number.isSafeInteger(limit) && limit > 0 ? limit : 0; + // A small margin keeps requests away from the backend's minute boundary. + const interval = limit ? Math.ceil(60_000 / limit) + 50 : 0; + for (;;) { + const slot = await this.locked(key, signal, () => { + signal?.throwIfAborted(); + assertIdentity(); + const now = this.now(), state = this.read(key, now); + const next = Math.max(state.blockedUntil, limit ? (state.sent.at(-1) ?? -Infinity) + interval : 0, + limit && state.sent.length >= limit ? state.sent[state.sent.length - limit] + WINDOW_MS : 0); + if (next > now) return { wait: next - now }; + state.sent.push(now); + this.write(key, state); + // Start fetch while holding the short storage lock; never hold it over the network. + return { response: send() }; + }); + if (slot.response) return slot.response; + await this.sleep(Math.min(slot.wait, 1000), signal); + } + } + + async defer(key, retryAfter) { + const now = this.now(); + const seconds = retryAfter?.trim() ? Number(retryAfter) : NaN; + const date = Date.parse(retryAfter); + const until = Number.isFinite(seconds) && seconds >= 0 ? now + seconds * 1000 + : Number.isFinite(date) ? date : now + WINDOW_MS; + await this.locked(key, null, () => { + const state = this.read(key, this.now()); + state.blockedUntil = Math.max(state.blockedUntil, until + 50); + this.write(key, state); + }); + } +} + +export const cadAgentRateLimiter = new CadAgentRateLimiter(); diff --git a/js/cad/api.js b/js/cad/api.js index 0afb77a..f7f539b 100644 --- a/js/cad/api.js +++ b/js/cad/api.js @@ -1,11 +1,22 @@ import { auth, API_BASE, ApiError } from '../api.js'; import { locale } from './i18n.js'; +import { cadAgentRateLimiter } from './agent-rate-limit.js'; export { auth, ApiError }; const id = encodeURIComponent; const PROJECTS = '/cad/workspace/projects'; +const AI = '/cad/ai'; +export const MAX_COVER_BYTES = 5 * 1024 * 1024; export const userId = () => auth.user?.userCode ?? null; +export function projectCoverUrl(value) { + if (typeof value !== 'string' || !value || value.length > 2048) return null; + try { + const url = new URL(value); + return url.protocol === 'https:' && !url.username && !url.password ? url.href : null; + } catch { return null; } +} + export function cadError(code, message = code) { const error = new Error(message); error.code = code; @@ -26,6 +37,7 @@ function projectRecord(value) { if (!record || typeof record.cadProjectCode !== 'string' || !record.cadProjectCode) throw cadError('BAD_RESPONSE'); return { ...record, + coverUrl: projectCoverUrl(record.coverUrl), id: record.cadProjectCode, cadProjectCode: record.cadProjectCode, headVersion: record.version, @@ -45,11 +57,34 @@ function signatureRecord(value) { return record; } +function aiCapabilities(value) { + const limits = value?.limits ?? {}; + const tools = value?.tools; + const limitNames = [ + 'requestBytes', 'imageBytes', 'imageMaxEdge', 'imagesPerRequest', 'textBytes', + 'toolResultTextBytes', 'historyItems', + 'requestTimeoutSeconds', 'requestsPerMinute', + ]; + if (!value || typeof value.enabled !== 'boolean' || value.protocolVersion !== 'cad-agent-v1' + || typeof value.model !== 'string' || !Array.isArray(tools) || tools.length > 64 + || !limits || typeof limits !== 'object' || Array.isArray(limits) + || limitNames.some((name) => limits[name] != null && (!Number.isSafeInteger(limits[name]) || limits[name] < 0))) throw cadError('BAD_RESPONSE'); + if (value.enabled && (!value.model.trim() || !tools.length)) throw cadError('BAD_RESPONSE'); + for (const tool of tools) { + if (!tool || typeof tool.name !== 'string' || !/^[a-z][a-z0-9_]{0,63}$/.test(tool.name) + || typeof tool.description !== 'string' || !tool.parameters || typeof tool.parameters !== 'object' + || Array.isArray(tool.parameters)) throw cadError('BAD_RESPONSE'); + } + return { ...value, limits }; +} + export class CadApi { - constructor({ token = auth.token, user = userId(), fetcher = globalThis.fetch.bind(globalThis) } = {}) { + constructor({ token = auth.token, user = userId(), fetcher = globalThis.fetch.bind(globalThis), agentRateLimiter = cadAgentRateLimiter } = {}) { this.token = token; this.user = user; this.fetcher = fetcher; + this.agentRateLimiter = agentRateLimiter; + this.agentRequestsPerMinute = 0; } assertIdentity() { @@ -87,14 +122,51 @@ export class CadApi { throw error; } + async aiCapabilities(signal) { + const capabilities = aiCapabilities(await this.call(AI + '/capabilities', { signal })); + this.agentRequestsPerMinute = capabilities.limits.requestsPerMinute || 0; + return capabilities; + } + + async aiChat(body, signal, onStart) { + this.assertIdentity(); + if (!body || typeof body !== 'object' || Array.isArray(body)) throw cadError('BAD_REQUEST'); + const key = 'vm.cad.ai-rate:' + API_BASE + ':' + this.user; + const response = await this.agentRateLimiter.run(key, this.agentRequestsPerMinute, () => { + onStart?.(); + return this.fetcher(API_BASE + AI + '/chat', { + method: 'POST', + headers: { + Accept: 'text/event-stream', + Authorization: 'Bearer ' + this.token, + 'Content-Type': 'application/json', + 'Accept-Language': locale() === 'zh' ? 'zh-CN' : 'en', + }, + body: JSON.stringify(body), + cache: 'no-store', + credentials: 'omit', + redirect: 'error', + signal, + }); + }, signal, () => this.assertIdentity()); + this.assertIdentity(); + if (response.status === 401 && auth.token === this.token) auth.clear(); + if (response.status === 429) { + await this.agentRateLimiter.defer(key, response.headers.get('Retry-After')); + this.assertIdentity(); + } + return response; + } + async list({ page = 1, pageSize = 20, keyword = '' } = {}, signal) { const result = await this.call(PROJECTS, { query: { page, size: pageSize, keyword }, signal }); if (!result || !Array.isArray(result.items) || !Number.isSafeInteger(result.total)) throw cadError('BAD_RESPONSE'); return { ...result, items: result.items.map(projectRecord), page: result.page, size: result.size }; } - async create(name, description = '') { - return projectRecord(await this.call(PROJECTS, { method: 'POST', body: { name, description } })); + 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) { @@ -105,6 +177,33 @@ export class CadApi { return projectRecord(await this.call(PROJECTS + '/' + id(project), { method: 'PATCH', body: { name } })); } + async setCover(project, coverUrl) { + if (coverUrl !== '' && !projectCoverUrl(coverUrl)) throw cadError('BAD_COVER'); + return projectRecord(await this.call(PROJECTS + '/' + id(project), { method: 'PATCH', body: { coverUrl } })); + } + + async uploadCover(cover, signal) { + if (!(cover?.bytes instanceof Uint8Array) || cover.bytes.byteLength <= 0 + || cover.bytes.byteLength > MAX_COVER_BYTES || !['image/png', 'image/jpeg', 'image/webp'].includes(cover.mimeType)) throw cadError('BAD_COVER'); + const signature = await this.call('/uploads/project-covers/signature', { + method: 'POST', body: { contentType: cover.mimeType, fileSize: cover.bytes.byteLength }, signal, + }); + if (!signature || !projectCoverUrl(signature.coverUrl) || typeof signature.uploadUrl !== 'string' + || !signature.formFields || typeof signature.formFields !== 'object' || Array.isArray(signature.formFields) + || Object.values(signature.formFields).some((value) => typeof value !== 'string')) throw cadError('BAD_RESPONSE'); + this.assertIdentity(); + const body = new FormData(); + for (const [key, value] of Object.entries(signature.formFields)) body.append(key, value); + const extension = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }[cover.mimeType]; + body.append('file', new Blob([cover.bytes], { type: cover.mimeType }), 'cover.' + extension); + const response = await this.fetcher(storageUrl(signature.uploadUrl), { + method: 'POST', body, credentials: 'omit', cache: 'no-store', signal, referrerPolicy: 'no-referrer', + }); + this.assertIdentity(); + if (response.status !== 200) throw cadError('COVER_UPLOAD_FAILED'); + return signature.coverUrl; + } + delete(project) { return this.call(PROJECTS + '/' + id(project), { method: 'DELETE' }); } @@ -134,7 +233,7 @@ export class CadApi { } } -export function signedUrl(value) { +export function storageUrl(value) { const url = new URL(value, location.href); if (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.origin === location.origin)) throw cadError('BAD_RESPONSE'); if (url.username || url.password) throw cadError('BAD_RESPONSE'); @@ -149,13 +248,13 @@ export async function sha256(bytes) { export async function downloadSource(file, maxBytes, progress = () => {}, signal) { const size = file?.sizeBytes; if (!Number.isSafeInteger(size) || size <= 0 || size > maxBytes) throw cadError('SOURCE_TOO_LARGE'); - const response = await fetch(signedUrl(file.downloadUrl), { + const response = await fetch(storageUrl(file.downloadUrl), { credentials: 'omit', cache: 'no-store', signal, referrerPolicy: 'no-referrer', }); - if (!response.ok) throw cadError(response.status === 403 ? 'DOWNLOAD_EXPIRED' : 'DOWNLOAD_FAILED'); + 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'); @@ -194,7 +293,7 @@ export async function uploadSource(signature, bytes, fileName, signal) { 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); - const response = await fetch(signedUrl(authorization.uploadUrl), { + const response = await fetch(storageUrl(authorization.uploadUrl), { method: 'POST', body, credentials: 'omit', @@ -202,5 +301,5 @@ export async function uploadSource(signature, bytes, fileName, signal) { signal, referrerPolicy: 'no-referrer', }); - if (!response.ok) throw cadError(response.status === 403 ? 'CAD_UPLOAD_EXPIRED' : 'UPLOAD_FAILED'); + if (!response.ok) throw cadError('UPLOAD_FAILED'); } diff --git a/js/cad/app.js b/js/cad/app.js index f883e0f..2e83a74 100644 --- a/js/cad/app.js +++ b/js/cad/app.js @@ -3,7 +3,7 @@ import { auth, getMe, logout } from '../api.js'; import { openLogin } from '../auth-dialog.js'; import { CAD, desktopAllowed, projectUrl, filename } from './config.js'; import { locale, setLocale, t, errorText, LOCALE_KEY } from './i18n.js'; -import { CadApi, userId, cadError, downloadSource } from './api.js'; +import { CadApi, userId, cadError, downloadSource, sha256 } from './api.js'; import { DraftStore } from './drafts.js'; import { SaveCoordinator } from './save.js'; import { choose, nameDialog } from './dialog.js'; @@ -13,10 +13,19 @@ 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'); const store = new DraftStore(), session = crypto.randomUUID(); let api, bridge, project, binding, saver, boundUser = null, state = {}, epoch = 0, page = 1, query = '', total = 0; -let request, booting = false, restartBoot = false, modalCount = 0, authLocked = true, viewportReady = false, saveState = 'never', draftBusy = false, unsubscribe; +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 assistantAvailable = false; +let assistantRequest; const projectId = new URLSearchParams(location.search).get('project'); function context() { return { epoch, client: api, owner: boundUser, binding }; } +async function agentRevision(value) { + const revision = String(value ?? ''); + if (!revision) throw cadError('BAD_RESPONSE'); + // The bridge revision includes visibility state; the Agent API allows only 128 characters. + return sha256(new TextEncoder().encode(revision)); +} function assertContext(value, document = false) { value.client?.assertIdentity(); if (value.epoch !== epoch || value.owner !== boundUser || (document && value.binding !== binding)) throw cadError('STALE_BINDING'); @@ -34,17 +43,22 @@ function initEditorHeader() { navigate(CAD.list); }); header.querySelector('.nav-inner > .nav-links')?.remove(); - const menus = document.createElement('nav'); - menus.className = 'nav-links cad-engine-menus'; - menus.setAttribute('aria-label', t('file')); - menus.innerHTML = '' - + '' - + ''; - logo.after(menus); + const left = document.createElement('div'); + left.className = 'cad-appbar-left'; + left.innerHTML = '' + + '' + + ''; + logo.after(left); const actions = header.querySelector('.nav-actions'); actions.querySelector('.nav-search')?.remove(); actions.querySelectorAll('[data-publish], .nav-menu').forEach((node) => node.remove()); header.querySelector('.sheet')?.remove(); + const menus = document.createElement('nav'); + menus.className = 'nav-links cad-engine-menus cad-editor-utility'; + menus.setAttribute('aria-label', t('help')); + menus.innerHTML = '' + + ''; + actions.prepend(menus); const authSlot = actions.querySelector('[data-auth]'); authSlot?.classList.remove('hide-sm'); const saveStatus = document.createElement('span'); @@ -53,33 +67,62 @@ function initEditorHeader() { saveStatus.setAttribute('role', 'status'); saveStatus.textContent = t(saveState); const saveButton = document.createElement('button'); - saveButton.className = 'btn btn-sm btn-primary'; + saveButton.className = 'icon-btn cad-appbar-icon'; saveButton.type = 'button'; saveButton.dataset.save = ''; - saveButton.textContent = t('save'); + saveButton.innerHTML = icon('save', 18); + saveButton.setAttribute('aria-label', t('save')); + saveButton.title = t('save'); saveButton.disabled = !binding || authLocked; if (authSlot) { actions.insertBefore(saveStatus, authSlot); - actions.insertBefore(saveButton, authSlot); } else { - actions.append(saveStatus, saveButton); + actions.append(saveStatus); } - menus.addEventListener('click', (event) => { + left.append(saveButton); + header.addEventListener('click', (event) => { const button = event.target.closest('[data-engine-menu]'); if (!button || !bridge) return; bridge.showMenu(button.dataset.engineMenu).catch(showError); }); + left.querySelectorAll('[data-history]').forEach((button) => button.addEventListener('click', async () => { + if (authLocked || button.disabled) return; + try { + await window.solidcraft.execute(button.dataset.history === 'undo' ? 'edit.undo' : 'edit.redo', {}); + state = await bridge.getState(); + drawHeader(); + } catch (error) { showError(error); } + })); saveButton.addEventListener('click', () => save().catch(showError)); } function drawHeader() { if (editor) { + // The engine owns the full-height split. Match its measured column in the HTML bar, + // including after a divider drag or a CAD UI zoom change. Older engines keep their inset. + const fullHeight = state.assistant?.fullHeight === true; + const fraction = Number(state.assistant?.panelFraction); + const assistantWidth = fullHeight && state.assistant?.open && Number.isFinite(fraction) + ? Math.max(0, Math.min(0.5, fraction)) * 100 : 0; + document.body.classList.toggle('cad-full-height', fullHeight); + document.body.style.setProperty('--cad-assistant-width', `${assistantWidth}%`); 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.textContent = t('save'); saveButton.disabled = !binding || authLocked; } + if (saveButton) { saveButton.disabled = !binding || authLocked; saveButton.title = t('save'); saveButton.setAttribute('aria-label', t('save')); } header.querySelector('[data-engine-menu="file"]').textContent = t('file'); - header.querySelector('[data-engine-menu="preferences"]').textContent = t('preferences'); - header.querySelector('[data-engine-menu="help"]').textContent = t('help'); + 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')); } + 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)); } + } + const assistant = header.querySelector('[data-engine-menu="assistant"]'); + if (assistant) { + assistant.hidden = !assistantAvailable || state.assistant?.enabled === false || state.assistant?.toolbar === false; + assistant.disabled = authLocked || !binding || !viewportReady || modalCount > 0; + assistant.setAttribute('aria-pressed', String(!!state.assistant?.open)); + } document.title = project ? project.name + ' — ' + CAD.product : CAD.product; } else { document.title = t('projects') + ' — ' + CAD.product; @@ -91,6 +134,10 @@ function drawHeader() { } function status(key, error) { saveState = key; drawHeader(); + if (key === 'coverFailed' || key === 'coverUnavailable') { + notice(t(key) + (error?.requestId ? ` (${error.requestId})` : '')); + return; + } if (error && error.code !== 'STALE_IDENTITY' && error.code !== 'STALE_BINDING') showError(error); } function showError(error) { @@ -108,7 +155,7 @@ function stage(key, progress) { message(key); const p = main.querySelector('h1') async function signIn() { await openLogin({ locale: locale() }); if (!authLocked && !binding && editor) boot(); } async function signOut() { if (!(await guard())) return; - leaving = true; signingOut = true; + leaving = true; signingOut = true; authLocked = true; updateLock(); await clearAssistant(); try { await logout(); } catch { /* a rejected logout still clears this browser's identity */ } auth.clear(); signingOut = false; if (editor) location.assign('/cad/'); else { authLocked = true; drawHeader(); message('loginRequired', 'loginHint', signIn, 'signIn'); } @@ -123,6 +170,58 @@ function updateLock() { if (!blocker.hidden) blocker.innerHTML = `

${esc(t('expand'))}

${esc(t('protected'))}

`; } } +async function bindAssistant() { + if (!assistantAvailable || !binding || !boundUser) return; + const ctx = context(); + assistantRequest?.abort(); assistantRequest = new AbortController(); + const capabilityRequest = assistantRequest; + if (window.__VIBEMAKE_CAD__) window.__VIBEMAKE_CAD__.agentChat = null; + let capabilities = null; + try { + capabilities = await api.aiCapabilities(capabilityRequest.signal); + assertContext(ctx, true); + } catch (error) { + if (error.code === 'STALE_IDENTITY' || error.code === 'STALE_BINDING') throw error; + if (error.name !== 'AbortError') notice(errorText(error)); + } finally { + if (assistantRequest === capabilityRequest) assistantRequest = null; + } + if (capabilityRequest.signal.aborted) return; + assertContext(ctx, true); + const client = api, engine = bridge, documentContext = context(); + const host = window.__VIBEMAKE_CAD__; + if (host) { + host.agentChat = capabilities?.enabled ? async (requestBody, signal, onStart) => { + assertContext(documentContext, true); + const current = await engine.getState(); + const documentRevision = await agentRevision(current.revision); + assertContext(documentContext, true); + const request = { + ...requestBody, + cadProjectCode: project.id, + context: { ...requestBody.context, documentRevision }, + }; + return client.aiChat(request, signal, () => { + assertContext(documentContext, true); + onStart?.(); + }); + } : null; + } + await bridge.setAgentContext({ + userId: boundUser, + projectId: project.id, + binding, + sessionId: session, + documentSessionCode: session, + aiCapabilities: capabilities, + }); + assertContext(ctx, true); +} +async function clearAssistant() { + assistantRequest?.abort(); assistantRequest = null; + if (typeof bridge?.setAgentContext === 'function') await bridge.setAgentContext(null).catch(() => {}); + if (window.__VIBEMAKE_CAD__) window.__VIBEMAKE_CAD__.agentChat = null; +} async function validateIdentity() { if (!auth.token) return false; const token = auth.token; @@ -149,7 +248,8 @@ async function boot() { if (boundUser && boundUser !== userId()) { await releaseAccount(); location.replace('/cad/'); return; } boundUser = userId(); if (editor && binding) { - saver.api = api; saver.closed = false; updateLock(); + saver.api = api; saver.closed = false; + await bindAssistant(); updateLock(); if (saver.operation) await saver.save(); drawHeader(); main.hidden = true; return; } @@ -179,8 +279,13 @@ async function loadList() { total = result.total; if (!result.items.length && page > 1) { page--; return fetchResults(); } const target = main.querySelector('[data-results]'); - target.innerHTML = result.items.length ? `
${result.items.map((p) => `

${esc(p.name)}

${p.lastSavedAt ? `${esc(t('savedAt'))} ${esc(new Date(p.lastSavedAt).toLocaleString(locale() === 'zh' ? 'zh-CN' : 'en'))}` : esc(t('noSave'))}
${esc(t('open'))}
`).join('')}
` + target.innerHTML = result.items.length ? `
${result.items.map((p) => `

${esc(p.name)}

${p.lastSavedAt ? `${esc(t('savedAt'))} ${esc(new Date(p.lastSavedAt).toLocaleString(locale() === 'zh' ? 'zh-CN' : 'en'))}` : esc(t('noSave'))}
${esc(t('open'))}
`).join('')}
` : `
${icon('cube', 48)}

${esc(t(query ? 'noResults' : 'empty'))}

${esc(t('emptyHint'))}

`; + target.querySelectorAll('.cad-card-art img').forEach((image) => { + const fallback = () => { image.parentElement.innerHTML = icon('cube', 52); }; + image.addEventListener('error', fallback, { once: true }); + if (image.complete && !image.naturalWidth) fallback(); + }); target.querySelector('[data-prev]')?.addEventListener('click', () => { page--; fetchResults(); }); target.querySelector('[data-next]')?.addEventListener('click', () => { page++; fetchResults(); }); target.querySelectorAll('[data-rename]').forEach((button) => button.addEventListener('click', async () => { @@ -222,18 +327,13 @@ async function openEditor(current) { 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(); + assistantAvailable = engineReady.capabilities?.assistant === true && typeof bridge.setAgentContext === 'function'; + if (!assistantAvailable) notice(t('assistantUpdate')); let bytes = null; if (source) { stage('download'); - try { - bytes = await downloadSource(source, CAD.maxSourceBytes, (received, size) => stage('download', Math.round(received / size * 100) + '%')); - } catch (error) { - if (error.code !== 'DOWNLOAD_EXPIRED') throw error; - source = await api.document(projectId); - project.version = source.version; - project.headVersion = source.version; - bytes = await downloadSource(source, CAD.maxSourceBytes); - } + bytes = await downloadSource(source, CAD.maxSourceBytes, (received, size) => stage('download', Math.round(received / size * 100) + '%')); } if (current !== epoch) return; stage('rebuild'); @@ -243,27 +343,50 @@ async function openEditor(current) { 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(); } 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; state = next; - if (!saver?.active && !['conflict', 'failed', 'expired', 'unavailable', 'pending'].includes(saveState)) { saveState = project?.version ? (next.dirty ? 'dirty' : 'saved') : 'never'; drawHeader(); } + if (!saver?.active && !['conflict', 'failed', 'expired', 'unavailable', 'pending'].includes(saveState)) { + saveState = project?.version ? (next.dirty ? 'dirty' : saver?.pendingCover ? 'coverFailed' : saver?.coverUnavailable ? 'coverUnavailable' : 'saved') : 'never'; + } + drawHeader(); if (next.intent && !authLocked && modalCount === 0) hostIntent(next.intent).catch(showError); if (next.locale && next.locale !== locale() && !next.fontFailed && !recovering) { setLocale(next.locale); drawHeader(); } } -async function save() { if (authLocked || !saver) throw cadError('UNAUTHORIZED'); if (copying) throw cadError('SAVE_IN_PROGRESS'); if (recoveryPending) throw cadError('PENDING_SAVE'); const ctx = context(); let result; try { result = await saver.save(); } catch (error) { if (error.code === 'SNAPSHOT_BUSY' && state.pendingMoves) await bridge.requestSave(); throw error; } assertContext(ctx, true); state = await bridge.getState(); status(state.dirty ? 'dirty' : 'saved'); if (!draftWarning) notice(''); return result; } -async function draft() { - if (recovering || !bridge || !binding || !boundUser || draftBusy || !state.dirty || !state.snapshotAvailable || state.revision === lastDraftRevision) return; - draftBusy = true; const oldBinding = binding, owner = boundUser, target = project.id, version = project.version, revision = state.revision; - let snapshot; - try { - snapshot = await bridge.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 }); - if (oldBinding === binding) lastDraftRevision = revision; - } catch (error) { if (error.code !== 'SNAPSHOT_BUSY') storageWarning(); } - finally { if (snapshot) await bridge.releaseSnapshot(snapshot.snapshotId); draftBusy = false; } +async function save() { + if (authLocked || !saver) throw cadError('UNAUTHORIZED'); + if (copying) throw cadError('SAVE_IN_PROGRESS'); + if (recoveryPending) throw cadError('PENDING_SAVE'); + const ctx = context(); let result; + try { result = await saver.save(); } + catch (error) { if (error.code === 'SNAPSHOT_BUSY' && state.pendingMoves) await bridge.requestSave(); throw error; } + assertContext(ctx, true); + state = await bridge.getState(); + status(state.dirty ? 'dirty' : result.coverPending ? 'coverFailed' : result.coverUnavailable ? 'coverUnavailable' : 'saved'); + if (result.coverPending) notice(t('coverFailed')); + else if (result.coverUnavailable) notice(t('coverUnavailable')); + else if (!draftWarning) notice(''); + return result; +} +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; + 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 }); + 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; @@ -348,10 +471,30 @@ async function renameCurrent() { } async function guard() { if (!binding || leaving) return true; + const ctx = context(), target = project.id; const snapshot = await bridge.getState(); if (!snapshot.dirty && !saver?.operation && !recoveryPending) return true; const choice = await choose(t('leave'), t('leaveHint'), [['save', t('saveLeave'), true], ['discard', t('discardLeave')], ['stay', t('stay')]]); - if (choice === 'discard') return true; + if (choice === 'discard') { + const previous = discardedDraft, discarded = { binding: ctx.binding, revision: snapshot.revision, pending: true }; + try { + assertContext(ctx, true); + discardedDraft = discarded; + // Finish any earlier write before deleting; page-hide autosave must not recreate it. + await draftTask; + assertContext(ctx, true); + const drafts = await store.list(ctx.owner, target, 'draft'); + assertContext(ctx, true); + for (const value of drafts) await store.remove(value.key, value.snapshotId); + assertContext(ctx, true); + discarded.pending = false; + return true; + } catch (error) { + if (discardedDraft === discarded) discardedDraft = previous; + if (['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) showError(error); else storageWarning(); + return false; + } + } if (choice === 'save') try { await save(); return !(await bridge.getState()).dirty && !saver.operation; } catch (error) { showError(error); } return false; } @@ -366,10 +509,10 @@ async function saveAs() { try { const name = await nameDialog(project.name); if (!name) return; assertContext(ctx, true); - snapshot = await bridge.createSnapshot(); const originalBinding = binding, owner = boundUser; + snapshot = await bridge.createSnapshot({ includeCover: true }); const originalBinding = binding, owner = boundUser; const destination = await api.create(name); if (originalBinding !== binding || owner !== userId()) throw cadError('STALE_BINDING'); // Dedicated destination coordinator uses the captured snapshot, never ACKs the original document. - const copyBridge = { createSnapshot: async () => snapshot, acknowledgeSave: async () => {}, releaseSnapshot: async () => {} }; + const copyBridge = { createSnapshot: async () => snapshot, getState: () => bridge.getState(), acknowledgeSave: async () => {}, releaseSnapshot: async () => {} }; const copySaver = new SaveCoordinator({ api, bridge: copyBridge, store, user: owner, project: destination, binding, session: session + ':copy', onState: (key) => { if (key !== 'saved') notice(t(key)); }, onStorageError: storageWarning }); await copySaver.save(); assertContext(ctx, true); copying = false; @@ -415,24 +558,26 @@ 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() { + await clearAssistant(); await draft(); saver?.dispose(); unsubscribe?.(); binding = null; viewportReady = false; await bridge?.releaseProject(); project = null; state = {}; recoveryPending = false; updateLock(); } async function authChanged() { if (signingOut) return; if (booting) { - if (api && (api.token !== auth.token || api.user !== userId())) { ++epoch; authLocked = true; restartBoot = true; updateLock(); } + if (api && (api.token !== auth.token || api.user !== userId())) { ++epoch; authLocked = true; restartBoot = true; updateLock(); await clearAssistant(); } return; } if (auth.token === authToken && userId() === boundUser) return; ++epoch; request?.abort(); if (!auth.token) { authToken = null; authLocked = true; updateLock(); status('expired'); + await clearAssistant(); await draft(); if (!editor || !binding) message('loginRequired', 'loginHint', signIn, 'signIn'); await openLogin({ locale: locale() }); if (auth.token) boot(); } else if (boundUser && userId() !== boundUser) { - authLocked = true; updateLock(); await releaseAccount(); leaving = true; location.replace('/cad/'); + authLocked = true; updateLock(); await clearAssistant(); await releaseAccount(); leaving = true; location.replace('/cad/'); } else boot(); } auth.onChange(authChanged); diff --git a/js/cad/i18n.js b/js/cad/i18n.js index c27638b..1cc593d 100644 --- a/js/cad/i18n.js +++ b/js/cad/i18n.js @@ -1,5 +1,6 @@ // 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.'], 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.'], @@ -10,9 +11,12 @@ const messages = { logout: ['退出登录', 'Sign out'], home: ['返回首页', 'Home'], list: ['返回项目列表', 'Projects'], previous: ['上一页', 'Previous'], next: ['下一页', 'Next'], loading: ['加载中…', 'Loading…'], identity: ['验证账号…', 'Verifying account…'], metadata: ['读取项目…', 'Reading project…'], engine: ['加载编辑器…', 'Loading editor…'], download: ['下载工程…', 'Downloading design…'], rebuild: ['重建模型…', 'Rebuilding model…'], - file: ['文件', 'File'], preferences: ['首选项', 'Preferences'], help: ['帮助', 'Help'], + file: ['文件', 'File'], preferences: ['首选项', 'Preferences'], help: ['帮助', 'Help'], undo: ['撤销', 'Undo'], redo: ['重做', 'Redo'], save: ['保存', 'Save'], never: ['尚未保存到云端', 'Not saved to cloud'], saved: ['已保存到云端', 'Saved to cloud'], dirty: ['有未保存更改', 'Unsaved changes'], preparing: ['正在准备…', 'Preparing…'], uploading: ['正在上传…', 'Uploading…'], verifying: ['正在确认…', 'Confirming…'], + coverUploading: ['工程已保存,正在更新封面…', 'Design saved. Updating cover…'], + coverFailed: ['工程已保存,封面更新失败;再次点击保存可重试。', 'Design saved. Cover update failed; save again to retry.'], + coverUnavailable: ['工程已保存,当前模型预览暂不可用,已保留原封面。', 'Design saved. Model preview is unavailable; the previous cover is unchanged.'], offline: ['离线 · 更改尚未保存到云端', 'Offline · changes not saved to cloud'], failed: ['保存失败', 'Save failed'], conflict: ['云端版本冲突', 'Cloud version conflict'], expired: ['登录失效,请重新登录', 'Session expired. Please sign in again.'], unavailable: ['项目已删除或无权限', 'Project deleted or access denied'], error: ['暂时无法完成,请重试。', 'Unable to complete. Please retry.'], @@ -38,6 +42,8 @@ const messages = { refresh: ['检查并刷新', 'Refresh'], 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.'], + storageUnavailable: ['云端存储未开启或 OSS 连接配置不完整,请联系管理员;当前设计已保留。', 'Cloud storage is disabled or the OSS connection is not fully configured. Contact your administrator. Your design is preserved.'], }; export const LOCALE_KEY = 'vm.cad.locale'; let language = 'zh'; @@ -59,7 +65,7 @@ export function errorText(error) { SAVE_UNAVAILABLE: 'pending', UPLOAD_NOT_READY: 'pending', UPLOAD_AUTH_EXPIRED: 'uploadExpired', CAD_UPLOAD_EXPIRED: 'uploadExpired', CAD_FILE_MISSING: 'pending', CAD_FILE_SIZE_MISMATCH: 'invalidFile', CAD_INVALID_FILE: 'invalidFile', CAD_FILE_TOO_LARGE: 'tooLarge', REQUEST_TOO_LARGE: 'tooLarge', - CAD_OSS_ERROR: 'pending', CAD_STORAGE_UNAVAILABLE: 'pending', CAD_STORAGE_UNSAFE: 'pending', + DOWNLOAD_FORBIDDEN: 'downloadForbidden', CAD_OSS_ERROR: 'pending', CAD_STORAGE_UNAVAILABLE: 'storageUnavailable', CAD_STORAGE_UNSAFE: 'storageUnavailable', CAD_CODE_BUSY: 'pending', REDIS_UNAVAILABLE: 'pending' }; const key = keys[error?.code] || (error?.status === 401 ? 'expired' : error?.status === 429 ? 'rateLimit' : error?.status === 413 ? 'tooLarge' : 'error'); return t(key) + (error?.requestId ? ` (${error.requestId})` : ''); diff --git a/js/cad/save.js b/js/cad/save.js index 8cad40f..7a64fe6 100644 --- a/js/cad/save.js +++ b/js/cad/save.js @@ -1,4 +1,4 @@ -import { cadError, sha256, uploadSource } from './api.js'; +import { cadError, sha256, uploadSource, MAX_COVER_BYTES, projectCoverUrl } from './api.js'; import { filename, CAD } from './config.js'; const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -21,6 +21,8 @@ export class SaveCoordinator { this.operation = null; this.closed = false; this.conflicted = false; + this.pendingCover = null; + this.coverUnavailable = false; } assertCurrent() { @@ -54,9 +56,11 @@ export class SaveCoordinator { async run() { this.assertCurrent(); if (this.conflicted) throw cadError('HEAD_CONFLICT'); + // Retrying a failed cover must not upload the native file or increment its version again. + if (!this.operation && this.pendingCover && !(await this.bridge.getState()).dirty) return this.finishCover(); if (!this.operation) { this.onState('preparing'); - const snapshot = await this.bridge.createSnapshot(); + const snapshot = await this.bridge.createSnapshot({ includeCover: true }); if (snapshot.binding !== this.binding) { await this.bridge.releaseSnapshot(snapshot.snapshotId); throw cadError('STALE_BINDING'); @@ -83,6 +87,7 @@ export class SaveCoordinator { snapshotId: snapshot.snapshotId, snapshot, bytes: snapshot.bytes, + cover: snapshot.cover, digest: await this.hash(snapshot.bytes), request, uploadCode: null, @@ -115,10 +120,9 @@ export class SaveCoordinator { this.onState('uploading'); try { await this.uploader(signature, operation.bytes, operation.request.fileName); - } catch (error) { - if (!isRetryableBatchError(error)) throw error; - lastBatchError = error; - continue; + } catch { + // OSS may have accepted the bytes even when its response was lost or refused. + // Only confirmation can decide whether this batch needs another upload. } this.assertCurrent(); this.onState('verifying'); @@ -143,14 +147,25 @@ export class SaveCoordinator { try { await this.store.clearAcknowledged(this.user, operation.projectId, operation.snapshotId, { binding: this.binding, revision: operation.snapshot.revision }); - await this.store.remove(operation.journalKey, operation.snapshotId); + await this.store.remove(operation.journalKey || this.store.key(this.user, operation.projectId, this.session, 'operation'), + operation.snapshotId); } catch (error) { this.onStorageError(error); } await this.bridge.releaseSnapshot(operation.snapshotId); this.operation = null; - this.onState('saved'); - return reply; + if (this.pendingCover) await this.clearCover(this.pendingCover); + this.coverUnavailable = !operation.cover; + if (operation.cover) { + this.pendingCover = { + user: this.user, projectId: operation.projectId, snapshotId: operation.snapshotId, + version: reply.version, savedAt: reply.savedAt, cover: operation.cover, + }; + await this.persistCover(); + return this.finishCover(); + } + this.onState(this.coverUnavailable ? 'coverUnavailable' : 'saved'); + return { ...reply, ...(this.coverUnavailable ? { coverUnavailable: true } : {}) }; } catch (error) { const conflict = ['HEAD_CONFLICT', 'CAD_VERSION_CONFLICT'].includes(error?.code); if (conflict) { @@ -166,6 +181,81 @@ export class SaveCoordinator { } } + async persistCover() { + if (!this.pendingCover) return; + try { + await this.store.put(this.user, this.project.id, this.session, 'cover', this.pendingCover); + } catch (error) { this.onStorageError(error); } + } + + async restoreCover() { + try { + const records = await this.store.list(this.user, this.project.id, 'cover'); + this.assertCurrent(); + const pending = records.find((record) => record.user === this.user && record.projectId === this.project.id + && record.version === this.project.version && record.cover?.bytes instanceof Uint8Array + && record.cover.bytes.byteLength > 0 && record.cover.bytes.byteLength <= MAX_COVER_BYTES); + if (pending) { + this.pendingCover = pending; + this.onState('coverFailed'); + } + } catch (error) { + if (['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) throw error; + this.onStorageError(error); + } + } + + async clearCover(pending) { + try { + await this.store.remove(pending.key || this.store.key(this.user, this.project.id, this.session, 'cover'), pending.snapshotId); + } catch (error) { this.onStorageError(error); } + if (this.pendingCover === pending) this.pendingCover = null; + } + + async finishCover() { + const pending = this.pendingCover; + if (!pending) throw cadError('BAD_COVER'); + const receipt = { cadProjectCode: pending.projectId, version: pending.version, savedAt: pending.savedAt }; + try { + this.assertCurrent(); + this.onState('coverUploading'); + // PATCH has no version precondition. These checks avoid known stale publications; + // atomic cross-client protection would require a backend conditional update. + const current = await this.api.get(pending.projectId); + this.assertCurrent(); + if (current.version !== pending.version) { + await this.clearCover(pending); + this.onState('saved'); + return { ...receipt, coverSuperseded: true }; + } + if (!pending.coverUrl) { + const coverUrl = await this.api.uploadCover(pending.cover); + this.assertCurrent(); + if (!projectCoverUrl(coverUrl)) throw cadError('BAD_RESPONSE'); + pending.coverUrl = coverUrl; + await this.persistCover(); + } + const latest = await this.api.get(pending.projectId); + this.assertCurrent(); + if (latest.version !== pending.version) { + await this.clearCover(pending); + this.onState('saved'); + return { ...receipt, coverSuperseded: true }; + } + const updated = await this.api.setCover(pending.projectId, pending.coverUrl); + this.assertCurrent(); + this.project.coverUrl = updated.coverUrl; + this.coverUnavailable = false; + await this.clearCover(pending); + this.onState('saved'); + return receipt; + } catch (error) { + if (['STALE_IDENTITY', 'STALE_BINDING'].includes(error.code)) throw error; + this.onState('coverFailed', error); + return { ...receipt, coverPending: true }; + } + } + async forget(operation) { try { await this.store.put(this.user, operation.projectId, this.session, 'draft', { diff --git a/js/layout.js b/js/layout.js index 66242e8..0c7c44f 100644 --- a/js/layout.js +++ b/js/layout.js @@ -55,7 +55,11 @@ export const ICON = { trash: '', download: '', history: '', + save: '', + undo: '', + redo: '', gear: '', + help: '', lock: '', globe: '', chevron: '', diff --git a/package.json b/package.json index 0ddafde..fc288cc 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,9 @@ "build": "npm run build:walking && node scripts/build.mjs", "build:dev": "npm run build:walking && node scripts/build.mjs --env=dev", "test:cad": "node --test tests/cad/*.test.js scripts/cad-engine.test.mjs", - "test:cad:browser": "node tests/cad/browser-e2e.mjs" + "test:cad:browser": "node tests/cad/browser-e2e.mjs", + "test:cad:assistant": "node tests/cad/assistant-browser.mjs", + "test:cad:platform-agent": "node tests/cad/platform-agent-browser.mjs" }, "devDependencies": { "@gltf-transform/core": "4.1.1", diff --git a/pcb.html b/pcb.html index 935bcd1..2d26714 100644 --- a/pcb.html +++ b/pcb.html @@ -1,118 +1,12 @@ - - - - - - make PCB - - - - - - - - - - - - + + + + + VibeMake PCB + + +

PCB 编辑器已迁移到 VibeMake PCB。

+ diff --git a/scripts/build.mjs b/scripts/build.mjs index 591b655..b6c248a 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -6,24 +6,20 @@ 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 BUILD_ENV = process.argv.find((arg) => arg.startsWith('--env='))?.slice(6) || 'auto'; if (!['auto', 'dev'].includes(BUILD_ENV)) throw new Error(`不支持的打包环境:${BUILD_ENV}`); -const cadEngine = readCadEngine(process.env.VIBEMAKE_CAD_ENGINE_DIST); +const PCB_DIST = resolve(process.env.PCB_DIST || join(ROOT, '../ziro-designer-main/designer/dist')); +if (!existsSync(join(PCB_DIST, 'index.html'))) + throw new Error(`PCB build not found at ${PCB_DIST}. Build ziro-designer-main/designer first, or set PCB_DIST.`); const SKIP = /(^|\/)(\.DS_Store|Thumbs\.db)$/; const copy = (rel) => cpSync(join(ROOT, rel), join(DIST, rel), { recursive: true, filter: (src) => !SKIP.test(src) }); -// Retain prior immutable CAD assets so existing tabs and rollback builds stay usable. +// Rebuild the site package from scratch; the CAD engine is built and deployed separately. mkdirSync(DIST, { recursive: true }); -for (const name of readdirSync(DIST)) { - if (name !== 'cad') rmSync(join(DIST, name), { recursive: true, force: true }); -} -if (existsSync(join(DIST, 'cad'))) for (const name of readdirSync(join(DIST, 'cad'))) { - if (name !== '_assets') rmSync(join(DIST, 'cad', name), { recursive: true, force: true }); -} +for (const name of readdirSync(DIST)) rmSync(join(DIST, name), { recursive: true, force: true }); for (const f of ['index.html', 'css', 'js', 'assets', 'data', 'vendor', 'play']) copy(f); const apiFile = join(DIST, 'js/api.js'); @@ -33,14 +29,14 @@ writeFileSync(apiFile, apiSource.replace("export const BUILD_ENV = 'auto';", `ex // 浏览器标签、收藏夹和添加到手机桌面使用独立的简化机器人图标。 for (const f of ['favicon.svg', 'favicon.ico', 'apple-touch-icon.png', 'site.webmanifest', 'icon-16.png', 'icon-32.png', 'icon-48.png', 'icon-64.png', 'icon-192.png', 'icon-512.png']) copy(f); // 静态网站:每个页面放进同名目录的 index.html,地址是 /explore/、/studio/、/cad/、/pcb/、/project/?id=…、/workspace/?code=… -for (const page of ['explore', 'project', 'studio', 'cad', 'pcb', 'workspace']) { +for (const page of ['explore', 'project', 'studio', 'cad', 'workspace']) { mkdirSync(join(DIST, page), { recursive: true }); cpSync(join(ROOT, `${page}.html`), join(DIST, page, 'index.html')); } +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')); -copyCadEngine(cadEngine, DIST); // 只带 robots.json 里用到的模型目录(demo-* 是早期示例,不上线) mkdirSync(join(DIST, 'robots')); @@ -76,7 +72,9 @@ ${BUILD_ENV === 'dev' ? `本包仅用于 dev 环境,接口固定为 https://de ` : ''}静态网站,1Panel 新建「静态网站」,把本目录所有文件放到网站根目录即可,不需要运行 npm 或 Node 服务。 - 页面地址:\`/\`、\`/explore/\`、\`/studio/\`、\`/cad/\`、\`/pcb/\`、\`/project/?id=<编号>\`、\`/workspace/\`、\`/workspace/?code=<编号>\` -- 页面嵌入:/cad/ 为同源项目列表,/cad/editor/?project= 直接加载 Rust/WASM;/pcb/ 加载 https://cadworld-studio.robotquan.com/pcb;仅电脑端开放,手机 / 平板或 820px 及以下窄屏访问时回到首页,且不加载编辑器。 +- PCB:与主站同源部署在 /pcb/,由独立 PCB 仓库构建;项目列表和工程深链接由 PCB 单页应用处理。站点包将 PCB_DIST 指定的独立构建复制到 dist/pcb,无需合并两份源码。 +- CAD:/cad/ 为同源项目列表,/cad/editor/?project= 直接加载 Rust/WASM;CAD / PCB 仅电脑端开放。 +- 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'}; 方法 GET/POST/PUT/PATCH/DELETE/OPTIONS;请求头 Authorization、Content-Type、Accept;暴露 X-Request-Id)。 @@ -108,5 +106,6 @@ try { console.log('没有找到 zip 命令,只生成了 dist 目录'); } console.log(`dist:${DIST}`); +console.log(`PCB:${join(DIST, 'pcb')} ← ${PCB_DIST}`); console.log(`模型:${dirs.join('、')}`); if (!existsSync(join(DIST, 'robots/so101/so101.urdf'))) throw new Error('模型文件没有复制成功'); diff --git a/scripts/server.mjs b/scripts/server.mjs index 2d5cbe0..ff81b76 100644 --- a/scripts/server.mjs +++ b/scripts/server.mjs @@ -5,13 +5,14 @@ // dev-vibemake.robotquan.com、localhost、127.0.0.1、局域网 IP → https://dev-vibemake-api.robotquan.com // vibemake.robotquan.com 等正式域名 → https://vibemake-api.robotquan.com // -// 本地:node scripts/server.mjs → http://localhost:8090 +// 本地:node scripts/server.mjs → http://localhost:8091 // 线上浏览器直接请求后端域名(见 js/api.js 的 API_HOSTS),这里的域名判断只用于本地调试 -// 环境变量:PORT 端口(默认 8090);API_TARGET 强制所有域名都转发到这个后端;API_DEV / API_PROD 改两个后端地址; +// 环境变量:PORT 端口(默认 8091);API_TARGET 强制所有域名都转发到这个后端;API_DEV / API_PROD 改两个后端地址; // SITE_ROOT 页面文件目录(默认:在 scripts/ 里运行时是项目根目录,在 dist/ 里运行时是 dist 本身) import http from 'node:http'; import https from 'node:https'; import zlib from 'node:zlib'; +import { spawn } from 'node:child_process'; import { createReadStream, existsSync, statSync } from 'node:fs'; import { basename, dirname, extname, join, normalize, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -22,7 +23,30 @@ 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 PORT = Number(process.env.PORT || 8090); +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' + ? null + : process.env.PCB_DEV_TARGET + ? new URL(process.env.PCB_DEV_TARGET) + : !process.env.SITE_ROOT && existsSync(join(PCB_APP_ROOT, 'package.json')) + ? new URL('http://127.0.0.1:5173') + : null; +let pcbDevProcess = null; +const PCB_API_MODE = process.env.PCB_API_MODE || 'real'; +if (!['real', 'mock'].includes(PCB_API_MODE)) throw new Error('PCB_API_MODE must be real or mock'); +if (PCB_DEV_TARGET && !process.env.PCB_DEV_TARGET && process.env.PCB_DEV !== 'off') { + const vite = join(PCB_APP_ROOT, 'node_modules/vite/bin/vite.js'); + if (existsSync(vite)) { + pcbDevProcess = spawn(process.execPath, [vite, '--mode', PCB_API_MODE === 'mock' ? 'mock' : 'development', '--host', '127.0.0.1', '--strictPort'], { + cwd: PCB_APP_ROOT, + stdio: 'inherit', + env: { ...process.env, VITE_PCB_API_MODE: PCB_API_MODE }, + }); + } else { + console.warn(`PCB Vite dependency not found at ${vite}; /pcb/ proxy will fail until it is installed.`); + } +} const API_DEV = process.env.API_DEV || 'https://dev-vibemake-api.robotquan.com'; const API_PROD = process.env.API_PROD || 'https://vibemake-api.robotquan.com'; @@ -62,11 +86,41 @@ function proxy(req, res) { req.pipe(upstream); } +function isPcbRoute(pathname) { + return pathname === '/pcb' || pathname.startsWith('/pcb/'); +} + +function proxyPcb(req, res) { + const target = PCB_DEV_TARGET; + const { connection, host, origin, ...headers } = req.headers; + const upstream = http.request({ + hostname: target.hostname, + port: target.port || 80, + method: req.method, + path: req.url, + headers: { ...headers, host: target.host, ...(origin ? { origin: target.origin } : {}) }, + }, (response) => { + res.writeHead(response.statusCode, response.headers); + response.pipe(res); + }); + upstream.on('error', (error) => { + if (res.headersSent) { + res.destroy(); + return; + } + res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }); + res.end(`PCB development server unavailable at ${target.origin}: ${error.code || error.message}`); + }); + res.on('close', () => { if (!res.writableFinished) upstream.destroy(); }); + req.pipe(upstream); +} + // ---------- 页面路由 ---------- -const PAGES = { '/': 'index.html', '/explore': 'explore.html', '/studio': 'studio.html', '/cad': 'cad.html', '/cad/editor': 'cad/editor/index.html', '/pcb': 'pcb.html', '/workspace': 'workspace.html' }; +const PAGES = { '/': 'index.html', '/explore': 'explore.html', '/studio': 'studio.html', '/cad': 'cad.html', '/cad/editor': 'cad/editor/index.html', '/pcb': 'pcb/index.html', '/workspace': 'workspace.html' }; function pageFor(pathname) { pathname = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname; // /explore/ 和 /explore 一样 return PAGES[pathname] + || (/^\/pcb(?:\/.*)?$/.test(pathname) && !extname(pathname) && 'pcb/index.html') || (/^\/project(\/[^/]+)?\/?$/.test(pathname) && 'project.html') || (/^\/workspace\/[^/]+\/?$/.test(pathname) && 'workspace.html'); } @@ -144,14 +198,53 @@ function serveStatic(req, res) { sendFile(req, res, file); } -http.createServer((req, res) => { +const server = http.createServer((req, res) => { if (req.url === '/api' || req.url.startsWith('/api/')) proxy(req, res); else if (req.url.startsWith(`${MODEL_ASSET_ROUTE}/`)) proxyModelAsset(req, res); + else if (PCB_DEV_TARGET && isPcbRoute(new URL(req.url, 'http://localhost').pathname)) proxyPcb(req, res); else if (req.method === 'GET' || req.method === 'HEAD') serveStatic(req, res); else res.writeHead(405).end(); -}).listen(PORT, () => { +}); +server.on('upgrade', (req, socket, head) => { + const pathname = new URL(req.url, 'http://localhost').pathname; + if (!PCB_DEV_TARGET || !isPcbRoute(pathname)) { + socket.destroy(); + return; + } + const upstream = http.request({ + hostname: PCB_DEV_TARGET.hostname, + port: PCB_DEV_TARGET.port || 80, + path: req.url, + headers: { ...req.headers, host: PCB_DEV_TARGET.host, origin: PCB_DEV_TARGET.origin }, + }); + upstream.on('upgrade', (response, upstreamSocket, upstreamHead) => { + socket.write(`HTTP/${response.httpVersion} ${response.statusCode} ${response.statusMessage}\r\n`); + for (let i = 0; i < response.rawHeaders.length; i += 2) + socket.write(`${response.rawHeaders[i]}: ${response.rawHeaders[i + 1]}\r\n`); + socket.write('\r\n'); + if (head.length) upstreamSocket.write(head); + if (upstreamHead.length) socket.write(upstreamHead); + upstreamSocket.pipe(socket); + socket.pipe(upstreamSocket); + 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('close', () => upstream.destroy()); + upstream.end(); +}); +server.listen(PORT, () => { console.log(`vibemake 已启动 端口 ${PORT} 页面目录 ${ROOT}`); + if (PCB_DEV_TARGET) console.log(` /pcb/ → ${PCB_DEV_TARGET.origin}(${PCB_API_MODE === 'mock' ? '开发模拟' : '真实接口'}模式,同源代理)`); console.log(` dev-* / localhost / 127.0.0.1 / 局域网 /api → ${process.env.API_TARGET || API_DEV}`); console.log(` 其他域名(正式) /api → ${process.env.API_TARGET || API_PROD}`); console.log(` 本地:http://localhost:${PORT}(后端数据) http://127.0.0.1:${PORT}(本地演示数据)`); }); +for (const signal of ['SIGINT', 'SIGTERM']) { + process.once(signal, () => { + pcbDevProcess?.kill(signal); + server.close(() => process.exit(0)); + }); +} diff --git a/tests/cad/api.test.js b/tests/cad/api.test.js index 70c2ef5..6911cbb 100644 --- a/tests/cad/api.test.js +++ b/tests/cad/api.test.js @@ -7,10 +7,79 @@ globalThis.localStorage = { getItem: (key) => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value), }; -const { CadApi, auth, downloadSource, uploadSource, sha256 } = await import('../../js/cad/api.js'); +const { CadApi, auth, downloadSource, uploadSource, sha256, projectCoverUrl, MAX_COVER_BYTES } = await import('../../js/cad/api.js'); +const { CadAgentRateLimiter } = await import('../../js/cad/agent-rate-limit.js'); const { validName, filename, CAD } = await import('../../js/cad/config.js'); +const { errorText, setLocale } = await import('../../js/cad/i18n.js'); -beforeEach(() => auth.set({ token: 'token-a', user: { userCode: 'owner-a' } })); +beforeEach(() => { storage.clear(); auth.set({ token: 'token-a', user: { userCode: 'owner-a' } }); }); + +test('CAD project covers use the documented signature and anonymous OSS form upload', async () => { + const calls = [], bytes = new Uint8Array([137, 80, 78, 71]); + const api = new CadApi({ fetcher: async (url, options) => { + calls.push({ url, options }); + if (calls.length === 1) return Response.json({ code: 'OK', data: { + uploadUrl: 'https://oss.example/upload', formFields: { key: 'project-covers/fixed.png', policy: 'signed', 'x-oss-forbid-overwrite': 'true' }, + coverUrl: 'https://cdn.example/project-covers/fixed.png', + } }); + return new Response(null, { status: 200 }); + } }); + assert.equal(await api.uploadCover({ bytes, mimeType: 'image/png' }), 'https://cdn.example/project-covers/fixed.png'); + assert.equal(calls[0].url, '/api/uploads/project-covers/signature'); + assert.deepEqual(JSON.parse(calls[0].options.body), { contentType: 'image/png', fileSize: 4 }); + assert.equal(calls[0].options.headers.Authorization, 'Bearer token-a'); + const upload = calls[1]; + assert.equal(upload.url, 'https://oss.example/upload'); + assert.equal(upload.options.credentials, 'omit'); + assert.equal(upload.options.headers, undefined); + assert.deepEqual([...upload.options.body.keys()], ['key', 'policy', 'x-oss-forbid-overwrite', 'file']); + const file = upload.options.body.get('file'); + assert.equal(file.name, 'cover.png'); + assert.equal(file.type, 'image/png'); + assert.deepEqual(new Uint8Array(await file.arrayBuffer()), bytes); +}); + +test('CAD metadata accepts, displays and clears HTTPS covers without changing document fields', async () => { + const calls = [], url = 'https://cdn.example/project-covers/plate.png'; + 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 } }); + } }); + assert.equal((await api.create('Plate', '', url)).coverUrl, url); + assert.deepEqual(JSON.parse(calls[0].options.body), { name: 'Plate', description: '', coverUrl: url }); + assert.equal((await api.setCover('cad/a', url)).version, 4); + assert.equal(calls[1].path, '/api/cad/workspace/projects/cad%2Fa'); + assert.equal(calls[1].options.method, 'PATCH'); + assert.deepEqual(JSON.parse(calls[1].options.body), { coverUrl: url }); + assert.equal((await api.setCover('cad/a', '')).coverUrl, null); + assert.deepEqual(JSON.parse(calls[2].options.body), { coverUrl: '' }); +}); + +test('invalid cover links and oversized or unsupported images are rejected before upload', async () => { + let requests = 0; + const api = new CadApi({ fetcher: async () => { requests++; throw new Error('must not fetch'); } }); + for (const url of ['javascript:alert(1)', 'data:image/png;base64,AAAA', 'http://cdn.example/a.png', '/project-covers/a.png', 'https://user:secret@cdn.example/a.png', 'https://cdn.example/' + 'x'.repeat(2048)]) { + assert.equal(projectCoverUrl(url), null); + await assert.rejects(api.setCover('p', url), { code: 'BAD_COVER' }); + } + for (const cover of [{ bytes: new Uint8Array(), mimeType: 'image/png' }, + { bytes: new Uint8Array(MAX_COVER_BYTES + 1), mimeType: 'image/png' }, + { bytes: new Uint8Array([1]), mimeType: 'image/svg+xml' }]) await assert.rejects(api.uploadCover(cover), { code: 'BAD_COVER' }); + assert.equal(requests, 0); +}); + +test('cover upload cannot patch or publish a response after the account changes', async () => { + const api = new CadApi({ fetcher: async (url) => { + if (url.includes('/signature')) return Response.json({ code: 'OK', data: { + uploadUrl: 'https://oss.example/upload', formFields: { key: 'cover.png' }, coverUrl: 'https://cdn.example/cover.png', + } }); + auth.set({ token: 'token-b', user: { userCode: 'owner-b' } }); + return new Response(null, { status: 200 }); + } }); + await assert.rejects(api.uploadCover({ bytes: new Uint8Array([1]), mimeType: 'image/png' }), { code: 'STALE_IDENTITY' }); + assert.equal(auth.token, 'token-b'); +}); test('workspace API uses the documented root, bearer token, no-store and query names', async () => { let requested; @@ -25,6 +94,216 @@ test('workspace API uses the documented root, bearer token, no-store and query n assert.equal(requested.options.headers['Accept-Language'], 'zh-CN'); }); +const aiLimits = { + requestBytes: 4194304, imageBytes: 1048576, imageMaxEdge: 2048, imagesPerRequest: 2, + textBytes: 262144, toolResultTextBytes: 32768, historyItems: 256, + maxModelCallsPerTurn: 12, maxChangesPerTurn: 24, requestTimeoutSeconds: 60, requestsPerMinute: 30, +}; + +test('CAD AI capabilities use the authenticated endpoint and reject incompatible protocols', async () => { + const api = new CadApi({ fetcher: async (url, options) => { + assert.equal(url, '/api/cad/ai/capabilities'); + assert.equal(options.headers.Authorization, 'Bearer token-a'); + return Response.json({ code: 'OK', data: { + enabled: true, protocolVersion: 'cad-agent-v1', model: 'doubao-test', + tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], + limits: aiLimits, + } }); + } }); + assert.equal((await api.aiCapabilities()).model, 'doubao-test'); + const incompatible = new CadApi({ fetcher: async () => Response.json({ code: 'OK', data: { + enabled: true, protocolVersion: 'cad-agent-v2', model: 'model', tools: [], limits: aiLimits, + } }) }); + await assert.rejects(incompatible.aiCapabilities(), { code: 'BAD_RESPONSE' }); +}); + +test('CAD AI capabilities accept absent, zero or larger backend limits without inventing frontend quotas', async () => { + const limits = { ...aiLimits }; + delete limits.maxModelCallsPerTurn; + delete limits.maxChangesPerTurn; + const capabilities = (limits) => ({ + enabled: true, protocolVersion: 'cad-agent-v1', model: 'model', + tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], limits, + }); + for (const value of [limits, {}, { ...limits, imagesPerRequest: 0, requestTimeoutSeconds: null, maxModelCallsPerTurn: 0, maxChangesPerTurn: 0 }, + { ...limits, imagesPerRequest: 5, historyItems: 1024, requestBytes: 8388608, textBytes: 524288 }]) { + const api = new CadApi({ fetcher: async () => Response.json({ code: 'OK', data: capabilities(value) }) }); + assert.deepEqual((await api.aiCapabilities()).limits, value); + } + const invalid = new CadApi({ fetcher: async () => Response.json({ + code: 'OK', data: capabilities({ ...limits, requestTimeoutSeconds: -1 }), + }) }); + await assert.rejects(invalid.aiCapabilities(), { code: 'BAD_RESPONSE' }); +}); + +test('CAD AI chat streams authenticated same-origin SSE without query credentials', async () => { + const controller = new AbortController(); + const body = { protocolVersion: 'cad-agent-v1', documentSessionCode: 'doc-1', turnCode: 'turn-1', history: [], context: { documentRevision: '4' } }; + const api = new CadApi({ fetcher: async (url, options) => { + assert.equal(url, '/api/cad/ai/chat'); + assert.equal(options.method, 'POST'); + assert.equal(options.headers.Authorization, 'Bearer token-a'); + assert.equal(options.headers.Accept, 'text/event-stream'); + assert.equal(options.credentials, 'omit'); + assert.equal(options.cache, 'no-store'); + assert.equal(options.redirect, 'error'); + assert.equal(options.signal, controller.signal); + assert.deepEqual(JSON.parse(options.body), body); + return new Response('event: completed\\n\\n', { headers: { 'Content-Type': 'text/event-stream' } }); + } }); + const response = await api.aiChat(body, controller.signal); + assert.equal(response.headers.get('content-type'), 'text/event-stream'); +}); + +test('a CAD AI response from an old identity is discarded', async () => { + const api = new CadApi({ fetcher: async () => { + auth.set({ token: 'token-b', user: { userCode: 'owner-b' } }); + return new Response(null, { status: 200 }); + } }); + await assert.rejects(api.aiChat({}), { code: 'STALE_IDENTITY' }); + assert.equal(auth.token, 'token-b'); +}); + +function rateClock() { + let time = Date.UTC(2026, 10, 4); + const records = new Map(); + const options = { + now: () => time, + sleep: async (ms, signal) => { signal?.throwIfAborted(); time += ms; }, + storage: { getItem: (key) => records.get(key) ?? null, setItem: (key, value) => records.set(key, value) }, + locks: null, + }; + return { options, advance: (ms) => { time += ms; }, limiter: () => new CadAgentRateLimiter(options) }; +} + +test('all CAD AI calls, including tool continuations, stay under 30 per rolling minute and are evenly paced', async () => { + const clock = rateClock(), sent = [], started = []; + const api = new CadApi({ agentRateLimiter: clock.limiter(), fetcher: async (url) => { + if (url.endsWith('/capabilities')) return Response.json({ code: 'OK', data: { + enabled: true, protocolVersion: 'cad-agent-v1', model: 'model', + tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], + limits: { ...aiLimits, requestsPerMinute: 30 }, + } }); + sent.push(clock.options.now()); + assert.equal(started.length, sent.length, 'network timeout starts with dispatch'); + return new Response(null); + } }); + await api.aiCapabilities(); + for (let i = 0; i < 65; i++) await api.aiChat({ turnCode: 'same-turn', history: i ? [{ type: 'toolResult' }] : [] }, + undefined, () => started.push(clock.options.now())); + assert.equal(sent.length, 65, 'rate limiting queues long turns without a total call cap'); + for (let i = 1; i < sent.length; i++) assert.ok(sent[i] - sent[i - 1] >= 2050); + for (const end of sent) assert.ok(sent.filter((time) => time > end - 60_000 && time <= end).length <= 30); + assert.deepEqual(started, sent); +}); + +test('CAD AI pacing uses higher backend limits and adds no rate limit when absent or zero', async () => { + for (const rate of [120, 0, undefined]) { + const clock = rateClock(), sent = []; + const limits = { ...aiLimits, requestsPerMinute: rate }; + const api = new CadApi({ agentRateLimiter: clock.limiter(), fetcher: async (url) => { + if (url.endsWith('/capabilities')) return Response.json({ code: 'OK', data: { + enabled: true, protocolVersion: 'cad-agent-v1', model: 'model', + tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], limits, + } }); + sent.push(clock.options.now()); return new Response(null); + } }); + await api.aiCapabilities(); + for (let i = 0; i < 130; i++) await api.aiChat({}); + for (let i = 1; i < sent.length; i++) assert.equal(sent[i] - sent[i - 1], rate ? 550 : 0); + if (rate) for (const end of sent) assert.ok(sent.filter((time) => time > end - 60_000 && time <= end).length <= rate); + } +}); + +test('CAD AI pacing follows a stricter advertised rate', async () => { + const clock = rateClock(), sent = []; + const api = new CadApi({ agentRateLimiter: clock.limiter(), fetcher: async (url) => { + if (url.endsWith('/capabilities')) return Response.json({ code: 'OK', data: { + enabled: true, protocolVersion: 'cad-agent-v1', model: 'model', + tools: [{ name: 'inspect_design', description: 'Inspect design', parameters: { type: 'object' } }], + limits: { ...aiLimits, requestsPerMinute: 5 }, + } }); + sent.push(clock.options.now()); return new Response(null); + } }); + await api.aiCapabilities(); + for (let i = 0; i < 7; i++) await api.aiChat({}); + for (let i = 1; i < sent.length; i++) assert.ok(sent[i] - sent[i - 1] >= 12_050); +}); + +test('new CAD API clients and refreshed limiter instances share the account request history', async () => { + const clock = rateClock(), sent = [], limiter = clock.limiter(); + const fetcher = async () => { sent.push(clock.options.now()); return new Response(null); }; + for (const [project, rateLimiter] of [['first', limiter], ['second', limiter], ['refreshed', clock.limiter()]]) { + const api = new CadApi({ fetcher, agentRateLimiter: rateLimiter }); + api.agentRequestsPerMinute = 30; + await api.aiChat({ cadProjectCode: project }); + } + assert.deepEqual(sent.map((time) => time - sent[0]), [0, 2050, 4100]); +}); + +test('Stop cancels queued CAD AI calls before fetch or its timeout starts and consumes no request slot', async () => { + const clock = rateClock(), controller = new AbortController(); + let sent = 0, started = 0; + const api = new CadApi({ agentRateLimiter: new CadAgentRateLimiter({ ...clock.options, sleep: undefined }), + fetcher: async () => { sent++; return new Response(null); } }); + api.agentRequestsPerMinute = 30; + const start = () => { started++; }; + await api.aiChat({}, undefined, start); + const queued = api.aiChat({}, controller.signal, start); + const rejected = assert.rejects(queued, { name: 'AbortError' }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(started, 1); + controller.abort(); + await rejected; + assert.equal(sent, 1); + clock.advance(2050); + await api.aiChat({}, undefined, start); + assert.equal(sent, 2); +}); + +test('a queued CAD AI call rechecks identity before dispatch', async () => { + const clock = rateClock(); + let sent = 0; + const limiter = new CadAgentRateLimiter({ ...clock.options, sleep: async (ms) => { + clock.advance(ms); + auth.set({ token: 'token-b', user: { userCode: 'owner-b' } }); + } }); + const api = new CadApi({ agentRateLimiter: limiter, fetcher: async () => { sent++; return new Response(null); } }); + api.agentRequestsPerMinute = 30; + await api.aiChat({}); + await assert.rejects(api.aiChat({}), { code: 'STALE_IDENTITY' }); + assert.equal(sent, 1); + assert.equal(auth.token, 'token-b'); +}); + +test('429 Retry-After pauses future CAD AI requests without replaying a modelling request', async () => { + for (const kind of ['seconds', 'date', 'absent']) { + const clock = rateClock(), sent = []; + const header = kind === 'seconds' ? '90' : kind === 'date' ? new Date(clock.options.now() + 5000).toUTCString() : null; + const fetcher = async () => { + sent.push(clock.options.now()); + return sent.length === 1 ? new Response(null, { status: 429, headers: header ? { 'Retry-After': header } : {} }) : new Response(null); + }; + const response = await new CadApi({ fetcher, agentRateLimiter: clock.limiter() }).aiChat({}); + assert.equal(response.status, 429); + assert.equal(sent.length, 1, 'never automatically replay a rejected request'); + await new CadApi({ fetcher, agentRateLimiter: clock.limiter() }).aiChat({}); + assert.ok(sent[1] - sent[0] >= (kind === 'seconds' ? 90_050 : kind === 'date' ? 5050 : 60_550)); + assert.equal(auth.token, 'token-a'); + } +}); + +test('CAD AI pacing survives unavailable browser storage within the shared transport', async () => { + const clock = rateClock(), sent = []; + const limiter = new CadAgentRateLimiter({ ...clock.options, storage: { getItem: () => { throw new Error('unavailable'); } } }); + const fetcher = async () => { sent.push(clock.options.now()); return new Response(null); }; + const api = new CadApi({ fetcher, agentRateLimiter: limiter }); + api.agentRequestsPerMinute = 30; + await api.aiChat({}); + await api.aiChat({}); + assert.equal(sent[1] - sent[0], 2050); +}); + test('project records use opaque codes and Shanghai timestamps are parsed with +08:00', async () => { const api = new CadApi({ fetcher: async (url) => { assert.equal(url, '/api/cad/workspace/projects/code%2Fwith%2Fslash'); @@ -78,6 +357,25 @@ test('old 401 cannot sign out a newly logged-in account', async () => { assert.equal(auth.token, 'token-b'); }); +test('project deletion sends the opaque code with DELETE and no request body, and accepts null data', async () => { + const api = new CadApi({ fetcher: async (url, options) => { + assert.equal(url, '/api/cad/workspace/projects/code%2Fwith%2Fslash'); + assert.equal(options.method, 'DELETE'); + assert.equal(options.body, undefined); + assert.equal(options.headers.Authorization, 'Bearer token-a'); + assert.equal(options.headers['Content-Type'], undefined); + return Response.json({ code: 'OK', message: 'OK', data: null, requestId: 'delete-test' }); + } }); + assert.equal(await api.delete('code/with/slash'), null); +}); + +test('failed deletion preserves the backend error and never reports success', async () => { + const api = new CadApi({ fetcher: async () => Response.json({ + code: 'RATE_LIMITED', message: 'Try later', data: null, requestId: 'delete-limited', + }, { status: 429 }) }); + await assert.rejects(api.delete('cad-code'), { code: 'RATE_LIMITED', status: 429, requestId: 'delete-limited' }); +}); + test('current 401 clears identity while network failures preserve it', async () => { let api = new CadApi({ fetcher: async () => { throw new Error('network'); } }); await assert.rejects(api.get('cad-code')); @@ -92,6 +390,24 @@ test('empty document uses its documented error code', async () => { await assert.rejects(api.document('cad-code'), { code: 'CAD_DOCUMENT_NOT_FOUND', status: 404 }); }); +test('document accepts a permanent public URL with null expiry and its own snapshot version', async () => { + const api = new CadApi({ fetcher: async () => Response.json({ code: 'OK', data: { + downloadUrl: 'https://cdn.example/cad-projects/part.sc', expiresAt: null, + version: 7, fileName: 'part.sc', sizeBytes: 3, + } }) }); + const source = await api.document('cad-code'); + assert.equal(source.expiresAt, null); + assert.equal(source.version, 7); + assert.equal(source.downloadUrl, 'https://cdn.example/cad-projects/part.sc'); +}); + +test('public OSS/CDN access denial is not a download signature expiry or platform sign-out', async (t) => { + t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 })); + await assert.rejects(downloadSource({ sizeBytes: 3, expiresAt: null, + downloadUrl: 'https://cdn.example/cad-projects/part.sc' }, 10), { code: 'DOWNLOAD_FORBIDDEN' }); + assert.equal(auth.token, 'token-a'); +}); + test('downloads validate the exact byte count and omit bearer credentials', async (t) => { const bytes = new Uint8Array([1, 2, 3]); t.mock.method(globalThis, 'fetch', async (url, options) => { @@ -106,21 +422,44 @@ test('downloads validate the exact byte count and omit bearer credentials', asyn }); test('OSS POST preserves signed fields and appends the raw .sc file last', async (t) => { + const formFields = { key: 'fixed', policy: 'signed', 'Content-Type': 'application/octet-stream', + 'Content-Disposition': 'attachment; filename="Plate.sc"', 'x-oss-forbid-overwrite': 'true' }; t.mock.method(globalThis, 'fetch', async (url, options) => { assert.equal(url, 'https://oss.example/post'); assert.equal(options.headers, undefined); assert.equal(options.credentials, 'omit'); const fields = [...options.body]; - assert.deepEqual(fields.slice(0, 2), [['key', 'fixed'], ['policy', 'signed']]); + assert.deepEqual(fields.slice(0, -1), Object.entries(formFields)); + assert.equal(options.body.has('x-oss-object-acl'), false); assert.equal(fields.at(-1)[0], 'file'); assert.equal(fields.at(-1)[1].size, 3); assert.equal(fields.at(-1)[1].name, 'Plate.sc'); return new Response(null, { status: 200 }); }); - await uploadSource({ uploadCode: 'u', uploadUrl: 'https://oss.example/post', formFields: { key: 'fixed', policy: 'signed' } }, + await uploadSource({ uploadCode: 'u', uploadUrl: 'https://oss.example/post', formFields }, new Uint8Array([1, 2, 3]), 'Plate.sc'); }); +test('OSS upload 403 does not claim that the upload batch expired', async (t) => { + t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 })); + await assert.rejects(uploadSource({ uploadCode: 'u', uploadUrl: 'https://oss.example/post', formFields: {} }, + new Uint8Array([1, 2, 3]), 'Plate.sc'), { code: 'UPLOAD_FAILED' }); + assert.equal(auth.token, 'token-a'); +}); + +test('storage configuration errors explain the administrator action in both languages', () => { + try { + for (const language of ['zh', 'en']) { + setLocale(language, false); + for (const code of ['CAD_STORAGE_UNAVAILABLE', 'CAD_STORAGE_UNSAFE']) { + assert.match(errorText({ code }), language === 'zh' ? /管理员/ : /administrator/); + assert.doesNotMatch(errorText({ code }), /private|私有|独立.*Bucket/); + } + assert.match(errorText({ code: 'DOWNLOAD_FORBIDDEN' }), /OSS\/CDN/); + } + } finally { setLocale('zh', false); } +}); + test('project names and 256 MiB limit match the workspace contract', () => { assert.equal(CAD.maxSourceBytes, 268435456); assert.equal(validName('机械臂支架'), true); diff --git a/tests/cad/assistant-browser.mjs b/tests/cad/assistant-browser.mjs new file mode 100644 index 0000000..0baa3f8 --- /dev/null +++ b/tests/cad/assistant-browser.mjs @@ -0,0 +1,407 @@ +import assert from 'node:assert/strict'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { chromium } from 'playwright'; + +const base = (process.env.VM_CAD_BASE_URL || 'http://localhost:8094').replace(/\/$/, ''); +const provider = process.env.VM_CAD_MODEL_URL || 'http://127.0.0.1:8092/__assistant/v1'; +const auth = { token: 'cad-browser-test-token', user: { userCode: 'cad-browser-test-user', nickname: 'CAD Browser Test' } }; +const headers = { Authorization: `Bearer ${auth.token}`, 'Content-Type': 'application/json' }; +const request = (page, method, params = {}) => page.evaluate(([method, params]) => window.solidcraft.request(method, params), [method, params]); +const chat = (page, params = {}) => request(page, 'ui.agent_chat', params); +const inspect = (page) => page.evaluate(() => window.solidcraft.inspect({ measure: true })); +async function until(page, predicate, message, timeoutMs = 30000) { + for (let i = 0; i < Math.ceil(timeoutMs / 100); i++) { const state = await chat(page); if (predicate(state)) return state; await page.waitForTimeout(100); } + throw new Error(message + ': ' + JSON.stringify(await chat(page)).slice(0, 2000)); +} +async function ready(page) { + await page.waitForFunction(() => window.vibemakeCad && window.solidcraft, null, { timeout: 180000 }); + let stable = 0; + for (let i = 0; i < 900; i++) { + 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 && state.assistant?.enabled && hostReady ? stable + 1 : 0; + if (stable >= 3) return; + await page.waitForTimeout(100); + } + throw new Error('Host and assistant did not become interactive'); +} +async function clickHandle(page, name) { + for (let i = 0; i < 40; i++) { + const handles = await request(page, 'ui.handles', { prefix: name }); + const handle = handles.find((handle) => handle.name === name); + if (handle) { + const canvas = await page.locator('canvas').boundingBox(); + assert.ok(canvas, 'editor canvas must be visible'); + await page.mouse.click(canvas.x + handle.x, canvas.y + handle.y); + await page.waitForTimeout(150); return; + } + await page.waitForTimeout(100); + } + throw new Error('Missing UI handle: ' + name); +} +async function openAttachmentMenu(page) { + for (let attempt = 0; attempt < 5; attempt++) { + const handles = await request(page, 'ui.handles', { prefix: 'agent_chat:add_file' }); + if (handles.some((handle) => handle.name === 'agent_chat:add_file')) return; + await clickHandle(page, 'agent_chat:add'); + await page.waitForTimeout(200); + } + throw new Error('Attachment menu did not open'); +} +async function openAssistantSettings(page, language) { + await page.locator('[data-engine-menu="preferences"]').click(); + // The host menu is delivered on the next engine frame; select the page only + // after that frame, otherwise its General-page request can win the race. + await page.waitForTimeout(350); + await clickHandle(page, 'prefs:page:Assistant'); + await page.waitForFunction(async () => { + const handles = await window.solidcraft.request('ui.handles', { prefix: 'prefs:ai_features' }); + return handles.some((handle) => handle.name === 'prefs:ai_features'); + }); + await request(page, 'ui.prefs', { language, button: 'apply' }); + await page.waitForFunction(async (language) => (await window.vibemakeCad.getState()).locale === language, language); + await page.waitForTimeout(250); +} +async function configure(page, { id = 'browser-api', kind = 'api', model = 'mock-tools', url = provider, timeout = 30 } = {}) { + await chat(page, { add_agent: { id, name: id, kind, base_url: url, model, request_timeout_s: timeout }, agent: id, open: true }); +} +async function setKey(page, id, key, remember) { + await chat(page, { edit_dialog: id }); + await page.waitForTimeout(350); + await clickHandle(page, 'ai_add:key'); + await page.keyboard.press('ControlOrMeta+A'); + await page.keyboard.type(key, { delay: 15 }); + await page.waitForTimeout(150); + if (process.env.VM_CAD_ARTIFACT_DIR) await page.screenshot({ path: resolve(process.env.VM_CAD_ARTIFACT_DIR, 'assistant-key-setup.png') }); + if (remember) await clickHandle(page, 'ai_add:remember'); + await clickHandle(page, 'ai_add:add'); + await page.waitForTimeout(200); +} +async function reconnect(page, id) { + await chat(page, { agent: id, connect: true }); + await until(page, (state) => state.state === 'ready', 'model did not connect'); +} +async function turn(page, text, approve = true) { + await chat(page, { send: text, attach_view: false, attach_selection: false }); + const state = await until(page, (state) => state.waiting > 0 || state.state !== 'busy', 'tool never reached approval'); + if (state.waiting) await chat(page, { approve }); + return until(page, (state) => state.state !== 'busy' && state.waiting === 0, 'turn did not end'); +} +async function remembered(page) { + return page.evaluate(async () => { + const req = indexedDB.open('vm.cad.agent.credentials.v1', 1); + const db = await new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); + const tx = db.transaction('credentials', 'readonly'), get = tx.objectStore('credentials').get('cad-browser-test-user'); + const value = await new Promise((resolve, reject) => { get.onsuccess = () => resolve(get.result); get.onerror = () => reject(get.error); }); + db.close(); return JSON.parse(value || '{}'); + }); +} +async function saveAndReload(page) { + await page.locator('[data-save]').click(); + await page.waitForFunction(() => document.querySelector('.cad-save-state')?.dataset.state === 'saved', null, { timeout: 60000 }); + await page.reload(); await ready(page); +} +export async function runAssistantBrowserChecks(browser, artifactDir) { + const checks = [], errors = [], context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); + await context.addInitScript((value) => { if (!localStorage.getItem('vm.auth')) localStorage.setItem('vm.auth', JSON.stringify(value)); }, auth); + const page = await context.newPage(); page.on('pageerror', (error) => errors.push(String(error))); + page.on('dialog', (dialog) => dialog.accept()); + let url; + const screenshot = async (name) => { if (artifactDir) { await mkdir(artifactDir, { recursive: true }); await page.screenshot({ path: resolve(artifactDir, name) }); } }; + try { + const created = await (await fetch(`${base}/api/cad/workspace/projects`, { method: 'POST', headers, body: JSON.stringify({ name: 'Assistant browser regression' }) })).json(); + assert.equal(created.code, 'OK'); + url = `${base}/cad/editor/?project=${created.data.cadProjectCode}`; + await page.goto(url); await ready(page); + const readyInfo = await page.evaluate(() => window.vibemakeCad.ready()); + assert.equal(readyInfo.capabilities.assistant, true); + const utilities = await page.locator('.cad-editor-utility button').evaluateAll((buttons) => buttons.map((button) => button.dataset.engineMenu)); + assert.deepEqual(utilities, ['preferences', 'help']); + assert.equal((await chat(page)).permissions, 'ask'); + await until(page, (state) => state.open, 'assistant did not open'); + await screenshot('assistant-zh.png'); + checks.push('original-panel-and-ask-default'); + + await page.route('http://localhost:11434/v1/models', (route) => route.fulfill({ json: { data: [] } })); + await page.route('https://openrouter.ai/api/v1/models', (route) => route.fulfill({ json: { data: [] } })); + await chat(page, { add_dialog: 'api' }); + await page.waitForTimeout(350); + // All original connection kinds stay visible. Unsupported native kinds cannot change the form. + await clickHandle(page, 'ai_add:ui.ai_add_installed'); + let dialogHandles = await request(page, 'ui.handles', { prefix: 'ai_add:' }); + assert.ok(dialogHandles.some((handle) => handle.name === 'ai_add:protocol:openai')); + assert.ok(dialogHandles.some((handle) => handle.name === 'ai_add:ui.ai_add_custom')); + await clickHandle(page, 'ai_add:preset'); + await clickHandle(page, 'ai_add:preset:OpenRouter'); + await screenshot('assistant-original-presets-zh.png'); + await chat(page, { add_dialog: false }); + checks.push('original-connection-kind-layout-and-service-presets'); + + await context.grantPermissions(['clipboard-read', 'clipboard-write']); + await page.evaluate(async () => { + const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 12; + canvas.getContext('2d').fillRect(0, 0, 12, 12); + const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); + await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]); + }); + await openAttachmentMenu(page); + await screenshot('assistant-attachment-menu-zh.png'); + await clickHandle(page, 'agent_chat:paste_picture'); + await until(page, (state) => state.attachments.length === 1, 'clipboard picture did not attach'); + await screenshot('assistant-clipboard-picture-zh.png'); + await clickHandle(page, 'agent_chat:file_remove:0'); + await openAttachmentMenu(page); + const [fileChoice] = await Promise.all([page.waitForEvent('filechooser'), clickHandle(page, 'agent_chat:add_file')]); + await fileChoice.setFiles({ name: 'design-notes.svg', mimeType: 'image/svg+xml', buffer: Buffer.from('CAD design notes') }); + await until(page, (state) => state.attachments.includes('design-notes.svg'), 'original SVG text attachment did not load'); + await clickHandle(page, 'agent_chat:file_remove:0'); + const panel = await request(page, 'ui.handles', { prefix: 'agent_chat:add' }); + const addTarget = panel.find((handle) => handle.name === 'agent_chat:add'); + const canvas = await page.locator('canvas').boundingBox(); + await page.mouse.move(canvas.x + addTarget.x, canvas.y + addTarget.y - 60); + await page.waitForTimeout(200); + await page.evaluate(() => { + const data = new DataTransfer(); + data.items.add(new File(['First design note'], 'dropped-first.md', { type: 'text/plain' })); + data.items.add(new File(['Second design note'], 'dropped-second.txt', { type: 'text/plain' })); + document.querySelector('canvas').dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: data })); + }); + await until(page, (state) => state.attachments.includes('dropped-first.md') && state.attachments.includes('dropped-second.txt'), 'both dropped text files must attach'); + await screenshot('assistant-dropped-files-zh.png'); + await clickHandle(page, 'agent_chat:file_remove:0'); + await clickHandle(page, 'agent_chat:file_remove:0'); + checks.push('original-attachment-menu-clipboard-picture-and-text-file-picker'); + checks.push('browser-drops-attach-multiple-files-without-opening-another-design'); + + await configure(page); await setKey(page, 'browser-api', 'synthetic-memory-key', false); + assert.deepEqual(await remembered(page), {}); + await reconnect(page, 'browser-api'); + const connected = await chat(page); + assert.deepEqual(connected.models.map((model) => model.id).sort(), ['chat-only', 'mock-tools']); + assert.equal(connected.models.find((model) => model.id === 'mock-tools').name, 'Deterministic CAD test model'); + assert.equal(connected.modelsNote, null); + checks.push('connection-loads-original-model-picker-and-provider-display-names'); + const before = await inspect(page); + await chat(page, { send: 'vm-test:create', attach_view: false, attach_selection: false }); + await until(page, (state) => state.waiting > 0, 'missing approval'); + assert.equal((await inspect(page)).bodies.length, before.bodies.length); + await screenshot('assistant-approval-zh.png'); + await chat(page, { approve: true }); + await until(page, (state) => state.state === 'ready' && !state.waiting, 'approved tool did not finish'); + assert.equal((await inspect(page)).bodies.length, 1); + assert.equal((await page.evaluate(() => window.vibemakeCad.getState())).dirty, true); + await screenshot('assistant-result-zh.png'); + const providerCalls = await (await fetch(provider.replace(/\/v1$/, '/requests'))).json(); + assert.ok(providerCalls.some((call) => call.authorization === 'Bearer synthetic-memory-key')); + assert.ok(providerCalls.every((call) => call.cookie === '' && call.authorization !== `Bearer ${auth.token}`)); + assert.ok(!JSON.stringify(await page.evaluate(() => window.vibemakeCad.getState())).includes('synthetic-memory-key')); + assert.ok(!(await page.evaluate(() => localStorage.getItem('vm.cad.engine.prefs') || '')).includes('browser-api')); + checks.push('browser-provider-request-no-site-credentials-and-approval-before-mutation'); + + await chat(page, { new_chat: true }); + await page.waitForTimeout(200); + assert.deepEqual((await chat(page)).items, [], 'new conversation must not begin with a stale cancelled notice'); + checks.push('new-conversation-starts-with-a-clean-transcript'); + await turn(page, 'vm-test:repeat-id first'); + await turn(page, 'vm-test:repeat-id second'); + assert.equal((await chat(page)).items.filter((item) => item.tool).length, 2, 'reused provider IDs must retain both tool cards'); + await screenshot('assistant-tool-history.png'); + checks.push('reused-provider-tool-ids-retain-separate-transcript-cards'); + + for (const scenario of ['tool-error', 'unknown-tool', 'invalid-arguments']) { + await chat(page, { new_chat: true }); + const state = await turn(page, `vm-test:${scenario}`); + assert.ok(JSON.stringify(state.items).includes('CAD tool result received'), `${scenario}: model must receive the error and finish its answer`); + assert.ok(state.items.some((item) => item.tool && item.status === 'Failed'), `${scenario}: failed tool stays visible`); + } + checks.push('failed-unknown-and-malformed-tools-return-feedback-to-model'); + + await saveAndReload(page); + assert.equal((await inspect(page)).bodies.length, 1); + assert.equal((await chat(page)).items.length, 0); + // Ordinary configuration remains, but memory-only credentials do not. + await reconnect(page, 'browser-api'); + await turn(page, 'vm-test:read'); + assert.ok(JSON.stringify((await chat(page)).items).includes('AIBox'), 'read tool result must describe the current design'); + const afterReload = await (await fetch(provider.replace(/\/v1$/, '/requests'))).json(); + assert.equal(afterReload.at(-1).authorization, ''); + checks.push('ai-native-model-saves-reopens-and-chat-memory-clears'); + + await chat(page, { new_chat: true }); + const count = (await inspect(page)).bodies.length; + await turn(page, 'vm-test:create', false); + assert.equal((await inspect(page)).bodies.length, count); + checks.push('denial-prevents-model-changes'); + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:create', attach_view: false, attach_selection: false }); + await until(page, (state) => state.waiting > 0, 'missing stale approval'); + await page.evaluate(() => window.solidcraft.execute('solid.box', { length: 3, width: 4, height: 5, body_name: 'Human' })); + await until(page, (state) => !state.waiting && !state.turn, 'stale approval was not cancelled'); + assert.equal((await inspect(page)).bodies.length, count + 1); + checks.push('manual-edits-invalidate-ai-approval'); + + await configure(page, { id: 'anthropic-api', kind: 'anthropic' }); + await setKey(page, 'anthropic-api', 'synthetic-remembered-key', true); + for (let i = 0; i < 40 && !(await remembered(page))['anthropic-api']; i++) await page.waitForTimeout(100); + assert.equal((await remembered(page))['anthropic-api'], 'synthetic-remembered-key'); + await reconnect(page, 'anthropic-api'); + await chat(page, { permissions: 'edits' }); + await turn(page, 'vm-test:read'); + checks.push('anthropic-compatible-browser-protocol-and-opt-in-idb-key'); + + await chat(page, { new_chat: true }); + await turn(page, 'vm-test:tool-error'); + const failedCalls = await (await fetch(provider.replace(/\/v1$/, '/requests'))).json(); + assert.ok(failedCalls.some((call) => call.path.endsWith('/messages') && call.body.messages?.at(-1)?.content?.some?.((part) => part.type === 'tool_result' && part.is_error === true))); + checks.push('anthropic-failed-tools-carry-is-error-and-continue-conversation'); + + await chat(page, { new_chat: true }); + await turn(page, 'vm-test:batch'); + assert.equal((await inspect(page)).bodies.length, count + 3); + await chat(page, { undo: true }); + assert.equal((await inspect(page)).bodies.length, count + 1, 'one AI undo must remove the complete batch'); + checks.push('multi-step-ai-batch-retains-original-undo-group'); + + await openAssistantSettings(page, 'zh'); + await screenshot('assistant-settings-zh.png'); + await request(page, 'ui.prefs', { button: 'cancel' }); + await saveAndReload(page); + await reconnect(page, 'anthropic-api'); + const rememberedCalls = await (await fetch(provider.replace(/\/v1$/, '/requests'))).json(); + assert.equal(rememberedCalls.at(-1).key, 'synthetic-remembered-key'); + checks.push('opt-in-remembered-key-restores-after-refresh'); + + // Changing a service URL must not use its old key for listing, testing or a new connection. + await chat(page, { edit_dialog: 'anthropic-api' }); + await page.waitForTimeout(350); + await clickHandle(page, 'ai_add:url'); + await page.keyboard.press('ControlOrMeta+A'); + await page.keyboard.type(provider.replace('/v1', '/other/v1'), { delay: 10 }); + await page.waitForTimeout(150); + await clickHandle(page, 'ai_add:add'); + assert.equal((await chat(page)).state, 'off', 'editing the active endpoint must release its old connection and key'); + await reconnect(page, 'anthropic-api'); + const changedCalls = await (await fetch(provider.replace(/\/v1$/, '/requests'))).json(); + assert.ok(changedCalls.some((call) => call.path.includes('/other/')), 'edited endpoint must actually receive a request'); + assert.ok(changedCalls.filter((call) => call.path.includes('/other/')).every((call) => !call.key && !call.authorization)); + for (let i = 0; i < 50 && (await remembered(page))['anthropic-api']; i++) await page.waitForTimeout(100); + assert.equal((await remembered(page))['anthropic-api'], undefined); + checks.push('changed-service-does-not-inherit-key-and-deletes-persisted-copy'); + + await page.evaluate(() => window.vibemakeCad.setLocale('en')); + await page.evaluate(() => window.vibemakeCad.ready()); + await openAssistantSettings(page, 'en'); + await screenshot('assistant-settings-en.png'); + await request(page, 'ui.prefs', { button: 'cancel' }); + await chat(page, { open: true }); + await screenshot('assistant-en.png'); + + await configure(page, { id: 'chat-only', model: 'chat-only' }); await reconnect(page, 'chat-only'); + await turn(page, 'vm-test:create'); + assert.equal((await inspect(page)).bodies.length, count + 1); + const only = await chat(page); + assert.ok(only.modelWarning?.includes('Chat only') || JSON.stringify(only).includes('Chat only')); + checks.push('chat-only-model-never-advertises-cad-editing'); + + for (const model of ['unauthorized', 'rate-limit', 'bad-json', 'redirect']) { + await configure(page, { id: model, model }); + await chat(page, { connect: true }); + const failed = await until(page, (state) => !['starting', 'busy'].includes(state.state), model + ' did not fail'); + assert.notEqual(failed.state, 'ready'); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('vm.auth')).token), auth.token); + } + checks.push('provider-auth-rate-limit-malformed-and-redirect-errors-do-not-log-out'); + + await configure(page, { id: 'no-cors', url: provider.replace('/v1', '/no-cors/v1') }); + await chat(page, { connect: true }); + const cors = await until(page, (state) => !['starting', 'busy'].includes(state.state), 'CORS rejection did not settle'); + assert.notEqual(cors.state, 'ready'); + assert.ok(JSON.stringify(cors.items).includes('Cannot reach')); + checks.push('browser-cors-rejection-reports-network-context'); + + await reconnect(page, 'browser-api'); + await chat(page, { permissions: 'all', send: 'vm-test:forbidden' }); + await until(page, (state) => state.state === 'ready' && !state.turn, 'platform restriction did not settle'); + assert.equal((await inspect(page)).bodies.length, count + 1); + checks.push('all-mode-preserves-host-project-binding'); + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:slow', attach_view: false, attach_selection: false }); + await page.waitForTimeout(100); + await chat(page, { cancel: true }); + await page.waitForTimeout(1800); + assert.equal((await inspect(page)).bodies.length, count + 1); + checks.push('stop-cancels-in-flight-request-and-preserves-completed-model'); + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:timeout', attach_view: false, attach_selection: false }); + const timedOut = await until(page, (state) => state.state !== 'busy' && !state.turn, 'request timeout did not abort the response', 45000); + assert.ok(JSON.stringify(timedOut.items).includes('timed out')); + assert.equal((await inspect(page)).bodies.length, count + 1); + checks.push('configured-timeout-aborts-response-without-model-changes'); + + await context.setOffline(true); + try { + await chat(page, { connect: true }); + const offline = await until(page, (state) => !['starting', 'busy'].includes(state.state), 'offline request did not settle'); + assert.notEqual(offline.state, 'ready'); + assert.ok(JSON.stringify(offline.items).includes('Cannot reach')); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('vm.auth')).token), auth.token); + } finally { await context.setOffline(false); } + checks.push('offline-model-request-does-not-change-site-authentication'); + + await configure(page, { id: 'storage-unavailable' }); + await page.evaluate(() => { + window.__cadTestIdbOpen = IDBFactory.prototype.open; + IDBFactory.prototype.open = function(name, ...args) { + if (name === 'vm.cad.agent.credentials.v1') throw new DOMException('Test storage denied', 'SecurityError'); + return window.__cadTestIdbOpen.call(this, name, ...args); + }; + }); + try { + await setKey(page, 'storage-unavailable', 'synthetic-unremembered-key', true); + const failedStorage = await until(page, (state) => JSON.stringify(state.items).includes('could not be remembered'), 'storage failure notice is missing'); + assert.ok(failedStorage.items.length); + await reconnect(page, 'storage-unavailable'); + const calls = await (await fetch(provider.replace(/\/v1$/, '/requests'))).json(); + assert.equal(calls.at(-1).authorization, 'Bearer synthetic-unremembered-key', 'failed persistence retains the page-memory key'); + } finally { + await page.evaluate(() => { IDBFactory.prototype.open = window.__cadTestIdbOpen; delete window.__cadTestIdbOpen; }); + } + assert.equal((await remembered(page))['storage-unavailable'], undefined); + checks.push('credential-storage-failure-is-explicit-and-memory-key-remains-usable'); + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:slow', attach_view: false, attach_selection: false }); + await page.waitForTimeout(100); + const bound = await page.evaluate(() => window.vibemakeCad.getState()); + await page.evaluate(([binding, project]) => window.vibemakeCad.setAgentContext({ userId: 'other-test-account', projectId: project, binding, sessionId: 'other-session' }), [bound.binding, created.data.cadProjectCode]); + await page.waitForTimeout(1800); + assert.equal((await inspect(page)).bodies.length, count + 1); + assert.equal((await chat(page)).permissions, 'ask'); + assert.equal((await chat(page)).items.length, 0); + const other = await chat(page); + assert.ok(!JSON.stringify(other).includes('synthetic-remembered-key')); + checks.push('late-responses-and-credentials-isolated-after-context-change'); + assert.deepEqual(errors, []); + return { checks, errors, url }; + } catch (error) { + await screenshot('assistant-failure.png').catch(() => {}); + if (artifactDir) await writeFile(resolve(artifactDir, 'assistant-failure.json'), JSON.stringify({ checks, errors, error: String(error), state: await chat(page).catch(() => null) }, null, 2)); + throw error; + } finally { await context.close(); } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const options = { headless: true, args: ['--enable-unsafe-webgpu', '--use-angle=swiftshader', '--enable-webgl'] }; + if (process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE) options.executablePath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE; + const browser = await chromium.launch(options), artifacts = process.env.VM_CAD_ARTIFACT_DIR; + try { + const result = await runAssistantBrowserChecks(browser, artifacts); + if (artifacts) await writeFile(resolve(artifacts, 'assistant-browser-results.json'), JSON.stringify(result, null, 2)); + console.log(JSON.stringify(result)); + } finally { await browser.close(); } +} diff --git a/tests/cad/assistant-model.mjs b/tests/cad/assistant-model.mjs new file mode 100644 index 0000000..791d605 --- /dev/null +++ b/tests/cad/assistant-model.mjs @@ -0,0 +1,246 @@ +// Test-only browser-accessible provider. Never used by the product or business API. +const calls = []; +const cadAgentCalls = []; +let next = 0; +const send = (res, value, status = 200) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); }; +const textContent = (message) => typeof message?.content === 'string' ? message.content : (message?.content || []).filter((item) => item.type === 'text').map((item) => item.text).join('\n'); +export async function assistantModel(req, res, url, bytes) { + if (url.pathname.startsWith('/cad/ai/')) { + if (req.headers.authorization !== 'Bearer cad-browser-test-token') { + send(res, { code: 'UNAUTHORIZED', message: 'Sign in required', data: null, requestId: 'cad-agent-test' }, 401); + return true; + } + if (url.pathname === '/cad/ai/requests') { send(res, cadAgentCalls); return true; } + if (url.pathname === '/cad/ai/capabilities' && req.method === 'GET') { + cadAgentCalls.push({ path: url.pathname, method: req.method, authorization: req.headers.authorization }); + send(res, { code: 'OK', message: 'OK', requestId: 'cad-agent-capabilities', data: { + enabled: true, protocolVersion: 'cad-agent-v1', model: 'Mock CAD Agent', + tools: [ + { name: 'batch', description: 'Run CAD commands transactionally', parameters: { type: 'object', properties: { + commands: { type: 'array', items: { type: 'object' } }, rollback: { type: 'boolean' }, + }, required: ['commands'], additionalProperties: false } }, + { name: 'execute', description: 'Run a CAD command', parameters: { type: 'object', properties: { + command: { type: 'string' }, params: { type: 'object' }, verbose: { type: 'boolean' }, expect: { type: 'object' }, + }, required: ['command'], additionalProperties: false } }, + { name: 'inspect_design', description: 'Inspect the current design', parameters: { type: 'object', properties: { + measure: { type: 'boolean' }, sketches: { type: 'boolean' }, joints: { type: 'boolean' }, + }, additionalProperties: false } }, + { name: 'measure', description: 'Measure a body or the design summary', parameters: { type: 'object', properties: { + body: { type: 'string' }, summary: { type: 'boolean' }, + }, additionalProperties: false } }, + { name: 'screenshot', description: 'Capture the CAD model view', parameters: { type: 'object', properties: { + view: { type: 'string' }, width: { type: 'integer' }, height: { type: 'integer' }, source: { type: 'string' }, + camera: { type: 'object' }, + grid: { type: 'boolean' }, axes: { type: 'boolean' }, + }, additionalProperties: false } }, + ], + limits: { + requestBytes: 4194304, imageBytes: 1048576, imageMaxEdge: 2048, imagesPerRequest: 2, textBytes: 262144, + toolResultTextBytes: 32768, historyItems: 256, maxModelCallsPerTurn: 12, maxChangesPerTurn: 24, + requestTimeoutSeconds: 60, requestsPerMinute: 30, + }, + } }); + return true; + } + if (url.pathname !== '/cad/ai/chat' || req.method !== 'POST') { + send(res, { code: 'NOT_FOUND', message: 'Not found', data: null, requestId: 'cad-agent-test' }, 404); + return true; + } + let body; + try { body = JSON.parse(bytes.toString()); } catch { send(res, { code: 'BAD_REQUEST', message: 'Invalid JSON', data: null }, 400); return true; } + const revision = body.context?.documentRevision; + if (typeof revision !== 'string' || revision.length < 1 || revision.length > 128) { + send(res, { code: 'BAD_REQUEST', message: 'Invalid documentRevision', data: null }, 400); + return true; + } + const record = { path: url.pathname, authorization: req.headers.authorization, receivedAt: Date.now(), body }; + cadAgentCalls.push(record); + const history = body.history || [], last = history.at(-1); + const prompt = [...history].reverse().find((item) => item.type === 'message' && item.role === 'user'); + const text = textContent(prompt); + const envelope = (data) => ({ code: 'OK', message: 'OK', data: { documentSessionCode: body.documentSessionCode, turnCode: body.turnCode, ...data }, requestId: 'cad-agent-request-' + cadAgentCalls.length }); + const write = async (event, data) => { + const bytes = Buffer.from(`event:${event}\r\ndata:${JSON.stringify(envelope(data))}\r\n\r\n`); + for (let at = 0; at < bytes.length; at += 17) { + if (res.destroyed) return; + res.write(bytes.subarray(at, at + 17)); + await new Promise((resolve) => setTimeout(resolve, 1)); + } + }; + res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }); + if (text.includes('vm-test:tool-text-budget')) { + const step = history.filter((item) => item.type === 'toolResult').length; + if (step >= 2) { + await write('completed', { finishReason: 'stop', output: [{ type: 'message', role: 'assistant', content: [ + { type: 'text', text: 'Used a smaller read-only summary after the oversized result; no modifications were replayed.' }, + ] }], usage: null }); + } else { + const tool = step === 0 ? { name: 'inspect_design', arguments: { measure: true } } + : { name: 'measure', arguments: { body: 'LongTurnBox_0', summary: true } }; + const callCode = 'text_budget_' + cadAgentCalls.length; + await write('tool_call', { callCode, ...tool }); + await write('completed', { finishReason: 'tool_calls', output: [{ type: 'toolCall', callCode, ...tool }], usage: null }); + } + res.end(); return true; + } + if (text.includes('vm-test:budget-')) { + const step = history.filter((item) => item.type === 'toolResult').length; + if (step >= 4) { + await write('completed', { finishReason: 'stop', output: [{ type: 'message', role: 'assistant', content: [ + { type: 'text', text: 'Finished with the backend image budget and CAD inspection.' }, + ] }], usage: null }); + } else { + // Deliberately request one image beyond the default quota. The frontend + // must stop it before changing camera/rendering, then still feed back the error. + const tool = step < 3 ? { name: 'screenshot', arguments: { view: ['iso', 'front', 'top'][step], width: 160, height: 100 } } + : { name: 'inspect_design', arguments: {} }; + const callCode = 'budget_' + cadAgentCalls.length; + await write('tool_call', { callCode, ...tool }); + await write('completed', { finishReason: 'tool_calls', output: [{ type: 'toolCall', callCode, ...tool }], usage: null }); + } + res.end(); return true; + } + if (text.includes('vm-test:long-turn')) { + // Keep capabilities at 12 calls / 24 changes to catch frontend per-turn caps. + const step = history.filter((item) => item.type === 'toolResult').length; + if (step < 15) { + const tool = { name: 'batch', arguments: { commands: [0, 1].map((offset) => { + const index = step * 2 + offset; + return { command: 'solid.box', params: { + length: 2, width: 3, height: 4, corner: [index * 4, 0, 0], body_name: 'LongTurnBox_' + index, + } }; + }) } }; + const callCode = 'long_turn_' + cadAgentCalls.length; + await write('tool_call', { callCode, ...tool }); + await write('completed', { finishReason: 'tool_calls', output: [{ type: 'toolCall', callCode, ...tool }], usage: null }); + } else { + await write('completed', { finishReason: 'stop', output: [{ type: 'message', role: 'assistant', content: [ + { type: 'text', text: 'Completed 30 CAD changes over 16 model calls in one turn.' }, + ] }], usage: null }); + } + res.end(); return true; + } + if (text.includes('vm-test:recover') || text.includes('vm-test:partial')) { + const results = history.filter((item) => item.type === 'toolResult'); + const partial = text.includes('vm-test:partial'); + const step = results.length; + let tool; + if (step === 0) { + // The gear prompt in the report used m for its module, but m is the reserved metre unit. + const bad = { command: 'set_parameter', params: { name: 'm', value: '3 mm' } }; + tool = { name: 'batch', arguments: partial + ? { rollback: false, commands: [{ command: 'solid.box', params: { length: 2, width: 3, height: 4, body_name: 'KeptStep' } }, bad] } + : { commands: Array.from({ length: 24 }, () => bad) } }; + } else if (step === 1) { + tool = { name: 'inspect_design', arguments: { measure: true } }; + } else if (step === 2) { + const parameter = partial ? 'partial_gear_module' : 'gear_module'; + tool = { name: 'batch', arguments: { commands: [ + { command: 'set_parameter', params: { name: parameter, value: '3 mm' } }, + { command: 'solid.box', params: { length: parameter, width: 3, height: 4, body_name: partial ? 'PartialRecovery' : 'RecoveredBox' } }, + ] } }; + } else { + const resultText = 'Analysed the failed parameter, inspected the design, and completed the corrected step.'; + await write('completed', { finishReason: 'stop', output: [{ type: 'message', role: 'assistant', content: [{ type: 'text', text: resultText }] }], usage: null }); + res.end(); return true; + } + const callCode = 'recovery_' + cadAgentCalls.length; + await write('tool_call', { callCode, ...tool }); + await write('completed', { finishReason: 'tool_calls', output: [{ type: 'toolCall', callCode, ...tool }], usage: null }); + res.end(); return true; + } + if (text.includes('vm-test:screenshot-recover')) { + const step = history.filter((item) => item.type === 'toolResult').length; + const tool = step === 0 ? { name: 'screenshot', arguments: { view: 'MissingAgentView', width: 320, height: 200 } } + : step === 1 ? { name: 'inspect_design', arguments: {} } + : { name: 'screenshot', arguments: { view: 'iso', width: 320, height: 200 } }; + if (step >= 3) { + await write('completed', { finishReason: 'stop', output: [{ type: 'message', role: 'assistant', content: [ + { type: 'text', text: 'Inspected the design, corrected the view, and received the screenshot.' }, + ] }], usage: null }); + } else { + const callCode = 'screenshot_recovery_' + cadAgentCalls.length; + await write('tool_call', { callCode, ...tool }); + await write('completed', { finishReason: 'tool_calls', output: [{ type: 'toolCall', callCode, ...tool }], usage: null }); + } + res.end(); return true; + } + if (last?.type === 'toolResult') { + await write('text_delta', { text: 'CAD tool result received.' }); + await write('completed', { finishReason: 'stop', output: [{ type: 'message', role: 'assistant', content: [{ type: 'text', text: 'CAD tool result received.' }] }], usage: null }); + res.end(); return true; + } + if (text.includes('vm-test:truncated')) { + await write('text_delta', { text: 'A tool is being considered.' }); + await write('tool_call', { callCode: 'call-truncated', name: 'execute', arguments: { command: 'solid.box', params: { length: 2, width: 3, height: 4 } } }); + res.end(); return true; + } + const callCode = 'call_' + cadAgentCalls.length; + const tool = text.includes('vm-test:screenshot-camera') + ? { name: 'screenshot', arguments: { camera: { target: [1, 1.5, 2], yaw: 1, pitch: 0.2, distance: 12, fov: 0.5, roll: 0.3 }, width: 320, height: 200, source: 'model', grid: false, axes: false } } + : text.includes('vm-test:screenshot') + ? { name: 'screenshot', arguments: { view: text.includes('vm-test:screenshot-named') ? 'AgentSavedView' + : text.includes('vm-test:screenshot-isometric') ? 'Isometric' : 'iso', width: 320, height: 200, source: 'model', grid: false, axes: false } } + : text.includes('vm-test:read') + ? { name: 'inspect_design', arguments: { measure: true, sketches: false, joints: false } } + : { name: 'execute', arguments: { command: 'solid.box', params: { length: 2, width: 3, height: 4, body_name: 'PlatformAIBox' }, expect: { bodies: 1, volume_mm3: 24 } } }; + const assistantText = 'I will inspect or update the current CAD design.'; + await write('text_delta', { text: assistantText }); + await write('tool_call', { callCode, ...tool }); + await new Promise((resolve) => setTimeout(resolve, 250)); + if (res.destroyed) return true; + await write('completed', { finishReason: 'tool_calls', output: [ + { type: 'message', role: 'assistant', content: [{ type: 'text', text: assistantText }] }, + { type: 'toolCall', callCode, ...tool }, + ], usage: null }); + res.end(); return true; + } + if (!url.pathname.startsWith('/__assistant/')) return false; + if (!url.pathname.includes('/no-cors/')) { + res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'content-type, authorization, x-api-key, anthropic-version, anthropic-dangerous-direct-browser-access'); + } + if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return true; } + if (url.pathname === '/__assistant/requests') { send(res, calls); return true; } + if (url.pathname === '/__assistant/reset') { calls.length = 0; send(res, {}); return true; } + let body; + try { body = bytes.length ? JSON.parse(bytes.toString()) : {}; } catch { send(res, { error: 'bad json' }, 400); return true; } + calls.push({ path: url.pathname, authorization: req.headers.authorization || '', key: req.headers['x-api-key'] || '', cookie: req.headers.cookie || '', body }); + if (url.pathname.endsWith('/models')) { + if (url.pathname.includes('/models-fail/')) send(res, { error: 'listing unavailable' }, 500); + else send(res, { data: [{ id: 'mock-tools', name: 'Deterministic CAD test model' }, { id: 'chat-only' }] }); + return true; + } + if (body.model === 'unauthorized') { send(res, { error: 'invalid test key' }, 401); return true; } + if (body.model === 'rate-limit') { send(res, { error: 'rate limited' }, 429); return true; } + if (body.model === 'bad-json') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{not json'); return true; } + if (body.model === 'redirect') { res.writeHead(307, { Location: '/__assistant/redirect-target' }); res.end(); return true; } + const protocol = url.pathname.endsWith('/messages') ? 'anthropic' : 'openai'; + const messages = body.messages || [], last = messages.at(-1); + const prompt = [...messages].reverse().find((item) => item.role === 'user' && textContent(item).includes('vm-test:')); + const text = textContent(prompt); + const reply = (toolCalls, content = 'Test model response') => { + const id = text.includes('vm-test:repeat-id') ? 'reused-provider-call' : 'mock-call-' + ++next; + if (protocol === 'anthropic') send(res, { id, type: 'message', role: 'assistant', model: body.model, content: toolCalls.length ? toolCalls.map(([name, input], index) => ({ type: 'tool_use', id: id + '-' + index, name, input })) : [{ type: 'text', text: content }], stop_reason: toolCalls.length ? 'tool_use' : 'end_turn' }); + else send(res, { choices: [{ message: { role: 'assistant', content: toolCalls.length ? null : content, ...(toolCalls.length ? { tool_calls: toolCalls.map(([name, args], index) => ({ id: id + '-' + index, type: 'function', function: { name, arguments: text.includes('vm-test:invalid-arguments') ? '{invalid-json' : JSON.stringify(args) } })) } : {}) }, finish_reason: toolCalls.length ? 'tool_calls' : 'stop' }] }); + }; + if (body.model === 'chat-only') { reply([], 'Chat-only test response'); return true; } + const probe = body.tools?.some((tool) => (tool.function?.name || tool.name) === 'cad_connection_test'); + if (probe) { reply([['cad_connection_test', { ok: true }]]); return true; } + const toolResult = last?.role === 'tool' || last?.content?.some?.((item) => item.type === 'tool_result'); + if (toolResult) { reply([], 'CAD tool result received. Test turn complete.'); return true; } + if (text.includes('vm-test:slow')) await new Promise((resolve) => setTimeout(resolve, 1500)); + if (text.includes('vm-test:timeout')) await new Promise((resolve) => setTimeout(resolve, 32000)); + if (res.destroyed) return true; + if (text.includes('vm-test:read') || text.includes('vm-test:repeat-id')) reply([['inspect_design', { measure: true, sketches: true }]]); + else if (text.includes('vm-test:tool-error') || text.includes('vm-test:invalid-arguments')) reply([['execute', { command: 'assistant.nonexistent_command', params: {} }]]); + else if (text.includes('vm-test:unknown-tool')) reply([['not_a_cad_tool', {}]]); + else if (text.includes('vm-test:forbidden')) reply([['execute', { command: 'file.new', params: {} }]]); + else if (text.includes('vm-test:batch')) reply([['batch', { commands: [ + { command: 'solid.box', params: { length: 2, width: 3, height: 4, body_name: 'BatchA' } }, + { command: 'solid.box', params: { length: 3, width: 4, height: 5, body_name: 'BatchB' } }, + ] }]]); + else reply([['execute', { command: 'solid.box', params: { length: 2, width: 3, height: 4, body_name: 'AIBox' }, expect: { bodies: 1, volume_mm3: 24 } }]]); + return true; +} diff --git a/tests/cad/browser-e2e.mjs b/tests/cad/browser-e2e.mjs index 48d5101..034ab87 100644 --- a/tests/cad/browser-e2e.mjs +++ b/tests/cad/browser-e2e.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { mkdir, writeFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import { chromium } from 'playwright'; +import { runPlatformAgentBrowserChecks } from './platform-agent-browser.mjs'; const base = (process.env.VM_CAD_BASE_URL || 'http://localhost:8091').replace(/\/$/, ''); const artifactDir = process.env.VM_CAD_ARTIFACT_DIR ? resolve(process.env.VM_CAD_ARTIFACT_DIR) : null; @@ -12,13 +13,20 @@ const auth = { token: 'cad-browser-test-token', user: { userCode: 'cad-browser-t 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); + 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()) }); + }); return context; } async function ready(page) { - await page.waitForFunction(() => window.vibemakeCad && window.solidcraft, null, { timeout: 180000 }); + await page.waitForFunction(() => window.vibemakeCad && typeof window.solidcraft?.execute === 'function', null, { timeout: 180000 }); + let stable = 0; for (let i = 0; i < 900; i++) { const state = await page.evaluate(() => window.vibemakeCad.getState()); - if (state.binding && !state.locked) return; + const hostReady = await page.evaluate(() => document.querySelector('#cad-main')?.hidden && !document.querySelector('#cad-viewport')?.inert); + stable = state.binding && !state.locked && hostReady ? stable + 1 : 0; + if (stable >= 3) return; await page.waitForTimeout(200); } throw new Error('CAD editor did not become interactive'); @@ -65,7 +73,22 @@ 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.equal(await first.locator('.cad-engine-menus button').count(), 3); + assert.deepEqual(await first.locator('.cad-engine-menus button').evaluateAll((buttons) => buttons.map((button) => button.dataset.engineMenu)), ['file', 'assistant', 'preferences', 'help']); + 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(); + const actions = header.querySelector('.nav-actions').getBoundingClientRect(); + const height = header.getBoundingClientRect().height; + return { height, logoLeft: logo.left, controlsLeft: left.left, actionsRight: actions.right, viewportWidth: innerWidth }; + }); + assert.equal(editorBar.height, 42); + assert.ok(editorBar.logoLeft < editorBar.controlsLeft); + assert.ok(editorBar.actionsRight >= editorBar.viewportWidth - 20); + 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'), '保存'); + assert.equal(await first.locator('[data-history="undo"]').isDisabled(), true); + assert.equal(await first.locator('[data-history="redo"]').isDisabled(), true); assert.equal(await first.locator('.cad-language').count(), 0); assert.equal(await first.getByText('VibeMake CAD', { exact: true }).count(), 0); const listLogo = first.getByRole('link', { name: '返回项目列表' }); @@ -73,8 +96,16 @@ try { assert.equal((await listLogo.innerText()).trim(), ''); assert.equal(await first.locator('header.nav select').count(), 0); assert.equal(await first.locator('.nav-logo').getAttribute('href'), '/cad/'); - checks.push('editor-uses-single-main-site-bar-without-project-or-locale-controls'); + checks.push('editor-uses-cad-app-bar-with-logo-and-hidden-locale-controls'); await execute(first, 'solid.box', { length: 20, width: 30, height: 8 }); + await first.waitForFunction(async () => (await window.vibemakeCad.getState()).canUndo === true); + await first.locator('[data-history="undo"]').click(); + await first.waitForFunction(async () => { const state = await window.vibemakeCad.getState(); return !state.canUndo && state.canRedo; }); + assert.equal((await first.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 0); + await first.locator('[data-history="redo"]').click(); + await first.waitForFunction(async () => { const state = await window.vibemakeCad.getState(); return state.canUndo && !state.canRedo; }); + assert.equal((await first.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 1); + checks.push('editor-history-controls-follow-engine-state'); const atomic = await first.evaluate(async () => { const before = await window.vibemakeCad.getState(); let code; try { await window.vibemakeCad.openProject({ projectId: 'invalid', bytes: new Uint8Array([1, 2, 3]) }); } catch (error) { code = error.code; } @@ -90,15 +121,109 @@ try { const dirty = (await bridge.getState()).dirty; await bridge.releaseSnapshot(snapshot.snapshotId); return dirty; }); assert.equal(snapshotAck, true); checks.push('snapshot-ack-keeps-later-edits-dirty'); + const coverCapture = await first.evaluate(async () => { + const bridge = window.vibemakeCad; + const capture = async () => { + const snapshot = await bridge.createSnapshot({ includeCover: true }); + const result = { bytes: Array.from(snapshot.cover?.bytes || []), width: snapshot.cover?.width, height: snapshot.cover?.height, mimeType: snapshot.cover?.mimeType }; + await bridge.releaseSnapshot(snapshot.snapshotId); + return result; + }; + const original = await window.solidcraft.request('ui.inspect', {}); + const first = await capture(); + await window.solidcraft.request('ui.view', { view: 'back' }); + const before = await window.solidcraft.request('ui.inspect', {}); + const second = await capture(); + const after = await window.solidcraft.request('ui.inspect', {}); + return { first, second, cameraStable: JSON.stringify(before.camera) === JSON.stringify(after.camera), originalCamera: original.camera }; + }); + assert.equal(coverCapture.first.width, 640); + assert.equal(coverCapture.first.height, 400); + assert.equal(coverCapture.first.mimeType, 'image/png'); + assert.ok(coverCapture.first.bytes.length > 1000); + assert.deepEqual(coverCapture.second.bytes, coverCapture.first.bytes); + assert.equal(coverCapture.cameraStable, true); + if (artifactDir) await writeFile(resolve(artifactDir, 'fixed-camera-cover.png'), Buffer.from(coverCapture.first.bytes)); + checks.push('fixed-isometric-cover-ignores-live-camera-and-leaves-it-unchanged'); + const saveRequests = []; + first.on('request', (request) => { + if (['POST', 'PUT'].includes(request.method()) && /\/api\/cad\/(workspace\/projects\/|mock-oss\/)/.test(request.url()) && !request.url().includes('/mock-oss/cover-')) { + saveRequests.push({ url: request.url(), body: request.url().includes('/mock-oss/') ? null : request.postDataJSON() }); + } + }); + await first.route('**/api/cad/mock-oss/*', async (route) => { + assert.equal(route.request().headers().authorization, undefined); + const response = await route.fetch(); + assert.equal(response.status(), 200); + await route.abort('failed'); + }, { times: 1 }); await first.locator('[data-save]').click(); await first.waitForFunction(() => document.querySelector('[data-state]')?.dataset.state === 'saved', null, { timeout: 90000 }); assert.equal((await first.evaluate(() => window.vibemakeCad.getState())).dirty, false); checks.push('manual-cloud-save-commits'); + assert.equal(saveRequests.length, 3); + assert.ok(saveRequests[0].url.endsWith('/uploads/signature')); + assert.ok(saveRequests[1].url.includes('/mock-oss/')); + assert.ok(saveRequests[2].url.endsWith('/document')); + assert.equal(saveRequests[2].body.uploadCode, saveRequests[1].url.split('/').at(-1)); + assert.equal(await first.locator('#cad-notice').isHidden(), true); + checks.push('lost-upload-response-confirms-original-batch-once'); + const covered = (await (await fetch(`${base}/api/cad/workspace/projects/${project.cadProjectCode}`, { headers: apiHeaders })).json()).data; + assert.match(covered.coverUrl, /^https:\/\/cad-covers\.example\.test\//); + assert.equal(covered.version, 1); + const listPage = await firstContext.newPage(), listEngineRequests = []; + listPage.on('request', (request) => { if (request.url().includes('/cad/_assets/') || request.url().includes('/cad/engine.json')) listEngineRequests.push(request.url()); }); + await listPage.goto(`${base}/cad/`); + await listPage.getByRole('searchbox').fill(projectName); + const coveredCard = listPage.locator('.cad-card').filter({ hasText: projectName }); + const image = coveredCard.locator('.cad-card-art img'); + await image.waitFor(); + await image.evaluate((node) => node.decode()); + assert.equal(await image.getAttribute('src'), covered.coverUrl); + assert.equal(await image.getAttribute('loading'), 'lazy'); + assert.equal(await image.evaluate((node) => node.naturalWidth), 640); + assert.deepEqual(listEngineRequests, []); + if (artifactDir) await listPage.screenshot({ path: resolve(artifactDir, 'project-list-with-cover-zh.png') }); + await listPage.route('https://cad-covers.example.test/**', (route) => route.fulfill({ status: 404, body: '' })); + await listPage.reload(); + await listPage.getByRole('searchbox').fill(projectName); + await coveredCard.locator('.cad-card-art svg').waitFor(); + assert.equal(await coveredCard.locator('.cad-card-art img').count(), 0); + await listPage.close(); + checks.push('native-save-publishes-cover-list-displays-it-without-engine-and-broken-images-fall-back'); 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))); second.on('dialog', (dialog) => dialog.accept()); - await second.goto(url); await ready(second); + let documentReads = 0, sourceReads = 0, saveBase; + second.on('request', (request) => { + if (request.method() === 'GET' && request.url().endsWith('/document')) documentReads++; + if (request.url().includes('/mock-source/')) { + sourceReads++; + assert.equal(request.headers().authorization, undefined); + } + if (request.url().endsWith('/uploads/signature')) saveBase = request.postDataJSON().expectedVersion; + }); + await second.route('**/api/cad/workspace/projects/' + project.cadProjectCode, async (route) => { + const response = await route.fetch(), json = await response.json(); + json.data.version = 500; // Detail may be from a different snapshot than the document. + await route.fulfill({ response, json }); + }); + 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(); + assert.equal(documentReads, 1); + assert.equal(sourceReads, 1); + assert.equal((await second.evaluate(() => JSON.parse(localStorage.getItem('vm.auth')))).token, auth.token); + if (artifactDir) await second.screenshot({ path: resolve(artifactDir, 'public-file-forbidden-zh.png') }); + checks.push('public-url-403-does-not-renew-or-sign-out'); + await second.unroute('**/api/cad/mock-source/*'); + await second.locator('#cad-main [data-action]').click(); + await ready(second); + const document = (await (await fetch(`${base}/api/cad/workspace/projects/${project.cadProjectCode}/document`, { headers: apiHeaders })).json()).data; + assert.equal(document.expiresAt, null); + assert.equal(new URL(document.downloadUrl, base).search, ''); + checks.push('native-design-reopens-from-public-url-with-null-expiry'); assert.equal((await second.evaluate(() => window.vibemakeCad.getState())).dirty, false); assert.equal((await second.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 2); checks.push('independent-context-reopens-native-design'); await execute(first, 'solid.box', { length: 4, width: 4, height: 4, corner: [40, 0, 0] }); @@ -108,6 +233,8 @@ try { await second.locator('[data-save]').click(); await second.getByRole('dialog').waitFor(); assert.match(await second.getByRole('dialog').innerText(), /冲突/); await second.locator('[data-choice=stay]').click(); + assert.equal(saveBase, document.version); + checks.push('save-base-comes-from-document-snapshot-not-project-detail'); assert.equal((await second.evaluate(() => window.vibemakeCad.getState())).dirty, true); checks.push('concurrent-save-keeps-local-work-on-cas-conflict'); if (artifactDir) await second.screenshot({ path: resolve(artifactDir, 'conflict-zh.png') }); @@ -125,6 +252,11 @@ try { const draftContext = await authenticatedContext(), draftPage = await draftContext.newPage(); draftPage.on('pageerror', (error) => errors.push(String(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 }); + assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, false); + assert.match(await draftPage.locator('#cad-notice').innerText(), /工程已保存/); + checks.push('empty-design-saves-without-replacing-the-cover'); await execute(draftPage, 'solid.box', { length: 8, width: 9, height: 10 }); await draftPage.evaluate(async () => { const bridge = window.vibemakeCad, snapshot = await bridge.createSnapshot(), project = new URL(location.href).searchParams.get('project'); @@ -134,7 +266,7 @@ try { }); await new Promise((resolve, reject) => { const tx = db.transaction('records', 'readwrite'), key = JSON.stringify(['cad-browser-test-user', project, crypto.randomUUID(), 'draft']); - tx.objectStore('records').put({ key, user: 'cad-browser-test-user', project, session: 'draft-tab', kind: 'draft', updatedAt: Date.now(), snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: 0, binding: snapshot.binding, revision: snapshot.revision }); + tx.objectStore('records').put({ key, user: 'cad-browser-test-user', project, session: 'draft-tab', kind: 'draft', updatedAt: Date.now(), snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: 1, binding: snapshot.binding, revision: snapshot.revision }); tx.oncomplete = resolve; tx.onerror = () => reject(tx.error); }); await bridge.releaseSnapshot(snapshot.snapshotId); db.close(); @@ -144,6 +276,62 @@ try { assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, true); checks.push('binary-indexeddb-draft-restores'); if (artifactDir) await draftPage.screenshot({ path: resolve(artifactDir, 'draft-restore-zh.png') }); + const localDrafts = (page, user, project) => page.evaluate(async ({ user, project }) => { + const { DraftStore } = await import('/js/cad/drafts.js'); + return (await new DraftStore().list(user, project, 'draft')).map(({ key, snapshotId }) => ({ key, snapshotId })); + }, { user, project }); + const restoredDrafts = await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode); + assert.ok(restoredDrafts.length > 0); + await draftPage.locator('.nav-logo').click(); + await draftPage.locator('[data-choice=stay]').click(); + assert.deepEqual(await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode), restoredDrafts); + assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, true); + checks.push('keep-editing-preserves-local-drafts'); + + await draftPage.evaluate(async ({ user, project }) => { + const { DraftStore } = await import('/js/cad/drafts.js'); + const store = new DraftStore(), bytes = new Uint8Array([1, 2, 3]); + await store.put('other-owner', project, 'other-tab', 'draft', { snapshotId: 'other-owner-draft', bytes }); + await store.put(user, 'other-project', 'other-tab', 'draft', { snapshotId: 'other-project-draft', bytes }); + const bridge = window.vibemakeCad, capture = bridge.createSnapshot.bind(bridge); + bridge.createSnapshot = async (...args) => { + window.draftCaptureStarted = true; + await new Promise((resolve) => { window.finishDraftCapture = resolve; }); + return capture(...args); + }; + Object.defineProperty(document, 'hidden', { configurable: true, value: true }); + document.dispatchEvent(new Event('visibilitychange')); + delete document.hidden; + }, { user: auth.user.userCode, project: draftProject.cadProjectCode }); + await draftPage.waitForFunction(() => window.draftCaptureStarted); + await draftPage.locator('.nav-logo').click(); + const discardClick = draftPage.locator('[data-choice=discard]').click(); + await draftPage.waitForTimeout(100); + assert.equal(new URL(draftPage.url()).pathname, '/cad/editor/'); + await draftPage.evaluate(() => { + Object.defineProperty(document, 'hidden', { configurable: true, value: true }); + document.dispatchEvent(new Event('visibilitychange')); + delete document.hidden; + window.finishDraftCapture(); + }); + await discardClick; + await draftPage.waitForURL(`${base}/cad/`); + await draftPage.getByRole('heading', { name: '我的 CAD 项目' }).waitFor(); + assert.deepEqual(await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode), []); + assert.equal((await localDrafts(draftPage, 'other-owner', draftProject.cadProjectCode)).length, 1); + assert.equal((await localDrafts(draftPage, auth.user.userCode, 'other-project')).length, 1); + checks.push('discard-clears-restored-and-in-flight-drafts-only-for-this-owner-and-project'); + await draftPage.goto(`${base}/cad/editor/?project=${draftProject.cadProjectCode}`); + await ready(draftPage); + assert.equal(await draftPage.getByRole('dialog').count(), 0); + assert.equal((await draftPage.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 0); + assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, false); + 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') }); + + const platformAgentResult = await runPlatformAgentBrowserChecks(browser); checks.push(...platformAgentResult.checks); errors.push(...platformAgentResult.errors); + const mobileContext = await authenticatedContext({ width: 700, height: 900 }), mobile = await mobileContext.newPage(), mobileEngineRequests = []; mobile.on('request', (request) => { if (request.url().includes('/cad/engine.json') || request.url().includes('/cad/_assets/')) mobileEngineRequests.push(request.url()); }); await mobile.goto(url); await mobile.getByRole('heading', { name: '请在电脑端使用 VibeMake CAD' }).waitFor(); diff --git a/tests/cad/mock-server.mjs b/tests/cad/mock-server.mjs index c19c55e..9ad4928 100644 --- a/tests/cad/mock-server.mjs +++ b/tests/cad/mock-server.mjs @@ -1,5 +1,6 @@ import http from 'node:http'; import { randomUUID } from 'node:crypto'; +import { assistantModel } from './assistant-model.mjs'; const projects = new Map(), uploads = new Map(), objects = new Map(); const owner = 'cad-browser-test-user', token = 'cad-browser-test-token'; @@ -18,18 +19,19 @@ function projectData(project) { cadProjectCode: project.cadProjectCode, name: project.name, description: project.description, + coverUrl: project.coverUrl || null, hasDocument: !!project.document, version: project.version, - fileName: project.document?.request.fileName || '', - sizeBytes: project.document?.request.sizeBytes || 0, + fileName: project.document?.upload.request.fileName || '', + sizeBytes: project.document?.upload.request.sizeBytes || 0, savedAt: project.document?.savedAt || null, createdAt: project.createdAt, updatedAt: project.updatedAt, }; } -function createProject(name, description = '') { +function createProject(name, description = '', coverUrl = null) { const cadProjectCode = 'cad-' + randomUUID(); - const project = { cadProjectCode, name, description, version: 0, document: null, createdAt: timestamp(), updatedAt: timestamp() }; + const project = { cadProjectCode, name, description, coverUrl, version: 0, document: null, createdAt: timestamp(), updatedAt: timestamp() }; projects.set(cadProjectCode, project); return project; } @@ -40,6 +42,7 @@ const server = http.createServer(async (req, res) => { const url = new URL(req.url, 'http://localhost'); if (url.pathname.startsWith('/api/')) url.pathname = url.pathname.slice('/api'.length); const body = await bodyOf(req); + if (await assistantModel(req, res, url, body)) return; if (url.pathname === '/auth/captcha') return json(res, { captchaCode: 'browser-test', @@ -63,6 +66,14 @@ const server = http.createServer(async (req, res) => { return res.end(bytes); } + const coverMatch = url.pathname.match(/^\/cad\/mock-cover-source\/([^/]+)\.png$/); + if (coverMatch) { + const bytes = objects.get(coverMatch[1]); + if (!bytes) return json(res, null, 404, 'NOT_FOUND'); + res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': bytes.length, 'Cache-Control': 'no-store' }); + return res.end(bytes); + } + const ossMatch = url.pathname.match(/^\/cad\/mock-oss\/([^/]+)$/); if (ossMatch && req.method === 'POST') { const uploadCode = ossMatch[1], contentType = String(req.headers['content-type'] || ''); @@ -74,13 +85,24 @@ const server = http.createServer(async (req, res) => { if (!boundary || start < 0 || dataStart < 4 || end < dataStart) return json(res, null, 400, 'INVALID_UPLOAD'); const existing = objects.get(uploadCode); const incoming = body.subarray(dataStart, end); - if (existing && !existing.equals(incoming)) return json(res, null, 409, 'OBJECT_ALREADY_EXISTS'); + if (existing) return json(res, null, 409, 'OBJECT_ALREADY_EXISTS'); objects.set(uploadCode, Buffer.from(incoming)); res.writeHead(200).end(); return; } if (req.headers.authorization !== 'Bearer ' + token) return json(res, null, 401, 'UNAUTHORIZED'); + 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) + || input.fileSize <= 0 || input.fileSize > 5 * 1024 * 1024) return json(res, null, 400, 'BAD_REQUEST'); + const code = 'cover-' + randomUUID(); + return json(res, { + uploadUrl: '/api/cad/mock-oss/' + code, + formFields: { key: code, policy: 'mock-cover-policy' }, + coverUrl: 'https://cad-covers.example.test/' + code + '.png', + }); + } const root = '/cad/workspace/projects'; if (url.pathname === root && req.method === 'GET') { const page = Number(url.searchParams.get('page') || 1); @@ -92,7 +114,7 @@ const server = http.createServer(async (req, res) => { } if (url.pathname === root && req.method === 'POST') { const input = JSON.parse(body); - return json(res, projectData(createProject(input.name, input.description || ''))); + return json(res, projectData(createProject(input.name, input.description || '', input.coverUrl || null))); } const match = url.pathname.match(/^\/cad\/workspace\/projects\/([^/]+)(?:\/(.*))?$/); @@ -104,6 +126,7 @@ const server = http.createServer(async (req, res) => { const input = JSON.parse(body); if (input.name !== undefined && input.name !== null) project.name = input.name; if (input.description !== undefined && input.description !== null) project.description = input.description; + if (input.coverUrl !== undefined && input.coverUrl !== null) project.coverUrl = input.coverUrl || null; project.updatedAt = timestamp(); return json(res, projectData(project)); } @@ -117,10 +140,10 @@ const server = http.createServer(async (req, res) => { if (!project.document) return json(res, null, 404, 'CAD_DOCUMENT_NOT_FOUND'); return json(res, { downloadUrl: '/api/cad/mock-source/' + project.document.upload.uploadCode, - expiresAt: timestamp(), + expiresAt: null, version: project.document.version, - fileName: project.document.request.fileName, - sizeBytes: project.document.request.sizeBytes, + fileName: project.document.upload.request.fileName, + sizeBytes: project.document.upload.request.sizeBytes, savedAt: project.document.savedAt, }); } diff --git a/tests/cad/platform-agent-browser.mjs b/tests/cad/platform-agent-browser.mjs new file mode 100644 index 0000000..7e429b1 --- /dev/null +++ b/tests/cad/platform-agent-browser.mjs @@ -0,0 +1,594 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { writeFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; +import { chromium } from 'playwright'; + +const base = (process.env.VM_CAD_BASE_URL || 'http://localhost:8091').replace(/\/$/, ''); +const auth = { token: 'cad-browser-test-token', user: { userCode: 'cad-browser-test-user', nickname: 'CAD Browser Test' } }; +const headers = { Authorization: `Bearer ${auth.token}`, 'Content-Type': 'application/json' }; +const chat = (page, params = {}) => page.evaluate((params) => window.solidcraft.request('ui.agent_chat', params), params); +const inspect = (page) => page.evaluate(() => window.solidcraft.inspect({ measure: true })); +const agentCalls = async () => (await fetch(`${base}/api/cad/ai/requests`, { headers })).json(); + +async function clickHandle(page, name) { + for (let i = 0; i < 40; i++) { + const handle = (await page.evaluate((prefix) => window.solidcraft.request('ui.handles', { prefix }), name)).find((h) => h.name === name); + if (handle) { + const canvas = await page.locator('canvas').boundingBox(); + await page.mouse.click(canvas.x + handle.x, canvas.y + handle.y); + return; + } + await page.waitForTimeout(100); + } + throw new Error(`Missing CAD handle: ${name}`); +} + +async function until(page, predicate, message, timeoutMs = 30000) { + for (let i = 0; i < timeoutMs / 100; i++) { + // Draft recovery can replace the engine after the host's first binding. + // Poll read-only state through that transition; never retry a mutation here. + const state = await page.evaluate(async () => { + if (!window.solidcraft) return null; + try { return await window.solidcraft.request('ui.agent_chat', {}); } + catch (error) { + if (String(error).includes('HOST_INTERACTION_LOCKED')) return null; + throw error; + } + }); + if (!state) { await page.waitForTimeout(100); continue; } + if (predicate(state)) return state; + await page.waitForTimeout(100); + } + throw new Error(`${message}: ${JSON.stringify(await chat(page)).slice(0, 2000)}`); +} + +async function run(browser) { + const checks = [], errors = []; + const project = await (await fetch(`${base}/api/cad/workspace/projects`, { + method: 'POST', headers, body: JSON.stringify({ name: 'Platform Agent browser test', description: '' }), + })).json(); + assert.equal(project.code, 'OK'); + const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); + await context.addInitScript((value) => localStorage.setItem('vm.auth', JSON.stringify(value)), auth); + const page = await context.newPage(); + page.on('pageerror', (error) => errors.push(String(error))); + try { + await page.goto(`${base}/cad/editor/?project=${project.data.cadProjectCode}`); + await page.waitForFunction(() => window.vibemakeCad && window.solidcraft, null, { timeout: 180000 }); + await page.waitForFunction(async () => { + const host = await window.vibemakeCad.getState(); + return host.binding && !host.locked && document.querySelector('#cad-main')?.hidden; + }, null, { timeout: 180000 }); + await page.waitForFunction(async () => { + const state = await window.vibemakeCad.getState(); + return state.assistant?.fullHeight && state.assistant?.open && state.assistant?.connection === 'ready' + && !state.locked && !document.querySelector('#cad-viewport').inert && document.body.classList.contains('cad-full-height'); + }); + // Binding, draft recovery and agent capabilities settle over separate engine frames. + await page.waitForTimeout(1500); + async function assertSplitLayout() { + await page.waitForFunction(async () => { + const state = await window.vibemakeCad.getState(); + const canvas = document.querySelector('#cad-viewport').getBoundingClientRect(); + const bar = document.querySelector('body > header.nav').getBoundingClientRect(); + return !state.locked && !document.querySelector('#cad-viewport').inert && canvas.y === 0 && canvas.height === innerHeight + && Math.abs(bar.width - innerWidth * (1 - state.assistant.panelFraction)) < 2; + }); + const host = await page.evaluate(() => window.vibemakeCad.getState()); + const canvas = await page.locator('#cad-viewport').boundingBox(); + const bar = await page.locator('body > header.nav').boundingBox(); + const size = page.viewportSize(); + assert.equal(canvas.y, 0); + assert.equal(canvas.height, size.height); + assert.equal(bar.y, 0); + assert.equal(bar.height, 42); + assert.ok(Math.abs(bar.width - size.width * (1 - host.assistant.panelFraction)) < 2, 'HTML menu ends at the native divider'); + const handles = await page.evaluate(() => window.solidcraft.request('ui.handles', { prefix: 'agent_chat:' })); + const newChat = handles.find((handle) => handle.name === 'agent_chat:newchat'); + assert.ok(newChat.x > bar.width && Math.abs(newChat.y - bar.height / 2) < 2, 'assistant actions share the menu baseline'); + for (const action of ['close', 'minimize', 'pop_out', 'grip']) { + assert.ok(!handles.some((handle) => handle.name === `agent_chat:${action}`), `no ${action} action in the permanent column`); + } + const input = handles.find((handle) => handle.name === 'agent_chat:input'); + assert.ok(input.x > bar.width && input.y < size.height && input.y > size.height / 2, 'composer stays inside the right column'); + const ui = await page.evaluate(() => window.solidcraft.request('ui.inspect', {})); + assert.ok(ui.viewport[0] + ui.viewport[2] <= bar.width + 2, 'CAD viewport clears the assistant'); + const chrome = await page.locator('header .nav-logo, header .cad-appbar-left, header .nav-actions').evaluateAll((nodes) => nodes.map((node) => { + const rect = node.getBoundingClientRect(); return { left: rect.left, right: rect.right }; + })); + for (let i = 1; i < chrome.length; i++) assert.ok(chrome[i - 1].right <= chrome[i].left + 1, 'menu controls never overlap'); + assert.ok(chrome.at(-1).right <= bar.width + 1, 'menu actions stay in the left column'); + } + await assertSplitLayout(); + checks.push('assistant-opens-automatically-in-full-height-split-with-aligned-title-bar'); + await until(page, (state) => state.open && state.state === 'ready' && state.agent === 'Mock CAD Agent', 'platform agent did not become ready', 60000); + await chat(page, { open: false, minimized: true, popped: true, side: 'left' }); + await page.waitForTimeout(250); + assert.equal((await chat(page)).open, true); + await assertSplitLayout(); + checks.push('assistant-cannot-be-hidden-folded-popped-out-or-moved-left'); + await chat(page, { minimized: false, popped: false, side: 'right' }); + const beforeResize = (await page.evaluate(() => window.vibemakeCad.getState())).assistant.panelFraction; + const divider = (await page.evaluate(() => window.solidcraft.request('ui.handles', { prefix: 'agent_chat:resize' })))[0]; + await page.mouse.move(divider.x, divider.y); + await page.mouse.down(); + await page.mouse.move(divider.x - 80, divider.y, { steps: 12 }); + await page.mouse.up(); + await page.waitForTimeout(500); + assert.ok((await page.evaluate(() => window.vibemakeCad.getState())).assistant.panelFraction > beforeResize + 0.02, 'divider resizes the actual column'); + await assertSplitLayout(); + await chat(page, { width: 380 }); + await page.waitForTimeout(350); + for (const width of [1024, 821]) { + await page.setViewportSize({ width, height: 720 }); + await page.waitForTimeout(500); + await assertSplitLayout(); + } + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.waitForTimeout(350); + await assertSplitLayout(); + checks.push('divider-resizes-both-columns-and-menus-fit-at-821-and-1024-pixels'); + + const beforeCalls = await (await fetch(`${base}/api/cad/ai/requests`, { headers })).json(); + assert.equal(beforeCalls.at(-1).authorization, `Bearer ${auth.token}`); + assert.ok(beforeCalls.at(-1).path === '/cad/ai/capabilities'); + assert.equal(await page.evaluate(() => window.__VIBEMAKE_CAD__.agentChat instanceof Function), true); + assert.equal(await page.locator('input[type=password], [data-engine-menu="assistant"] + input').count(), 0); + checks.push('capabilities-use-platform-auth-and-fixed-agent-has-no-key-input'); + if (process.env.VM_CAD_SCREENSHOT) await page.screenshot({ path: process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, '-empty.png') }); + await page.locator('[data-engine-menu="preferences"]').click(); + await page.waitForFunction(async () => (await window.solidcraft.request('ui.handles', { prefix: 'prefs:page:' })).some((h) => h.name === 'prefs:page:General')); + const pages = await page.evaluate(() => window.solidcraft.request('ui.handles', { prefix: 'prefs:page:' })); + assert.ok(!pages.some((h) => h.name === 'prefs:page:Assistant')); + await page.evaluate(() => window.solidcraft.request('ui.prefs', { button: 'cancel' })); + checks.push('platform-preferences-hide-local-assistant-configuration'); + + // 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 clickHandle(page, 'agent_chat:input'); + await page.keyboard.type('vm-test:read ', { delay: 35 }); + const cdp = await context.newCDPSession(page); + for (const [pinyin, text] of [['nihao', '你好'], ['shijie', '世界']]) { + await cdp.send('Input.imeSetComposition', { text: pinyin, selectionStart: pinyin.length, selectionEnd: pinyin.length }); + await page.waitForTimeout(100); + await cdp.send('Input.insertText', { text }); + await page.waitForTimeout(200); + } + await page.keyboard.press('ArrowLeft'); + await page.keyboard.press('ArrowLeft'); + await page.keyboard.type('X'); + 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); + 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'); + await chat(page, { new_chat: true }); + + const empty = await inspect(page); + assert.equal(empty.bodies.length, 0); + const initialRevision = await page.evaluate(async () => (await window.vibemakeCad.getState()).revision); + await chat(page, { send: 'vm-test:create', attach_view: false, attach_selection: false }); + let calls = []; + for (let i = 0; i < 300; i++) { + calls = await agentCalls(); + if (calls.some((call) => call.path === '/cad/ai/chat' && call.body?.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('vm-test:create')))) break; + await page.waitForTimeout(100); + } + const firstChat = calls.find((call) => call.path === '/cad/ai/chat' && call.body?.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('vm-test:create'))); + assert.ok(firstChat, `chat request was not recorded: ${JSON.stringify(calls)}`); + assert.equal(firstChat.body.cadProjectCode, project.data.cadProjectCode); + assert.equal(typeof firstChat.body.context.documentRevision, 'string'); + const firstRuntime = JSON.parse(firstChat.body.history[0].content.find((part) => part.text)?.text.split('[CAD Web runtime context]\n')[1]).cadWebRuntime; + assert.equal(firstRuntime.backendLimits.imagesPerRequest, 2); + assert.equal(firstRuntime.remainingImages, 2); + assert.ok(!Object.hasOwn(firstRuntime.backendLimits, 'maxModelCallsPerTurn')); + assert.match(firstRuntime.rules, /Do not request screenshots when remainingImages is zero/); + assert.match(firstChat.body.context.documentRevision, /^[a-f0-9]{64}$/); + assert.equal(firstChat.body.context.documentRevision, createHash('sha256').update(String(initialRevision)).digest('hex')); + assert.ok(firstChat.body.documentSessionCode); + assert.ok(firstChat.body.turnCode); + await page.waitForTimeout(100); + assert.equal((await inspect(page)).bodies.length, 0, 'tool_call display must not execute before completed'); + await until(page, (state) => !state.turn && state.state === 'ready', 'completed model turn did not finish', 60000); + assert.equal((await inspect(page)).bodies.length, 1); + assert.equal((await inspect(page)).bodies[0].name, 'PlatformAIBox'); + checks.push('fragmented-sse-and-completed-output-authorize-tool-execution'); + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:truncated', attach_view: false, attach_selection: false }); + await until(page, (state) => !state.turn && state.state === 'ready', 'truncated stream did not stop', 30000); + assert.equal((await inspect(page)).bodies.length, 1, 'EOF without completed must never execute an announced tool'); + checks.push('eof-without-completed-does-not-run-announced-tool'); + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:screenshot', attach_view: false, attach_selection: false }); + await until(page, (state) => !state.turn && state.state === 'ready', 'screenshot tool turn did not finish', 60000); + const finalCalls = await agentCalls(); + const firstTurn = finalCalls.filter((call) => call.path === '/cad/ai/chat' && call.body.turnCode === firstChat.body.turnCode); + assert.equal(firstTurn.length, 2); + assert.notEqual(firstTurn[0].body.context.documentRevision, firstTurn[1].body.context.documentRevision); + const screenshotCall = finalCalls.find((call) => call.path === '/cad/ai/chat' && call.body.cadProjectCode === project.data.cadProjectCode && call.body.history.some((item) => item.type === 'toolResult' && item.content?.some((part) => part.type === 'image'))); + assert.ok(screenshotCall, 'model continuation must receive the CAD-only screenshot image'); + const picture = screenshotCall.body.history.flatMap((item) => item.content || []).find((part) => part.type === 'image'); + assert.equal(picture.mimeType, 'image/png'); + assert.ok(picture.data.startsWith('iVBORw0KGgo')); + checks.push('screenshot-tool-returns-model-render-as-an-image-block'); + + await chat(page, { new_chat: true }); + const beforeCameraShot = await inspect(page); + await chat(page, { send: 'vm-test:screenshot-camera', attach_view: false, attach_selection: false }); + const cameraState = await until(page, (s) => !s.turn && s.items.some((i) => i.user), 'custom camera screenshot did not finish', 60000); + assert.equal(cameraState.items.filter((i) => i.status === 'Failed').length, 0, JSON.stringify(cameraState.items)); + assert.equal(cameraState.items.filter((i) => i.status === 'Completed').length, 1, JSON.stringify(cameraState.items)); + const cameraCalls = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('vm-test:screenshot-camera'))); + assert.equal(cameraCalls.length, 2, 'custom camera screenshot must continue the same model turn'); + assert.equal(cameraCalls[0].body.turnCode, cameraCalls[1].body.turnCode); + const cameraResult = cameraCalls[1].body.history.at(-1); + assert.equal(cameraResult.type, 'toolResult'); + assert.equal(cameraResult.isError, false); + const cameraImage = cameraResult.content.find((part) => part.type === 'image'); + assert.equal(cameraImage?.mimeType, 'image/png'); + const cameraPng = Buffer.from(cameraImage.data, 'base64'); + assert.equal(cameraPng.subarray(0, 8).toString('hex'), '89504e470d0a1a0a'); + assert.equal(cameraPng.readUInt32BE(16), 320); + assert.equal(cameraPng.readUInt32BE(20), 200); + // ui.render uses the stored camera; ui.camera reports the viewport preference's FOV. + const camera = await page.evaluate(async () => (await window.solidcraft.request('ui.inspect', {})).camera); + assert.deepEqual(camera.target, [1, 1.5, 2]); + for (const [key, value] of Object.entries({ yaw: 1, pitch: 0.2, distance: 12, fov: 0.5, roll: 0.3 })) { + assert.ok(Math.abs(camera[key] - value) < 1e-9, `screenshot camera ${key}: ${camera[key]}`); + } + assert.deepEqual((await inspect(page)).bodies, beforeCameraShot.bodies, 'taking a screenshot must preserve the model'); + checks.push('custom-camera-screenshot-applies-camera-and-returns-png-to-the-same-model-turn'); + if (process.env.VM_CAD_SCREENSHOT) { + await page.screenshot({ path: process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, '-camera.png') }); + await writeFile(process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, '-camera-render.png'), cameraPng); + } + + const savedCamera = { target: [1, 1.5, 2], yaw: 0.4, pitch: 0.7, distance: 20, fov: 0 }; + await page.evaluate((camera) => window.solidcraft.request('engine.execute', { + command: 'view.save', params: { name: 'AgentSavedView', camera }, + }), savedCamera); + for (const view of ['named', 'isometric']) { + await chat(page, { new_chat: true }); + await chat(page, { send: `vm-test:screenshot-${view}`, attach_view: false, attach_selection: false }); + const state = await until(page, (s) => !s.turn && s.items.some((i) => i.user), `${view} screenshot did not finish`, 60000); + assert.equal(state.items.filter((i) => i.status === 'Completed').length, 1, JSON.stringify(state.items)); + const requests = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes(`vm-test:screenshot-${view}`))); + assert.equal(requests.length, 2, 'named and alias views must return their screenshot to the model'); + assert.ok(requests[1].body.history.at(-1).content.some((part) => part.type === 'image')); + const camera = await page.evaluate(async () => (await window.solidcraft.request('ui.inspect', {})).camera); + if (view === 'named') { + for (const [key, value] of Object.entries(savedCamera)) assert.deepEqual(camera[key], value); + } else { + assert.ok(Math.abs(camera.yaw + Math.PI / 4) < 1e-9); + assert.ok(Math.abs(camera.pitch - 0.6154797086703874) < 1e-9); + } + checks.push(`${view}-screenshot-view-matches-the-native-engine-and-returns-an-image`); + } + + await chat(page, { new_chat: true }); + await chat(page, { send: 'vm-test:screenshot-recover', attach_view: false, attach_selection: false }); + const recoveredShot = await until(page, (s) => !s.turn && s.items.some((i) => i.user), 'invalid screenshot view did not recover', 60000); + assert.equal(recoveredShot.items.filter((i) => i.status === 'Failed').length, 1, JSON.stringify(recoveredShot.items)); + assert.equal(recoveredShot.items.filter((i) => i.status === 'Completed').length, 2, JSON.stringify(recoveredShot.items)); + const shotRecoveryCalls = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('vm-test:screenshot-recover'))); + assert.equal(shotRecoveryCalls.length, 4); + assert.equal(new Set(shotRecoveryCalls.map((call) => call.body.turnCode)).size, 1); + const viewFailure = shotRecoveryCalls[1].body.history.at(-1); + assert.equal(viewFailure.isError, true); + assert.match(viewFailure.content[0].text, /no named view `MissingAgentView`/); + assert.ok(viewFailure.content.some((part) => part.text?.includes('Omit view and camera'))); + assert.ok(shotRecoveryCalls[3].body.history.at(-1).content.some((part) => part.type === 'image')); + checks.push('invalid-screenshot-view-is-returned-to-the-model-inspected-and-corrected-in-the-same-turn'); + if (process.env.VM_CAD_SCREENSHOT) await page.screenshot({ path: process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, '-view-recovery.png') }); + + for (const scenario of ['recover', 'partial']) { + await chat(page, { new_chat: true }); + const before = (await inspect(page)).bodies.length; + await chat(page, { send: `vm-test:${scenario}`, attach_view: false, attach_selection: false }); + const state = await until(page, (s) => !s.turn && s.items.some((i) => i.user), `${scenario} did not recover`, 60000); + assert.equal(state.items.filter((i) => i.status === 'Failed').length, 1, JSON.stringify(state.items)); + assert.equal(state.items.filter((i) => i.status === 'Completed').length, 2, JSON.stringify(state.items)); + assert.ok(!state.items.some((i) => i.notice?.includes('模型已变化'))); + assert.equal((await inspect(page)).bodies.length, before + (scenario === 'partial' ? 2 : 1)); + const recorded = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' && call.body.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes(`vm-test:${scenario}`))); + assert.equal(recorded.length, 4, JSON.stringify(recorded.map((c) => c.body.history))); + assert.equal(new Set(recorded.map((c) => c.body.turnCode)).size, 1); + const failed = recorded[1].body.history.at(-1); + assert.equal(failed.isError, true); + const detail = JSON.parse(failed.content[0].text); + assert.match(detail.failed.error, /`m` is a unit name/); + assert.deepEqual(detail.applied, scenario === 'partial' ? [0] : []); + const feedback = JSON.parse(failed.content.at(-1).text); + assert.ok(!Object.hasOwn(feedback, 'remainingChanges')); + assert.ok(!Object.hasOwn(feedback, 'remainingModelCalls')); + assert.match(feedback.recovery, /Analyse the tool error/); + checks.push(`${scenario}-tool-failure-is-analysed-inspected-and-corrected-without-replaying-applied-steps`); + } + + await chat(page, { new_chat: true }); + const beforeLongTurn = (await inspect(page)).bodies.length; + await chat(page, { send: 'vm-test:long-turn', attach_view: false, attach_selection: false }); + const longTurn = await until(page, (s) => !s.turn && s.items.some((i) => i.user), 'long turn did not finish', 120000); + assert.equal(longTurn.items.filter((i) => i.status === 'Failed').length, 0, JSON.stringify(longTurn.items)); + assert.equal(longTurn.items.filter((i) => i.status === 'Completed').length, 15, JSON.stringify(longTurn.items)); + assert.ok(JSON.stringify(longTurn.items).includes('Completed 30 CAD changes over 16 model calls')); + const afterLongTurn = await inspect(page); + assert.equal(afterLongTurn.bodies.length, beforeLongTurn + 30); + assert.equal(afterLongTurn.bodies.filter((body) => body.name.startsWith('LongTurnBox_')).length, 30); + const longCalls = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === project.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('vm-test:long-turn'))); + assert.equal(longCalls.length, 16); + assert.equal(new Set(longCalls.map((call) => call.body.turnCode)).size, 1); + assert.equal(new Set(longCalls.map((call) => call.body.documentSessionCode)).size, 1); + assert.equal(longCalls.at(-1).body.history.filter((item) => item.type === 'toolResult').length, 15); + checks.push('one-turn-completes-16-model-calls-and-30-changes-despite-capabilities-12-and-24'); + const arrivals = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === project.data.cadProjectCode).map((call) => call.receivedAt); + for (const end of arrivals) assert.ok(arrivals.filter((time) => time > end - 60_000 && time <= end).length <= 30, + 'tool continuations must stay under 30 network requests in every rolling minute'); + checks.push('all-model-and-tool-continuation-requests-stay-under-30-per-rolling-minute'); + assert.deepEqual(errors, []); + if (process.env.VM_CAD_SCREENSHOT) { + await page.screenshot({ path: process.env.VM_CAD_SCREENSHOT }); + } + + // A real populated model produces an oversized inspect result. + await context.route('**/api/cad/ai/capabilities', async (route) => { + const response = await route.fetch(), body = await response.json(); + body.data.limits.toolResultTextBytes = 1024; + await route.fulfill({ response, json: body }); + }); + const textBudgetProject = await (await fetch(`${base}/api/cad/workspace/projects`, { + method: 'POST', headers, body: JSON.stringify({ name: 'Tool result budget', description: '' }), + })).json(); + assert.equal(textBudgetProject.code, 'OK'); + await page.goto(`${base}/cad/editor/?project=${textBudgetProject.data.cadProjectCode}`); + await page.waitForFunction(async () => { + if (!window.vibemakeCad || !window.solidcraft) return false; + const state = await window.vibemakeCad.getState(); + return state.binding && !state.locked && document.querySelector('#cad-main')?.hidden; + }, null, { timeout: 180000 }); + await until(page, (state) => state.open && state.state === 'ready', 'text budget agent did not become ready', 60000); + for (let index = 0; index < 4; index++) await page.evaluate((index) => window.solidcraft.execute('solid.box', { + length: 2, width: 3, height: 4, corner: [index * 4, 0, 0], body_name: 'LongTurnBox_' + index, + }), index); + const beforeTextBudget = await inspect(page); + assert.ok(Buffer.byteLength(JSON.stringify(beforeTextBudget)) > 1024, 'real inspect result must exceed the advertised test quota'); + await chat(page, { send: 'vm-test:tool-text-budget', attach_view: false, attach_selection: false }); + const textBudget = await until(page, (state) => !state.turn && state.items.some((item) => item.user), 'text budget recovery did not finish', 60000); + const textRequests = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === textBudgetProject.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('vm-test:tool-text-budget'))); + assert.equal(textRequests.length, 3, JSON.stringify(textBudget)); + const textResults = textRequests.at(-1).body.history.filter((item) => item.type === 'toolResult'); + assert.equal(textResults[0].isError, true); + const withheld = JSON.parse(textResults[0].content[0].text); + assert.equal(withheld.error, 'tool_result_too_large'); + assert.equal(withheld.toolResultTextBytes, 1024); + assert.ok(withheld.textBytes > 1024); + assert.match(withheld.recovery, /No partial JSON was sent/); + assert.match(withheld.recovery, /never replay modifications/); + assert.equal(textResults[1].isError, false, JSON.stringify(textResults[1])); + assert.deepEqual((await inspect(page)).bodies, beforeTextBudget.bodies); + for (const result of textResults) assert.ok(result.content.reduce((total, part) => total + Buffer.byteLength(part.text || ''), 0) <= 1024); + checks.push('oversized-tool-result-is-an-explicit-delivery-error-and-recovers-with-read-only-summary-without-partial-json'); + await context.unroute('**/api/cad/ai/capabilities'); + + await context.route('**/api/cad/ai/capabilities', async (route) => { + const response = await route.fetch(), body = await response.json(); + body.data.limits.textBytes = 8192; + await route.fulfill({ response, json: body }); + }); + const textProject = await (await fetch(`${base}/api/cad/workspace/projects`, { + method: 'POST', headers, body: JSON.stringify({ name: 'UTF-8 request budget', description: '' }), + })).json(); + assert.equal(textProject.code, 'OK'); + await page.goto(`${base}/cad/editor/?project=${textProject.data.cadProjectCode}`); + await page.waitForFunction(async () => { + if (!window.vibemakeCad || !window.solidcraft) return false; + const state = await window.vibemakeCad.getState(); + return state.binding && !state.locked && document.querySelector('#cad-main')?.hidden; + }, null, { timeout: 180000 }); + await until(page, (state) => state.open && state.state === 'ready', 'request budget agent did not become ready', 60000); + // The user text alone fits (8100 UTF-8 bytes); the mandatory runtime context + // pushes the combined request beyond 8192, exercising aggregate accounting. + await chat(page, { send: '限'.repeat(2700), attach_view: false, attach_selection: false }); + const overText = await until(page, (state) => !state.turn && state.items.some((item) => item.user), 'oversized request did not stop'); + assert.match(JSON.stringify(overText), /textBytes=\d+\/8192/); + assert.equal((await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === textProject.data.cadProjectCode).length, 0, 'oversized UTF-8 request never reaches the backend'); + await context.unroute('**/api/cad/ai/capabilities'); + checks.push('oversized-current-turn-stops-before-network-with-the-exact-backend-byte-quota'); + + for (const scenario of ['images', 'higher', 'unlimited', 'compressed']) { + await context.route('**/api/cad/ai/capabilities', async (route) => { + const response = await route.fetch(), body = await response.json(); + if (scenario === 'higher') Object.assign(body.data.limits, { + imagesPerRequest: 5, historyItems: 1024, imageBytes: 2097152, imageMaxEdge: 4096, + requestBytes: 8388608, textBytes: 524288, toolResultTextBytes: 65536, requestTimeoutSeconds: 180, + }); + if (scenario === 'unlimited') body.data.limits = { imagesPerRequest: 0, historyItems: 0 }; + if (scenario === 'compressed') Object.assign(body.data.limits, { imagesPerRequest: 3, imageBytes: 128 }); + await route.fulfill({ response, json: body }); + }); + const budgetProject = await (await fetch(`${base}/api/cad/workspace/projects`, { + method: 'POST', headers, body: JSON.stringify({ name: `Backend budget ${scenario}`, description: '' }), + })).json(); + assert.equal(budgetProject.code, 'OK'); + await page.goto(`${base}/cad/editor/?project=${budgetProject.data.cadProjectCode}`); + await page.waitForFunction(async () => { + if (!window.vibemakeCad || !window.solidcraft) return false; + const state = await window.vibemakeCad.getState(); + return state.binding && !state.locked && document.querySelector('#cad-main')?.hidden; + }, null, { timeout: 180000 }); + await until(page, (state) => state.open && state.state === 'ready', 'budget agent did not become ready', 60000); + await chat(page, { send: `vm-test:budget-${scenario}`, attach_view: false, attach_selection: false }); + const finished = await until(page, (state) => !state.turn && state.items.some((item) => item.user), `${scenario} budget did not finish`, 60000); + const requests = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' && call.body.cadProjectCode === budgetProject.data.cadProjectCode); + assert.equal(requests.length, 5, JSON.stringify(finished)); + assert.equal(new Set(requests.map((call) => call.body.turnCode)).size, 1); + const notes = requests.map((call) => { + const text = call.body.history[0].content.find((part) => part.type === 'text').text; + assert.equal(text.split('[CAD Web runtime context]').length, 2, 'runtime context must be replaced, never accumulated'); + return JSON.parse(text.split('[CAD Web runtime context]\n')[1]).cadWebRuntime; + }); + const results = requests.at(-1).body.history.filter((item) => item.type === 'toolResult'); + if (scenario === 'images') { + assert.equal(finished.items.filter((item) => item.status === 'Failed').length, 1); + assert.deepEqual(notes.map((note) => note.remainingImages), [2, 1, 0, 0, 0]); + assert.equal(results[2].isError, true); + assert.match(results[2].content[0].text, /Screenshot not executed: backend imagesPerRequest=2/); + assert.ok(!results[2].content.some((part) => part.type === 'image')); + const camera = await page.evaluate(async () => (await window.solidcraft.request('ui.inspect', {})).camera); + assert.ok(Math.abs(camera.pitch) < 1e-9, 'blocked top screenshot must preserve the previous front camera'); + checks.push('backend-image-quota-is-explained-to-model-and-blocked-before-camera-or-render-with-recovery'); + } else { + assert.equal(finished.items.filter((item) => item.status === 'Failed').length, 0, JSON.stringify(finished)); + assert.equal(results.flatMap((item) => item.content).filter((part) => part.type === 'image').length, 3); + if (scenario === 'compressed') { + for (const picture of results.flatMap((item) => item.content).filter((part) => part.type === 'image')) { + const png = Buffer.from(picture.data, 'base64'); + assert.ok(png.length <= 128, 'actual image bytes must fit the advertised quota'); + assert.ok(png.readUInt32BE(16) < 160 && png.readUInt32BE(20) < 100, 'oversized PNG is scaled down before sending'); + } + checks.push('screenshots-are-automatically-scaled-and-reencoded-to-the-advertised-image-byte-quota'); + } else if (scenario === 'higher') { + assert.deepEqual(notes.map((note) => note.remainingImages), [5, 4, 3, 2, 2]); + assert.equal(notes[0].backendLimits.historyItems, 1024); + assert.equal(notes[0].backendLimits.requestTimeoutSeconds, 180); + checks.push('larger-backend-quotas-are-used-without-the-old-two-image-and-256-item-clamps'); + } else { + assert.deepEqual(notes.map((note) => note.remainingImages), [null, null, null, null, null]); + assert.deepEqual(notes[0].backendLimits, {}); + checks.push('missing-or-zero-backend-quotas-do-not-acquire-frontend-image-history-or-timeout-limits'); + } + } + if (process.env.VM_CAD_SCREENSHOT) await page.screenshot({ path: process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, `-budget-${scenario}.png`) }); + if (scenario === 'images') { + // No new chat: a new message frees old screenshots by dropping whole + // completed rounds, including their call/result pairs. + await chat(page, { send: 'vm-test:screenshot after-budget', attach_view: false, attach_selection: false }); + const resumed = await until(page, (state) => !state.turn && state.items.some((item) => item.user?.includes('after-budget')), + 'new message did not recover image budget', 60000); + const resumedRequests = (await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === budgetProject.data.cadProjectCode + && call.body.history[0]?.content?.some((part) => part.text?.includes('after-budget'))); + assert.equal(resumedRequests.length, 2, JSON.stringify(resumed)); + assert.equal(resumedRequests[0].body.history.length, 1, 'only the new complete user round is retained'); + assert.equal(resumedRequests[1].body.history.at(-1).isError, false); + assert.equal(resumedRequests[1].body.history.at(-1).content.filter((part) => part.type === 'image').length, 1); + checks.push('new-user-message-reclaims-old-image-budget-by-trimming-only-complete-rounds'); + } + await context.unroute('**/api/cad/ai/capabilities'); + } + + // A long turn waits at the request rate boundary and can still be stopped. + await context.route('**/api/cad/ai/capabilities', async (route) => { + const response = await route.fetch(); + const body = await response.json(); + body.data.limits.requestsPerMinute = 1; + body.data.limits.requestTimeoutSeconds = 3; + await route.fulfill({ response, json: body }); + }); + const pacedProject = await (await fetch(`${base}/api/cad/workspace/projects`, { + method: 'POST', headers, body: JSON.stringify({ name: 'Paced Agent browser test', description: '' }), + })).json(); + assert.equal(pacedProject.code, 'OK'); + await page.goto(`${base}/cad/editor/?project=${pacedProject.data.cadProjectCode}`); + await page.waitForFunction(async () => { + if (!window.vibemakeCad || !window.solidcraft) return false; + const host = await window.vibemakeCad.getState(); + return host.binding && !host.locked && document.querySelector('#cad-main')?.hidden; + }, null, { timeout: 180000 }); + await page.waitForFunction(() => window.solidcraft && window.vibemakeCad, null, { timeout: 60000 }); + await until(page, (s) => s.open && s.state === 'ready', 'paced agent did not become ready', 60000); + // Isolate this scenario's quota from the previous long turn. + await page.evaluate(() => { + for (const key of Object.keys(localStorage)) if (key.startsWith('vm.cad.ai-rate:')) localStorage.removeItem(key); + }); + await chat(page, { send: 'vm-test:read paced-cancel', attach_view: false, attach_selection: false }); + await until(page, (s) => s.turn && s.items.some((i) => i.status === 'Completed'), 'first paced tool did not execute'); + await page.waitForTimeout(3500); + 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.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 }); + await until(page, (s) => !s.turn, 'Stop did not cancel rate-limit waiting'); + await page.waitForTimeout(500); + assert.equal((await agentCalls()).filter((call) => call.body?.turnCode === pacedCalls[0].body.turnCode).length, 1); + checks.push('rate-limit-waits-without-ending-the-turn-and-stop-cancels-the-wait'); + checks.push('queued-time-is-excluded-from-the-model-request-timeout'); + + const otherProject = await (await fetch(`${base}/api/cad/workspace/projects`, { + method: 'POST', headers, body: JSON.stringify({ name: 'Shared account quota test', description: '' }), + })).json(); + assert.equal(otherProject.code, 'OK'); + const otherPage = await context.newPage(); + otherPage.on('pageerror', (error) => errors.push(String(error))); + try { + await otherPage.goto(`${base}/cad/editor/?project=${otherProject.data.cadProjectCode}`); + await otherPage.waitForFunction(async () => { + if (!window.vibemakeCad || !window.solidcraft) return false; + const host = await window.vibemakeCad.getState(); + return host.binding && !host.locked && document.querySelector('#cad-main')?.hidden; + }, null, { timeout: 180000 }); + await until(otherPage, (s) => s.open && s.state === 'ready', 'second tab agent did not become ready', 60000); + await chat(otherPage, { send: 'vm-test:read shared-account-quota', attach_view: false, attach_selection: false }); + await until(otherPage, (s) => s.turn, 'second tab did not queue its request'); + await otherPage.waitForTimeout(500); + assert.ok((await chat(otherPage)).turn); + assert.equal((await agentCalls()).filter((call) => call.path === '/cad/ai/chat' + && call.body.cadProjectCode === otherProject.data.cadProjectCode).length, 0, + 'a new document/tab must retain the account quota'); + await chat(otherPage, { cancel: true }); + await until(otherPage, (s) => !s.turn, 'second tab queued request did not cancel'); + checks.push('new-documents-and-browser-tabs-share-the-account-request-quota'); + } finally { + await otherPage.close(); + } + assert.deepEqual(errors, []); + return { checks, errors, url: page.url() }; + } catch (error) { + if (process.env.VM_CAD_SCREENSHOT) { + await page.screenshot({ path: process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, '-failure.png') }).catch(() => {}); + await writeFile(process.env.VM_CAD_SCREENSHOT.replace(/\.png$/, '-failure.json'), JSON.stringify({ + checks, error: String(error), host: await page.evaluate(() => window.vibemakeCad?.getState()).catch(() => null), + inert: await page.locator('#cad-viewport').evaluate((element) => element.inert).catch(() => null), + }, null, 2)); + } + throw error; + } finally { + await context.close(); + } +} + +export { run as runPlatformAgentBrowserChecks }; + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const options = { headless: true, args: ['--enable-unsafe-webgpu', '--use-angle=swiftshader', '--enable-webgl'] }; + if (process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE) options.executablePath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE; + const browser = await chromium.launch(options); + try { console.log(JSON.stringify(await run(browser))); } + finally { await browser.close(); } +} diff --git a/tests/cad/save.test.js b/tests/cad/save.test.js index 70a26cd..b2c06bb 100644 --- a/tests/cad/save.test.js +++ b/tests/cad/save.test.js @@ -17,6 +17,7 @@ function fixture() { revision: 7, }; const bridge = { + getState: async () => ({ dirty: dirty || currentRevision !== snapshot.revision }), createSnapshot: async ({ snapshotId } = {}) => { logs.push('capture'); return { ...snapshot, snapshotId: snapshotId || snapshot.snapshotId }; @@ -42,6 +43,9 @@ function fixture() { record.user === user && record.project === project && record.kind === kind), }; const api = { + get: async () => ({ cadProjectCode: 'project-a', version }), + uploadCover: async (cover) => { logs.push(['cover-upload', cover]); return 'https://cdn.example/project-covers/plate.png'; }, + setCover: async (projectId, coverUrl) => { logs.push(['cover-patch', projectId, coverUrl]); return { version, coverUrl }; }, assertIdentity() {}, signCalls: [], commitCalls: [], @@ -73,6 +77,93 @@ function fixture() { }; } +function withCover(value = fixture()) { + value.snapshot.cover = { bytes: new Uint8Array([137, 80, 78, 71]), mimeType: 'image/png', width: 640, height: 400 }; + return value; +} + +test('cover comes from the saved snapshot and is uploaded only after the document ACK', async () => { + const value = withCover(), original = value.snapshot.cover; + value.saver.uploader = async () => { value.setRevision(8); value.snapshot.cover = { bytes: new Uint8Array([99]), mimeType: 'image/png' }; }; + await value.saver.save(); + const coverUpload = value.logs.find((entry) => entry[0] === 'cover-upload'); + assert.equal(coverUpload[1], original); + assert.ok(value.logs.findIndex((entry) => entry[0] === 'ack') < value.logs.indexOf(coverUpload)); + assert.equal(value.project.coverUrl, 'https://cdn.example/project-covers/plate.png'); + assert.equal(value.dirty(), true, 'later edits must remain unsaved'); + assert.equal(value.saver.pendingCover, null); + assert.equal([...value.records.values()].filter((record) => record.kind === 'cover').length, 0); +}); + +test('failed cover upload preserves a saved native document and retries without a new version', async () => { + const value = withCover(), states = []; + value.saver.onState = (state) => states.push(state); + const upload = value.api.uploadCover; + value.api.uploadCover = async () => { throw Object.assign(new Error('disabled'), { code: 'OSS_DISABLED', status: 503 }); }; + const result = await value.saver.save(); + assert.equal(result.coverPending, true); + assert.equal(value.project.version, 4); + assert.equal(value.dirty(), false); + assert.equal(value.saver.operation, null); + assert.equal(states.at(-1), 'coverFailed'); + assert.equal([...value.records.values()].filter((record) => record.kind === 'cover').length, 1); + value.api.uploadCover = upload; + await value.saver.save(); + assert.equal(value.api.signCalls.length, 1); + assert.equal(value.api.commitCalls.length, 1); + assert.equal(value.logs.filter((entry) => entry === 'capture').length, 1); + assert.equal(value.project.version, 4); + assert.equal(states.at(-1), 'saved'); +}); + +test('cover PATCH retries reuse the uploaded URL and a refreshed page can restore that job', async () => { + const value = withCover(), patch = value.api.setCover; + value.api.setCover = async () => { throw new Error('response lost'); }; + await value.saver.save(); + assert.equal(value.saver.pendingCover.coverUrl, 'https://cdn.example/project-covers/plate.png'); + value.saver.pendingCover = null; + await value.saver.restoreCover(); + assert.ok(value.saver.pendingCover); + value.api.setCover = patch; + await value.saver.save(); + assert.equal(value.logs.filter((entry) => entry[0] === 'cover-upload').length, 1); + assert.equal(value.api.commitCalls.length, 1); + assert.equal(value.saver.pendingCover, null); +}); + +test('a remote version advancing during cover upload prevents a stale PATCH', async () => { + const value = withCover(); + value.api.uploadCover = async () => { + value.api.get = async () => ({ version: 5 }); + return 'https://cdn.example/project-covers/old.png'; + }; + const reply = await value.saver.save(); + assert.equal(reply.coverSuperseded, true); + assert.equal(value.logs.some((entry) => entry[0] === 'cover-patch'), false); + assert.equal(value.saver.pendingCover, null); +}); + +test('disposal during cover upload never patches the project bound to a later session', async () => { + const value = withCover(); + value.api.uploadCover = async () => { value.saver.dispose(); return 'https://cdn.example/project-covers/old.png'; }; + await assert.rejects(value.saver.save(), { code: 'STALE_BINDING' }); + assert.equal(value.dirty(), false, 'the native document was already saved'); + assert.equal(value.logs.some((entry) => entry[0] === 'cover-patch'), false); +}); + +test('unavailable previews preserve an existing cover and still save the native document', async () => { + for (const cover of [null, undefined]) { + const value = fixture(); + value.project.coverUrl = 'https://cdn.example/project-covers/previous.png'; + value.snapshot.cover = cover; + const reply = await value.saver.save(); + assert.equal(reply.coverUnavailable, true, 'an older bridge without cover data must also report the unavailable preview'); + assert.equal(value.project.coverUrl, 'https://cdn.example/project-covers/previous.png'); + assert.equal(value.dirty(), false); + assert.equal(value.logs.some((entry) => entry[0] === 'cover-patch'), false); + } +}); + test('manual save signs, uploads, commits, then ACKs the exact snapshot', async () => { const value = fixture(); await value.saver.save(); @@ -128,6 +219,77 @@ test('lost PUT response retries the same uploadCode without another signature or assert.equal(value.saver.operation, null); }); +test('lost OSS response confirms the original batch before any new upload', async () => { + const value = fixture(); + value.saver.uploader = async (signature) => { + value.logs.push(['upload', signature.uploadCode]); + throw new TypeError('upload response lost'); + }; + await value.saver.save(); + assert.equal(value.api.signCalls.length, 1); + assert.deepEqual(value.api.commitCalls, [{ project: 'project-a', uploadCode: 'upload-1' }]); + assert.equal(value.logs.filter((entry) => Array.isArray(entry) && entry[0] === 'upload').length, 1); + assert.equal(value.dirty(), false); +}); + +test('failed OSS POST renews a batch only after confirmation reports a missing file', async () => { + const value = fixture(); + value.saver.uploader = async (signature) => { + value.logs.push(['upload', signature.uploadCode]); + if (signature.uploadCode === 'upload-1') throw Object.assign(new Error('OSS refused'), { code: 'UPLOAD_FAILED' }); + }; + value.api.commitHandler = async (project, uploadCode, count) => { + if (count === 1) throw Object.assign(new Error('missing'), { code: 'CAD_FILE_MISSING' }); + return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' }; + }; + await value.saver.save(); + assert.deepEqual(value.api.commitCalls.map((call) => call.uploadCode), ['upload-1', 'upload-2']); + assert.deepEqual(value.logs.filter((entry) => typeof entry === 'string' && ['signature', 'put-document'].includes(entry)), + ['signature', 'put-document', 'signature', 'put-document']); +}); + +test('unknown confirmation after a failed upload retains its batch and snapshot for retry', async () => { + const value = fixture(); + value.saver.uploader = async (signature) => { + value.logs.push(['upload', signature.uploadCode]); + throw Object.assign(new Error('OSS response denied'), { code: 'CAD_UPLOAD_EXPIRED' }); + }; + value.api.commitHandler = async (project, uploadCode, count) => { + if (count === 1) throw Object.assign(new Error('OSS unavailable'), { code: 'CAD_OSS_ERROR', status: 502 }); + return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' }; + }; + await assert.rejects(value.saver.save(), { code: 'CAD_OSS_ERROR' }); + assert.equal(value.saver.operation.uploadCode, 'upload-1'); + assert.equal(value.dirty(), true); + assert.equal(value.logs.some((entry) => Array.isArray(entry) && entry[0] === 'ack'), false); + await value.saver.save(); + assert.equal(value.api.signCalls.length, 1); + assert.equal(value.logs.filter((entry) => Array.isArray(entry) && entry[0] === 'upload').length, 1); + assert.deepEqual(value.api.commitCalls.map((call) => call.uploadCode), ['upload-1', 'upload-1']); +}); + +test('only a backend expiry or size mismatch renews an uploaded batch', async () => { + for (const code of ['CAD_UPLOAD_EXPIRED', 'CAD_FILE_SIZE_MISMATCH']) { + const value = fixture(); + value.api.commitHandler = async (project, uploadCode, count) => { + if (count === 1) throw Object.assign(new Error(code), { code, status: 409 }); + return { cadProjectCode: project, version: 4, savedAt: '2026-11-03T04:00:00.000Z' }; + }; + await value.saver.save(); + assert.equal(value.api.signCalls.length, 2); + assert.deepEqual(value.api.commitCalls.map((call) => call.uploadCode), ['upload-1', 'upload-2']); + assert.equal(value.project.version, 4); + } +}); + +test('a confirmed save removes its journal with a valid key', async () => { + const value = fixture(), removed = []; + value.store.remove = async (key) => { assert.equal(typeof key, 'string'); removed.push(key); }; + value.saver.onStorageError = (error) => assert.fail(error.message); + await value.saver.save(); + assert.deepEqual(removed, [value.store.key('owner-a', 'project-a', 'tab-a', 'operation')]); +}); + test('refresh recovery confirms the persisted uploadCode first', async () => { const value = fixture(); value.api.commitHandler = async (project) => ({