Files
dxdesigner-part-replacement/tools/accept_dsh_blockers.py
阿白叔 cf6e3f9d2a
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
feat(dsh): show AI readiness and prevent repeated intervention on status changes
2026-11-05 16:09:41 +08:00

252 lines
13 KiB
Python

"""Real desktop/model acceptance for BOM validation and resource intervention."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
import time
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--provider-config', type=Path, required=True)
parser.add_argument('--output', type=Path, default=REPO / 'build/dsh-blocker-desktop-acceptance')
parser.add_argument('--port', type=int, default=9238)
args = parser.parse_args()
output = args.output.resolve() / time.strftime('%Y%m%d-%H%M%S')
output.mkdir(parents=True)
data = output / 'data'
from accept_dsh_desktop import copy_provider_configuration
copy_provider_configuration(args.provider_config, data / 'dsh')
(data / 'dsh/issue-config.json').write_text(json.dumps({'enabled': False, 'acceptance': True}), encoding='utf8')
project = output / 'fixtures/Board-A/board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf8')
project_hash = hashlib.sha256(project.read_bytes()).hexdigest()
workbook_path = output / 'fixtures/invalid-bom.xlsx'
from openpyxl import Workbook
workbook = Workbook()
workbook.active.append(['invalid_required_headers'])
workbook.active.append(['controlled invalid BOM row'])
workbook.save(workbook_path)
workbook.close()
os.environ.pop('QT_QPA_PLATFORM', None)
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = f'127.0.0.1:{args.port}'
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QFileDialog, QDialogButtonBox, QLineEdit
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs)
from dx_productivity.dsh import health
# This isolated acceptance never reads machine issue-reporting credentials.
health.load_bootstrap = lambda: None
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
report = {'status': 'running', 'driver': 'real QApplication/QTest and native live model',
'output': str(output), 'checks': [], 'incidents': []}
state = {'phase': 'select', 'deadline': time.monotonic() + 540,
'resources_pending': False, 'cleanup_calls': 0, 'empty_reads_after_cleanup': 0,
'cad_reads': 0, 'parser_calls': 0, 'completed': {}}
resource = {'state': 'blocked', 'outcome': 'completed_resources_pending',
'resource_id': 'owned-acceptance-fixture', 'backend': 'controlled-memory-fixture',
'message': 'Owned acceptance resource requires resource-only cleanup; no CAD handle or OS process exists.'}
def save_report():
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
def build_window(service):
def resources():
if state['resources_pending']:
return (dict(resource),)
if state['cleanup_calls']:
state['empty_reads_after_cleanup'] += 1
return ()
def cleanup():
state['cleanup_calls'] += 1
state['resources_pending'] = False
# Deliberately stale return: resolution must come from an independent read.
return (dict(resource),)
def no_cad(*args, **kwargs):
state['cad_reads'] += 1
raise AssertionError('Unexpected CAD access in desktop acceptance')
preview_sources = service.preview_bom_sources
def inspect(task_id, paths, **options):
state['parser_calls'] += 1
return preview_sources(task_id, paths, **options)
service.pending_batch_resources = resources
service.cleanup_batch_resources = cleanup
service.preview_bom_sources = inspect
service.collect_target_inventory = no_cad
service.collect_target_inventory_for_bom = no_cad
tasks = service.create_project_tasks(project.parent.parent)
window = TrialTaskCenterWindow(service, close_plan_confirmer=lambda: 'discard')
window.resize(1380, 900)
window.archive_on_close_check.setChecked(False)
def capture(name):
window.grab().save(str(output / name))
def finish(error=None):
if state['phase'] == 'closing':
return
state['phase'] = 'closing'
report.update(status='failed' if error else 'passed',
cleanupCalls=state['cleanup_calls'], emptyReadsAfterCleanup=state['empty_reads_after_cleanup'],
parserCalls=state['parser_calls'], cadReads=state['cad_reads'],
projectUnchanged=hashlib.sha256(project.read_bytes()).hexdigest() == project_hash)
if error:
report['error'] = type(error).__name__ + ': ' + str(error)
capture('failure.png')
automation = window._dsh_automation
if automation:
automation._runtime_stopped()
if window._dsh_view:
window._dsh_view.shutdown()
save_report()
window.close()
def pick_bom():
try:
modal = QApplication.activeModalWidget()
if not isinstance(modal, QFileDialog):
raise AssertionError('Actual Qt BOM file dialog did not open')
edit = modal.findChild(QLineEdit, 'fileNameEdit')
assert edit is not None
edit.setFocus()
QTest.keyClicks(edit, str(workbook_path))
buttons = modal.findChild(QDialogButtonBox)
assert buttons is not None
QTest.mouseClick(buttons.button(QDialogButtonBox.StandardButton.Open), Qt.MouseButton.LeftButton)
report['checks'].append('clicked Import BOM and selected the owned invalid XLSX in the actual Qt file dialog')
state['phase'] = 'bom'
save_report()
except Exception as error:
finish(error)
def completed_incident(code):
if code in state['completed']:
return state['completed'][code]
automation = window._dsh_automation
if not automation or automation.worker is not None:
return None
row = automation.latest
if row.get('issue_code') != code or row.get('status') not in {'resolved', 'pending_issue', 'escalated'}:
return None
evidence = Path(row['evidence_dir'])
persisted = json.loads((evidence / 'incident.json').read_text(encoding='utf8'))
assert any(evidence.glob('*.zip')), 'Incident evidence archive missing'
analyses = persisted.get('analyses', [])
assert analyses and all('reply' in entry for entry in analyses), 'Live model analysis failed'
assert all(entry.get('session_id') for entry in analyses), 'Native model session missing'
record = {'issue_code': code, 'incident_id': row['incident_id'], 'status': row['status'],
'sessions': [entry['session_id'] for entry in analyses],
'phases': [entry['phase'] for entry in analyses], 'evidence_dir': str(evidence),
'attempts': row.get('attempts'), 'action': persisted.get('action', 'none'),
'verification': persisted.get('verification', {})}
report['incidents'].append(record)
state['completed'][code] = record
return record
def stage_rendered(label):
if state.get('rendered_stage') == label:
return True
if state.get('checking_stage'):
return False
state['checking_stage'] = True
def observed(text):
state['checking_stage'] = False
if text == label:
state['rendered_stage'] = label
window._dsh_view.web.page().runJavaScript(
"document.querySelector('[data-testid=dx-auto-status]')?.textContent", observed)
return False
def tick():
try:
if state['phase'] == 'closing':
window.close()
return
codes = [json.loads(path.read_text(encoding='utf8')).get('issue_code')
for path in (data / 'dsh/incidents').glob('*/incident.json')]
if any(codes.count(code) > 1 for code in {'bom_import', 'batch_resources_pending'}):
raise AssertionError('Duplicate automatic incident detected; live acceptance stopped')
if time.monotonic() > state['deadline']:
raise TimeoutError('Desktop blocker acceptance exceeded nine minutes')
if state['phase'] == 'select' and window.task_list.list.count() and not window._task_query.busy:
item = window.task_list.list.item(0)
QTest.mouseClick(window.task_list.list.viewport(), Qt.MouseButton.LeftButton,
pos=window.task_list.list.visualItemRect(item).center())
state['phase'] = 'import'
elif state['phase'] == 'import' and window._context and not window._loading and not window._workers:
assert window._context.task.task_id == tasks[0].task_id
assert window._dsh_view is None, 'Assistant was opened before the blocker'
tabs = window.mapping_tabs.tabBar()
QTest.mouseClick(tabs, Qt.MouseButton.LeftButton, pos=tabs.tabRect(1).center())
assert window.plan_panel.import_bom_button.isVisible()
assert window.plan_panel.import_bom_button.isEnabled()
capture('task-before-bom.png')
state['phase'] = 'picker'
QTimer.singleShot(350, pick_bom)
QTest.mouseClick(window.plan_panel.import_bom_button, Qt.MouseButton.LeftButton)
elif state['phase'] == 'bom':
row = completed_incident('bom_import')
if row and stage_rendered('证据已保存,工单待完整提交'):
assert row['phases'] == ['diagnose', 'reflect'], row
assert row['status'] == 'pending_issue' and row['attempts'] == 0
assert state['parser_calls'] == 1 and state['cad_reads'] == 0
capture('bom-native-diagnosis.png')
report['checks'].append('BOM parser failure automatically opened a native session with real model diagnosis, reflection and local evidence; remote issue submission disabled')
state['resources_pending'] = True
state['phase'] = 'resource'
# Trigger the actual poll path; no error callback is injected.
window._resource_status._poll()
save_report()
elif state['phase'] == 'resource':
row = completed_incident('batch_resources_pending')
if row and stage_rendered('处理结果已通过核验'):
assert row['status'] == 'resolved', row
assert row['action'] == 'cleanup_resources', row
assert row['verification'].get('resources_released') is True
assert state['cleanup_calls'] == 1 and state['empty_reads_after_cleanup'] >= 1
assert set(row['sessions']).isdisjoint(report['incidents'][0]['sessions'])
assert not list(data.rglob('command.tsv'))
capture('resource-cleanup-resolved.png')
report['checks'].append('real model requested resource-only cleanup; independently reread empty resources and resolved in a distinct native session')
finish()
except Exception as error:
finish(error)
timer = QTimer(window)
timer.setInterval(200)
timer.timeout.connect(tick)
timer.start()
return window
application._load_window = lambda: build_window
code = application.main(['--data-root', str(data)])
log_path = data / 'logs/application.log'
log = log_path.read_text(encoding='utf8') if log_path.is_file() else ''
report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in log
report['uncaughtErrors'] = 'uncaught_main_thread' in log
if code or report['status'] != 'passed' or not report['cleanShutdown'] or report['uncaughtErrors']:
report['status'] = 'failed'
save_report()
print(json.dumps(report, ensure_ascii=True))
return 0 if report['status'] == 'passed' else 1
if __name__ == '__main__':
raise SystemExit(main())