const assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path') const {chromium}=require('C:/Users/Administrator/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright') ;(async()=>{ const login=await(await fetch('http://127.0.0.1:8080/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:'admin',password:'admin123',code:'',uuid:''})})).json() assert.equal(login.code,200) const browser=await chromium.launch({channel:'chrome',headless:true,args:['--disable-gpu','--js-flags=--max-old-space-size=256']}) const out=path.resolve(__dirname,'../../.codex-tmp/home-assistant-check');fs.mkdirSync(out,{recursive:true}) const errors=[],analyzed=[],executed=[];let realQuery=true,handler,executeResult,release try{ const context=await browser.newContext({viewport:{width:1366,height:768}}) await context.addCookies([{name:'Admin-Token',value:login.token,url:'http://127.0.0.1:8088'}]) const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message)) await page.route('**/dev-api/**',async route=>{ const request=route.request(),url=new URL(request.url()) if(url.pathname.endsWith('/warehouse/agent/analyze')){ const body=request.postDataJSON();analyzed.push(body) if(realQuery){assert.ok(['查询库存','查询采购状态'].includes(body.text));return route.continue()} return route.fulfill({json:{code:200,data:await handler(body)}}) } if(url.pathname.endsWith('/warehouse/agent/execute')){assert.equal(realQuery,false);executed.push(request.postDataJSON());if(release)await release;return route.fulfill({json:{code:200,data:executeResult}})} assert.ok(['GET','HEAD'].includes(request.method()),'Unexpected business mutation '+url.pathname) return route.continue() }) await page.goto('http://127.0.0.1:8088/index',{waitUntil:'domcontentloaded'}) await page.waitForFunction(()=>document.querySelector('.business-home')?.__vue__?.loadedOnce&&!document.querySelector('.business-home').__vue__.loading) const input=page.locator('.assistant-input input'),analyze=page.locator('.assistant-input button').filter({hasText:'分析'}) const result=page.locator('.el-dialog__wrapper').filter({has:page.locator('.assistant-plan-title')}) async function run(text){await input.fill(text);await analyze.click();await page.waitForFunction(()=>!!document.querySelector('.inventory-assistant').__vue__.plan&&!document.querySelector('.inventory-assistant').__vue__.loading);await result.waitFor({state:'visible'});await page.waitForTimeout(350)} async function close(){await result.locator('.el-dialog__footer button').filter({hasText:'关闭'}).click();await result.waitFor({state:'hidden'})} async function vmEvaluate(fn){return page.evaluate(fn)} await run('查询库存') const real=await vmEvaluate(()=>{const v=document.querySelector('.inventory-assistant').__vue__;return {action:v.plan.action,count:(v.plan.results||[]).length,warnings:v.plan.warnings||[],confirm:v.plan.needConfirm}}) assert.equal(real.action,'query_stock');assert.equal(real.confirm,false);assert.equal(executed.length,0) assert.equal(await result.locator('.el-dialog__footer button').filter({hasText:'确认执行'}).count(),0) await page.screenshot({path:path.join(out,'real-inventory-query.png')});await close() await run('查询采购状态') const realPurchase=await vmEvaluate(()=>{const v=document.querySelector('.inventory-assistant').__vue__;return {action:v.plan.action,count:(v.plan.results||[]).length,warnings:v.plan.warnings||[],confirm:v.plan.needConfirm}}) assert.equal(realPurchase.action,'query_purchase');assert.equal(realPurchase.confirm,false);assert.equal(executed.length,0) await close();realQuery=false const draft={action:'create_out_record',summary:'测试草稿,不写入数据库',needConfirm:true,executable:true,commandId:'fixture-command',productName:'验证物品',quantity:2,unit:'个',areaName:'验证库区',usageProjectName:'验证项目'} handler=()=>({...draft});executeResult={action:'create_out_record',needConfirm:false,executable:false,message:'验证执行结果(模拟)'} await run('验证出库 2 个');assert.equal(await vmEvaluate(()=>document.querySelector('.inventory-assistant').__vue__.canExecute),true) const execute=result.locator('.el-dialog__footer button').filter({hasText:'确认执行'}) await execute.click();await page.locator('.el-message-box').waitFor();assert.equal(executed.length,0) await page.locator('.el-message-box button').filter({hasText:'返回核对'}).click();await page.waitForFunction(()=>!document.querySelector('.inventory-assistant').__vue__.executing);assert.equal(executed.length,0) await vmEvaluate(()=>{document.querySelector('.inventory-assistant').__vue__.text='修改后的指令'}) assert.equal(await execute.isDisabled(),true) await vmEvaluate(()=>{const v=document.querySelector('.inventory-assistant').__vue__;v.text=v.analyzedText;v.plan.commandId=null}) assert.equal(await execute.isDisabled(),true) await vmEvaluate(()=>{const v=document.querySelector('.inventory-assistant').__vue__;v.plan.commandId='fixture-command';v.$store.commit('SET_PERMISSIONS',['ai:assistant:use'])}) assert.equal(await execute.isDisabled(),true) await vmEvaluate(()=>document.querySelector('.inventory-assistant').__vue__.$store.commit('SET_PERMISSIONS',['*:*:*'])) await execute.click();await page.locator('.el-message-box button').filter({hasText:'确认执行'}).click() await page.waitForFunction(()=>!document.querySelector('.inventory-assistant').__vue__.executing) assert.equal(executed.length,1);assert.equal(await result.locator('.el-dialog__footer button').filter({hasText:'确认执行'}).count(),0);await close() // Duplicate submits stay disabled while an intercepted execution is in flight. let unblock;release=new Promise(resolve=>{unblock=resolve}) await run('再次验证出库');await execute.click();await page.locator('.el-message-box button').filter({hasText:'确认执行'}).click() await page.waitForFunction(()=>document.querySelector('.inventory-assistant').__vue__.executing) await vmEvaluate(()=>{const v=document.querySelector('.inventory-assistant').__vue__;v.execute();v.execute()}) await page.waitForTimeout(150);assert.equal(executed.length,2);unblock();release=null await page.waitForFunction(()=>!document.querySelector('.inventory-assistant').__vue__.executing);await close() // Candidate selection obtains a new server draft and preserves an intentional zero count. let selection handler=body=>{if(body.contextResults.length){selection=body;return {...draft,action:'create_stock_check',quantity:0}}return {...draft,action:'create_stock_check',commandId:null,executable:false,quantity:0,results:[{id:123,productId:123,productName:'验证物品',unit:'个',stockNum:10}]}} await run('盘点验证物品实际 0 个');await result.getByRole('button',{name:'选择此项'}).click() await page.waitForFunction(()=>!!document.querySelector('.inventory-assistant').__vue__.plan?.commandId) assert.ok(selection.text.includes('实际0个'));assert.equal(selection.contextResults[0].id,123);assert.equal(executed.length,2);await close() // A setup response's nextPlan is not executable: original text must be re-analyzed. let nextAnalyses=0 handler=()=>++nextAnalyses===1?{...draft,action:'create_area'}:{...draft,commandId:'newly-registered-command'} executeResult={action:'create_area',needConfirm:false,message:'验证库区创建(模拟)',nextPlan:{...draft,commandId:null}} await run('先建库区再入库');await execute.click();await page.locator('.el-message-box button').filter({hasText:'确认执行'}).click() await page.waitForFunction(()=>document.querySelector('.inventory-assistant').__vue__.plan?.commandId==='newly-registered-command') assert.equal(nextAnalyses,2);assert.equal(executed.length,3);await close() // Large query results scroll inside the dialog, leaving its header/footer visible. handler=()=>({action:'query_stock',needConfirm:false,results:Array.from({length:50},(_,i)=>({id:i+1,productName:'验证长结果 '+i,stockNum:i,unit:'个'}))}) await run('布局验证查询') const geometry=await result.evaluate(e=>{const body=e.querySelector('.el-dialog__body'),footer=e.querySelector('.el-dialog__footer'),header=e.querySelector('.el-dialog__header');return {scroll:body.scrollHeight-body.clientHeight,footer:footer.getBoundingClientRect().bottom,top:header.getBoundingClientRect().top,height:innerHeight,documentOverflow:document.documentElement.scrollHeight-innerHeight}}) assert.ok(geometry.scroll>0);assert.ok(geometry.footer<=geometry.height);assert.ok(geometry.top>=0);assert.ok(geometry.documentOverflow<=2) await close() // Analysis finishing after the user leaves Home must not reopen the global dialog. let finish;handler=()=>new Promise(resolve=>{finish=resolve}) await input.fill('延迟查询');await analyze.click();await page.waitForTimeout(150) await vmEvaluate(async()=>{await document.querySelector('#app').__vue__.$router.push('/project/info')}) finish({action:'query_stock',needConfirm:false,results:[]});await page.waitForTimeout(400) assert.equal(await page.locator('.el-dialog__wrapper:visible').filter({hasText:'智能库存助手'}).count(),0) await vmEvaluate(async()=>{await document.querySelector('#app').__vue__.$router.push('/index')}) await page.waitForFunction(()=>document.querySelector('.inventory-assistant')?.__vue__?.active) assert.equal(await vmEvaluate(()=>document.querySelector('.inventory-assistant').__vue__.busy),false) // Leaving Home while the confirmation prompt is open revokes client execution. handler=()=>({...draft});await run('离开首页的确认验证');await execute.click();await page.locator('.el-message-box').waitFor() await vmEvaluate(async()=>{await document.querySelector('#app').__vue__.$router.push('/project/info')}) await page.locator('.el-message-box button').filter({hasText:'确认执行'}).click();await page.waitForTimeout(250) assert.equal(executed.length,3) assert.deepEqual(errors,[]) console.log('PASS: real read-only inventory/purchase queries; simulated draft/permission/cancel/duplicate/context/next-step/navigation/dialog tests. No real business writes. Real queries:',JSON.stringify({inventory:real,purchase:realPurchase})) }finally{await browser.close()} })().catch(e=>{console.error(e);process.exitCode=1})