diff --git a/docs/superpowers/plans/2026-10-15-packaged-acceptance-tutorial.md b/docs/superpowers/plans/2026-10-15-packaged-acceptance-tutorial.md index 96bca81..8b0aaa4 100644 --- a/docs/superpowers/plans/2026-10-15-packaged-acceptance-tutorial.md +++ b/docs/superpowers/plans/2026-10-15-packaged-acceptance-tutorial.md @@ -6,9 +6,11 @@ Scope: local candidate, no tag or remote release; preserve all existing data and - [x] Review prior evidence, current packaging and recording dependencies. - [x] Correct obsolete log-window and historical-interface instructions. -- [ ] Run the standard build checks and build the current source. -- [ ] Stage a clean candidate, hash it, archive and extract it; use that extracted EXE for acceptance. -- [ ] Operate the actual candidate UI to create project tasks, export/fill/import BOM, inspect rejected and accepted rows, edit/save, execute and inspect genuine results. -- [ ] Verify saved engineering state, old-data-copy startup, lazy details and owned-process/desktop cleanup. -- [ ] Produce window-only GIF(s) with step labels and explicit shortened waits; inspect exported frames. -- [ ] Write the acceptance result and limitations, commit and push reproducible tooling/docs. +- [x] Run the standard build checks and build the current source. +- [x] Stage a clean candidate, hash it, archive and extract it; use that extracted EXE for acceptance. +- [x] Operate the actual candidate UI to create project tasks, export/fill/import BOM, inspect rejected and accepted rows, edit/save, execute and inspect genuine results. +- [x] Verify saved engineering state, old-data-copy startup, lazy details and owned-process/desktop cleanup. +- [x] Produce window-only GIF(s) with step labels and explicit shortened waits; inspect exported frames. +- [x] Write the acceptance result and limitations in `docs/testing/2026-10-15-packaged-acceptance.md`. + +Integration: commit and push the reproducible tooling, report, and GIF on the development branch. No tag or remote release. diff --git a/docs/testing/2026-10-15-packaged-acceptance.md b/docs/testing/2026-10-15-packaged-acceptance.md new file mode 100644 index 0000000..577f77d --- /dev/null +++ b/docs/testing/2026-10-15-packaged-acceptance.md @@ -0,0 +1,64 @@ +# 1.1.2 本机冻结候选验收与窗口教程 + +结论:**本轮列出的本机成品验收通过,可用于限定环境的小范围试用交付**。不是所有 CAD、中央库和机器环境的稳定性认证;没有创建远端 Release 或版本标签。 + +## 候选身份 + +- 构建提交:`a16914bc7221dbc62c467b7a89e06ab0c40c1fbc`;产品代码与此前通过源码检查的 `ce574dd` 一致,期间仅增加发布评估和说明文档。 +- 标准构建脚本源码检查:**369 passed,1 warning,63.39 秒**;PyInstaller 构建与冻结 EXE 启动/退出检查通过。 +- 候选从 `dist/DxPartReplace` 另复制到干净 staging,排除 `data`,再压缩、解压。实际操作的是 `build/packaged-acceptance-20261015/extracted/DxPartReplace/DxPartReplace.exe`。运行进程路径、EXE 哈希和副本工程身份另行核对。 +- EXE SHA256:`73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75`。 +- VBS SHA256:`9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc`,与源码一致。 +- ZIP SHA256:`bfbc089c4362a9a9c43320b81ee9d4f7af0750bee6da25d16fc58733130319c2`,52,589,346 字节。 + +候选、完整工程副本、原始记录均在 `build/packaged-acceptance-20261015`。候选 ZIP 为本地验收包,不改变当前已发布版本。 + +## 实际操作及断言 + +使用 Windows UI Automation 定位真实控件,向目标窗口发送鼠标消息,操作原生文件选择与确认弹窗。没有导入产品内部 UI 类驱动主流程,没有模拟 CAD worker,也没有向数据库或日志注入成功状态。数据库检查使用只读连接。 + +| 验收项 | 结果 | +| --- | --- | +| 创建任务 | 实际创建弹窗读取 Audio_D2128、Audio_T605A 的独立副本;一工程一任务 | +| 长路径 | 两工程路径分别 297、131 字符;长路径实际采集、替换、保存重开与独立读取均完成;本轮使用本机可用的 8.3 短入口,未重复强制 junction 路线 | +| 默认 BOM | 点击导出原模板,确认 11 列、两个工程;只填写原表单元格,不改模板结构 | +| 错误导入 | 两条有效 RV05 + 不存在的 R_DOES_NOT_EXIST:通过 2、失败 1、未检查 0,明确 Excel 第 4 行;没有部分保存 | +| 修正导入 | 通过 2、失败 0、未检查 0;预览不写计划,点击保存后形成 4 个库存位号,只有两个 RV05 启用 | +| 任务搜索 | T605A 过滤为 1 个,清空后恢复 2 个;执行成员未变 | +| Value 策略 | 逐任务通过界面启用 Part Label → Value,并核对数据库中的选项持久化 | +| 顺序执行 | 实际确认两个工程范围,分别执行原生 Replace Part、保存、关闭和重开核验;两工程各一条真实 saved_ok 事件,均含 RV05 的旧新料号 | +| 结果/日志 | 实际结果单元格包含 RV05、新料号和“已保存并核验”;切换完整日志、关闭再打开,结果仍正确 | +| 独立读取 | 使用全新私有 CAD 会话读取实际保存工程,结果如下;启动/退出 helper 使用同一冻结 EXE,属性读取器为独立源码诊断脚本 | +| 新轮次 | 独立核验后实际点击开始新一轮,两任务恢复 draft,旧目标计划清空;两份 plan.json 及执行证据归档保留;本轮不重复执行已完成的原生替换 | +| 旧版数据兼容 | 实际 1.1.1 发布 EXE 创建两个元数据测试任务;复制其数据库交给候选打开,正常退出,两个任务 ID/名称均保留,旧数据库未变;不是对任意历史数据的全量迁移认证 | +| 工程与资源 | 两个原工程的全部文件 SHA256 未变;10 个观察到的自有 CAD 进程退出、10 个私有桌面释放,无观察错误,未抢主桌面;最后仅保留用户原 CAD PID 18732 | +| 应用退出 | 验收和录制后候选主窗口正常关闭,没有遗留候选 GUI 或自有 CAD | + +独立实际结果: + +| 工程 | 位号 | UID | 实际保存料号 | Part Label | Value | +| --- | --- | --- | --- | --- | --- | +| Audio_D2128 | RV05 | $2I2014 | 4100-CA0000-T0 | 0R | 0R | +| Audio_D2128 | RV11(保留) | $2I2022 | 4100-CA0000-T7 | 0R | 0R | +| Audio_T605A | RV05 | $2I2014 | 4100-CA0000-T0 | 0R | 0R | +| Audio_T605A | RV11(保留) | $2I2022 | 4100-CA0000-T7 | 0R | 0R | + +## 耗时及记录 + +- 含错误项的首次 BOM 导入和实际库存核验:285.406 秒;修正后有效缓存下重新导入:5.735 秒。 +- 点击确认执行到两工程完成并恢复界面:258.984 秒,约 4 分 19 秒;这是两个工程合计,包含原生处理及保存回读,不代表每个位号都需要同等耗时。 +- 独立读取:37.922、46.172 秒,分别包含全新会话启动、打开读取和退出。 +- 阶段计时:`execution-measurements.csv`;实际状态、导入标题、保存事件及调试尝试保存在 `ui-acceptance.json`,失败的驱动适配尝试没有删除。驱动修正没有修改产品代码或绕过原生核验。 +- 其他记录:`candidate-manifest.json`、`independent-report.json`、`source-integrity.json`、`v111-upgrade-report.json`、`desktop-observation-{bom,execute,independent}.json`、`tutorial-report.json`。 + +## 窗口 GIF + +[打开操作教程](../user/media/v1.1.2-window-bom-tutorial.gif):20 个步骤,47.5 秒,约 2.65 MB,1280×980。 + +GIF 由本轮实际窗口操作的分步截图组成,使用 PrintWindow 仅读取指定候选进程的主窗口及其弹窗,不读取桌面图像,不包含 Excel 或 CAD 窗口。模板填项在窗口录制之外由脚本完成。字幕说明实际等待被压缩;数分钟的 CAD 等待没有按实时长度保留。抽查了导出 GIF 中的错误报告、成功回读和新轮次帧,中文及内容可读。 + +可复用工具:`packaged_window_driver.py`、`accept_packaged_ui.py`、`probe_packaged_upgrade.py`、`verify_packaged_saved_state.py`、`finalize_window_tutorial.py`。工具有副本路径和成品身份守卫,执行错误时不自动重复替换。UIA 与窗口绘制接口仍属于同步调用,本次工具用于有人监督的本机验收,不作为具有硬超时保证的无人值守门禁。 + +## 保留的限制 + +既有 COM 偶发启动阻塞的根因仍未解决;本轮所有会话最终成功并释放,不能据此证明问题消失。超长任务名称在执行反馈中占用较多空间、任务列表状态在批次结束前可能滞后,是后续体验改善项,不影响本轮真实回读结论。未新增其他库版本、其他机器或 Packager/ERC 验收。之前千步性能单次 29.517 秒达标的范围仍仅为模拟 worker,不与本轮实际 CAD 时间混用。 diff --git a/docs/user/media/v1.1.2-window-bom-tutorial.gif b/docs/user/media/v1.1.2-window-bom-tutorial.gif new file mode 100644 index 0000000..54cf14c Binary files /dev/null and b/docs/user/media/v1.1.2-window-bom-tutorial.gif differ diff --git a/docs/user/v1.1.0-project-tasks.md b/docs/user/v1.1.0-project-tasks.md index 9164953..aeecaab 100644 --- a/docs/user/v1.1.0-project-tasks.md +++ b/docs/user/v1.1.0-project-tasks.md @@ -2,6 +2,8 @@ V1.1.0 沿用原有任务视图和料号规则编辑,增加按工程拆分的任务、按位号选择的替换计划及可选 Excel 操作。 +[窗口 GIF 操作教程(1.1.2 本地验收候选)](media/v1.1.2-window-bom-tutorial.gif):创建任务、导出/导入 BOM、错误行提示、保存、顺序执行、查看结果和开始新一轮。仅含工具窗口及其弹窗,实际 CAD 等待已压缩。 + ## 日常流程 1. 点击“新建”,填写或选择根目录,点击“读取工程”。勾选要处理的 `.prj` 后创建任务,每个工程对应一个任务。已存在未完成任务的工程不会重复创建。 diff --git a/tools/accept_packaged_ui.py b/tools/accept_packaged_ui.py new file mode 100644 index 0000000..bfd2d03 --- /dev/null +++ b/tools/accept_packaged_ui.py @@ -0,0 +1,358 @@ +"""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): + observation = json.loads(path.read_text(encoding='utf-8')) + assert not observation['observer_errors'], observation['observer_errors'] + 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 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 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' + started = time.monotonic() + driver.click(yes) + driver.record('13 后台按工程顺序执行;等待段已压缩', duration=2000) + last_status = None + def finished(): + nonlocal last_status + states = database(root, 'select 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 + if any(t['status'] == 'failed' for t in states): + raise AssertionError(f'Native execution failed; do not auto-retry: {states}') + return all(t['status'] == 'completed' for t in states) + 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', '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()) + 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() diff --git a/tools/finalize_window_tutorial.py b/tools/finalize_window_tutorial.py new file mode 100644 index 0000000..ebee4f6 --- /dev/null +++ b/tools/finalize_window_tutorial.py @@ -0,0 +1,55 @@ +"""Assemble numbered PrintWindow operation frames; shorten only idle waits.""" +import argparse +import json +from pathlib import Path + +from PIL import Image + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + root = args.root.resolve(strict=True) + events = json.loads((root / 'recording/frames.json').read_text(encoding='utf-8')) + by_number = {} + for entry in events: + first = entry['caption'].split(maxsplit=1)[0] + if not first.isdigit(): + continue + number = int(first) + # Early driver setup retries are not part of the instructional sequence. + if number not in by_number or number in (1, 2): + by_number[number] = entry + assert set(by_number) == set(range(1, 21)), sorted(by_number) + selected = [by_number[n] for n in range(1, 21)] + images = [Image.open(root / f'recording/frame-{e["frame"]:03d}.png').convert('RGB') for e in selected] + assert {image.size for image in images} == {(1280, 980)} + # A shared palette samples every real state, including error and success colors. + contact = Image.new('RGB', (1024, 980), '#f3f5f8') + for n, image in enumerate(images): + thumb = image.resize((256, 196), Image.Resampling.LANCZOS) + contact.paste(thumb, ((n % 4) * 256, (n // 4) * 196)) + palette = contact.quantize(colors=192) + frames = [image.quantize(palette=palette, dither=Image.Dither.NONE) for image in images] + args.output.parent.mkdir(parents=True, exist_ok=True) + durations = [max(e['duration_ms'], 2200) for e in selected] + frames[0].save(args.output, save_all=True, append_images=frames[1:], + duration=durations, loop=0, optimize=True, disposal=2) + contact.save(root / 'tutorial-contact-sheet.png') + with Image.open(args.output) as exported: + assert exported.n_frames == 20 and exported.size == (1280, 980) + for number in (0, 5, 14, 19): + exported.seek(number) + exported.convert('RGB').save(root / f'tutorial-gif-check-{number:02d}.png') + report = dict(gif=str(args.output.resolve()), bytes=args.output.stat().st_size, + frames=20, duration_seconds=sum(durations) / 1000, + capture='PrintWindow surfaces of the candidate process only', + waits_shortened=True, steps=selected) + (root / 'tutorial-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') + print(json.dumps({k: v for k, v in report.items() if k != 'steps'}, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/packaged_window_driver.py b/tools/packaged_window_driver.py new file mode 100644 index 0000000..5727dd7 --- /dev/null +++ b/tools/packaged_window_driver.py @@ -0,0 +1,163 @@ +"""External Windows UI driver and PrintWindow-only instructional capture. + +This utility cannot import application internals or fabricate task state. It +operates the executable through Windows accessibility and records only windows +owned by that executable. Workbook edits and acceptance assertions belong to +the calling scenario. +""" +from __future__ import annotations + +import ctypes +from ctypes import wintypes +import json +from pathlib import Path +import time + +from PIL import Image, ImageDraw, ImageFont +from pywinauto import Application +import win32con +import win32gui +import win32process +import win32ui + + +def window_image(hwnd): + """Read this HWND's drawing surface, never the desktop framebuffer.""" + left, top, right, bottom = win32gui.GetWindowRect(hwnd) + width, height = right - left, bottom - top + dc = win32gui.GetWindowDC(hwnd) + source = win32ui.CreateDCFromHandle(dc) + target = source.CreateCompatibleDC() + bitmap = win32ui.CreateBitmap() + bitmap.CreateCompatibleBitmap(source, width, height) + target.SelectObject(bitmap) + try: + print_window = ctypes.windll.user32.PrintWindow + print_window.argtypes = (wintypes.HWND, wintypes.HDC, wintypes.UINT) + print_window.restype = wintypes.BOOL + if not print_window(hwnd, target.GetSafeHdc(), 2): + raise RuntimeError(f'PrintWindow failed for {hwnd}') + return Image.frombuffer('RGB', (width, height), bitmap.GetBitmapBits(True), 'raw', 'BGRX', 0, 1).copy() + finally: + win32gui.DeleteObject(bitmap.GetHandle()) + target.DeleteDC() + source.DeleteDC() + win32gui.ReleaseDC(hwnd, dc) + + +class WindowDriver: + def __init__(self, pid, output): + self.pid, self.output = pid, Path(output) + self.output.mkdir(parents=True, exist_ok=True) + self.app = Application(backend='uia').connect(process=pid, timeout=15) + self.frames, self.durations, self.steps = [], [], [] + self.font = ImageFont.truetype('C:/Windows/Fonts/msyh.ttc', 22) + if (self.output / 'frames.json').exists(): + self.steps = json.loads((self.output / 'frames.json').read_text(encoding='utf-8')) + self.frames = [Image.open(self.output / f'frame-{s["frame"]:03d}.png').convert('RGB') for s in self.steps] + self.durations = [s['duration_ms'] for s in self.steps] + + def windows(self): + handles = [] + def collect(handle, _): + if win32gui.IsWindowVisible(handle) and win32process.GetWindowThreadProcessId(handle)[1] == self.pid: + left, top, right, bottom = win32gui.GetWindowRect(handle) + if right - left > 100 and bottom - top > 80: + handles.append(handle) + win32gui.EnumWindows(collect, None) + return [self.app.window(handle=handle).wrapper_object() for handle in handles] + + def main(self): + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + for window in self.windows(): + if window.window_text().startswith('DxDesigner '): + return window + time.sleep(.2) + raise TimeoutError('Application main window not found') + + def find(self, text=None, *, kind=None, automation_id=None, window=None): + root = window or self.main() + # Do not recursively enumerate virtual Qt table cells through UIA. + def walk(parent, depth=0): + if depth > 12: + return + for child in parent.children(): + yield child + if child.element_info.control_type not in { + 'Table', 'DataGrid', 'List', 'ScrollBar', 'Header', 'Edit', + 'Button', 'Text', 'CheckBox', 'ComboBox', 'TitleBar', 'MenuBar', 'MenuItem'}: + yield from walk(child, depth + 1) + controls = walk(root) + matches = [c for c in controls if (kind is None or c.element_info.control_type == kind) + and (text is None or c.window_text() == text) + and (automation_id is None or c.element_info.automation_id == automation_id + or c.element_info.automation_id.endswith('.' + automation_id)) + and c.is_visible()] + if len(matches) != 1: + raise LookupError(f'Expected one {text!r}/{automation_id!r}, got {len(matches)}') + return matches[0] + + def click(self, control): + # Posted window mouse events allow modal dialogs without blocking the driver. + self.point(control) + + def point(self, control, *, dx=None, dy=None, double=False): + rect = control.rectangle() + if dx is None and control.element_info.control_type in ('ListItem', 'DataItem'): + dx = 20 # Qt may expose the full elided text width beyond its viewport. + root = control + while not root.handle or not win32gui.IsWindow(root.handle): + root = root.parent() + x = rect.left + (dx if dx is not None else rect.width() // 2) + y = rect.top + (dy if dy is not None else rect.height() // 2) + x, y = win32gui.ScreenToClient(root.handle, (x, y)) + value = (y << 16) | (x & 0xFFFF) + for _ in range(2 if double else 1): + win32gui.PostMessage(root.handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, value) + win32gui.PostMessage(root.handle, win32con.WM_LBUTTONUP, 0, value) + time.sleep(.2) + + def type_text(self, control, text): + control.set_edit_text(text) + time.sleep(.2) + + def record(self, caption, *, highlight=None, duration=1600): + main = self.main() + image = window_image(main.handle) + left, top, _, _ = win32gui.GetWindowRect(main.handle) + # Owned modal/detail windows are composited from their own surfaces. + for other in reversed(self.windows()): + if other.handle == main.handle: + continue + other_left, other_top, _, _ = win32gui.GetWindowRect(other.handle) + image.paste(window_image(other.handle), (other_left - left, other_top - top)) + draw = ImageDraw.Draw(image) + if highlight is not None: + rect = highlight.rectangle() + box = (rect.left - left - 3, rect.top - top - 3, + rect.right - left + 3, rect.bottom - top + 3) + draw.rounded_rectangle(box, radius=5, outline='#e35d30', width=4) + # Fixed canvas dimensions allow window resizing without desktop capture. + image.thumbnail((1280, 900), Image.Resampling.LANCZOS) + canvas = Image.new('RGB', (1280, 980), '#f3f5f8') + canvas.paste(image, ((1280 - image.width) // 2, 0)) + draw = ImageDraw.Draw(canvas) + draw.rectangle((0, 900, 1280, 980), fill='#172b45') + draw.text((24, 914), caption, font=self.font, fill='white') + draw.text((24, 946), '窗口操作实录 · 等待过程已压缩 · 工程副本验收', + font=ImageFont.truetype('C:/Windows/Fonts/msyh.ttc', 16), fill='#bdcfdf') + index = len(self.frames) + canvas.save(self.output / f'frame-{index:03d}.png') + self.frames.append(canvas) + self.durations.append(duration) + self.steps.append(dict(frame=index, caption=caption, duration_ms=duration, wall_time=time.time())) + (self.output / 'frames.json').write_text(json.dumps(self.steps, ensure_ascii=False, indent=2), encoding='utf-8') + + def save_gif(self, path): + if not self.frames: + raise RuntimeError('No window frames captured') + palette = self.frames[0].quantize(colors=160) + images = [frame.quantize(palette=palette, dither=Image.Dither.NONE) for frame in self.frames] + images[0].save(path, save_all=True, append_images=images[1:], + duration=self.durations, loop=0, optimize=True, disposal=2) diff --git a/tools/probe_packaged_upgrade.py b/tools/probe_packaged_upgrade.py new file mode 100644 index 0000000..d87100b --- /dev/null +++ b/tools/probe_packaged_upgrade.py @@ -0,0 +1,76 @@ +"""Create task data with the real 1.1.1 EXE, then open its copy in the candidate.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import sqlite3 +import subprocess +import time + +import win32con +import win32gui + +from accept_packaged_ui import wait +from packaged_window_driver import WindowDriver + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', type=Path, required=True) + args = parser.parse_args() + root = args.root.resolve(strict=True) + repository = Path(__file__).resolve().parents[1] + legacy = repository / 'dist/DxPartReplace-1.1.1/DxPartReplace/DxPartReplace.exe' + release = json.loads((repository / 'docs/releases/v1.1.1-build.json').read_text(encoding='utf-8')) + assert hashlib.sha256(legacy.read_bytes()).hexdigest() == release['artifacts']['exe_sha256'] + old_data, new_data = root / 'v111-created-data', root / 'v111-upgraded-copy' + old_data.mkdir(exist_ok=False) + projects = root / 'upgrade-fixture-projects' + for name in ('Legacy-A', 'Legacy-B'): + path = projects / name / 'board.prj' + path.parent.mkdir(parents=True) + path.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf-8') + env = dict(os.environ, TEMP=str(repository / 'build/test-temp-remediation'), + TMP=str(repository / 'build/test-temp-remediation'), LOCALAPPDATA=str(root / 'profile')) + for key in ('PYTHONPATH', 'PYTHONHOME', 'DX_TASK_CENTER_HOME', 'QT_QPA_PLATFORM'): + env.pop(key, None) + process = subprocess.Popen([str(legacy), '--data-root', str(old_data)], env=env, + creationflags=subprocess.CREATE_NO_WINDOW) + driver = WindowDriver(process.pid, root / 'upgrade-recording') + window = driver.main() + try: + driver.click(driver.find(automation_id='newTaskButton')) + dialog = wait(lambda: next((w for w in driver.windows() if w.window_text() == '从目录创建工程任务'), None), timeout=15) + driver.type_text(driver.find(automation_id='taskDirectory', window=dialog), str(projects)) + driver.click(driver.find(automation_id='readTaskProjects', window=dialog)) + create = driver.find('创建任务', kind='Button', window=dialog) + wait(create.is_enabled, timeout=20) + driver.click(create) + def read_tasks(path): + with sqlite3.connect(path) as db: + return db.execute('select task_id,name from tasks order by task_id').fetchall() + original = wait(lambda: (rows if len(rows := read_tasks(old_data / 'task-center.db')) == 2 else None), timeout=20) + time.sleep(.5) + finally: + win32gui.PostMessage(window.handle, win32con.WM_CLOSE, 0, 0) + process.wait(timeout=30) + before = hashlib.sha256((old_data / 'task-center.db').read_bytes()).hexdigest() + new_data.mkdir() + with sqlite3.connect((old_data / 'task-center.db').as_uri() + '?mode=ro', uri=True) as src, sqlite3.connect(new_data / 'task-center.db') as dst: + src.backup(dst) + env['QT_QPA_PLATFORM'] = 'offscreen' + candidate = root / 'extracted/DxPartReplace/DxPartReplace.exe' + result = subprocess.run([str(candidate), '--smoke-test', '--data-root', str(new_data)], + env=env, capture_output=True, timeout=90) + report = dict(legacy_version='1.1.1', task_count=len(original), candidate_exit_code=result.returncode, + task_identities_preserved=read_tasks(new_data / 'task-center.db') == original, + legacy_source_unchanged=hashlib.sha256((old_data / 'task-center.db').read_bytes()).hexdigest() == before, + fixture_is_metadata_only=True, cad_launched=False) + assert result.returncode == 0 and report['task_identities_preserved'] and report['legacy_source_unchanged'], report + (root / 'v111-upgrade-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') + print(json.dumps(report, ensure_ascii=False, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/verify_packaged_saved_state.py b/tools/verify_packaged_saved_state.py new file mode 100644 index 0000000..fd1cc00 --- /dev/null +++ b/tools/verify_packaged_saved_state.py @@ -0,0 +1,79 @@ +"""Independently read saved disposable projects after frozen-EXE execution.""" +import argparse +import json +from pathlib import Path +import sys +import time + +import win32api + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) +from dx_productivity.trial_task_center import isolated_cad +from accept_packaged_ui import database, verify_disposable_projects, verify_observation +from private_desktop_observer import PrivateDesktopObserver + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', type=Path, required=True) + parser.add_argument('--run-native', action='store_true', required=True) + args = parser.parse_args() + root = args.root.resolve(strict=True) + verify_disposable_projects(root) + tasks = database(root, 'select task_id,status from tasks') + assert len(tasks) == 2 and all(t['status'] == 'completed' for t in tasks) + candidate = root / 'extracted/DxPartReplace/DxPartReplace.exe' + original = isolated_cad._helper_command + def helper(action, evidence, pid): + return (str(candidate), '--private-cad-action', action, + '--private-cad-evidence', str(evidence), '--private-cad-pid', str(pid)) + isolated_cad._helper_command = helper + report = dict(reader='independent source attribute reader in fresh private CAD; frozen probe/quit helpers', projects=[]) + try: + with PrivateDesktopObserver(root): + for task in tasks: + rows = database(root, "select * from target_plan where task_id='" + task['task_id'] + "'") + selected = next(row for row in rows if row['enabled']) + project = Path(selected['project_path']).resolve(strict=True) + assert project.is_relative_to(root / 'projects') + reader = root / 'data/tasks' / task['task_id'] / 'quick-run-history/sheet-discovery-acceptance-independent' + reader.mkdir(exist_ok=False) + destination = root / ('independent-attributes-' + task['task_id'] + '.json') + started = time.monotonic() + with isolated_cad.IsolatedCadSession(reader) as session: + process = session.start_worker((sys.executable, + str(Path(__file__).with_name('probe_part_label_live.py')), + '--inspect-project', win32api.GetShortPathName(str(project)), + '--schematic', selected['schematic_name'], '--sheet', selected['sheet_number'], + '--output', str(destination)), stdout=-1, stderr=-1) + try: + if process.wait(timeout=150): + raise AssertionError(process.stderr.read().decode('utf-8', errors='replace')) + finally: + process.close() + actual = json.loads(destination.read_text(encoding='utf-8')) + by_ref = {r['refdes']: r for r in actual} + assert set(by_ref) == {'RV05', 'RV11'} + assert by_ref['RV05']['part_number'] == '4100-CA0000-T0' + assert by_ref['RV05']['part_label'] == by_ref['RV05']['value'] == '0R' + for before in rows: + after = by_ref[before['refdes']] + assert before['uid'] == after['uid'] + if not before['enabled']: + assert after['part_number'] == before['old_part_number'] + assert after['value'] == before['old_value'] + entry = dict(task_id=task['task_id'], project=str(project), components=actual, + seconds=time.monotonic() - started) + report['projects'].append(entry) + print(json.dumps(entry, ensure_ascii=False), flush=True) + observation = root / 'desktop-observation-independent.json' + observation.write_bytes((root / 'desktop-observation.json').read_bytes()) + verify_observation(observation) + report['passed'] = True + finally: + isolated_cad._helper_command = original + (root / 'independent-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') + + +if __name__ == '__main__': + main()