"""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('--model-settings-check', action='store_true', help='Create an isolated custom provider using a local model-list fixture') parser.add_argument('--file-check', action='store_true', help='Pick and upload a real local text file and ZIP in the official UI') 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) if args.file_check: import zipfile fixtures = output / 'file-fixtures' fixtures.mkdir(exist_ok=True) (fixtures / 'dsh-upload.txt').write_text('DSH_UPLOAD_CONTENT_中文\n', encoding='utf8') with zipfile.ZipFile(fixtures / 'dsh-upload.zip', 'w', zipfile.ZIP_DEFLATED) as archive: archive.writestr('中文目录/说明.txt', 'DSH_ZIP_UPLOAD_CONTENT_中文') 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, QFileDialog, QLineEdit if args.file_check: QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs) 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() + (600 if args.file_check else 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)) if window._dsh_view is not None: report['runtimeStatus'] = window._dsh_view.status.text() (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') if state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view.retry.isVisible(): from dx_productivity.dsh.provider_config import load_provider key = load_provider(data / 'dsh').get('DSH_API_KEY', '') diagnostic = window._dsh_view.last_error if key: diagnostic = diagnostic.replace(key, '[redacted]') report['startupDiagnostic'] = diagnostic[-8000:] raise RuntimeError(window._dsh_view.status.text()) modal = QApplication.activeModalWidget() if state['phase'] == 'ready' and window._dsh_view is not None and not report.get('officialLoadingPassed') and not state.get('checkingLoading'): state['checkingLoading'] = True def loading_ready(value): state['checkingLoading'] = False if value and not report.get('officialLoadingPassed'): assert not window._dsh_view.status.isVisible() report['officialLoadingPassed'] = True state['loadingCapture'] = subprocess.Popen(['node', str(REPO / 'tools/dsh_cdp.mjs'), '--capture-loading', str(args.port), str(output / 'official-loading.png')], cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0) report['checks'].append('unmodified official frontend HARNESS loading spinner rendered before local runtime readiness') window._dsh_view.web.page().runJavaScript("!!document.querySelector('[data-dsh-boot] [data-dsh-boot-spinner]')", loading_ready) if args.file_check and isinstance(modal, QFileDialog) and not modal.property('dshAcceptancePicked'): modal.setProperty('dshAcceptancePicked', True) selected = (output / 'file-picker-request.json') assert selected.is_file(), 'Unexpected file picker' files = json.loads(selected.read_text(encoding='utf8')) edit = modal.findChild(QLineEdit, 'fileNameEdit') assert edit is not None QApplication.clipboard().setText(' '.join('"' + str(Path(f).resolve()) + '"' for f in files)) edit.setFocus() QTest.keyClick(edit, Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier) QTest.keyClick(edit, Qt.Key.Key_V, Qt.KeyboardModifier.ControlModifier) buttons = modal.findChild(QDialogButtonBox) assert buttons is not None QTest.mouseClick(buttons.button(QDialogButtonBox.StandardButton.Open), Qt.MouseButton.LeftButton) report['checks'].append('selected owned text and ZIP fixtures in the real Qt file picker and clicked Open') 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' state['runtimeWaitStarted'] = time.monotonic() 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' state['runtimeWaitStarted'] = time.monotonic() elif state['phase'] == 'ready' and window._dsh_view is not None and window._dsh_view._started: if 'runtimeWaitStarted' in state: report['runtimeWaitSeconds'] = round(time.monotonic() - state['runtimeWaitStarted'], 2) 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.model_settings_check: command.append('--model-settings-check') if args.file_check: command.append('--file-check') 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)]) capture = state.get('loadingCapture') if capture is not None: try: capture.communicate(timeout=5) except subprocess.TimeoutExpired: capture.terminate() capture.communicate(timeout=5) report['officialLoadingScreenshot'] = capture.returncode == 0 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_tools = ['read', 'extract_zip'] if args.file_check else ['dx_task_create' if args.create_task else 'dx_task_snapshot'] report['modelToolSucceeded'] = all(any(row['name'] == name and row['is_error'] is False for row in audit) for name in expected_tools) (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())