feat(dsh): intervene on blocking states and verify resource recovery
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 2s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 2s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
1 parent
389fc917b9
commit
de9cb2908d
21 files changed
+1557
-46
No files matched your search
@@ -0,0 +1,249 @@
|
||||
"""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
|
||||
from types import SimpleNamespace
|
||||
|
||||
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.bom_import_report import inspect_batch
|
||||
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')
|
||||
|
||||
def inspect(task_id, path, **options):
|
||||
state['parser_calls'] += 1
|
||||
return inspect_batch(service, task_id, path,
|
||||
runtime=SimpleNamespace(bind_logs=lambda *args: None), **options)
|
||||
|
||||
service.pending_batch_resources = resources
|
||||
service.cleanup_batch_resources = cleanup
|
||||
service.inspect_bom_batch = 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
|
||||
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_validation_failed')
|
||||
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())
|
||||
Reference in new issue
Block a user