Files
dxdesigner-part-replacement/tools/accept_dsh_desktop.py
T

235 lines
15 KiB
Python

"""Click the real task-center navigation, then test its embedded official page."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import hashlib
import traceback
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
def copy_provider_configuration(source: Path, destination: Path):
"""Copy one validated snapshot, including versioned or legacy DPAPI keys."""
from dx_productivity.dsh.provider_config import load_provider, save_provider
values = load_provider(source)
if not values:
raise ValueError('provider_configuration_missing')
save_provider(destination, base_url=values['DSH_API_BASE'],
models=json.loads(values['DX_DSH_MODELS']), default_model=values['DSH_MODEL'],
api_key=values['DSH_API_KEY'])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=REPO / 'build/dsh-native-desktop-verification')
parser.add_argument('--port', type=int, default=9227)
parser.add_argument('--provider-config', type=Path)
parser.add_argument('--live-model', action='store_true')
parser.add_argument('--incident', action='store_true', help='Inject a read-only controlled failure and verify automatic diagnosis and Git escalation')
parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue')
parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable')
parser.add_argument('--create-task', action='store_true', help='Create real project tasks from a live native model conversation')
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
data = output / ('data-' + time.strftime('%Y%m%d-%H%M%S'))
project_root = output / 'source-projects'
source_hashes = {}
if args.create_task:
for name in ('Board-A', 'Board-B'):
path = project_root / name / 'board.prj'
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf8')
source_hashes[str(path)] = hashlib.sha256(path.read_bytes()).hexdigest()
if args.provider_config:
copy_provider_configuration(args.provider_config, data / 'dsh')
if args.incident:
(data / 'dsh').mkdir(parents=True, exist_ok=True)
(data / 'dsh/issue-config.json').write_text(json.dumps({'enabled': not args.outbox_only, 'acceptance': True}), encoding='utf8')
if args.without_git:
original_run = subprocess.run
def no_git_run(command, *positional, **keywords):
if isinstance(command, (list, tuple)) and Path(str(command[0])).stem.casefold() == 'git':
raise FileNotFoundError('Git is not installed in this acceptance client')
return original_run(command, *positional, **keywords)
subprocess.run = no_git_run
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = f'127.0.0.1:{args.port}'
os.environ.pop('QT_QPA_PLATFORM', None)
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QMessageBox, QDialogButtonBox
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
from dx_productivity.trial_task_center.ui.dsh_task_creation import DshTaskCreationDialog
report = {'driver': 'Qt QTest mouse clicks + Chromium CDP Input events', 'checks': []}
state = {'phase': 'select', 'child': None, 'creation_step': 'input',
'deadline': time.monotonic() + (420 if args.incident else 300 if args.create_task else 240 if args.live_model else 150)}
def build_window(service):
if not args.create_task:
service.create_task('DSH接入验收任务')
window = TrialTaskCenterWindow(service)
window.resize(1380, 860)
def click_navigation(action):
window.activateWindow()
button = window.dsh_navigation if action is window.dsh_action else window.task_center_navigation
assert button.isVisible() and button.defaultAction() is action
assert window.task_center_navigation.geometry().right() < window.dsh_navigation.geometry().left()
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
QApplication.processEvents()
assert button.isChecked()
def failed(error):
report.update(status='failed', error=type(error).__name__ + ': ' + str(error))
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
child = state['child']
if child and child.poll() is None:
child.terminate()
timer.stop()
window.close()
def tick():
try:
if time.monotonic() > state['deadline']:
raise TimeoutError('Native desktop acceptance timed out')
modal = QApplication.activeModalWidget()
if args.create_task and isinstance(modal, DshTaskCreationDialog):
if state['creation_step'] == 'input':
assert modal.name_edit.text() == 'DSH对话换料验收'
assert modal.spec['rules'][0]['old_part_number'] == 'OLD123'
assert modal.spec['rules'][0]['new_part_number'] == 'NEW456'
QTest.keyClicks(modal.directory, str(project_root))
QTest.mouseClick(modal.scan, Qt.MouseButton.LeftButton)
report['checks'].append('typed source directory and clicked native project scan for model-authored draft')
state['creation_step'] = 'reading'
elif state['creation_step'] == 'reading' and modal._worker is None and modal.projects.count() == 2:
QTest.mouseClick(modal.buttons.button(QDialogButtonBox.StandardButton.Ok), Qt.MouseButton.LeftButton)
report['checks'].append('clicked native confirm to create both selected project tasks')
state['creation_step'] = 'confirmed'
if isinstance(modal, QMessageBox) and modal.windowTitle().startswith('DSH助手'):
button = modal.button(QMessageBox.StandardButton.No)
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
report['checks'].append('clicked No in the actual Qt confirmation dialog')
if state['phase'] == 'select' and args.create_task and not window._task_query.busy:
assert window.task_list.list.count() == 0
click_navigation(window.dsh_action)
state['phase'] = 'ready'
report['checks'].append('opened native assistant from an empty task center')
elif 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'] = 'menu'
elif state['phase'] == 'menu' and window._context is not None and not window._loading:
window.grab().save(str(output / 'task-center.png'))
if args.incident:
from dx_productivity.trial_task_center.errors import TaskCenterError
window._show_error(TaskCenterError('dsh_acceptance_failure',
'DSH 自动介入受控验收:模拟不可重试错误,任务没有工程数据,不执行 CAD 写入。'))
report['checks'].append('injected controlled failure in real error entry without opening assistant manually')
else:
click_navigation(window.dsh_action)
assert window.content_stack.currentWidget() is window._dsh_view
report['checks'].append('clicked task row and opened DSH with one click on the right navigation item')
state['phase'] = 'ready'
elif state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view._started:
script = 'verify_dsh_task_creation_ui.mjs' if args.create_task else 'verify_dsh_incident_ui.mjs' if args.incident else 'verify_dsh_native_ui.mjs'
command = ['node', str(REPO / 'tools' / script), str(output), str(args.port), '--confirm-cancel']
if args.live_model:
command.append('--live-model')
if args.outbox_only:
command.append('--outbox-only')
state['child'] = subprocess.Popen(command, cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
state['phase'] = 'web'
elif state['phase'] == 'web' and state['child'].poll() is not None:
stdout, stderr = state['child'].communicate()
if state['child'].returncode:
raise RuntimeError(stderr.decode('utf8', 'replace'))
report['web'] = json.loads((output / 'report.json').read_text(encoding='utf8'))
click_navigation(window.task_center_action)
assert window.content_stack.currentIndex() == 0
click_navigation(window.dsh_action)
assert window.content_stack.currentWidget() is window._dsh_view
report['checks'].append('clicked left navigation for task center and right navigation for the same native page')
state['phase'] = 'check-preserved'
def validate_preserved(text):
if '请分析当前任务' not in (text or ''):
failed(AssertionError('Composer draft was lost when switching navigation items'))
return
report['checks'].append('native composer draft survived direct navigation')
if args.incident:
row = window._dsh_automation.latest
assert row['issue_code'] == 'dsh_acceptance_failure', 'Unexpected UI error replaced controlled incident'
assert row['status'] == ('pending_issue' if args.outbox_only else 'escalated') and row['attempts'] == 0
if not args.outbox_only:
assert row['ticket']['attachment_status'] == 'uploaded'
if args.without_git:
assert row['ticket']['credential_source'] == 'prefilled_issue_token'
report['checks'].append('client without Git used only the prefilled issue reporter token')
report['incident'] = row
report['checks'].append('real native automatic diagnosis and reflection, evidence and ' +
('retryable local issue outbox' if args.outbox_only else 'Git issue attachment') + ' completed without CAD mutations')
if args.create_task:
tasks = service._store.list_tasks()
assert len(tasks) == 2 and window.task_list.list.count() == 2
assert all(task.primary_project_id and task.status.value == 'draft' and task.copy_part_number_to_value for task in tasks)
assert all([(r.old_part_number, r.new_part_number) for r in service._store.list_rules(task.task_id)] == [('OLD123', 'NEW456')] for task in tasks)
assert all(hashlib.sha256(Path(path).read_bytes()).hexdigest() == digest for path, digest in source_hashes.items())
assert not list(data.rglob('command.tsv'))
report['createdTasks'] = [{'task_id': t.task_id, 'name': t.name} for t in tasks]
report['sourceProjectHashesUnchanged'] = True
report['checks'].append('real SQLite tasks, names, rules, Value policy and project bindings verified with unchanged source files')
window.grab().save(str(output / 'dsh-in-tool.png'))
report['status'] = 'passed'
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
timer.stop()
window.close()
def preserved(text):
try:
validate_preserved(text)
except Exception as error:
report['callbackTraceback'] = traceback.format_exc()
failed(error)
window._dsh_view.web.page().runJavaScript("document.querySelector('[contenteditable=true]')?.textContent", preserved)
except Exception as error:
failed(error)
timer = QTimer(window)
timer.setInterval(150)
timer.timeout.connect(tick)
timer.start()
return window
application._load_window = lambda: build_window
code = application.main(['--data-root', str(data)])
if code or report.get('status') != 'passed':
print(json.dumps(report, ensure_ascii=False))
return 1
log = (data / 'logs/application.log').read_text(encoding='utf8')
report['cleanShutdown'] = 'application_clean_shutdown exit_code=0' in log
report['uncaughtErrors'] = 'uncaught_main_thread' in log
report['unexpectedUiErrors'] = 'operation=ui message=' in log
if args.live_model or args.incident or args.create_task:
audit_file = data / 'dsh/harness-home/task-tool-audit.jsonl'
audit = [json.loads(line) for line in audit_file.read_text(encoding='utf8').splitlines()] if audit_file.is_file() else []
report['modelToolCalls'] = audit
expected_tool = 'dx_task_create' if args.create_task else 'dx_task_snapshot'
report['modelToolSucceeded'] = any(row['name'] == expected_tool and row['is_error'] is False for row in audit)
(output / 'desktop-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
print(json.dumps(report, ensure_ascii=True))
return 0 if report['cleanShutdown'] and not report['uncaughtErrors'] and not report['unexpectedUiErrors'] and (not (args.live_model or args.incident or args.create_task) or report['modelToolSucceeded']) else 1
if __name__ == '__main__':
raise SystemExit(main())