Files
cad-world/frontend/tests/browser/agent-window.check.cjs
T
2026-09-22 10:36:28 +08:00

173 lines
10 KiB
JavaScript

const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const { parse, compileScript, compileStyle } = require('@vue/compiler-sfc')
const ts = require('typescript')
const { chromium } = require('playwright')
// Mount the actual workspace SFC while isolating controller/network/GPU dependencies.
const root = path.resolve(__dirname, '../..')
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8')
const javascript = (source) => ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText
const themeCss = (file) => read(file).replace(/@import ['"]([^'"]+)['"];?/g, (_, relative) => themeCss(path.join(path.dirname(file), relative)))
const source = read('src/components/assemble/AssembleAgentChatWorkspace.vue')
const { descriptor } = parse(source)
const script = javascript(compileScript(descriptor, { id: 'window-check', inlineTemplate: true }).content)
const css = compileStyle({ source: descriptor.styles[0].content, filename: 'Workspace.vue', id: 'data-v-window-check', scoped: true })
assert.deepEqual(css.errors, [])
const frameScript = javascript(read('src/components/assemble/floating-window-frame.ts'))
async function mount(page) {
await page.setContent(`<meta name="viewport" content="width=device-width,initial-scale=1"><style>${themeCss('src/theme/index.css')} ${css.code}
body{margin:0} .assemble-agent-workspace{height:100vh}
.agent-chat-panel__message-content,.agent-chat-panel__footer,.agent-chat-panel__composer{backdrop-filter:blur(10px)}
</style><div id="app"></div><div class="assemble-agent-workspace__export-popover el-popper">Export</div>`)
await page.addScriptTag({ path: path.join(root, 'node_modules/vue/dist/vue.global.prod.js') })
await page.evaluate(({ script, frameScript }) => {
const Vue = window.Vue
const noop = () => {}
const slot = { setup: (_, { slots }) => () => slots.default?.() }
const empty = { render: () => null }
const controller = Vue.reactive({
overlays: { projectEntrancePhase: 'idle', isAgentModelPreparing: false },
viewport: { sceneRenderInstances: [], setCameraAutoRotateOnIdle: () => true },
leftPanel: { robotConversation: { messages: [], isSending: false } }, bom: {},
})
const store = Vue.reactive({ resolvedTheme: 'dark', setThemePreference: noop })
const frames = { exports: {} }
new Function('module', 'exports', frameScript)(frames, frames.exports)
const dependencies = {
vue: Vue,
pinia: { storeToRefs: Vue.toRefs },
'vue-router': { useRoute: () => ({ query: {} }), useRouter: () => ({ resolve: () => ({ href: '' }) }) },
'element-plus': { ElMessage: { error: noop, success: noop } },
'@element-plus/icons-vue': Object.fromEntries(['ChatDotRound', 'Close', 'Cpu', 'Download', 'Moon', 'Sunny', 'Tickets'].map((name) => [name, empty])),
'@/workbench/session/useWorkbenchSession': { useWorkbenchSession: () => ({ applyPreset: noop, disposeSharedSceneHost: noop }) },
'@/workbench/composables/useAssemblyWorkbenchController': { useAssemblyWorkbenchController: () => controller },
'@/stores/ui-shell': { useUiShellStore: () => store },
'@/composables/useWorkbenchExportActions': { useWorkbenchExportActions: () => ({ isExporting: Vue.ref(false), statusText: Vue.ref('') }) },
'@/composables/useBomHost': { useBomHost: () => ({ open: noop, download: noop, fallbackUrl: Vue.ref(''), error: Vue.ref(''), canDownload: Vue.ref(false) }) },
'@/composables/usePcbSceneHost': { usePcbSceneHost: () => ({ open: noop, fallbackUrl: Vue.ref('') }) },
'./floating-window-frame': frames.exports,
}
const module = { exports: {} }
const require = (id) => {
if (id in dependencies) return dependencies[id]
if (id.endsWith('AssemblySceneViewport.vue')) return { default: { render: () => Vue.h('div', { id: 'viewport-host', 'data-render-effects': 'full' }) } }
if (id.endsWith('AgentChatPanel.vue')) return { default: { render: () => Vue.h('div', ['message-content', 'footer', 'composer'].map((name) => Vue.h('div', { class: `agent-chat-panel__${name}` }, name))) } }
if (id.endsWith('.vue')) return { default: empty }
throw new Error(`Unexpected dependency: ${id}`)
}
new Function('require', 'module', 'exports', script)(require, module, module.exports)
module.exports.default.__scopeId = 'data-v-window-check'
const app = Vue.createApp(module.exports.default)
for (const name of ['RouterLink', 'el-tooltip', 'el-icon', 'el-select', 'el-option']) app.component(name, slot)
app.component('el-popover', { setup: (_, { slots }) => () => slots.reference?.() })
window.windowTestApp = app
app.mount('#app')
}, { script, frameScript })
await page.locator('.assemble-agent-window').waitFor()
await waitForWindowTransition(page)
}
const waitForWindowTransition = (page) => page.waitForFunction(() => {
const element = document.querySelector('.assemble-agent-window')
return element && !element.className.includes('-active') && getComputedStyle(element).transform === 'none'
})
async function main() {
const browser = await chromium.launch({ headless: true })
try {
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } })
const errors = []
page.on('pageerror', (error) => errors.push(error.message))
await mount(page)
const panel = page.locator('.assemble-agent-window')
const original = await panel.boundingBox()
await page.evaluate(() => {
document.body.style.cursor = 'crosshair'
document.body.style.userSelect = 'text'
const workspace = document.querySelector('.assemble-agent-workspace')
const measure = workspace.getBoundingClientRect.bind(workspace)
window.workspaceMeasurements = 0
workspace.getBoundingClientRect = () => { window.workspaceMeasurements++; return measure() }
})
await page.mouse.move(original.x + 80, original.y + 20)
await page.mouse.down()
await page.mouse.move(original.x - 120, original.y - 40, { steps: 16 })
// An unrelated touch must neither move nor end the captured drag.
await page.evaluate(() => {
window.dispatchEvent(new PointerEvent('pointermove', { pointerId: 999, clientX: 5, clientY: 5 }))
window.dispatchEvent(new PointerEvent('pointerup', { pointerId: 999, clientX: 5, clientY: 5 }))
})
assert.ok((await panel.getAttribute('class')).includes('--interacting'))
await page.mouse.up()
const moved = await panel.boundingBox()
assert.ok(Math.abs(moved.x - (original.x - 200)) < 1)
assert.ok(Math.abs(moved.y - (original.y - 60)) < 1)
assert.equal(moved.width, original.width)
const state = await panel.evaluate((element) => ({ left: element.style.left, top: element.style.top, translate: element.style.translate, measurements: window.workspaceMeasurements, cursor: document.body.style.cursor, userSelect: document.body.style.userSelect }))
assert.equal(state.left, '')
assert.equal(state.top, '')
assert.ok(state.translate)
assert.ok(state.measurements <= 2, JSON.stringify(state))
assert.equal(state.cursor, 'crosshair')
assert.equal(state.userSelect, 'text')
// Resize still changes layout dimensions, but is coalesced by the same frame task.
const resizeHandle = await page.locator('.assemble-agent-window__resize-handle--se').boundingBox()
const resizeStart = { x: resizeHandle.x + resizeHandle.width / 2, y: resizeHandle.y + resizeHandle.height / 2 }
await page.mouse.move(resizeStart.x, resizeStart.y)
await page.mouse.down()
await page.mouse.move(resizeStart.x + 40, resizeStart.y + 30, { steps: 8 })
await page.mouse.up()
const resized = await panel.boundingBox()
assert.ok(Math.abs(resized.width - moved.width - 40) < 1, JSON.stringify({ moved, resized }))
assert.ok(Math.abs(resized.height - moved.height - 30) < 1, JSON.stringify({ moved, resized }))
// Pressure styles follow the renderer's attribute and recover when it is removed.
const blur = () => page.locator('.assemble-agent-window').evaluate((element) => getComputedStyle(element).backdropFilter)
assert.match(await blur(), /blur/)
await page.locator('#viewport-host').evaluate((element) => { element.dataset.renderEffects = 'minimal' })
assert.equal(await blur(), 'none')
for (const selector of ['.assemble-agent-window__header', '.agent-chat-panel__footer', '.agent-chat-panel__composer', '.agent-chat-panel__message-content', '.assemble-agent-workspace__export-popover']) {
assert.equal(await page.locator(selector).evaluate((element) => getComputedStyle(element).backdropFilter), 'none', selector)
}
await page.locator('#viewport-host').evaluate((element) => { delete element.dataset.renderEffects })
assert.match(await blur(), /blur/)
await page.getByRole('button', { name: '隐藏 Agent 窗口' }).click()
await page.getByRole('button', { name: '显示 Agent 窗口' }).click()
await waitForWindowTransition(page)
assert.deepEqual(await panel.boundingBox(), resized)
// A cancelled drag restores body styles; queued work must not survive unmount.
await page.mouse.move(resized.x + 60, resized.y + 20)
await page.mouse.down()
await page.evaluate(() => window.dispatchEvent(new Event('blur')))
assert.ok(!(await panel.getAttribute('class')).includes('--interacting'))
await page.mouse.up()
await page.evaluate(() => window.windowTestApp.unmount())
assert.deepEqual(errors, [])
for (const viewport of [{ width: 375, height: 812 }, { width: 812, height: 375 }]) {
const context = await browser.newContext({ viewport, hasTouch: true, isMobile: true, reducedMotion: 'reduce' })
const mobile = await context.newPage()
mobile.on('pageerror', (error) => errors.push(error.message))
await mount(mobile)
assert.equal(await mobile.locator('.assemble-agent-window').evaluate((element) => getComputedStyle(element).backdropFilter), 'none')
assert.equal(await mobile.locator('.assemble-agent-window__header').evaluate((element) => getComputedStyle(element).backdropFilter), 'none')
const box = await mobile.locator('.assemble-agent-window').boundingBox()
assert.ok(box.x >= 0 && box.x + box.width <= await mobile.evaluate(() => innerWidth))
await context.close()
}
assert.deepEqual(errors, [])
console.log('PASS: actual workspace drag/resize, pointer ownership, rect cache, body-style cleanup, transition position, minimal pressure recovery, and coarse-pointer portrait/landscape blur.')
} finally {
await browser.close()
}
}
main().catch((error) => { console.error(error); process.exitCode = 1 })