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

145 lines
7.6 KiB
Python

"""Click the real task-center menus, 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 shutil
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'src'))
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')
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'))
if args.provider_config:
(data / 'dsh').mkdir(parents=True, exist_ok=True)
for name in ('provider.json', 'provider-key.dpapi'):
shutil.copy2(args.provider_config / name, data / 'dsh' / name)
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
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
report = {'driver': 'Qt QTest mouse clicks + Chromium CDP Input events', 'checks': []}
state = {'phase': 'select', 'child': None, 'deadline': time.monotonic() + (240 if args.live_model else 150)}
def build_window(service):
service.create_task('DSH接入验收任务')
window = TrialTaskCenterWindow(service)
window.resize(1380, 860)
def click_menu(action):
window.activateWindow()
bar = window.menuBar()
top = bar.actions()[0]
menu = top.menu()
QTest.mouseClick(bar, Qt.MouseButton.LeftButton, pos=bar.actionGeometry(top).center())
QApplication.processEvents()
if not menu.isVisible():
raise AssertionError('The tool menu did not open after mouse click')
QTest.mouseClick(menu, Qt.MouseButton.LeftButton, pos=menu.actionGeometry(action).center())
QApplication.processEvents()
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 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 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:
click_menu(window.dsh_action)
assert window.content_stack.currentWidget() is window._dsh_view
report['checks'].append('clicked task row and Tools > DSH assistant in the real main window')
state['phase'] = 'ready'
elif state['phase'] == 'ready' and window._dsh_view._started:
command = ['node', str(REPO / 'tools/verify_dsh_native_ui.mjs'), str(output), str(args.port), '--confirm-cancel']
if args.live_model:
command.append('--live-model')
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_menu(window.task_center_action)
assert window.content_stack.currentIndex() == 0
click_menu(window.dsh_action)
assert window.content_stack.currentWidget() is window._dsh_view
report['checks'].append('clicked back to task center and returned to the same native page')
state['phase'] = 'check-preserved'
def preserved(text):
if '请分析当前任务' not in (text or ''):
failed(AssertionError('Composer draft was lost when switching tool menus'))
return
report['checks'].append('native composer draft survived tool-menu navigation')
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()
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
if args.live_model:
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
report['modelToolSucceeded'] = any(row['name'] == 'dx_task_snapshot' 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 args.live_model or report['modelToolSucceeded']) else 1
if __name__ == '__main__':
raise SystemExit(main())