"""Operate an extracted candidate through Windows UI, preserving real evidence. Workbook edits are test fixtures based on the application's exported template. No application Python modules, simulated workers or invented log events are used. """ from __future__ import annotations import argparse import ctypes from ctypes import wintypes import json from pathlib import Path import sqlite3 import time import traceback from openpyxl import load_workbook import win32con import win32api import win32gui from packaged_window_driver import WindowDriver from private_desktop_observer import PrivateDesktopObserver def wait(check, *, timeout=900): deadline, last = time.monotonic() + timeout, None while time.monotonic() < deadline: try: value = check() except LookupError: value = None # Qt can replace its accessible children during refresh. if value: return value if int(time.monotonic()) // 30 != last: last = int(time.monotonic()) // 30 print('Waiting for UI operation; evidence remains on disk.', flush=True) time.sleep(.3) raise TimeoutError('Candidate UI operation did not complete') def database(root, sql): with sqlite3.connect((root / 'data/task-center.db').as_uri() + '?mode=ro', uri=True) as db: db.row_factory = sqlite3.Row return [dict(row) for row in db.execute(sql)] def verify_identity(root, session): import hashlib executable = (root / 'extracted/DxPartReplace/DxPartReplace.exe').resolve(strict=True) assert Path(session['executable']).resolve(strict=True) == executable process = win32api.OpenProcess(0x1000, False, session['pid']) try: query = ctypes.windll.kernel32.QueryFullProcessImageNameW query.argtypes = (wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)) query.restype = wintypes.BOOL buffer, size = ctypes.create_unicode_buffer(32768), wintypes.DWORD(32768) assert query(int(process), 0, buffer, ctypes.byref(size)) assert Path(buffer.value).resolve(strict=True) == executable finally: process.Close() manifest = json.loads((root / 'candidate-manifest.json').read_text(encoding='utf-8')) assert hashlib.sha256(executable.read_bytes()).hexdigest() == manifest['exe_sha256'] def verify_disposable_projects(root): inputs = json.loads((root / 'inputs.json').read_text(encoding='utf-8')) expected = {Path(p).resolve(strict=True) for p in inputs['projects']} originals = {Path(p).resolve(strict=True) for p in inputs['sources']} assert len(expected) == 2 assert all(p.is_relative_to(root / 'projects') and p not in originals for p in expected) projects = database(root, 'select path from projects') if projects: assert {Path(p['path']).resolve(strict=True) for p in projects} == expected for row in database(root, 'select * from target_plan'): assert Path(row['project_path']).resolve(strict=True) in expected assert row['old_part_number'] == '4100-CA0000-T7' assert bool(row['enabled']) == (row['refdes'] == 'RV05') if row['enabled']: assert row['new_part_number'] == '4100-CA0000-T0' else: assert row['refdes'] == 'RV11' and row['old_value'] == '0R' def verify_observation(path, *, require_sessions=True): observation = json.loads(path.read_text(encoding='utf-8')) assert not observation['observer_errors'], observation['observer_errors'] if require_sessions: assert observation['sessions'] assert all(observation['cad_exit_confirmed'].values()) assert all(observation['desktop_absent'].values()) assert not observation['owned_cad_became_foreground'] assert not observation['owned_cad_on_input_desktop'] assert observation['input_desktop_before'] == observation['input_desktop_after'] assert observation['file_read_samples'] == observation['samples'] def verify_bom_resources(root): path = root / 'desktop-observation-bom.json' verify_observation(path, require_sessions=False) observation = json.loads(path.read_text(encoding='utf-8')) paths = list((root / 'data/tasks').glob('*/quick-run-history/native-inventory-*/native-inventory.json')) records = [json.loads(path.read_text(encoding='utf-8')) for path in paths] batches = [json.loads(path.read_text(encoding='utf-8')) for path in (root / 'data/batch-resources').glob('*/session.json')] ready = [row for row in records if row['state'] == 'ready'] for path, row in zip(paths, records): assert row['state'] in {'ready', 'fallback'} and not row.get('cleanup_error') assert row['backend'] == 'native_cli' if row['state'] == 'ready': assert row['source_hashes_unchanged'] assert not Path(row['workspace']).exists() cleanup = row['cleanup'] if cleanup.get('scope') == 'operation': assert cleanup['workers_closed'] and cleanup['desktop_retained_by_batch'] owners = [(batch, operation) for batch in batches for evidence, operation in batch.get('native_operations', {}).items() if Path(evidence).resolve() == path.parent.resolve()] assert len(owners) == 1, 'Native operation must have exactly one batch owner' batch, operation = owners[0] assert batch['state'] == 'released' and operation['workers_closed'] assert operation['binding']['session_id'] == batch['session_id'] assert operation['binding']['generation'] == batch['generation'] assert operation['binding']['attempt_id'] final = batch['cleanup'] assert final['desktop_handle_closed'] and final['desktop_confirmation']['released'] assert not final['errors'] else: assert cleanup['desktop_handle_closed'] and cleanup['desktop_confirmation']['released'] assert not cleanup['errors'] if row['state'] == 'ready': assert cleanup['processes'] for process in cleanup['processes']: assert process['job_active_processes'] == 0 and process['exit_code'] == 0 assert process['process_handle_closed'] and process['job_handle_closed'] assert not process['unconfirmed_descendant_handles'] and not process['errors'] if not observation['sessions']: expected = {Path(p).resolve() for p in json.loads((root/'inputs.json').read_text(encoding='utf-8'))['projects']} assert {Path(row['project']).resolve() for row in ready} == expected return {'cad_sessions': len(observation['sessions']), 'ready_native_cli_reads': len(ready)} def verify_bom(driver, root, report): """Read-only continuation after BOM assertions passed but old CAD-only verifier failed.""" assert report['template_columns'] == 11 and report['search_preserves_tasks'] assert len(report['imports']) == 2 assert '通过 2 / 失败 1 / 未检查 0' in report['imports'][0]['title'] assert '通过 2 / 失败 0 / 未检查 0' in report['imports'][1]['title'] assert report['saved_targets'] == database(root, 'select * from target_plan') assert len(report['saved_targets']) == 4 and sum(row['enabled'] for row in report['saved_targets']) == 2 report['bom_resources'] = verify_bom_resources(root) report['bom_passed'] = True report['bom_verifier_continuation'] = 'Native CLI inventory needs no CAD; validated existing CLI Job/desktop cleanup, without repeating import.' def verified_events(root): records = [] for task in database(root, 'select task_id from tasks'): path = root / 'data/tasks' / task['task_id'] / 'events.jsonl' events = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] saved = [e for e in events if e['operation'] == 'quick_run_executed' and e.get('details', {}).get('state') == 'saved_ok'] assert len(saved) == 1, f'Expected one genuinely saved step: {task}' assert 'RV05 4100-CA0000-T7 -> 4100-CA0000-T0' in saved[0]['message'] records.append(dict(task_id=task['task_id'], event=saved[0])) return records def file_dialog(driver, path, *, save=False): dialog = wait(lambda: next((w for w in driver.windows() if win32gui.GetClassName(w.handle) == '#32770'), None), timeout=15) # Native Windows Common Item Dialog FileNameControlHost has edit ID 1001. edits = dialog.descendants(control_type='Edit') target = next((c for c in edits if c.element_info.automation_id in ('1001', '1148')), None) if target is None: target = next(c for c in edits if 'FileName' in c.element_info.automation_id) target.set_edit_text(str(path)) button = next(c for c in dialog.descendants(control_type='Button') if c.element_info.automation_id == '1') # Native buttons own HWNDs, unlike Qt's lightweight children. win32gui.PostMessage(button.handle, win32con.BM_CLICK, 0, 0) wait(lambda: not win32gui.IsWindow(dialog.handle), timeout=20) def fill_template(template, path, *, invalid=False): workbook = load_workbook(template) sheet = workbook.active headers = [c.value for c in sheet[1]] assert len(headers) == 11 for number in range(2, sheet.max_row + 1): row = dict(zip(headers, (c.value for c in sheet[number]))) row.update(old_part_number='4100-CA0000-T7', new_part_number='4100-CA0000-T0', refdes='RV05', enabled=True, sync_nc=True) for column, header in enumerate(headers, 1): sheet.cell(number, column).value = row.get(header) if invalid: row['refdes'] = 'R_DOES_NOT_EXIST' sheet.append([row.get(h) for h in headers]) workbook.save(path) workbook.close() def bom(driver, root, report): tasks = database(root, 'select * from tasks') assert not any(t['status'] == 'completed' for t in tasks), 'Do not overwrite an executed acceptance run' if not tasks: dialogs = [w for w in driver.windows() if w.window_text() == '从目录创建工程任务'] if not dialogs: driver.click(driver.find(automation_id='newTaskButton')) dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '从目录创建工程任务'), None)) driver.type_text(driver.find(automation_id='taskDirectory', window=dialog), str(root / 'projects')) driver.record('02 填写工程根目录,点击“读取工程”', highlight=driver.find(automation_id='readTaskProjects', window=dialog)) driver.click(driver.find(automation_id='readTaskProjects', window=dialog)) create = driver.find('创建任务', kind='Button', window=dialog) wait(create.is_enabled, timeout=20) driver.record('03 勾选工程:每个工程创建一个任务', highlight=create) driver.click(create) wait(lambda: len(database(root, 'select * from tasks')) == 2, timeout=20) driver.click(driver.find('本批位号计划', kind='TabItem')) wait(lambda: driver.find(automation_id='exportBomTemplate').is_enabled(), timeout=20) driver.record('04 已创建两个任务;先导出本批默认 BOM 模板', highlight=driver.find(automation_id='exportBomTemplate')) template = root / '默认BOM模板.xlsx' if not template.exists(): driver.click(driver.find(automation_id='exportBomTemplate')) file_dialog(driver, template, save=True) wait(template.is_file, timeout=20) valid, invalid = root / 'BOM-替换RV05.xlsx', root / 'BOM-含错误位号.xlsx' fill_template(template, valid) fill_template(template, invalid, invalid=True) report['template_columns'] = 11 report['template'] = str(template) # Invalid and valid import both use the candidate's real CAD inventory reader. for path, expected_failed, caption in ( (invalid, True, '05 导入含错误位号的 BOM:先检查报告,不会部分保存'), (valid, False, '07 修正后重新导入:两工程各替换 RV05,RV11 保留'), ): driver.record(caption, highlight=driver.find(automation_id='importBomPlan')) started = time.monotonic() if not any(win32gui.GetClassName(w.handle) == '#32770' for w in driver.windows()): driver.click(driver.find(automation_id='importBomPlan')) file_dialog(driver, path) wait(lambda: driver.find(automation_id='importBomPlan').is_enabled(), timeout=1200) toggle = driver.find(automation_id='toggleBomReport') title = toggle.window_text() assert '通过 2' in title and '未检查 0' in title, title assert ('失败 1' in title) if expected_failed else ('失败 0' in title), title assert not database(root, 'select * from target_plan'), 'Import must not persist before Save' report.setdefault('imports', []).append(dict(file=path.name, seconds=time.monotonic() - started, title=title)) driver.click(toggle) detail = wait(lambda: next((w for w in driver.windows() if w.window_text() == '本批 BOM 导入校验详情'), None)) text = driver.find(automation_id='bomImportReport', window=detail).window_text() if expected_failed: assert 'R_DOES_NOT_EXIST' in text or 'Excel 第 4 行' in text, text driver.record('06 校验报告:通过 2 行 / 失败 1 行,错误定位到 Excel 行号' if expected_failed else '08 校验全部通过;当前是预览,点击保存才写入计划', duration=2500) win32gui.PostMessage(detail.handle, win32con.WM_CLOSE, 0, 0) wait(lambda: not win32gui.IsWindow(detail.handle), timeout=10) driver.click(driver.find(automation_id='saveTargetPlan')) wait(lambda: len(database(root, 'select * from target_plan')) == 4, timeout=20) rows = database(root, 'select * from target_plan') assert sum(r['enabled'] for r in rows) == 2 assert all(bool(r['enabled']) == (r['refdes'] == 'RV05') for r in rows) report['saved_targets'] = rows driver.record('09 保存本批计划:仅 RV05 替换,同料号 RV11 保持原样', duration=2300) # Search affects display only; it must not change batch execution membership. search = driver.find(automation_id='taskSearch') driver.type_text(search, 'T605A') assert len(driver.find(automation_id='taskList').children()) == 1 driver.record('10 左侧搜索只过滤显示,不改变同批执行范围', highlight=search) driver.type_text(search, '') assert len(driver.find(automation_id='taskList').children()) == 2 report['search_preserves_tasks'] = True def execution_complete(root, states, previous_queues): """Do not mistake a retryable task's RUNNING status for active CAD work.""" if any(task['status'] == 'failed' for task in states): raise AssertionError(f'Native execution failed; do not auto-retry: {states}') queues = [] for path in (root / 'data/task-queues').glob('*.json'): if path in previous_queues: continue queue = json.loads(path.read_text(encoding='utf-8')) if queue['task_ids'] != [task['task_id'] for task in states]: continue entries = queue['entries'] assert set(entries) == set(queue['task_ids']), 'Incomplete queue checkpoint' if any(entry['state'] in {'failed', 'blocked', 'skipped'} for entry in entries.values()): raise AssertionError(f'Native execution failed; do not auto-retry: {entries}') queues.append(queue) return (bool(states) and len(queues) == 1 and all(task['status'] == 'completed' for task in states) and all(entry['state'] == 'completed' for entry in queues[0]['entries'].values())) def execute(driver, root, report): verify_disposable_projects(root) tasks = database(root, 'select * from tasks') assert len(tasks) == 2 and all(t['status'] in ('draft', 'ready') for t in tasks) rows = database(root, 'select * from target_plan') assert len(rows) == 4 and sum(r['enabled'] for r in rows) == 2 for task in tasks: item = next(c for c in driver.find(automation_id='taskList').children() if task['name'] in c.window_text()) driver.click(item) wait(lambda: Path(task['name']).name in driver.find(automation_id='boundProjectPath').window_text(), timeout=20) copy = driver.find(automation_id='copyPartNumberToValue') wait(copy.is_enabled, timeout=20) if not copy.get_toggle_state(): driver.click(copy) wait(lambda: next(t for t in database(root, 'select * from tasks') if t['task_id'] == task['task_id'])['copy_part_number_to_value'], timeout=15) driver.record('11 开启 Part Label → Value;确认计划已保存', highlight=copy) driver.click(driver.find(automation_id='executeProjectTasks')) confirmation = wait(lambda: next((w for w in driver.windows() if w.window_text() == '确认顺序执行本批任务'), None)) driver.record('12 核对执行范围与保存回读说明,再确认执行', duration=2500) yes = None for text in ('Yes', '&Yes', '是(&Y)', '是'): try: yes = driver.find(text, kind='Button', window=confirmation) break except LookupError: pass assert yes is not None, 'Cannot identify native execution confirmation button' previous_queues = set((root / 'data/task-queues').glob('*.json')) started = time.monotonic() driver.click(yes) driver.record('13 后台按工程顺序执行;等待段已压缩', duration=2000) last_status = None def finished(): nonlocal last_status states = database(root, 'select task_id,name,status,error_id from tasks order by group_position') if states != last_status: print(json.dumps(states, ensure_ascii=False), flush=True) driver.record('执行中:按工程顺序替换、保存并重新打开核验', duration=1000) last_status = states return execution_complete(root, states, previous_queues) wait(finished, timeout=1800) wait(lambda: driver.find(automation_id='startNewRoundButton').is_enabled(), timeout=20) report['execution_seconds'] = time.monotonic() - started report['completed_tasks'] = database(root, 'select * from tasks') report['saved_readback_events'] = verified_events(root) driver.record('14 本批执行结束:查看真实替换结果与回读状态', duration=2500) def details(driver, root, report): dialogs = [w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志'] if not dialogs: driver.click(driver.find(automation_id='toggleLogButton')) dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志'), None)) table = driver.find(automation_id='executionResults', window=dialog) # The result table is populated from actual saved/reopened readback events. time.sleep(1) cells = [c.window_text() for c in table.children()] assert any('RV05' in text for text in cells), cells assert any('4100-CA0000-T0' in text for text in cells), cells assert any('已保存并核验' in text for text in cells), cells report['result_accessibility_cells'] = cells driver.record('15 位号替换结果:图页、位号、旧料号、回读料号、核验状态', duration=2700) driver.click(driver.find('完整日志', kind='TabItem', window=dialog)) driver.record('16 完整日志查看各阶段;可翻页查看历史记录', duration=2500) win32gui.PostMessage(dialog.handle, win32con.WM_CLOSE, 0, 0) wait(lambda: not win32gui.IsWindow(dialog.handle), timeout=10) driver.click(driver.find(automation_id='toggleLogButton')) reopened = wait(lambda: next((w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志'), None), timeout=10) assert reopened.handle != dialog.handle wait(lambda: any('RV05' in c.window_text() for c in driver.find( automation_id='executionResults', window=reopened).children()), timeout=15) driver.record('17 日志窗口关闭后可重新打开,结果仍可查看', duration=2000) detail = next(w for w in driver.windows() if w.window_text() == '当前任务 · 替换结果与执行日志') win32gui.PostMessage(detail.handle, win32con.WM_CLOSE, 0, 0) driver.record('18 已完成任务可“开始新一轮”;旧轮次证据保留', highlight=driver.find(automation_id='startNewRoundButton'), duration=2500) report['detail_reopened'] = True def new_round(driver, root, report): assert json.loads((root / 'independent-report.json').read_text(encoding='utf-8'))['passed'] tasks = database(root, 'select * from tasks') assert len(tasks) == 2 and all(t['status'] == 'completed' for t in tasks) driver.click(driver.find(automation_id='startNewRoundButton')) dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '开始新一轮'), None), timeout=15) driver.record('19 开始新一轮前确认:旧计划与执行证据会归档保留', duration=2500) yes = None for text in ('Yes', '&Yes', '是(&Y)', '是'): try: yes = driver.find(text, kind='Button', window=dialog) break except LookupError: pass assert yes is not None driver.click(yes) wait(lambda: all(t['status'] == 'draft' for t in database(root, 'select * from tasks')), timeout=20) assert not database(root, 'select * from target_plan') archives = list((root / 'data/tasks').glob('*/rounds/*/plan.json')) assert len(archives) == 2 driver.record('20 两任务已恢复待配置;按当前料号重新填 BOM 后可再执行', duration=3000) report['new_round_archives'] = [str(path) for path in archives] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', type=Path, required=True) parser.add_argument('--stage', choices=('bom', 'verify_bom', 'execute', 'details', 'new_round'), required=True) parser.add_argument('--run-native', action='store_true') args = parser.parse_args() if not args.run_native: parser.error('All stages require --run-native to acknowledge disposable CAD operations') root = args.root.resolve(strict=True) session = json.loads((root / 'ui-session.json').read_text(encoding='utf-8')) verify_identity(root, session) verify_disposable_projects(root) driver = WindowDriver(session['pid'], root / 'recording') report_path = root / 'ui-acceptance.json' report = json.loads(report_path.read_text(encoding='utf-8')) if report_path.exists() else {} report.pop(args.stage + '_passed', None) try: if args.stage in ('bom', 'execute'): with PrivateDesktopObserver(root): globals()[args.stage](driver, root, report) (root / f'desktop-observation-{args.stage}.json').write_bytes((root / 'desktop-observation.json').read_bytes()) if args.stage == 'bom': report['bom_resources'] = verify_bom_resources(root) else: verify_observation(root / f'desktop-observation-{args.stage}.json') else: globals()[args.stage](driver, root, report) report[args.stage + '_passed'] = True except Exception: report.setdefault('failures', []).append(dict(stage=args.stage, traceback=traceback.format_exc())) raise finally: report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') driver.save_gif(root / '窗口操作教程.gif') if __name__ == '__main__': main()