fix: inspect addressless ICDB projects and ask for PCB recovery version
This commit is contained in:
1 parent
c85696080d
commit
de952a68d6
11 files changed
+558
-22
No files matched your search
@@ -0,0 +1,65 @@
|
||||
# ICDB 持续失败:公开资料与实际入口核对
|
||||
|
||||
调查日期:2026-11-03。当前源码 `c856960`。本轮是网上资料检索及只读诊断,没有修改库、服务器设置或产品代码,不能作为修复验收。
|
||||
|
||||
## 本机确定的缺口
|
||||
|
||||
目前找到最近一次实际失败为隔离完整库 IP101GR 的 2026-11-03 16:19(北京时间)记录:
|
||||
|
||||
`diagnostics/feedback-final-ui/evidence/verify-85fd17bc6ed2/result.json`
|
||||
|
||||
错误为 `DATABASE_RECOVERY_REQUIRED`,阶段为 `PCB_STARTING`。原生提示询问:
|
||||
|
||||
> Continue to open the design with read/write access permission?
|
||||
|
||||
提示说明可能是文件系统/网络在 15 秒内未确定谁打开了设计,也可能是上一会话异常退出;要求确认没有其他用户正在使用。它没有证明数据库内容已损坏,也不是本轮原生 Repair 的失败结果。
|
||||
|
||||
代码及只读复核证据 `diagnostics/icdb-web-research-20261103/routing-evidence.json`:
|
||||
|
||||
1. `maintenance_entry.maintenance_needed` 仅在存在库阻止检查点或数据库地址记录时返回真。
|
||||
2. 当前 IP101GR 没有地址记录、没有阻止检查点,尽管请求 `maintenance=True`,仍返回 `routes_to_native_repair=false`。
|
||||
3. `select_maintenance_target` 额外要求恰好一个地址记录;无地址时返回 `需要唯一工程地址记录`,因此只改外层判断也不能打通流程。
|
||||
4. `verify_runner` 的自动补救仅针对 `ICDB_REPAIR_REQUIRED`;当前读写确认错误归入 `DATABASE_SAFETY_STOP`,不会触发该分支。
|
||||
5. 修复后一次性读写确认已有 `PostRepairProof` 机制,但只有本轮原生修复成功且释放已核实时才授权。当前入口绕过 Repair,自然没有这份证明。
|
||||
|
||||
因此,明确维护不能以“没有 sAddress.adr”推断无需维护。地址记录用于定位/占用判断,不应成为识别异常关闭状态的唯一依据。
|
||||
|
||||
## 网上资料:已读取原文
|
||||
|
||||
### 原生 Project Repair
|
||||
|
||||
[Mentor XP 如何修复文件](https://blog.csdn.net/qq_53931654/article/details/147240707)
|
||||
|
||||
原文步骤为打开 iCDB Project Backup,指定损坏工程路径,执行 `Project → Repair`。与本机已经接入的官方工具入口一致。本文是用户经验文章,没有证明当前完整自动链路或 CBB 校验限制已经解决。
|
||||
|
||||
本轮首次访问返回脚本验证页,后续正常请求取得正文;正文与截图链接保存在 `native-repair.json` / `native-repair.html`。
|
||||
|
||||
### 工程备份恢复
|
||||
|
||||
[“Unable to open iCDB connection”的解决方案](https://blog.csdn.net/zhangyang125/article/details/136188112)
|
||||
|
||||
原文建议从工程 `ProjectBackup/backups` 选择备份,恢复对应文件后重新打开。文章把复制/转移时文件丢失或损坏列为可能原因。该方案会回退版本,不等于保留最新内容的无损 Repair;仍需用户选择可接受版本,恢复后做工程身份与校验确认。
|
||||
|
||||
### 连接/监听地址
|
||||
|
||||
[Xpedition 2409 Designer 无法打开 iCDB 连接](https://blog.csdn.net/kkisscj/article/details/144323677)
|
||||
|
||||
原文描述在工作目录的 iCDB Server 配置中设置 `Network/Address` 为本机地址,并引用 VX2.8 管理文档。这说明“无法连接 iCDB”也可能是监听配置问题,不能一律解释为损坏。
|
||||
|
||||
但文章环境是 Xpedition 2409,本机是 EE7.9.5。现有日志未证实本机出现同类监听失败;本轮没有修改 Server 配置、服务或端口。
|
||||
|
||||
### 检索限制和排除项
|
||||
|
||||
英文 Google/DuckDuckGo 请求连接超时;Bing 多个精确错误查询无结果或结果无关,360 搜索提供了可进一步核对的中文线索。没有取得可直接适用于 EE7.9.5 当前弹窗的 Siemens 官方支持答复。检索及抓取原文保存在 `diagnostics/icdb-web-research-20261103/`。
|
||||
|
||||
标题/推荐摘要中含 “iCDB Server Monitor” 的另一页面,正文实际讨论 Android Studio Monitor,已排除,未把无关搜索结果当作技术依据。本机已有帮助文件检索也未找到能补足该弹窗处理条件的准确段落。
|
||||
|
||||
## 建议的修正与验证次序
|
||||
|
||||
1. 明确维护入口支持“无地址记录但需要检查”的工程:通过用户所选 CBB、唯一 PRJ/PCB 关系和明确数据库映射绑定目标;多个候选数据库必须明确区分,不能猜测共享库或另一个工程。
|
||||
2. 在本任务 PCB/启动器正常退出、库锁与数据库独占访问确认后,执行一次原生 Project Repair。不要因为看不到地址文件就直接退回打开 PCB。
|
||||
3. 仅在原生成功、目标一致、进程与地址释放确认后,使用已有修复后读写授权重新打开。未知或外部占用仍停止,不能把同意读写弹窗作为一般重试策略。
|
||||
4. 如要求选择 PCB 历史版本,明确记录选择及版本回退;随后验证集成、保存、关闭和权威 READY。
|
||||
5. 如果数据库检查通过,但仍被“已验证 CBB 不允许重新执行 BackAnnotate”阻止,应作为独立的 CBB 注册/校验状态问题处理。此前完整依赖库中“原生重新导入 → 自动校验 → READY”已通过,但不能把重新导入偷偷塞进 Repair 或称为无损修复。
|
||||
|
||||
此处已定位入口缺口和可验证的修正方向;尚未实现并完成“无地址记录”维护路径的真实自动链路验收。
|
||||
@@ -0,0 +1,26 @@
|
||||
# 无地址 ICDB 维护及 PCB 版本选择
|
||||
|
||||
沿用 `codex/temp-issue-2-icdb-recovery` 临时分支。依据实际错误日志与公开资料修正入口,用户明确授权在需要时弹窗选择版本。应用自动备份仍取消,操作前保留手动备份提醒;未修改原用户库。
|
||||
|
||||
## 本次行为
|
||||
|
||||
- 明确发起 ICDB 维护时,不再因为没有 `sAddress.adr` 或协调检查点而跳过原生检查。
|
||||
- 无地址时,所选 PCB 必须唯一反向引用主 PRJ,工程内数据库映射必须唯一。多数据库、共享地址、路径身份不符、原生进程/脚本占用及无法独占读取仍停止。
|
||||
- 原生 Repair 成功并确认释放后,沿同一任务重新打开。若原生要求选择历史 PCB 版本,主应用显示实际候选时间和“最后手动保存 / 自动保存 / 取消”。不默认选择任一历史版本。
|
||||
- 用户选择后,私有桌面代理重新核对窗口、进程、候选时间及单选状态,再确认恢复。选择过期、窗口变化或执行失败不重试确认。等待期间应用保持响应;取消停止当前项并保留原生现场。
|
||||
- 最终仍要求集成校验、保存关闭、进程退出及权威 READY。使用了历史 PCB 版本时,即便校验通过,也记录 `RESTORED_REVIEW_REQUIRED`(已恢复,版本待核对),不标记为无损 Repair。
|
||||
- 未提供交互入口的调用保留待选择结果,不自动选版本;普通 Verify 不获得修复后授权。
|
||||
|
||||
## 过程证据
|
||||
|
||||
无地址隔离工程 IP101GR 经实际应用维护按钮完成原生 Repair,地址为空且进程退出。之后严格的修复后授权通过读写确认,继续到 PCB 历史版本选择。证据为 `diagnostics/noaddr-ui/evidence/maintenance-c05e9c4b06b2/result.json`。
|
||||
|
||||
用户此前已选择最后手动保存版本(2026/9/24 23:06)。首次诊断续接沿用该选择,完成校验、保存关闭,`IsVerifiedReuseBlock` 返回 READY/raw=1;记录在 `diagnostics/icdb-addressless-20261103/authorized-last-manual/result.json`。该次还通过诊断操作确认了保存弹窗,不能记为完整自动链路通过,因此继续实现上述应用内选择流程。
|
||||
|
||||
后续应用内选择试验两次在原生修复前被其他脚本占用阻止。进一步日志显示来自另一工具的并行 `run_bridge.vbs` 测试;没有强制结束或忽略该进程。失败记录保留在 `source-choice-button/`、`source-choice-button-retry/`。
|
||||
|
||||
## 验证边界
|
||||
|
||||
集中回归覆盖无地址选目标、地址变化、共享/多个数据库、修复后授权、选择/取消、版本日期改变、重复确认、原生动作失败、错 PID/桌面、真实单选状态复读和历史恢复归类。独立代码审查无剩余实质问题。
|
||||
|
||||
最终全量测试、冻结构建及实际按钮结果统一记录在 `diagnostics/icdb-addressless-20261103/`。本文件不将历史版本恢复视为无损修复,也不将模拟测试或人工续接替代最终冻结链路结果。
|
||||
@@ -0,0 +1,12 @@
|
||||
# 无地址 ICDB 维护与 PCB 版本选择
|
||||
|
||||
用户要求按已确认的入口分析修复,并明确允许需要时弹窗让用户选择。沿用临时分支,不恢复应用自动备份,不改原库。
|
||||
|
||||
- [x] 无地址记录的明确维护也进入原生 Repair;仅允许唯一数据库与 PCB/PRJ 反向引用绑定,保留全库独占检查。新增回归先失败,集中 250 项通过,独立审查通过。
|
||||
- [x] 实际应用按钮在无地址 IP101GR 副本完成原生 Repair,随后需要 PCB 版本选择;沿用用户此前确认的手动保存版本,诊断续接已保存关闭并读取 READY。人工续接不算完整自动链路验收。
|
||||
- [ ] 在主应用显示候选时间和手动保存/自动保存/取消按钮。没有 UI 选择入口的调用保持待选择,不自动选版本;每个原生窗口只问一次,等待期间继续观察会话。
|
||||
- [ ] 原生动作仍由私有桌面代理执行,核对修复证明、进程、窗口和候选版本;先选择单选项并复读,再确认 OK;取消或窗口变化不确认恢复。
|
||||
- [ ] 用户选择后沿原校验链路继续,原生保存提示仍由已有监督器处理。最终 READY 保持原有门槛;使用历史 PCB 版本记录“已恢复,版本待核对”,不标记无损修复。
|
||||
- [ ] 测试 UI 取消、手动/自动选择、选择失效、重复弹窗、错 PID/桌面、原生失败和 READY 区分;独立审查、全量回归、冻结实际按钮验证并交付候选。
|
||||
|
||||
采用独立版本选择控制器与 Qt 对话框,复用原生代理及现有进度信号;不引入前台鼠标或自动重导入。界面只要求选择已有候选版本,不替用户推断应采用哪个版本。
|
||||
@@ -236,6 +236,14 @@ class DialogActionExecutor:
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
|
||||
channels = tuple(action.get("channels", ()))
|
||||
action_name = action.get("action")
|
||||
if action_name == 'user_selected_pcb_version':
|
||||
try:
|
||||
from .pcb_restore_prompt import validate_action_window
|
||||
if channels != ('win32_button_click',):
|
||||
raise ValueError('PCB_VERSION_ACTION_CHANNEL_MISMATCH')
|
||||
validate_action_window(snapshot, action)
|
||||
except Exception as error:
|
||||
return ActionResult(error_code='PCB_VERSION_CHOICE_REQUIRED', detail=str(error))
|
||||
if action_name == 'post_repair_local_read_write':
|
||||
try:
|
||||
from .post_repair_consent import validate_action_window
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""User-requested native inspection of a project with an existing advertisement.
|
||||
"""User-requested native inspection with or without an existing advertisement.
|
||||
|
||||
An advertisement is never deleted, quarantined or called stale by this module.
|
||||
Exclusive access permits a backed-up official inspection, not ordinary Verify.
|
||||
Exclusive access and exact project binding permit an official inspection.
|
||||
"""
|
||||
from contextlib import contextmanager, ExitStack
|
||||
from dataclasses import asdict, replace
|
||||
@@ -34,7 +34,8 @@ def assert_native_idle():
|
||||
automation = name in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
'--verify-worker', '--repair-worker', '--management-worker')):
|
||||
owners.append({'pid': int(item.ProcessId), 'name': str(item.Name)})
|
||||
owners.append({'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or '')})
|
||||
if owners:
|
||||
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
|
||||
|
||||
@@ -113,6 +114,15 @@ def select_maintenance_target(request):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
|
||||
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
|
||||
addresses = _scoped_addresses(request)
|
||||
if not addresses:
|
||||
# A crashed project may retain its internal open state after the server
|
||||
# advertisement disappears. Explicit maintenance must still inspect it.
|
||||
references = re.findall(r'^KEY ProjectFile "([^"\r\n]+)"', _project_text(pcb), re.M)
|
||||
if len(references) != 1 or (pcb.parent/references[0]).resolve() != project.resolve():
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: PCB 的 ProjectFile 未唯一指向所选主工程')
|
||||
if len(candidates) != 1:
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 无地址记录且存在多个工程数据库,不能推测修复目标')
|
||||
return candidates[0], project, pcb, addresses
|
||||
if len(addresses) != 1:
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 需要唯一工程地址记录;共享或多个数据库不能推测修复')
|
||||
matches = [target for target in candidates
|
||||
@@ -153,6 +163,10 @@ def maintenance_target_guard(request, expected=None):
|
||||
|
||||
|
||||
def maintenance_needed(request):
|
||||
# An explicit maintenance request must reach native inspection even when
|
||||
# no address/checkpoint remains. Selection and ownership are guarded later.
|
||||
if request.maintenance is True:
|
||||
return True
|
||||
from .library_lock import has_blocker
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
from .verify_runner import preflight
|
||||
@@ -198,8 +212,8 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
json.dump({'intent': 'explicit_maintenance', 'target': asdict(target),
|
||||
'maintenance_context': context}, stream, default=str, ensure_ascii=False)
|
||||
emit('native_repair_start', detail='核对占用后由官方工具检查/修复;应用不自动备份')
|
||||
# Repeat immediately before dispatch; worker repeats after complete
|
||||
# backup and before launching its native process as well.
|
||||
# Repeat immediately before dispatch; the worker repeats before
|
||||
# launching the native process as well.
|
||||
with maintenance_target_guard(request, context): pass
|
||||
recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin,
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=progress,
|
||||
@@ -227,6 +241,17 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||
recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED',
|
||||
validation_passed=good, validation_evidence=str(verified.evidence_path or ''))
|
||||
if good and verified.evidence_path:
|
||||
restored = Path(verified.evidence_path).parent/'pcb-version-restoration.json'
|
||||
if restored.exists():
|
||||
version = json.loads(restored.read_text(encoding='utf-8'))
|
||||
if (version.get('confirm_sent') is not True or version.get('historical_restore') is not True
|
||||
or Path(version['project']).resolve() != checked['project'].resolve()
|
||||
or version.get('choice') not in ('last_user_saved', 'autosave')):
|
||||
raise ValueError('PCB_VERSION_RESTORATION_EVIDENCE_INVALID')
|
||||
recovery.update(status='RESTORED_REVIEW_REQUIRED', pcb_version=version)
|
||||
verified = replace(verified, stdout=verified.stdout +
|
||||
f'\n已按用户选择恢复 PCB({version["date"]})并通过校验;版本待核对。')
|
||||
if verified.error_category == 'PCB_VERSION_CHOICE_REQUIRED':
|
||||
owner_safe = False
|
||||
good = False
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Explicit user choice for the owned PCB's native historical-version prompt."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
import time
|
||||
|
||||
from .dialog_rules import pcb_version_choice
|
||||
|
||||
|
||||
class RestoreChoice:
|
||||
def __init__(self, block, library, candidates):
|
||||
self.block, self.library = block, library
|
||||
self.candidates = tuple(dict(c) for c in candidates)
|
||||
self.decision = None
|
||||
self._lock = Lock()
|
||||
|
||||
def choose(self, kind):
|
||||
if kind != 'cancel' and not any(c['kind'] == kind and c['enabled'] for c in self.candidates):
|
||||
raise ValueError('Unknown or disabled PCB restoration version')
|
||||
with self._lock:
|
||||
if self.decision is None:
|
||||
self.decision = kind
|
||||
|
||||
|
||||
def _candidate_key(candidates):
|
||||
return tuple((c['kind'], c['control_id'], c['label'], c['date'], c['enabled']) for c in candidates)
|
||||
|
||||
|
||||
def _choice(snapshot):
|
||||
choice = pcb_version_choice(snapshot)
|
||||
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
|
||||
if (choice is None or any(c.control_id not in (6212, 6213, 6206, 1, 2) for c in buttons)
|
||||
or len([c for c in buttons if c.control_id == 1 and c.enabled and c.name == 'OK']) != 1):
|
||||
raise ValueError('PCB_VERSION_PROMPT_CHANGED')
|
||||
return choice
|
||||
|
||||
|
||||
class RestoreController:
|
||||
def __init__(self, job):
|
||||
from .post_repair_consent import _validate_grant
|
||||
self.job = job
|
||||
self.grant = _validate_grant(job)
|
||||
self.prompt = None
|
||||
self.original = None
|
||||
self.selection_sent = self.confirm_sent = self.failed = False
|
||||
self.sent_at = 0.0
|
||||
|
||||
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, companion_pids, show, perform):
|
||||
from . import post_repair_consent as consent
|
||||
from .dialog_supervisor import DialogPollResult
|
||||
from .management import _write_json
|
||||
try:
|
||||
choice = _choice(snapshot)
|
||||
if sum(c['selected'] for c in choice['candidates']) > 1:
|
||||
raise ValueError('PCB_VERSION_SELECTION_AMBIGUOUS')
|
||||
if self.failed or snapshot.pid != target_pid or len(snapshots) != 1:
|
||||
raise ValueError('PCB_VERSION_OWNER_OR_WINDOW_UNCONFIRMED')
|
||||
if self.original is not None and (snapshot.hwnd != self.original.hwnd
|
||||
or snapshot.pid != self.original.pid
|
||||
or _candidate_key(choice['candidates']) != _candidate_key(self.prompt.candidates)):
|
||||
raise ValueError('PCB_VERSION_CANDIDATES_CHANGED')
|
||||
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
|
||||
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
|
||||
or pre.get('worker_pid') != worker_pid or pre.get('supervisor_pid') != self.job['supervisor_pid']
|
||||
or pre.get('addresses') != []
|
||||
or not all(consent._same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
|
||||
raise ValueError('PCB_VERSION_PRELAUNCH_PROOF_INVALID')
|
||||
consent._validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
|
||||
if self.prompt is None:
|
||||
self.original = snapshot
|
||||
self.prompt = RestoreChoice(self.job['block_name'], self.job['lmc_file'], choice['candidates'])
|
||||
show(self.prompt)
|
||||
if self.prompt.decision is None:
|
||||
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
|
||||
if self.prompt.decision == 'cancel':
|
||||
raise ValueError('用户取消 PCB 版本选择;未确认恢复,保留原生现场。')
|
||||
selected = next(c for c in choice['candidates'] if c['kind'] == self.prompt.decision)
|
||||
if not selected['enabled']:
|
||||
raise ValueError('PCB_VERSION_DISABLED')
|
||||
if self.confirm_sent:
|
||||
if time.monotonic()-self.sent_at < 2:
|
||||
return DialogPollResult(activity=False, observed_snapshots=tuple(snapshots))
|
||||
raise ValueError('PCB_VERSION_CONFIRMATION_NOT_COMPLETED')
|
||||
if self.selection_sent and not selected['selected']:
|
||||
if time.monotonic()-self.sent_at < 2:
|
||||
return DialogPollResult(activity=False, observed_snapshots=tuple(snapshots))
|
||||
raise ValueError('PCB_VERSION_SELECTION_NOT_CONFIRMED')
|
||||
confirming = selected['selected'] and sum(c['selected'] for c in choice['candidates']) == 1
|
||||
control = 1 if confirming else selected['control_id']
|
||||
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
|
||||
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
|
||||
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
|
||||
self.selection_sent = True
|
||||
self.confirm_sent = confirming
|
||||
self.sent_at = time.monotonic()
|
||||
record = {'project': self.job['project'], 'pcb': self.job['pcb'], 'choice': selected['kind'],
|
||||
'date': selected['date'], 'historical_restore': True, 'confirm_sent': confirming,
|
||||
'snapshot': snapshot.to_record()}
|
||||
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', record)
|
||||
result = perform(snapshot, action, snapshot.phase)
|
||||
if result.error_code or result.accepted_controls != (control,):
|
||||
self.failed = True
|
||||
return DialogPollResult(error_code=result.error_code or 'PCB_VERSION_ACTION_FAILED', detail=result.detail,
|
||||
snapshot=snapshot, observed_snapshots=tuple(snapshots))
|
||||
if confirming:
|
||||
_write_json(Path(self.job['root'])/'pcb-version-restoration.json', record)
|
||||
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
|
||||
action=action['action'], channel=result.channel, accepted_controls=result.accepted_controls,
|
||||
rule_id='explicit-user-pcb-version', observed_snapshots=tuple(snapshots))
|
||||
except Exception as error:
|
||||
self.failed = True
|
||||
return DialogPollResult(error_code='PCB_VERSION_CHOICE_REQUIRED', detail=str(error),
|
||||
snapshot=snapshot, observed_snapshots=tuple(snapshots))
|
||||
|
||||
|
||||
def validate_action_window(snapshot, action):
|
||||
"""Recheck the exact live window and radio selection on the private desktop."""
|
||||
import win32gui, win32process
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .dialog_models import ControlSnapshot
|
||||
if (not str(action.get('desktop', '')).startswith('CbbVerify_')
|
||||
or _current_desktop_name() != action.get('desktop') or snapshot.pid != action.get('pid')
|
||||
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
|
||||
or win32gui.GetWindowText(snapshot.hwnd) != snapshot.title
|
||||
or win32gui.GetClassName(snapshot.hwnd) != snapshot.window_class
|
||||
or not win32gui.IsWindowVisible(snapshot.hwnd)):
|
||||
raise ValueError('PCB_VERSION_LIVE_WINDOW_MISMATCH')
|
||||
children = []
|
||||
win32gui.EnumChildWindows(snapshot.hwnd, lambda h, _: children.append(int(h)), None)
|
||||
live = []
|
||||
for h in children:
|
||||
control_id = win32gui.GetDlgCtrlID(h) & 0xFFFF
|
||||
checked = False
|
||||
if control_id in (6213, 6206):
|
||||
value = win32gui.SendMessageTimeout(h, 0x00F0, 0, 0, 2, 1000)
|
||||
checked = (value[-1] if isinstance(value, tuple) else value) == 1
|
||||
live.append(ControlSnapshot(h, control_id, win32gui.GetClassName(h), win32gui.GetWindowText(h),
|
||||
enabled=bool(win32gui.IsWindowEnabled(h)), checked=checked))
|
||||
choice = _choice(replace(snapshot, controls=tuple(live)))
|
||||
if _candidate_key(choice['candidates']) != _candidate_key(action.get('candidates', [])):
|
||||
raise ValueError('PCB_VERSION_LIVE_CANDIDATES_CHANGED')
|
||||
selected = next((c for c in choice['candidates'] if c['kind'] == action.get('choice') and c['enabled']), None)
|
||||
control_id = action.get('target', {}).get('control_id')
|
||||
if selected is None or control_id not in (selected['control_id'], 1):
|
||||
raise ValueError('PCB_VERSION_ACTION_MISMATCH')
|
||||
if control_id == 1 and (not selected['selected'] or sum(c['selected'] for c in choice['candidates']) != 1):
|
||||
raise ValueError('PCB_VERSION_LIVE_SELECTION_MISMATCH')
|
||||
target = next(c for c in live if c.control_id == control_id)
|
||||
if target.handle != next(c.handle for c in snapshot.controls if c.control_id == control_id):
|
||||
raise ValueError('PCB_VERSION_CONTROL_CHANGED')
|
||||
@@ -26,6 +26,7 @@ from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reas
|
||||
|
||||
class ProgressSignals(QObject):
|
||||
event = Signal(object)
|
||||
version_choice = Signal(object)
|
||||
|
||||
|
||||
STATUS_LABELS = {
|
||||
@@ -93,6 +94,8 @@ class MainWindow(QWidget):
|
||||
self._global_icdb_run = False
|
||||
self._icdb_completed = 0
|
||||
self.signals = ProgressSignals(self); self.signals.event.connect(self._progress)
|
||||
self.signals.version_choice.connect(self._show_version_choice)
|
||||
self.version_dialog = None
|
||||
self.lmc_edit = QLineEdit()
|
||||
self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9'))
|
||||
self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', ''))
|
||||
@@ -613,8 +616,8 @@ class MainWindow(QWidget):
|
||||
f'{MANUAL_BACKUP_NOTICE}\nMentor 原生修复可能生成自身备份。\n\n当前中心库:{self.loaded_path}\n\n'
|
||||
f'将检查 {len(names)} 个可见非 READY CBB'
|
||||
f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n'
|
||||
'无地址阻止时逐项校验;已有工程地址记录时先核对所有者和独占访问,'
|
||||
'再由官方工具确认未占用并检查/修复。不会删除地址文件。\n'
|
||||
'逐项核对工程身份、所有者和独占访问,再由官方工具检查/修复一次,成功后重新打开校验。'
|
||||
'没有地址记录也会检查;多个数据库无法明确目标时停止,不猜测或删除地址文件。\n'
|
||||
'仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。'
|
||||
'网络盘、UNC 或链接路径不自动确认该提示。\n'
|
||||
'共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;'
|
||||
@@ -707,7 +710,8 @@ class MainWindow(QWidget):
|
||||
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
|
||||
verify = self.verifier or (lambda req: run_verify(
|
||||
req, progress=lambda e: self.signals.event.emit(e),
|
||||
flag_reader=read_library_flag_if_available))
|
||||
flag_reader=read_library_flag_if_available,
|
||||
version_prompt=self.signals.version_choice.emit))
|
||||
def verifier(req):
|
||||
if maintenance:
|
||||
self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'})
|
||||
@@ -893,7 +897,19 @@ class MainWindow(QWidget):
|
||||
self.summary.setAttribute(Qt.WA_ShowWithoutActivating)
|
||||
self.summary.show()
|
||||
|
||||
def _show_version_choice(self, choice):
|
||||
from .pcb_restore_dialog import PcbRestoreDialog
|
||||
if not self.busy or self.stop.is_set():
|
||||
choice.choose('cancel')
|
||||
return
|
||||
self.version_dialog = PcbRestoreDialog(choice, self)
|
||||
self.status_label.setText(f'{choice.block}:等待选择 PCB 恢复版本。')
|
||||
self.icdb_phase.setText(f'{choice.block} · 等待选择 PCB 恢复版本')
|
||||
self.version_dialog.show()
|
||||
|
||||
def request_stop(self):
|
||||
if self.version_dialog is not None:
|
||||
self.version_dialog.reject()
|
||||
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
|
||||
|
||||
def _failed(self, error):
|
||||
@@ -903,6 +919,9 @@ class MainWindow(QWidget):
|
||||
if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error)
|
||||
|
||||
def _finished(self):
|
||||
if self.version_dialog is not None:
|
||||
self.version_dialog.reject()
|
||||
self.version_dialog = None
|
||||
self.busy = False; self._update()
|
||||
if self._reload_after_maintenance:
|
||||
from PySide6.QtCore import QTimer
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Show the native version dates without preselecting a recovery version."""
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
|
||||
class PcbRestoreDialog(QMessageBox):
|
||||
def __init__(self, choice, parent=None):
|
||||
super().__init__(parent)
|
||||
self.choice = choice
|
||||
self.setWindowTitle('选择 PCB 恢复版本')
|
||||
self.setIcon(QMessageBox.Question)
|
||||
candidates = {c['kind']: c for c in choice.candidates}
|
||||
manual, auto = candidates['last_user_saved'], candidates['autosave']
|
||||
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
|
||||
'原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n'
|
||||
f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n'
|
||||
'选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。'
|
||||
'\n取消将停止本项并保留原生现场,不自动选取版本。')
|
||||
self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole)
|
||||
self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole)
|
||||
self.manual_button.setEnabled(manual['enabled'])
|
||||
self.auto_button.setEnabled(auto['enabled'])
|
||||
self.cancel_button = self.addButton(QMessageBox.Cancel)
|
||||
self.setDefaultButton(self.cancel_button)
|
||||
self.setEscapeButton(self.cancel_button)
|
||||
self.buttonClicked.connect(self._chosen)
|
||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||
self.setModal(True)
|
||||
|
||||
def _chosen(self, button):
|
||||
self.choice.choose('last_user_saved' if button is self.manual_button else
|
||||
'autosave' if button is self.auto_button else 'cancel')
|
||||
@@ -506,7 +506,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
|
||||
|
||||
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None):
|
||||
dialog_supervisor_factory=None, version_prompt=None):
|
||||
# Cover contents checking, native work and final state reads with one
|
||||
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
|
||||
import win32event, win32con
|
||||
@@ -532,7 +532,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
return run_existing_address_maintenance(request, progress=progress,
|
||||
verify=lambda req: _run_verify_serialized(req, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory))
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt))
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
if Path(request.lmc_file).is_file():
|
||||
try:
|
||||
@@ -544,7 +544,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
result = _run_verify_serialized(
|
||||
request, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory)
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
|
||||
and result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
and result.evidence_path):
|
||||
@@ -580,7 +580,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
result = _run_verify_serialized(
|
||||
replace(request, auto_repair=False, maintenance=False), progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory)
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
recovery['validation_evidence'] = str(result.evidence_path or '')
|
||||
recovery['validation_passed'] = (result.status == 'PASS'
|
||||
and result.library_flag == 'GREEN' and result.safe_to_continue)
|
||||
@@ -636,11 +636,11 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
|
||||
|
||||
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
port_check=None, dialog_supervisor_factory=None):
|
||||
port_check=None, dialog_supervisor_factory=None, version_prompt=None):
|
||||
timing = RunTimings()
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory)
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} and result.evidence_path:
|
||||
job_path = result.evidence_path.with_name('request.json')
|
||||
if job_path.is_file():
|
||||
@@ -706,7 +706,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
|
||||
|
||||
def _run_verify(request, *, timing, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None):
|
||||
dialog_supervisor_factory=None, version_prompt=None):
|
||||
"""Refresh one CBB and record its evidence.
|
||||
|
||||
``flag_reader`` is a read-only probe returning an authoritative ``BridgeResult``.
|
||||
@@ -853,6 +853,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
deadline = ActivityDeadline(request.timeout_seconds)
|
||||
last_activity_key = None
|
||||
phase = DialogPhase.PCB_STARTING
|
||||
restore_controller = None
|
||||
dialog_agent = None
|
||||
latest_snapshots = ()
|
||||
if dialog_supervisor_factory is None:
|
||||
@@ -950,6 +951,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
from .dialog_rules import archive_version_choice
|
||||
choice_path = archive_version_choice(dialog_result.snapshot, root)
|
||||
dialog_result = replace(dialog_result, detail=dialog_result.detail + f'\n版本候选与原生窗口证据:{choice_path}')
|
||||
if (version_prompt is not None and consent is not None and dialog_agent is not None
|
||||
and dialog_result.snapshot.hwnd in {int(h) for h in process.desktop.EnumDesktopWindows()}):
|
||||
from .pcb_restore_prompt import RestoreController
|
||||
if restore_controller is None:
|
||||
restore_controller = RestoreController(job)
|
||||
dialog_result = restore_controller.handle(dialog_result.snapshot,
|
||||
dialog_result.observed_snapshots, target_pid=target_pid, launcher_pid=launcher_pid,
|
||||
worker_pid=process.pid, companion_pids=tuple(process.companion_pids),
|
||||
show=version_prompt, perform=dialog_supervisor.backend.perform)
|
||||
# Normal progress stays in memory. Only actions/errors and the
|
||||
# last failure snapshots are persisted, not every elapsed tick.
|
||||
latest_snapshots = dialog_result.observed_snapshots
|
||||
|
||||
@@ -47,21 +47,25 @@ def case(tmp_path, monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
|
||||
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config):
|
||||
@pytest.mark.parametrize('advertisement', ['present', 'absent'])
|
||||
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config, advertisement):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
if advertisement == 'absent':
|
||||
address.unlink()
|
||||
if pcb_config == 'legacy_template':
|
||||
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
|
||||
calls = []
|
||||
def repair(target, root, **kwargs):
|
||||
calls.append('repair')
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
assert kwargs['maintenance_context']['addresses'][str(address.resolve())]['sha256']
|
||||
# Native boundary fake simulates official removal of its address.
|
||||
native_repair.backup_project(target, root/'complete-backup')
|
||||
assert (root/'complete-backup/database/cdbsvr/sAddress.adr').read_bytes() == address.read_bytes()
|
||||
address.unlink()
|
||||
if advertisement == 'present':
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
assert kwargs['maintenance_context']['addresses'][str(address.resolve())]['sha256']
|
||||
address.unlink() # Simulated native release, never a production cleanup.
|
||||
else:
|
||||
assert kwargs['maintenance_context']['addresses'] == {}
|
||||
assert target.project == project
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a:
|
||||
@@ -82,6 +86,40 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
|
||||
assert 'session' not in record['maintenance_context']
|
||||
|
||||
|
||||
def test_addressless_target_binds_unique_project_and_rejects_new_address(case):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
with maintenance_target_guard(request) as checked:
|
||||
context = checked['context']
|
||||
assert checked['target'].project == project and context['addresses'] == {}
|
||||
address.write_bytes(b'owner appeared after preflight')
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
|
||||
with maintenance_target_guard(request, context): pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference', ['', 'KEY ProjectFile "../Other.prj"\n',
|
||||
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
|
||||
def test_addressless_target_requires_exact_pcb_back_reference(case, reference):
|
||||
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
(project.parent/'PCB/IP101GR.pcb').write_text(reference)
|
||||
with pytest.raises(ValueError, match='PCB.*ProjectFile'):
|
||||
select_maintenance_target(request)
|
||||
|
||||
|
||||
def test_addressless_multiple_project_databases_are_not_guessed(case):
|
||||
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
(project.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "database"\n')
|
||||
database = project.parent/'PCB/database'; database.mkdir()
|
||||
(database/'icdb.dat').write_bytes(b'another native database')
|
||||
with pytest.raises(ValueError, match='多个工程数据库'):
|
||||
select_maintenance_target(request)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('back_reference', ['', 'KEY ProjectFile "../other.prj"\n',
|
||||
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
|
||||
def test_legacy_maintenance_requires_unambiguous_pcb_back_reference(case, back_reference):
|
||||
@@ -328,3 +366,22 @@ def test_successful_icdb_repair_then_version_choice_reports_partial_completion(c
|
||||
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['status'] == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
|
||||
|
||||
def test_user_chosen_pcb_history_is_not_reported_as_lossless_repair(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda target, *a, **k: complete_native_success(target))
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
def verify(*a, **k):
|
||||
root = request.evidence_dir/'verify'; root.mkdir(exist_ok=True)
|
||||
(root/'pcb-version-restoration.json').write_text(json.dumps({'project': str(project),
|
||||
'choice': 'last_user_saved', 'date': '2026/9/24 23:06', 'confirm_sent': True, 'historical_restore': True}))
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=root/'result.json')
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'PASS'
|
||||
assert result.recovery_attempts[0]['status'] == 'RESTORED_REVIEW_REQUIRED'
|
||||
assert result.recovery_attempts[0]['pcb_version']['choice'] == 'last_user_saved'
|
||||
@@ -0,0 +1,132 @@
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from test_pcb_version_choice import captured
|
||||
from test_post_repair_consent import context, no_native_launch
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session(context, monkeypatch):
|
||||
from cbb_refresh_verify import post_repair_consent as consent
|
||||
from cbb_refresh_verify.pcb_restore_prompt import RestoreController
|
||||
_, _, proof, job = context
|
||||
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
|
||||
monkeypatch.setattr(consent, '_validate_current_processes', lambda *a: None)
|
||||
snapshot = captured()
|
||||
controller = RestoreController(job)
|
||||
prompts, calls = [], []
|
||||
def perform(snap, payload, phase):
|
||||
calls.append(payload)
|
||||
return SimpleNamespace(accepted_controls=(payload['target']['control_id'],),
|
||||
channel='win32_button_click', error_code='', detail='')
|
||||
def poll(snap=snapshot, snapshots=None):
|
||||
return controller.handle(snap, snapshots or (snap,), target_pid=snapshot.pid,
|
||||
launcher_pid=10, worker_pid=__import__('os').getpid(), companion_pids=(),
|
||||
show=prompts.append, perform=perform)
|
||||
return controller, snapshot, prompts, calls, poll, job
|
||||
|
||||
|
||||
def test_waits_for_user_once_and_rechecks_radio_before_confirm(session):
|
||||
controller, snapshot, prompts, calls, poll, job = session
|
||||
assert not poll().error_code
|
||||
poll()
|
||||
assert len(prompts) == 1 and not calls
|
||||
prompts[0].choose('last_user_saved')
|
||||
assert poll().action_sent and calls[-1]['target']['control_id'] == 6213
|
||||
assert not poll().action_sent and len(calls) == 1
|
||||
selected = replace(snapshot, controls=tuple(replace(c, checked=c.control_id == 6213,
|
||||
selected=c.control_id == 6213) if c.control_id in (6213, 6206) else c for c in snapshot.controls))
|
||||
assert poll(selected).action_sent and calls[-1]['target']['control_id'] == 1
|
||||
assert not poll(selected).action_sent and len(calls) == 2
|
||||
result = json.loads((Path(job['root'])/'pcb-version-restoration.json').read_text(encoding='utf-8'))
|
||||
assert result['choice'] == 'last_user_saved' and result['date'] == '2026/9/24 23:06'
|
||||
assert result['historical_restore'] and result['confirm_sent']
|
||||
|
||||
|
||||
def test_cancel_never_selects_or_confirms_a_version(session):
|
||||
_, _, prompts, calls, poll, _ = session
|
||||
poll(); prompts[0].choose('cancel')
|
||||
result = poll()
|
||||
assert result.error_code == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
assert '取消' in result.detail and not calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['date', 'pid', 'window', 'extra'])
|
||||
def test_changed_native_choice_invalidates_user_answer(session, change):
|
||||
_, snapshot, prompts, calls, poll, _ = session
|
||||
poll(); prompts[0].choose('last_user_saved')
|
||||
changed = snapshot
|
||||
if change == 'date':
|
||||
changed = replace(snapshot, controls=tuple(replace(c, name=c.name.replace('23:06', '23:07'))
|
||||
if c.control_id == 6213 else c for c in snapshot.controls))
|
||||
if change == 'pid': changed = replace(snapshot, pid=snapshot.pid + 1)
|
||||
if change == 'window': changed = replace(snapshot, hwnd=snapshot.hwnd + 1)
|
||||
result = poll(changed, (changed, changed) if change == 'extra' else None)
|
||||
assert result.error_code and not calls
|
||||
|
||||
|
||||
def test_native_action_failure_never_retries_or_confirms(session):
|
||||
controller, snapshot, prompts, calls, poll, _ = session
|
||||
poll(); prompts[0].choose('last_user_saved')
|
||||
def failed(*a):
|
||||
return SimpleNamespace(accepted_controls=(), channel='', error_code='ACTION_CHANNEL_FAILED', detail='timeout')
|
||||
result = controller.handle(snapshot, (snapshot,), target_pid=snapshot.pid, launcher_pid=10,
|
||||
worker_pid=__import__('os').getpid(), companion_pids=(), show=prompts.append, perform=failed)
|
||||
assert result.error_code == 'ACTION_CHANNEL_FAILED'
|
||||
assert poll().error_code and not calls
|
||||
|
||||
|
||||
def test_version_dialog_shows_dates_and_explicit_choices(qtbot):
|
||||
from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice
|
||||
from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog
|
||||
from cbb_refresh_verify.dialog_rules import pcb_version_choice
|
||||
choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates'])
|
||||
dialog = PcbRestoreDialog(choice)
|
||||
qtbot.addWidget(dialog)
|
||||
assert '2026/9/24 23:06' in dialog.text()
|
||||
assert choice.decision is None
|
||||
dialog.manual_button.click()
|
||||
assert choice.decision == 'last_user_saved'
|
||||
|
||||
|
||||
def test_closing_version_dialog_is_cancel_not_a_default_selection(qtbot):
|
||||
from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice
|
||||
from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog
|
||||
from cbb_refresh_verify.dialog_rules import pcb_version_choice
|
||||
choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates'])
|
||||
dialog = PcbRestoreDialog(choice)
|
||||
qtbot.addWidget(dialog)
|
||||
dialog.reject()
|
||||
assert choice.decision == 'cancel'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'date', 'disabled', 'selection', 'channel'])
|
||||
def test_private_agent_rechecks_live_version_before_confirmation(monkeypatch, change):
|
||||
import win32gui, win32process
|
||||
from cbb_refresh_verify.dialog_agent import DialogActionExecutor
|
||||
from cbb_refresh_verify.dialog_rules import pcb_version_choice
|
||||
snapshot = replace(captured(), controls=tuple(replace(c, checked=c.control_id == 6213,
|
||||
selected=c.control_id == 6213) if c.control_id in (6213, 6206) else c for c in captured().controls))
|
||||
controls = {c.handle: c for c in snapshot.controls if c.handle and c.class_name in ('Static', 'Button')}
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name',
|
||||
lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture')
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, snapshot.pid + (change == 'pid')))
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: snapshot.window_class if h == snapshot.hwnd else controls[h].class_name)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: snapshot.title if h == snapshot.hwnd else
|
||||
controls[h].name.replace('23:06', '23:07') if change == 'date' else controls[h].name)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: True)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: not (change == 'disabled' and controls[h].control_id == 6213))
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: controls[h].control_id)
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, callback, arg: [callback(c, arg) for c in controls])
|
||||
monkeypatch.setattr(win32gui, 'SendMessageTimeout', lambda h, *a: int(controls[h].control_id == (6206 if change == 'selection' else 6213)))
|
||||
calls = []
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: calls.append(a))
|
||||
action = {'action': 'user_selected_pcb_version', 'channels': ['uia_invoke' if change == 'channel' else 'win32_button_click'],
|
||||
'target': {'control_id': 1}, 'pid': snapshot.pid, 'desktop': 'CbbVerify_fixture',
|
||||
'choice': 'last_user_saved', 'candidates': pcb_version_choice(snapshot)['candidates']}
|
||||
result = DialogActionExecutor().perform(snapshot, action)
|
||||
assert bool(result.accepted_controls) is (change == '')
|
||||
assert len(calls) == (1 if change == '' else 0)
|
||||
Reference in new issue
Block a user