merge: reconcile UI updates with DSH audit fault isolation
This commit is contained in:
commit
e565f67b46
145 files changed
+3688
-112
No files matched your search
@@ -0,0 +1,151 @@
|
||||
"""Capture the real task-center UI above an owned, changing backdrop (Windows).
|
||||
|
||||
Uses only temporary sample projects and an isolated task store. Never starts CAD.
|
||||
Run: python tools/accept_acrylic_ui.py --output build/acrylic-acceptance
|
||||
"""
|
||||
import argparse
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
os.environ.pop('QT_QPA_PLATFORM',None)
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src'))
|
||||
from PySide6.QtCore import Qt,QRectF
|
||||
from PySide6.QtGui import QColor,QFont,QPainter,QLinearGradient,QPen
|
||||
from PySide6.QtWidgets import QApplication,QWidget,QToolTip
|
||||
from PIL import ImageGrab,ImageChops,ImageStat
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget,TargetPlanRow
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output',type=Path,default=Path('build/acrylic-acceptance'))
|
||||
args=parser.parse_args();out=args.output.resolve();out.mkdir(parents=True,exist_ok=True)
|
||||
app=QApplication([]);app.setFont(QFont('Microsoft YaHei UI',9))
|
||||
def settle(seconds=.2):
|
||||
deadline=time.monotonic()+seconds
|
||||
while time.monotonic()<deadline:
|
||||
app.processEvents();time.sleep(.01)
|
||||
class Background(QWidget):
|
||||
phase=0
|
||||
def paintEvent(self,event):
|
||||
p=QPainter(self);g=QLinearGradient(0,0,self.width(),self.height())
|
||||
g.setColorAt(0,QColor('#386eae')if self.phase==0 else QColor('#c17c51'))
|
||||
g.setColorAt(.5,QColor('#a5bfbb'));g.setColorAt(1,QColor('#cfa4ad')if self.phase==0 else QColor('#5b87b4'))
|
||||
p.fillRect(self.rect(),g);p.setPen(QPen(QColor(255,255,255,190),2))
|
||||
for x in range(0,self.width(),22):p.drawLine(x,0,x,self.height())
|
||||
p.setPen(QColor('#2e4a6b'));p.setFont(QFont('Segoe UI',32,QFont.Weight.Bold))
|
||||
for y in range(100,self.height(),150):p.drawText(20,y,'OWNED LIVE BACKDROP / '+str(self.phase+1))
|
||||
background=Background(None,Qt.WindowType.FramelessWindowHint|Qt.WindowType.Tool|Qt.WindowType.WindowStaysOnTopHint)
|
||||
screen=app.primaryScreen();area=screen.availableGeometry()
|
||||
width=min(1280,area.width()-80);height=min(880,area.height()-80)
|
||||
x=area.x()+(area.width()-width)//2;y=area.y()+(area.height()-height)//2
|
||||
background.setGeometry(x-18,y-40,width+36,height+60);background.show()
|
||||
user=ctypes.WinDLL('user32',use_last_error=True)
|
||||
class Point(ctypes.Structure):_fields_=[('x',ctypes.c_long),('y',ctypes.c_long)]
|
||||
user.WindowFromPoint.argtypes=[Point];user.WindowFromPoint.restype=wintypes.HWND
|
||||
user.GetWindowThreadProcessId.argtypes=[wintypes.HWND,ctypes.POINTER(wintypes.DWORD)]
|
||||
captures={};report={'cad_started':False,'sample_data_only':True,'ownership_checked':True,'os_build':sys.getwindowsversion().build}
|
||||
with tempfile.TemporaryDirectory(prefix='sample-',dir=out,ignore_cleanup_errors=True)as temp:
|
||||
root=Path(temp);projects=root/'projects'
|
||||
for name in ('Audio_D2128','Audio_T605A'):
|
||||
project=projects/name/(name+'.prj');project.parent.mkdir(parents=True)
|
||||
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
store=TaskStore(root/'tasks.db')
|
||||
service=TaskCenterService(store,configure_logging(root/'data'))
|
||||
tasks=service.create_project_tasks(projects)
|
||||
service.add_rule(tasks[0].task_id,'4100-CA0000-T7','4100-CA0000-T0')
|
||||
project=store.list_projects(tasks[0].task_id)[0].path
|
||||
rows=tuple(TargetPlanRow(ComponentTarget(project,'MAIN','1','sample-'+str(i),ref,'4100-CA0000-T7','100nF / 50V'),i==0,'4100-CA0000-T0')for i,ref in enumerate(('RV05','RV11','C103','C104','C105','C106')))
|
||||
store.record_target_inventory(tasks[0].task_id,tuple(row.target for row in rows))
|
||||
service.replace_target_plan(tasks[0].task_id,rows)
|
||||
window=TrialTaskCenterWindow(service,close_plan_confirmer=lambda:'discard')
|
||||
window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint,True)
|
||||
window.setGeometry(x,y,width,height);window.show();window.raise_();window.activateWindow()
|
||||
window.open_task(tasks[0].task_id)
|
||||
deadline=time.monotonic()+10
|
||||
while time.monotonic()<deadline:
|
||||
settle(.1)
|
||||
if not window._workers and not window._context_query.busy and not window._task_query.busy and not window._feedback_query.busy:break
|
||||
window.mapping_tabs.setCurrentIndex(1);settle(1)
|
||||
assert window.property('acrylicEnabled'),'Native Acrylic not available under current system policy'
|
||||
report['native_enabled']=True
|
||||
def capture(name):
|
||||
settle(.7)
|
||||
QToolTip.hideText();settle(.12)
|
||||
geo=window.geometry();scale=screen.devicePixelRatio()
|
||||
box=tuple(round(v*scale)for v in [geo.x(),geo.y(),geo.right()+1,geo.bottom()+1])
|
||||
def owns_rectangle():
|
||||
for cy in range(box[1]+3,box[3]-3,30):
|
||||
for cx in range(box[0]+3,box[2]-3,30):
|
||||
pid=wintypes.DWORD();user.GetWindowThreadProcessId(user.WindowFromPoint(Point(cx,cy)),ctypes.byref(pid))
|
||||
if pid.value!=os.getpid():return False
|
||||
return True
|
||||
for attempt in range(4):
|
||||
if owns_rectangle():break
|
||||
window.raise_();settle(.5)
|
||||
else:raise AssertionError('Capture occluded by a foreign window; no image saved')
|
||||
image=ImageGrab.grab(bbox=box,all_screens=True).convert('RGB');image.save(out/(name+'.png'));captures[name]=image
|
||||
return geo
|
||||
geometry=capture('native-app-backdrop-a')
|
||||
background.phase=1;background.update();capture('native-app-backdrop-b')
|
||||
scale=screen.devicePixelRatio()
|
||||
def relative_rect(widget):
|
||||
pt=widget.mapTo(window,widget.rect().topLeft());r=widget.rect()
|
||||
return [round(v*scale)for v in [pt.x(),pt.y(),pt.x()+r.width(),pt.y()+r.height()]]
|
||||
sidebar=relative_rect(window.task_list.list)
|
||||
sidebar=[sidebar[0]+8,sidebar[1]+round(190*scale),sidebar[2]-8,sidebar[3]-12]
|
||||
table=relative_rect(window.plan_panel.table.viewport())
|
||||
table=[table[0]+12,max(table[1]+8,table[3]-round(45*scale)),table[2]-20,table[3]-8]
|
||||
header=relative_rect(window.project_summary.path)
|
||||
execution=relative_rect(window.run_panel.execution_status)
|
||||
execution=[(execution[0]+execution[2])//2,execution[1],execution[2]-12,execution[3]]
|
||||
assert sidebar[3]>sidebar[1] and table[3]>table[1]
|
||||
a=captures['native-app-backdrop-a'];b=captures['native-app-backdrop-b']
|
||||
mean=lambda image:sum(ImageStat.Stat(image).mean)/3
|
||||
difference=ImageChops.difference(a,b)
|
||||
report['sidebar_backdrop_difference']=mean(difference.crop(sidebar))
|
||||
report['opaque_table_backdrop_difference']=mean(difference.crop(table))
|
||||
report['right_header_backdrop_difference']=mean(difference.crop(header))
|
||||
report['right_execution_backdrop_difference']=mean(difference.crop(execution))
|
||||
assert report['sidebar_backdrop_difference']>2,report
|
||||
assert report['right_header_backdrop_difference']>2,report
|
||||
assert report['right_execution_backdrop_difference']>2,report
|
||||
assert report['opaque_table_backdrop_difference']<1.5,report
|
||||
window.plan_panel.find_text.setText('RV');window.plan_panel.find()
|
||||
report['visible_search_feedback']=window.plan_panel.find_result.isVisible()
|
||||
assert '2 / 6'in window.plan_panel.find_result.text()
|
||||
capture('native-app-search')
|
||||
window.plan_panel.find_text.setText('NO-MATCH');window.plan_panel.find()
|
||||
report['empty_search_feedback']=window.plan_panel.table.empty_hint.isVisible()
|
||||
assert report['empty_search_feedback']
|
||||
capture('native-app-empty-search')
|
||||
window.plan_panel.clear_find();window.plan_panel.table.clearSelection()
|
||||
window.reduced_transparency_button.setChecked(True);capture('native-app-solid')
|
||||
assert not window.property('acrylicEnabled')
|
||||
solid=captures['native-app-solid']
|
||||
report['solid_sidebar_mean']=ImageStat.Stat(solid.crop(sidebar)).mean
|
||||
assert min(report['solid_sidebar_mean'])>200,report
|
||||
report['solid_fallback']=True
|
||||
window.reduced_transparency_button.setChecked(False);settle(.3)
|
||||
window.resize(980,700);capture('native-app-compact')
|
||||
report['compact_size']=[window.width(),window.height()]
|
||||
report['compact_table_height']=window.plan_panel.table.viewport().height()
|
||||
assert report['compact_size']==[980,700]
|
||||
assert report['compact_table_height']>=100
|
||||
window.project_options_button.setChecked(True);settle(.2)
|
||||
report['options_exposed']=window.run_panel.copy_value_check.isVisible()
|
||||
window.plan_panel.discard_all();window.close();settle(.3);store.close();logging.shutdown()
|
||||
background.close();app.processEvents()
|
||||
(out/'acceptance.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print(json.dumps(report,ensure_ascii=True))
|
||||
if __name__=='__main__':main()
|
||||
@@ -71,8 +71,16 @@ def phase(args):
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
from dx_productivity.trial_task_center.ui.dsh_task_lifecycle import DshLifecycleDialog
|
||||
from dx_productivity.trial_task_center.ui.dsh_operations import DshScheduleDialog
|
||||
from dx_productivity.trial_task_center.ui import dsh_automation
|
||||
from dx_productivity.dsh.run_journal import RunJournal
|
||||
report = {'phase': args.phase, 'executor': 'controlled_no_match', 'realCadStarted': False, 'checks': [], 'dialogs': []}
|
||||
def read_only_publisher(_config_path):
|
||||
def publish(record, _archive):
|
||||
report.setdefault('blockedIssueSubmissions', []).append(record['incident_id'])
|
||||
return {'status': 'unavailable', 'reason': 'acceptance_read_only'}
|
||||
return publish
|
||||
# Keep real ticket GETs, but a failed acceptance must never publish fixtures.
|
||||
dsh_automation.GitIssuePublisher = read_only_publisher
|
||||
state = {'child': None, 'stage': 'opening', 'deadline': time.monotonic() + 180, 'selection': None, 'scheduleDialogs': 0}
|
||||
selection_path = output / 'native-selection.json'
|
||||
if selection_path.is_file():
|
||||
@@ -167,6 +175,9 @@ def phase(args):
|
||||
elif state['stage'] == 'selected' and window._context and not window._loading:
|
||||
QTest.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton); state['stage'] = 'runtime'
|
||||
elif state['stage'] == 'runtime' and window._dsh_view._started:
|
||||
window._dsh_view.lifecycle_requested.connect(lambda value: report.setdefault('nativeRequests', []).append({
|
||||
'request_id': value.get('request_id'), 'capability': value.get('capability'),
|
||||
'operation': value.get('spec', {}).get('operation')}))
|
||||
state['child'] = subprocess.Popen(['node', str(REPO / 'tools/verify_dsh_operations_ui.mjs'), str(output), str(args.port), args.phase],
|
||||
cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
|
||||
|
||||
+4
-1
@@ -43,7 +43,10 @@ export async function connect(port=9226) {
|
||||
rect=await evaluate(`(()=>{const e=${expression};if(!e)throw Error('Missing click target');const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
|
||||
await call('Input.dispatchMouseEvent',{type:'mouseMoved',...rect});
|
||||
await evaluate('new Promise(resolve=>{setTimeout(resolve,150);requestAnimationFrame(()=>requestAnimationFrame(resolve));})');
|
||||
ready=await evaluate(`(()=>{const e=${expression};if(!e)return false;const r=e.getBoundingClientRect(),top=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return r.width>0 && r.height>0 && (e===top || e.contains(top));})()`);
|
||||
// Polling can re-render and move the target after mouseMoved. Dispatch
|
||||
// to the exact coordinates we just hit-tested, not the earlier point.
|
||||
const hit=await evaluate(`(()=>{const e=${expression};if(!e)return null;const r=e.getBoundingClientRect(),x=r.x+r.width/2,y=r.y+r.height/2,top=document.elementFromPoint(x,y);return r.width>0 && r.height>0 && !e.disabled && (e===top || e.contains(top))?{x,y}:null;})()`);
|
||||
ready=!!hit;if(hit)rect=hit;
|
||||
if(ready)break;
|
||||
await new Promise(resolve=>setTimeout(resolve,80));
|
||||
}
|
||||
|
||||
@@ -26,6 +26,26 @@ const element=id=>`document.querySelector('[data-testid="${id}"]')`;
|
||||
async function click(id){await wait(()=>c.evaluate(`!!${element(id)}&&!${element(id)}.disabled`),id);await c.click(element(id));}
|
||||
async function tab(id){await click('dx-operations-tab-'+id);}
|
||||
async function idle(){await wait(()=>c.evaluate(`![...document.querySelectorAll('button[aria-label="停止生成"]')].some(e=>e.getBoundingClientRect().width>0)`),'generation idle');}
|
||||
async function pauseLiveRun(){
|
||||
const original=(await context()).operations.live_run;
|
||||
report.pauseClicks=[];
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
const live=(await context()).operations.live_run;
|
||||
assert.equal(live.run_id,original.run_id,'pause may not retarget a different execution');
|
||||
assert.equal(live.active,true,'the original execution must still be active');
|
||||
await tab('running');await click('dx-running-pause');
|
||||
try{
|
||||
await wait(async()=>{const ops=(await context()).operations;return (ops.live_run?.run_id===original.run_id&&ops.live_run.pause_requested)||
|
||||
(ops.last_execution?.run_id===original.run_id&&ops.last_execution.status==='paused');},'safe pause admission',5000);
|
||||
report.pauseClicks.push({attempt:attempt+1,accepted:true});return;
|
||||
}catch(error){
|
||||
if(!error.message.startsWith('Timed out:'))throw error;
|
||||
const notice=await c.evaluate(`document.querySelector('[data-testid="dx-operations-notice"]')?.textContent||''`);
|
||||
report.pauseClicks.push({attempt:attempt+1,accepted:false,notice});
|
||||
}
|
||||
}
|
||||
throw Error('Actual pause clicks were not admitted: '+JSON.stringify(report.pauseClicks));
|
||||
}
|
||||
async function send(prompt){
|
||||
report.prompts.push(prompt);
|
||||
for(let i=0;i<5;i++){
|
||||
@@ -94,7 +114,7 @@ try{
|
||||
await select('Board-A');
|
||||
await send('现在执行 Board-A 任务,只运行这一个工程,按原生确认的范围处理。结束后告诉我真实保存、失败和未命中数量。');
|
||||
await wait(async()=>(await context()).operations?.live_run?.active===true,'live controlled run');
|
||||
await tab('running');await click('dx-running-pause');
|
||||
await pauseLiveRun();
|
||||
await wait(async()=>{const d=await context();return d.operations?.last_execution?.status==='paused'&&!d.operations?.live_run?.active;},'safe pause receipt');
|
||||
const receipt=(await context()).operations.last_execution;assert.equal(receipt.tasks[0].no_match_items,1);assert.equal(receipt.tasks[0].saved_items,0);
|
||||
report.runId=receipt.run_id;await idle();await c.screenshot(path.join(output,'paused-before-restart.png'));
|
||||
@@ -103,7 +123,20 @@ try{
|
||||
const prior=JSON.parse(await readFile(path.join(output,'paused-run.json'),'utf8'));
|
||||
await tab('running');await click('dx-history-refresh');
|
||||
await wait(async()=>{const d=await context();return d.operations?.activity?.status==='read'&&!d.operations?.busy;},'history read settled');
|
||||
await click('dx-resume-'+prior.run_id);
|
||||
report.resumeClicks=[];
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
await click('dx-resume-'+prior.run_id);
|
||||
try{
|
||||
await wait(async()=>{const d=await context();return (d.lifecycle?.request_id&&['awaiting_confirmation','executing','completed'].includes(d.lifecycle.status))||
|
||||
d.operations?.last_execution?.run_id===prior.run_id;},'original queue resume admission',4000);
|
||||
report.resumeClicks.push({attempt:attempt+1,accepted:true});break;
|
||||
}catch(error){
|
||||
if(!error.message.startsWith('Timed out:'))throw error;
|
||||
const notice=await c.evaluate(`document.querySelector('[data-testid="dx-operations-notice"]')?.textContent||''`);
|
||||
report.resumeClicks.push({attempt:attempt+1,accepted:false,notice});
|
||||
if(attempt===2)throw Error('Actual resume clicks were not admitted: '+JSON.stringify(report.resumeClicks));
|
||||
}
|
||||
}
|
||||
await wait(async()=>(await context()).operations?.last_execution?.status==='completed','restarted original queue completed');
|
||||
const result=(await context()).operations.last_execution;assert.equal(result.run_id,prior.run_id);assert.equal(result.queue_id,prior.queue_id);assert.equal(result.tasks[0].no_match_items,2);
|
||||
report.checks.push('second actual application process resumed original frozen queue and skipped completed item');
|
||||
|
||||
Reference in new issue
Block a user