| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- // Anonymous production browser acceptance. No local overrides or business write calls.
- import fs from 'node:fs';
- import path from 'node:path';
- import assert from 'node:assert/strict';
- import {spawn} from 'node:child_process';
- const verified=JSON.parse(fs.readFileSync('work/live-S3-v2-readback-20261103.json','utf8'));
- const template=JSON.parse(fs.readFileSync('work/first-live-S3-v2-template.json','utf8'));
- assert.ok(verified.ok);assert.equal(verified.artifactId,'ZW1FB5zeHr');assert.equal(verified.version,2);
- const base='https://kangshifu.fmode.cn',output='work/live-S3-v2-browser-verified-20261103-02.json';
- const runId=Date.now();
- assert.equal(fs.existsSync(output),false,'Preserve prior browser acceptance');
- const profile=path.resolve('work/browser-S3-v2-'+Date.now());fs.mkdirSync(profile);
- const browser=spawn('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',[
- '--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--disable-background-networking',
- '--remote-debugging-address=127.0.0.1','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'
- ],{windowsHide:true,stdio:'ignore'});
- const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
- const checks=[],errors=[],requests=[],observations=[],screenshots=[];
- let socket;
- try{
- let port;
- for(let i=0;i<100;i++){try{port=Number(fs.readFileSync(path.join(profile,'DevToolsActivePort'),'utf8').split('\n')[0]);}catch{}if(port)break;await sleep(100);}
- assert.ok(port,'browser debugger');
- const tabs=await(await fetch('http://127.0.0.1:'+port+'/json/list')).json();
- socket=new WebSocket(tabs.find(t=>t.type==='page').webSocketDebuggerUrl);
- await new Promise((resolve,reject)=>{socket.addEventListener('open',resolve,{once:true});socket.addEventListener('error',reject,{once:true});});
- let seq=0;const pending=new Map();
- socket.addEventListener('message',({data})=>{
- const message=JSON.parse(data);
- if(message.id&&pending.has(message.id)){const p=pending.get(message.id);clearTimeout(p.timer);pending.delete(message.id);message.error?p.reject(Error(message.error.message)):p.resolve(message.result);}
- if(message.method==='Runtime.exceptionThrown')errors.push({runtime:message.params.exceptionDetails.text});
- if(message.method==='Network.loadingFailed'&&message.params.errorText!=='net::ERR_ABORTED')errors.push({network:message.params.errorText});
- if(message.method==='Log.entryAdded'&&message.params.entry.level==='error'&&!message.params.entry.url?.endsWith('/favicon.ico'))errors.push({console:message.params.entry.text});
- if(message.method==='Network.requestWillBeSent'){
- const r=message.params.request;let cloudPath=null;
- if(r.url.endsWith('/api/functions')){try{cloudPath=JSON.parse(r.postData||'{}').path??null;}catch{}}
- requests.push({url:r.url,method:r.method,headerNames:Object.keys(r.headers||{}),cloudPath});
- }
- });
- const cdp=(method,params={})=>new Promise((resolve,reject)=>{
- const id=++seq,timer=setTimeout(()=>{pending.delete(id);reject(Error(method+' timeout'));},30000);
- pending.set(id,{resolve,reject,timer});socket.send(JSON.stringify({id,method,params}));
- });
- const evaluate=async expression=>{
- const r=await cdp('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});
- if(r.exceptionDetails)throw Error(r.exceptionDetails.text);return r.result.value;
- };
- const check=(name,passed)=>{checks.push({name,passed:Boolean(passed)});assert.ok(passed,name);};
- const helpers=`function find(root,selector){const hit=root.querySelector(selector);if(hit)return hit;for(const n of root.querySelectorAll('*'))if(n.shadowRoot){const found=find(n.shadowRoot,selector);if(found)return found;}return null;}
- function text(root){let out='';for(const n of root.childNodes){if(n.nodeType===Node.TEXT_NODE)out+=n.textContent;else if(n.nodeType===Node.ELEMENT_NODE&&!['STYLE','SCRIPT','NOSCRIPT','TEMPLATE'].includes(n.tagName)){out+=text(n);if(n.shadowRoot)out+=text(n.shadowRoot);}}return out;}`;
- const deepText=()=>evaluate(`(()=>{${helpers}return text(document);})()`);
- const compact=value=>value.replace(/\s/g,'');
- const quoteText=value=>value.replace(/\u2009/g,'');
- const screenshot=async label=>{
- const shot=await cdp('Page.captureScreenshot',{format:'png'}),file='work/live-S3-v2-'+label+'-'+runId+'.png';
- fs.writeFileSync(file,Buffer.from(shot.data,'base64'),{flag:'wx'});screenshots.push(file);
- };
- const navigate=async route=>{
- await cdp('Page.navigate',{url:base+route});let ready=false;
- for(let i=0;i<120;i++){await sleep(200);try{ready=await evaluate("import('/src/services/board-service.js').then(m=>m.boardService.status.get()==='ready')");}catch{}if(ready)break;}
- check(route+' public data loaded',ready);await sleep(250);
- };
- await cdp('Page.enable');await cdp('Runtime.enable');await cdp('Network.enable');await cdp('Log.enable');
- for(const mobile of [false,true]){
- const viewport=mobile?'390px':'desktop';
- await cdp('Emulation.setDeviceMetricsOverride',mobile?{width:390,height:844,deviceScaleFactor:1,mobile:true}:{width:1440,height:1000,deviceScaleFactor:1,mobile:false});
- for(const route of ['/members','/stages','/reports','/report/'+verified.artifactId]){
- await navigate(route);const content=compact(await deepText());
- // The members route presents the employee, while report routes present the artifact.
- const expectedVisible=route==='/members'?content.includes('员工待绑定·f83edd27dda7'):
- route==='/stages'?content.includes('S3')&&content.includes('用户需求与痛点'):
- content.includes(compact(template.title));
- check(route+' '+viewport+' relevant content visible',expectedVisible);
- check(route+' '+viewport+' no page overflow',await evaluate('document.documentElement.scrollWidth<=innerWidth'));
- if(!route.startsWith('/report/'))continue;
- // The normalized display model omits version; raw version=2 is checked independently.
- check('public model contains saved artifact and pending table '+viewport,await evaluate("import('/src/services/board-service.js').then(({boardService})=>{const a=boardService.db.get().artifactById['ZW1FB5zeHr'];return a?.id==='ZW1FB5zeHr'&&a?.report?.chapters?.[2]?.sections?.[3]?.title==='待补问题';})"));
- check('S3 title '+viewport,content.includes(compact(template.title)));
- check('classroom boundary '+viewport,content.includes('课堂过程成果')&&content.includes('未经员工正式确认'));
- check('historical sample boundary '+viewport,content.includes('2023—2024年')&&content.includes('不能代表当前市场'));
- check('series separated '+viewport,content.includes('燃魂')&&content.includes('香辣')&&content.includes('不跨产品推论'));
- check('hypotheses and priority '+viewport,content.includes('三项待验证改进方向')&&content.includes('先调查燃魂份量'));
- check('independent opportunity and project absent '+viewport,content.includes('独立机会卡和项目均不建立'));
- check('unknowns retained '+viewport,content.includes('未知')&&content.includes('支付意愿')&&content.includes('KANO'));
- for(const [index,question]of template.pendingQuestions.entries())check('pending question '+(index+1)+' '+viewport,content.includes(compact(question)));
- await screenshot('report-'+(mobile?'mobile':'desktop'));
- check('pending question table scrolled into view '+viewport,await evaluate(`(()=>{${helpers}function locate(root){for(const n of root.querySelectorAll('h2,h3,h4'))if(n.textContent.trim()==='待补问题')return n;for(const n of root.querySelectorAll('*'))if(n.shadowRoot){const hit=locate(n.shadowRoot);if(hit)return hit;}return null;}const heading=locate(document);if(!heading)return false;heading.scrollIntoView({block:'start'});return true;})()`));
- await sleep(250);
- await screenshot('pending-questions-'+(mobile?'mobile':'desktop'));
- const pendingRows=await evaluate(`(()=>{${helpers}const view=find(document,'view-report');const section=[...view.shadowRoot.querySelectorAll('section.sec')].find(s=>s.querySelector('h4')?.textContent.trim()==='待补问题');return [...section.querySelectorAll('tbody tr')].map(r=>[...r.querySelectorAll('td')].map(c=>c.textContent.replace(/\u2009/g,'')));})()`);
- check('eight pending table rows equal fixed template '+viewport,JSON.stringify(pendingRows)===JSON.stringify(template.pendingQuestions.map((q,i)=>[String(i+1),q])));
- for(let i=0;i<8;i++){
- check('pending table row '+(i+1)+' can be scrolled into readable viewport '+viewport,await evaluate(`(()=>{${helpers}const view=find(document,'view-report');const section=[...view.shadowRoot.querySelectorAll('section.sec')].find(s=>s.querySelector('h4')?.textContent.trim()==='待补问题');const row=section.querySelectorAll('tbody tr')[${i}];row.scrollIntoView({block:'center'});const r=row.getBoundingClientRect(),style=getComputedStyle(row);return style.visibility!=='hidden'&&style.display!=='none'&&r.width>0&&r.height>0&&r.top>=60&&r.bottom<=innerHeight-60&&r.left>=0&&r.right<=innerWidth;})()`));
- }
- await screenshot('pending-questions-end-'+(mobile?'mobile':'desktop'));
- for(const [key,entry]of Object.entries(template.report.evidence)){
- const selector=JSON.stringify('[data-anchor="'+key+'"]');
- check('evidence button '+key+' '+viewport,await evaluate(`(()=>{${helpers}const button=find(document,${selector});if(!button)return false;button.scrollIntoView({block:'center'});return true;})()`));
- await sleep(300);
- const point=await evaluate(`(()=>{${helpers}const r=find(document,${selector}).getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2};})()`);
- await cdp('Input.dispatchMouseEvent',{type:'mousePressed',...point,button:'left',clickCount:1});
- await cdp('Input.dispatchMouseEvent',{type:'mouseReleased',...point,button:'left',clickCount:1});
- await sleep(350);
- const drawer=await evaluate(`(()=>{${helpers}const host=find(document,'kf-drawer');const panel=host?.shadowRoot.querySelector('.panel');const body=host?.shadowRoot.querySelector('.body');const r=panel?.getBoundingClientRect();const style=panel?getComputedStyle(panel):null;return {open:host?.open===true,visible:!!r&&r.width>0&&r.height>0&&r.right>0&&r.left<innerWidth&&style.opacity==='1'&&style.pointerEvents==='auto',text:body?text(body):'',quotes:body?[...body.querySelectorAll('.quotes > li > p')].map(p=>p.textContent):[]};})()`);
- check('drawer visible '+key+' '+viewport,drawer.open&&drawer.visible);
- check('verbatim quote '+key+' '+viewport,JSON.stringify(drawer.quotes.map(quoteText))===JSON.stringify(entry.quotes.map(q=>quoteText(q.text))));
- check('registered source '+key+' '+viewport,drawer.text.includes('已关联原始资料')&&!drawer.text.includes('未关联来源记录'));
- check('open drawer no overflow '+key+' '+viewport,await evaluate('document.documentElement.scrollWidth<=innerWidth'));
- await screenshot('evidence-'+key+'-'+(mobile?'mobile':'desktop'));
- observations.push({viewport:mobile?390:1440,evidence:key,sourceId:entry.sourceId,drawerVisible:true,quoteCount:drawer.quotes.length,input:'browser mouse event'});
- await cdp('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
- await cdp('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});await sleep(300);
- check('drawer closed '+key+' '+viewport,await evaluate(`(()=>{${helpers}return find(document,'kf-drawer')?.open===false;})()`));
- }
- }
- }
- await navigate('/report/G8IrkkDG7X');check('S1 still readable',compact(await deepText()).includes('S1资料小结'));
- await navigate('/report/b7NOby5ys0');check('S2 still readable',compact(await deepText()).includes('S2用户需求与痛点'));
- await navigate('/report/oiNxX7o27j');check('S3 v1 still readable',compact(await deepText()).includes(compact(template.title)));
- check('S3 v1 report structure preserved',await evaluate("import('/src/services/board-service.js').then(({boardService})=>{const a=boardService.db.get().artifactById['oiNxX7o27j'];return a?.id==='oiNxX7o27j'&&a?.report?.chapters?.[2]?.sections?.length===3;})"));
- check('no browser errors',errors.length===0);
- const cloudRequests=requests.filter(r=>r.url.endsWith('/api/functions'));
- check('public cloud reads observed',cloudRequests.length>0);
- check('only public board cloud reads',cloudRequests.every(r=>r.method==='POST'&&r.cloudPath==='/ksfGetPublicBoard'));
- check('anonymous browser requests',!requests.some(r=>r.headerNames.some(k=>/master|authorization|session.token|ksf.service.token/i.test(k))));
- const result={ok:true,operation:'live-S3-v2-production-browser-verified',at:new Date().toISOString(),base,artifactId:verified.artifactId,version:2,
- browserVerified:true,scope:'production website, fresh anonymous Edge browser, no module overrides',readOnly:true,businessWrites:0,
- viewports:[1440,390],evidenceDrawersChecked:observations.length,quoteComparison:'All characters equal except display U+2009 thin spaces',
- checks,errors,observations,screenshots};
- fs.writeFileSync(output,JSON.stringify(result,null,2)+'\n',{flag:'wx'});
- console.log(JSON.stringify({ok:true,checks:checks.length,evidenceDrawersChecked:observations.length,screenshots:screenshots.length,browserVerified:true,businessWrites:0},null,2));
- }catch(error){
- const result={ok:false,at:new Date().toISOString(),artifactId:verified.artifactId,browserVerified:false,readOnly:true,businessWrites:0,
- checks,errors,observations,screenshots,error:error.message};
- fs.writeFileSync(output,JSON.stringify(result,null,2)+'\n',{flag:'wx'});console.error(JSON.stringify(result,null,2));process.exitCode=1;
- }finally{socket?.close();browser.kill();}
|