fix: stabilize ICDB preflight and organize UI into tabs
This commit is contained in:
1 parent
29959e2988
commit
223655fe00
10 files changed
+352
-57
No files matched your search
@@ -0,0 +1,39 @@
|
||||
# 三页界面与原生检查、退出修正
|
||||
|
||||
界面按“检验 / ICDB 维护 / 中心库管理”横向切换,共用中心库、清单、搜索和选择状态。默认收起运行日志,长状态信息限制高度,避免纵向堆叠操作区或报错撑长窗口。1000×620 布局预览保存在本轮诊断目录中。
|
||||
|
||||
## 本轮现场日志定位
|
||||
|
||||
用户运行的是 `29959e2` 冻结包。2026-11-04 14:21(北京时间)的维护在原生检查启动后报 `(2, 'EnumWindows', '系统找不到指定的文件。')`,并没有调用 Repair。随后手动释放检查发现 `1GPHY_8212`、`IP101GR` 的地址记录仍存在;它们不能直接当作已释放或直接删除。第二次在准备检查时取消,助手没有及时结束文件扫描。
|
||||
|
||||
## 修正
|
||||
|
||||
- 在实际空私有桌面复现了 Win32 旧错误码问题:先 `SetLastError(2)` 再枚举空桌面,pywin32 会报与现场相同的错误。现在枚举前清零旧错误;真实枚举异常继续上报,不把未知错误当作空闲。
|
||||
- 将取消信号传入修复助手的文件扫描。文件标记最多每 100 毫秒读取一次,取消后锁存;原生启动、Repair 命令和确认前仍立即读取取消信号。冻结实测曾因逐文件读取取消标记而在启动前超时,节流后已推进至实际原生检查和 Repair。
|
||||
- 手动备份模式下,助手只在启动前执行一次完整目标保护,移除原先自动备份取消后留下的重复检查。同一保护内复用初始完整扫描作地址和文件选择,取得全部独占读句柄后再做第二次完整扫描;地址变化或原生文件集合增删均停止。没有复用跨操作的旧快照。
|
||||
- 发出唯一正常关闭请求前仍严格确认任务进程、工程、私有桌面、空闲窗口和地址状态。关闭后只等待进程、启动器及地址释放,不再因退出途中 WMI 暂时缺少命令行而提前报身份未确认,也不再次关闭窗口。未实际退出仍保留未释放状态。
|
||||
|
||||
## 已有验证记录
|
||||
|
||||
本轮证据目录为 `diagnostics/tabs-release-20261104/`,含本机路径,不提交原始数据。
|
||||
|
||||
- 初轮完整回归 1,200 项通过,2 项旧测试替身未接收取消参数;同步接口后维护模块 48 项通过。
|
||||
- 扫描优化后的维护、原生修复等相关测试 225 项通过;随后退出等待等 91 项通过。包含实际私有桌面的 Win32 回归,而不只是窗口模拟。
|
||||
- 冻结程序取消试验 `frozen-cancel-local`:预检查中取消约 0.61 秒返回,未启动原生 Repair,应用正常退出。
|
||||
- 源码实际入口 `source-optimized`:原生确认未占用并要求修复,Repair 成功,按用户授权恢复最后手动保存版本;最终因 verified/once-verified CBB 禁止 BackAnnotate 失败。PCB 正常关闭,没有附加 PCB 释放未确认错误。
|
||||
- 冻结实际入口 `frozen-polling`:原生检查及 Repair 已完成,取消标记只读取 214 次、耗时 0.313 秒。随后 PCB 因数据库服务器启动晚于客户端截止时间而加载失败。服务器日志显示它后来实际启动并自行关闭,不据此宣称完整修复通过。
|
||||
- 同一次失败退出中,先记录了 `startup_close_requested`,随后 WMI 缺少进程信息导致 `STARTUP_PROCESS_UNCONFIRMED`,下一秒却已确认进程退出;该具体时序已转为回归测试。
|
||||
|
||||
最终完整回归:**1,207 passed**,588.26 秒,仅既有 pywinauto STA 警告;记录在 `pytest-final.log` / `pytest-final-result.json`。最终冻结构建、启动退出冒烟和 6 个关键模块的源码一致性检查通过。独立审查未发现剩余必要缺陷。
|
||||
|
||||
最终冻结实际入口为 `frozen-local-final`,使用 `C:\Temp\CbbTabsRelease20261104\library` 的独立副本:原生 `NOT_IN_USE` 且明确要求修复 → Repair 完成并释放 → 重新打开同一 PCB → 用户已授权的最后手动保存版本(2026/9/24 15:15)→ SynchCES / LoadCES → BackAnnotate 被原生拒绝。最终 **FAIL / UNKNOWN / REPAIR_VALIDATION_FAILED**,未取得 READY;退出记录确认进程结束,没有附加 `PCB_RELEASE_UNCONFIRMED`。应用正常退出返回 0。此前服务器迟启动的失败记录保留,不能从一次对照断定其全部成因。
|
||||
|
||||
原库 255 个已记录主要文件哈希复核全部未变,见 `source-final-check.json`。
|
||||
|
||||
最终包的 `frozen-cancel-final` 再次验证取消:约 1.16 秒返回,检查助手报告 `CANCELLED`,批次保持 `BLOCKED`,未启动 Repair,应用正常退出。取消只证明操作已停止,不计作修复成功。
|
||||
|
||||
## 验收限制
|
||||
|
||||
原库未执行本轮自动化写入。第一套 F 盘测试副本出现目录枚举属性与直接读取属性不一致,被链接检查阻止,未绕过检查。测试随后迁移到独立本机目录;`C:\Users` 目录会被 Mentor 转成共享路径,因此最终试验选择独立的 `C:\Temp` 路径,并保留前序失败记录。
|
||||
|
||||
完整 ICDB 修复仍必须取得权威 READY;原生 Repair 成功、能够取消、正常关闭或界面测试通过都不能替代该验收。未合并发布,工单保持未解决。
|
||||
@@ -32,7 +32,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
session. Unknown windows, live database addresses and other desktops are
|
||||
retained. WM_CLOSE is cooperative; no save prompt is accepted or killed.
|
||||
"""
|
||||
import win32con, win32gui, win32process
|
||||
import win32api, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
@@ -86,18 +86,19 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
break
|
||||
time.sleep(.2)
|
||||
continue
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if not sent:
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||
and win32gui.IsWindowVisible(hwnd)):
|
||||
windows.append(hwnd)
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
|
||||
and win32gui.GetWindowText(w).strip() in (
|
||||
@@ -112,6 +113,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '':
|
||||
window['rect'] = list(win32gui.GetWindowRect(window['hwnd']))
|
||||
window['children'] = []
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(window['hwnd'],
|
||||
lambda hwnd, _: window['children'].append(int(hwnd)), None)
|
||||
left, top, right, bottom = window['rect']
|
||||
@@ -126,6 +128,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
and win32gui.GetWindow(hwnd, win32con.GW_CHILD)):
|
||||
documents.append(hwnd)
|
||||
if len(main) == 1:
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and not addresses:
|
||||
@@ -135,6 +138,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
# Observe exit even when the caller requested no extra wait.
|
||||
continue
|
||||
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
||||
# After the single owned WM_CLOSE, WMI may lose the executable/
|
||||
# command fields before removing the PID. Only observe exit here;
|
||||
# never issue another close or treat missing fields as release.
|
||||
if time.monotonic() >= deadline:
|
||||
if sent:
|
||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
||||
|
||||
@@ -9,6 +9,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
@@ -43,11 +44,14 @@ def address_snapshot(paths):
|
||||
for path in paths}
|
||||
|
||||
|
||||
def _scoped_addresses(request, *, check=None):
|
||||
def _scoped_addresses(request, *, check=None, entries=None):
|
||||
from .scoped_manifest import scan_tree
|
||||
root = Path(request.lmc_file).parent
|
||||
addresses = []
|
||||
for path in scan_tree(root, check=check):
|
||||
if entries is None:
|
||||
entries = scan_tree(root, check=check)
|
||||
if check is not None: check()
|
||||
for path in entries:
|
||||
if path.name.casefold() != 'saddress.adr':
|
||||
continue
|
||||
parts = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
@@ -81,7 +85,7 @@ def maintenance_project_files(project, pcb):
|
||||
return (project,)
|
||||
|
||||
|
||||
def select_maintenance_target(request, *, check=None):
|
||||
def select_maintenance_target(request, *, check=None, entries=None):
|
||||
from .verify_runner import preflight
|
||||
from .backup_recovery import _project_text
|
||||
from .native_repair import RepairTarget
|
||||
@@ -109,7 +113,7 @@ def select_maintenance_target(request, *, check=None):
|
||||
if not (database/'icdb.dat').is_file():
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
|
||||
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
|
||||
addresses = _scoped_addresses(request, check=check)
|
||||
addresses = _scoped_addresses(request, check=check, entries=entries)
|
||||
if not addresses:
|
||||
# A crashed project may retain its internal open state after the server
|
||||
# advertisement disappears. Explicit maintenance must still inspect it.
|
||||
@@ -137,7 +141,11 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消占用检查')
|
||||
check()
|
||||
target, project, pcb, addresses = select_maintenance_target(request, check=check)
|
||||
library_root = Path(request.lmc_file).parent
|
||||
# Share one complete snapshot for target/address selection and file locks.
|
||||
# Refresh it again while the handles are held; do not reuse across guards.
|
||||
entries = scan_tree(library_root, check=check)
|
||||
target, project, pcb, addresses = select_maintenance_target(request, check=check, entries=entries)
|
||||
baseline = address_snapshot(addresses)
|
||||
context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name,
|
||||
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
|
||||
@@ -148,17 +156,21 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
|
||||
assert_native_idle()
|
||||
check()
|
||||
entries = scan_tree(Path(request.lmc_file).parent, check=check)
|
||||
files = [path for path in entries if (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')) and path.is_file()]
|
||||
def native_files(snapshot):
|
||||
return {path for path, info in snapshot.items() if stat.S_ISREG(info.st_mode) and (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))}
|
||||
files = native_files(entries)
|
||||
with ExitStack() as stack:
|
||||
for path in files:
|
||||
for path in sorted(files):
|
||||
check()
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
assert_native_idle()
|
||||
current_addresses = _scoped_addresses(request, check=check)
|
||||
current = scan_tree(library_root, check=check)
|
||||
if native_files(current) != files:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 检查期间库文件集合发生变化')
|
||||
current_addresses = _scoped_addresses(request, check=check, entries=current)
|
||||
if address_snapshot(current_addresses) != baseline:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 地址记录在检查期间变化')
|
||||
yield {'target': target, 'context': context, 'project': project, 'pcb': pcb}
|
||||
|
||||
@@ -98,7 +98,7 @@ def _repair_command(executable):
|
||||
|
||||
|
||||
def _windows(pid):
|
||||
import win32gui, win32process
|
||||
import win32api, win32gui, win32process
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
|
||||
@@ -109,10 +109,14 @@ def _windows(pid):
|
||||
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
|
||||
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
||||
# Empty window lists are valid. pywin32 otherwise interprets a stale
|
||||
# thread error (observed ERROR_FILE_NOT_FOUND) as an enum failure.
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
|
||||
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
|
||||
'children': children})
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
return windows
|
||||
|
||||
@@ -226,12 +230,35 @@ def _inspect_project(job, process, emit):
|
||||
return result
|
||||
|
||||
|
||||
class _CancellationFile:
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
self._next_poll = 0.0
|
||||
self._cancelled = False
|
||||
self.polls = 0
|
||||
self.poll_seconds = 0.0
|
||||
|
||||
def is_set(self):
|
||||
# scan_tree checks between every entry. Avoid issuing tens of
|
||||
# thousands of filesystem requests just to observe one IPC flag.
|
||||
# The direct checks before Popen/Repair remain immediate.
|
||||
now = time.monotonic()
|
||||
if not self._cancelled and now >= self._next_poll:
|
||||
self._cancelled = self.path.exists()
|
||||
finished = time.monotonic()
|
||||
self.polls += 1
|
||||
self.poll_seconds += finished-now
|
||||
self._next_poll = finished + .1
|
||||
return self._cancelled
|
||||
|
||||
|
||||
def repair_worker_main(job_path):
|
||||
import win32con, win32gui
|
||||
from .native_repair import RepairTarget, check_repair_access
|
||||
from .mentor_paths import discover_sdd_home
|
||||
from .icdb_recovery import snapshot_log
|
||||
job = json.loads(Path(job_path).read_text('utf-8'))
|
||||
stop = _CancellationFile(job['cancel_signal'])
|
||||
root = Path(job['root'])
|
||||
project, database = Path(job['project']), Path(job['database'])
|
||||
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database),
|
||||
@@ -265,17 +292,21 @@ def repair_worker_main(job_path):
|
||||
maintenance_request = VerifyRequest(Path(maintenance_context['library']),
|
||||
maintenance_context['block'], root, maintenance=True)
|
||||
emit(stage='native_preflight', detail='正在核对本次原生工具的目标及占用')
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
check_repair_access(RepairTarget(project, database))
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy',
|
||||
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
if maintenance_context is not None:
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context): pass
|
||||
# Manual backup policy leaves no mutation between preparation and
|
||||
# launch. Run the complete guard once here, retaining its identity,
|
||||
# address and exclusive-access checks immediately before Popen.
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context, stop=stop) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
emit(stage='native_preflight_complete', cancellation_polls=stop.polls,
|
||||
cancellation_poll_seconds=round(stop.poll_seconds, 3))
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
|
||||
@@ -391,6 +422,8 @@ def repair_worker_main(job_path):
|
||||
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
|
||||
except Exception as error:
|
||||
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
|
||||
result['preflight_cancellation'] = {'polls': stop.polls,
|
||||
'seconds': round(stop.poll_seconds, 3)}
|
||||
# Never terminate a repair or its database owner. Retained PID/desktop is
|
||||
# reported to the parent, including unknown native prompts.
|
||||
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
@@ -9,7 +9,8 @@ from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtGui import QColor, QIcon
|
||||
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QGroupBox, QVBoxLayout, QProgressBar, QComboBox)
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
|
||||
QTabBar, QStackedWidget, QSizePolicy)
|
||||
from PySide6.QtWidgets import QStyle
|
||||
try:
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
@@ -170,41 +171,54 @@ class MainWindow(QWidget):
|
||||
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2)
|
||||
self.status_label.setMaximumHeight(self.status_label.fontMetrics().lineSpacing()*3 + 4)
|
||||
self.status_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
# Integration emits repeated status snapshots. Keep the visible
|
||||
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
|
||||
# document without limit.
|
||||
self.output.document().setMaximumBlockCount(2000)
|
||||
layout = QFormLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addRow('中心库 .lmc', row)
|
||||
self.output.setMaximumHeight(180)
|
||||
layout = QVBoxLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
|
||||
row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addLayout(row)
|
||||
self.library_notice = QLabel()
|
||||
self.library_notice.setWordWrap(True)
|
||||
self.library_notice.setTextFormat(Qt.PlainText)
|
||||
self.library_notice.setStyleSheet('QLabel { color: #8a4b08; background: #fff3d6; padding: 6px; }')
|
||||
self.library_notice.hide()
|
||||
layout.addRow(self.library_notice)
|
||||
layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
|
||||
layout.addWidget(self.library_notice)
|
||||
self.section_tabs = QTabBar()
|
||||
self.section_tabs.setExpanding(True)
|
||||
for name in ('检验', 'ICDB 维护', '中心库管理'):
|
||||
self.section_tabs.addTab(name)
|
||||
layout.addWidget(self.section_tabs)
|
||||
filters = QHBoxLayout()
|
||||
for widget in (self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
|
||||
filters.addWidget(widget)
|
||||
layout.addRow('搜索 / 筛选', filters)
|
||||
layout.addRow(self.counts_label)
|
||||
layout.addRow('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin)
|
||||
layout.addRow(QLabel('逐项校验 CBB,完成后刷新状态。'))
|
||||
layout.addLayout(filters)
|
||||
layout.addWidget(self.counts_label)
|
||||
layout.addWidget(self.cbb_table, 1)
|
||||
self.section_stack = QStackedWidget()
|
||||
self.section_stack.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
|
||||
self.section_tabs.currentChanged.connect(self.section_stack.setCurrentIndex)
|
||||
verify_page = QWidget()
|
||||
verify_layout = QVBoxLayout(verify_page); verify_layout.setContentsMargins(0, 0, 0, 0)
|
||||
controls = QHBoxLayout()
|
||||
for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget)
|
||||
layout.addRow(controls)
|
||||
maintenance = QGroupBox('数据库维护')
|
||||
for widget in (self.selected_batch_button, self.batch_button): controls.addWidget(widget)
|
||||
controls.addStretch(); controls.addWidget(QLabel('超时')); controls.addWidget(self.timeout_spin)
|
||||
controls.addWidget(self.advanced_toggle)
|
||||
verify_layout.addLayout(controls); verify_layout.addWidget(self.advanced_panel)
|
||||
self.section_stack.addWidget(verify_page)
|
||||
maintenance = QWidget()
|
||||
maintenance_layout = QVBoxLayout(maintenance)
|
||||
maintenance_layout.setContentsMargins(0, 0, 0, 0)
|
||||
maintenance_row = QHBoxLayout()
|
||||
maintenance_row.addWidget(self.icdb_repair_button)
|
||||
description = QLabel('处理可见非 READY 项;有勾选时仅处理勾选中的可用项。未确认不等于损坏。\n操作前请手动备份;应用不自动备份。无法确认会话安全时停止。')
|
||||
description.setWordWrap(True)
|
||||
maintenance_row.addWidget(description, 1)
|
||||
maintenance_row.addWidget(self.backup_restore_button)
|
||||
maintenance_row.addWidget(self.reimport_button)
|
||||
maintenance_layout.addLayout(maintenance_row)
|
||||
maintenance_layout.addWidget(self.backup_restore_button)
|
||||
maintenance_layout.addWidget(self.reimport_button)
|
||||
self.icdb_progress = QProgressBar()
|
||||
self.icdb_progress.setVisible(False)
|
||||
self.icdb_phase = QLabel('')
|
||||
@@ -212,12 +226,13 @@ class MainWindow(QWidget):
|
||||
self.icdb_phase.setVisible(False)
|
||||
maintenance_layout.addWidget(self.icdb_progress)
|
||||
maintenance_layout.addWidget(self.icdb_phase)
|
||||
layout.addRow(maintenance)
|
||||
management = QGroupBox('CBB 管理(可处理 READY 项)')
|
||||
self.section_stack.addWidget(maintenance)
|
||||
management = QWidget()
|
||||
management_layout = QVBoxLayout(management)
|
||||
management_layout.setContentsMargins(0, 0, 0, 0)
|
||||
management_buttons = QHBoxLayout()
|
||||
self.add_button = QPushButton('新增 CBB…')
|
||||
self.update_button = QPushButton('用工程替换已选 CBB…(原生重新导入)')
|
||||
self.update_button = QPushButton('用工程替换已选 CBB…')
|
||||
self.remove_button = QPushButton('移除已选…')
|
||||
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
|
||||
widget.clicked.connect(lambda _=False, op=operation: self.manage_cbb(op))
|
||||
@@ -229,17 +244,20 @@ class MainWindow(QWidget):
|
||||
management_layout.insertWidget(0, self.management_capability_label)
|
||||
self.unfinished_label = QLabel(); self.unfinished_label.setWordWrap(True)
|
||||
management_layout.addWidget(self.unfinished_label)
|
||||
self.release_library_button = QPushButton('检查会话释放并解除协调阻止…')
|
||||
self.release_library_button = QPushButton('检查占用…')
|
||||
self.release_library_button.clicked.connect(self.check_library_release)
|
||||
management_layout.addWidget(self.release_library_button)
|
||||
layout.addRow(management)
|
||||
layout.addRow(self.status_label)
|
||||
management_buttons.addWidget(self.release_library_button)
|
||||
self.section_stack.addWidget(management)
|
||||
layout.addWidget(self.section_stack)
|
||||
layout.addWidget(self.status_label)
|
||||
self.runtime_log_toggle = QToolButton(); self.runtime_log_toggle.setText('查看运行日志')
|
||||
self.runtime_log_toggle.setCheckable(True)
|
||||
self.runtime_log_toggle.toggled.connect(self.output.setVisible)
|
||||
self.output.hide()
|
||||
layout.addRow(self.runtime_log_toggle); layout.addRow(self.output)
|
||||
layout.addRow(self.recovery_button)
|
||||
footer = QHBoxLayout()
|
||||
for widget in (self.stop_button, self.runtime_log_toggle, self.logs_button, self.recovery_button):
|
||||
footer.addWidget(widget)
|
||||
layout.addLayout(footer); layout.addWidget(self.output)
|
||||
self.lmc_edit.textChanged.connect(self._invalidate)
|
||||
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
|
||||
field.textChanged.connect(lambda _text: self._update())
|
||||
|
||||
@@ -90,6 +90,26 @@ def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypat
|
||||
assert records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exits', [True, False])
|
||||
def test_after_owned_close_transient_empty_command_waits_for_exit(tmp_path, monkeypatch, exits):
|
||||
from types import SimpleNamespace
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0.0]
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd, message))
|
||||
records[0] = (12, '', '', 11) # WMI during process teardown.
|
||||
def advance(seconds):
|
||||
ticks[0] += seconds
|
||||
if exits: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=advance))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
|
||||
assert ticks[0] > 0 and len(messages) == 1
|
||||
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
|
||||
assert 'STARTUP_PROCESS_UNCONFIRMED' not in result.get('detail', '')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['address', 'dialog', 'process'])
|
||||
def test_startup_close_waits_for_native_state_transitions(tmp_path, monkeypatch, obstacle):
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -115,6 +115,33 @@ def test_addressless_target_binds_unique_project_and_rejects_new_address(case):
|
||||
with maintenance_target_guard(request, context): pass
|
||||
|
||||
|
||||
def test_guard_reuses_full_tree_scan_but_still_refreshes_before_yield(case, monkeypatch):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
import cbb_refresh_verify.scoped_manifest as manifests
|
||||
request, _, _ = case
|
||||
scans = []
|
||||
original = manifests.scan_tree
|
||||
def scan(root, **kwargs):
|
||||
scans.append(Path(root))
|
||||
return original(root, **kwargs)
|
||||
monkeypatch.setattr(manifests, 'scan_tree', scan)
|
||||
with maintenance_target_guard(request): pass
|
||||
assert scans.count(request.lmc_file.parent) == 2
|
||||
|
||||
|
||||
def test_guard_rejects_new_native_database_appearing_during_checks(case, monkeypatch):
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
def idle():
|
||||
calls.append(1)
|
||||
if len(calls) == 2:
|
||||
(request.lmc_file.parent/'new.lmc').write_bytes(b'new native store')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', idle)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
|
||||
with entry.maintenance_target_guard(request): 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):
|
||||
@@ -284,7 +311,8 @@ def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, m
|
||||
values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
@contextmanager
|
||||
def guard(*args):
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui, '_native_output', lambda windows: output)
|
||||
@@ -293,7 +321,7 @@ def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, m
|
||||
assert any(message == win32con.WM_COMMAND for _, message in actions) is expected
|
||||
|
||||
|
||||
def test_worker_rechecks_address_after_complete_backup_before_native_launch(tmp_path, monkeypatch):
|
||||
def test_worker_rechecks_address_after_access_probe_before_native_launch(tmp_path, monkeypatch):
|
||||
from test_native_repair import repair_worker_fixture
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
@@ -301,15 +329,19 @@ def test_worker_rechecks_address_after_complete_backup_before_native_launch(tmp_
|
||||
values = json.loads(job.read_text()); values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
calls = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
|
||||
lambda *_: calls.append('access'))
|
||||
@contextmanager
|
||||
def guard(*args):
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
calls.append('guard')
|
||||
if len(calls) == 2: raise ValueError('address changed during complete backup')
|
||||
assert calls == ['access', 'guard']
|
||||
raise ValueError('address changed after access probe')
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **k: pytest.fail('mutation must stop native launch'))
|
||||
ui.repair_worker_main(job)
|
||||
assert calls == ['guard', 'guard']
|
||||
assert calls == ['access', 'guard']
|
||||
assert 'address changed' in json.loads((root/'repair-result.json').read_text())['detail']
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_empty_private_desktop_does_not_inherit_stale_windows_error(tmp_path):
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
script = tmp_path/'enumerate.py'
|
||||
result = tmp_path/'result.json'
|
||||
script.write_text(
|
||||
'import sys,json,win32api,win32gui,win32process\nfrom pathlib import Path\n'
|
||||
f'sys.path.insert(0,{str(Path("src").resolve())!r})\n'
|
||||
'from cbb_refresh_verify.native_repair_ui import _windows\n'
|
||||
'win32api.SetLastError(2)\n'
|
||||
'try:\n record={"windows":_windows(999999)}\n'
|
||||
'except Exception as error:\n record={"error":str(error)}\n'
|
||||
f'Path({str(result)!r}).write_text(json.dumps(record))\n', encoding='utf-8')
|
||||
worker = DesktopWorker([sys.executable, str(script)], 'CbbProbe_' + uuid4().hex[:12])
|
||||
try:
|
||||
assert worker.wait(timeout=20) == 0
|
||||
finally:
|
||||
worker.close()
|
||||
assert json.loads(result.read_text()) == {'windows': []}
|
||||
|
||||
|
||||
def test_real_window_enumeration_errors_still_propagate(monkeypatch):
|
||||
import win32gui, pywintypes
|
||||
from cbb_refresh_verify.native_repair_ui import _windows
|
||||
def denied(*args): raise pywintypes.error(5, 'EnumWindows', 'denied')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', denied)
|
||||
with pytest.raises(pywintypes.error): _windows(123)
|
||||
|
||||
|
||||
def test_cancel_reaches_prelaunch_scan(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
calls, interrupted = [], []
|
||||
@contextmanager
|
||||
def guard(*args, stop=None, **kwargs):
|
||||
calls.append(1)
|
||||
assert stop is not None, 'worker scan has no cancellation input'
|
||||
if len(calls) == 1:
|
||||
Path(data['cancel_signal']).touch()
|
||||
assert stop.is_set()
|
||||
interrupted.append(1)
|
||||
raise ValueError('MAINTENANCE_CANCELLED')
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('cancelled native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert interrupted == [1] and not actions
|
||||
|
||||
|
||||
def test_worker_uses_one_complete_guard_immediately_before_native_launch(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
order = []
|
||||
@contextmanager
|
||||
def guard(*args, stop=None, **kwargs):
|
||||
assert stop is not None
|
||||
order.append('guard')
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
order.append('guard_complete')
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
popen = ui.subprocess.Popen
|
||||
def launch(*args, **kwargs):
|
||||
order.append('launch')
|
||||
return popen(*args, **kwargs)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', launch)
|
||||
ui.repair_worker_main(job)
|
||||
assert order == ['guard', 'guard_complete', 'launch']
|
||||
|
||||
|
||||
def test_file_cancellation_polling_is_bounded_and_latches_cancel(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
import cbb_refresh_verify.native_repair_ui as ui
|
||||
now = [1.0]
|
||||
monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: now[0]))
|
||||
signal = ui._CancellationFile(tmp_path/'cancel.signal')
|
||||
reads = []
|
||||
signal.path = SimpleNamespace(exists=lambda: reads.append(1) or len(reads) > 1)
|
||||
for _ in range(50000):
|
||||
assert not signal.is_set()
|
||||
assert len(reads) == 1
|
||||
now[0] += .11
|
||||
assert signal.is_set()
|
||||
signal.path = SimpleNamespace(exists=lambda: pytest.fail('cancel must stay latched'))
|
||||
now[0] += 1
|
||||
assert signal.is_set()
|
||||
@@ -164,11 +164,11 @@ def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypat
|
||||
def guard(*a, **kw):
|
||||
calls.append(True)
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
if len(calls) == 2: Path(data['cancel_signal']).touch()
|
||||
Path(data['cancel_signal']).touch()
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert len(calls) == 2 and not actions
|
||||
assert len(calls) == 1 and not actions
|
||||
|
||||
|
||||
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
|
||||
def test_three_horizontal_sections_keep_one_catalog_and_only_their_actions(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
window.show()
|
||||
assert [window.section_tabs.tabText(i) for i in range(window.section_tabs.count())] == [
|
||||
'检验', 'ICDB 维护', '中心库管理']
|
||||
window.search_edit.setText('Beta')
|
||||
window.select_visible_button.click()
|
||||
for index, visible, hidden in (
|
||||
(0, window.batch_button, window.icdb_repair_button),
|
||||
(1, window.icdb_repair_button, window.add_button),
|
||||
(2, window.add_button, window.batch_button),
|
||||
):
|
||||
window.section_tabs.setCurrentIndex(index)
|
||||
assert visible.isVisible() and not hidden.isVisible()
|
||||
assert window.cbb_table.isVisible()
|
||||
assert window.search_edit.text() == 'Beta'
|
||||
assert [record.name for record in window.selected_records()] == ['Beta']
|
||||
assert window.minimumSizeHint().height() <= 650
|
||||
|
||||
|
||||
def test_long_status_does_not_expand_the_window(qtbot, tmp_path):
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
window = MainWindow(data_root=tmp_path)
|
||||
qtbot.addWidget(window)
|
||||
window.resize(1000, 650); window.show()
|
||||
window.status_label.setText('错误说明\n' * 80)
|
||||
qtbot.wait(20)
|
||||
assert window.height() <= 650
|
||||
assert window.status_label.height() <= window.status_label.fontMetrics().lineSpacing() * 3 + 4
|
||||
Reference in new issue
Block a user