fix: admit linked legacy ICDB projects and explain blocked actions

This commit is contained in:
阿白叔 committed 2026-11-03 13:51:05 +08:00
1 parent 5eac654c36
commit d36b6bcad0
8 files changed
+138 -18

No files matched your search

+3
View File
@@ -27,6 +27,8 @@ def configure_qt_application(app):
}
for role, color in colors.items():
palette.setColor(role, QColor(color))
for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText):
palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#858b94'))
app.setPalette(palette)
app.setStyleSheet(
'QWidget { color: #202124; }'
@@ -34,6 +36,7 @@ def configure_qt_application(app):
'background: #ffffff; color: #202124; selection-color: #202124; }'
'QHeaderView::section { background: #e9edf2; color: #202124; }'
'QPushButton, QToolButton { color: #202124; }'
'QPushButton:disabled, QToolButton:disabled { color: #858b94; background: #e3e6eb; }'
)
return app
+22 -3
View File
@@ -65,6 +65,25 @@ def _scoped_addresses(request):
return addresses
def maintenance_project_files(project, pcb):
"""A legacy linked PCB need not contain the auxiliary PCB/pcb.prj.
Its explicit ProjectFile must bind back to the main project. Never guess
template.prj (or another PRJ) as an alternative database repair target.
"""
from .backup_recovery import _project_text
project, pcb = Path(project), Path(pcb)
auxiliary = pcb.parent/'pcb.prj'
if auxiliary.is_file():
return project, auxiliary
if os.path.lexists(auxiliary):
raise ValueError(f'MAINTENANCE_TARGET_UNCONFIRMED: 工程配置不是文件:{auxiliary}')
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.prj,且 PCB 的 ProjectFile 未唯一指向当前主工程')
return (project,)
def select_maintenance_target(request):
from .verify_runner import preflight
from .backup_recovery import _project_text
@@ -75,7 +94,7 @@ def select_maintenance_target(request):
project, pcb = preflight(request)
scan_tree(project.parent)
candidates = []
for candidate in (project, pcb.parent/'pcb.prj'):
for candidate in maintenance_project_files(project, pcb):
if not candidate.is_file():
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少工程配置')
text = _project_text(candidate)
@@ -114,7 +133,7 @@ def maintenance_target_guard(request, expected=None):
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
'addresses': baseline,
'engineering_references': {str(p.resolve()): hash_file(p)
for p in (project, pcb, pcb.parent/'pcb.prj')}}
for p in (pcb, *maintenance_project_files(project, pcb))}}
if expected is not None and context != expected:
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
assert_native_idle()
@@ -223,4 +242,4 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
except Exception as error:
return save(VerifyResult('BLOCKED' if recovery is None else 'FAIL', stderr=str(error),
safe_to_continue=False, recovery_attempts=(recovery,) if recovery else (),
error_category='ICDB_MAINTENANCE_BLOCKED'))
error_category='ICDB_MAINTENANCE_BLOCKED', error_stage=record['stage']))
@@ -124,7 +124,8 @@ def prepare_launch(job, command):
if _current_desktop_name() != job['desktop']:
raise ValueError('POST_REPAIR_PRIVATE_DESKTOP_REQUIRED')
library, project, pcb = (Path(job[key]) for key in ('lmc_file', 'project', 'pcb'))
for path in (library, project, pcb, pcb.parent/'pcb.prj'):
from .maintenance_entry import maintenance_project_files
for path in (library, pcb, *maintenance_project_files(project, pcb)):
require_local_fixed(path)
if len(command) != 3 or not _same(command[1], pcb) or command[2] != '-ReusableCircuit':
raise ValueError('POST_REPAIR_LAUNCH_MISMATCH')
+49 -11
View File
@@ -167,7 +167,14 @@ class MainWindow(QWidget):
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); layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
layout.addRow('中心库 .lmc', 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)
filters = QHBoxLayout()
for widget in (self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
filters.addWidget(widget)
@@ -207,12 +214,9 @@ class MainWindow(QWidget):
widget.setToolTip(self.management_capabilities[operation].reason)
management_buttons.addWidget(widget)
management_layout.addLayout(management_buttons)
self.management_capability_label = QLabel('\n'.join(
f'{label}:{self.management_capabilities[op].reason}'
for op, label in (('add', '新增'), ('update', '同名更新'), ('remove', '移除'))
if not self.management_capabilities[op].supported))
self.management_capability_label = QLabel()
self.management_capability_label.setWordWrap(True)
management_layout.addWidget(self.management_capability_label)
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('检查会话释放并解除协调阻止…')
@@ -256,10 +260,21 @@ class MainWindow(QWidget):
self.icdb_repair_button.setEnabled(ready and bool(self._maintenance_names()))
self.backup_restore_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._maintenance_names()))
self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip()))
loaded = not self.busy and not self._management_unsafe and not self._maintenance_recovery_view and self.loaded_path == self.lmc_edit.text()
reasons = []
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
widget.setEnabled(loaded and self.management_capabilities[operation].supported
and (operation == 'add' or bool(self.selected_records())))
reason = self._management_block_reason(operation)
widget.setEnabled(not reason)
widget.setToolTip(reason or self.management_capabilities[operation].reason)
if reason:
reasons.append(reason)
self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons)))
notice = ('该库有未确认的会话记录,新增、替换、移除和普通校验已暂停。'
'请先执行 ICDB 维护;仍有数据库地址记录时,单独点击释放检查不会解除阻止。'
if self._maintenance_recovery_view else
'上次管理操作尚未确认安全释放,已暂停库操作。请先查看异常证据并检查会话释放。'
if self._management_unsafe else '')
self.library_notice.setText(notice)
self.library_notice.setVisible(bool(notice))
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
self.timeout_spin, self.advanced_toggle, self.advanced_panel,
self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
@@ -297,9 +312,26 @@ class MainWindow(QWidget):
self.status_label.setText(message); self.output.append(message)
self._start(lambda: release_retained_library(library, self.data_root/'release-checks'), completed)
def _management_block_reason(self, operation):
if self.busy:
return '当前任务尚未结束,请等待后再执行库管理操作。'
if self._maintenance_recovery_view:
return '库的会话释放尚未确认,管理操作已禁用;请先执行 ICDB 维护并查看逐项结果。'
if self._management_unsafe:
return '上次管理操作的会话尚未安全释放,请先查看异常证据并执行释放检查。'
capability = self.management_capabilities[operation]
if not capability.supported:
return capability.reason
if not self.loaded_path or self.loaded_path != self.lmc_edit.text():
return '请先选择并读取中心库。'
if operation != 'add' and not self.selected_records():
return '替换和移除需要先勾选当前可见的 CBB。'
return ''
def manage_cbb(self, operation):
if (self.busy or self._management_unsafe or self._maintenance_recovery_view or self.loaded_path != self.lmc_edit.text()
or not self.management_capabilities[operation].supported):
reason = self._management_block_reason(operation)
if reason:
self.status_label.setText(reason)
return
from cbb_refresh_verify.management import ManagementRequest
from .management_dialog import ManagementDialog
@@ -836,6 +868,12 @@ class MainWindow(QWidget):
f'原生修复 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
f'修复未确认 {counts["repair_unconfirmed"]}。')
first_failure = next((result.stderr for result in results
if result.status not in ('PASS', 'SKIPPED') and result.stderr), '')
if first_failure:
explanation = '\n首个未完成原因:' + first_failure[:1500]
status_text += explanation
text += explanation
self.status_label.setText(status_text); self.output.append(text)
self.summary = QMessageBox(self)
self.summary.setWindowTitle('非 READY ICDB 检查与修复结果' if self._global_icdb_run else 'CBB 校验结果'); self.summary.setText(text)
+3 -1
View File
@@ -209,7 +209,9 @@ def test_real_windows_job_abort_preserves_native_like_child(tmp_path):
script.write_text(
'import subprocess, sys, time\nfrom pathlib import Path\n'
'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])\n'
f'Path({str(pid_path)!r}).write_text(str(child.pid))\n'
f'pid_file = Path({str(pid_path)!r})\n'
'pending = pid_file.with_suffix(".pending")\n'
'pending.write_text(str(child.pid)); pending.replace(pid_file)\n'
'time.sleep(30)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], 'CbbSafetyTest_' + uuid.uuid4().hex[:8])
child_handle = None
+39 -1
View File
@@ -46,10 +46,13 @@ def case(tmp_path, monkeypatch):
if owner: owner['handle'].Close()
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch):
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config):
from cbb_refresh_verify import verify_runner as runner, native_repair
from test_native_repair import complete_native_success
request, project, address = case
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')
@@ -79,6 +82,40 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
assert 'session' not in record['maintenance_context']
@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):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, _ = case
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
(project.parent/'PCB/IP101GR.pcb').write_text(back_reference)
with pytest.raises(ValueError, match='MAINTENANCE_TARGET_UNCONFIRMED'):
select_maintenance_target(request)
def test_legacy_target_does_not_guess_template_for_physical_address(case):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, address = case
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
address.unlink()
physical = project.parent/'PCB/database/cdbsvr/sAddress.adr'
physical.parent.mkdir(parents=True); physical.write_bytes(b'physical owner')
with pytest.raises(ValueError, match='SHARED_DATABASE_REPAIR_UNSUPPORTED'):
select_maintenance_target(request)
def test_optional_pcb_project_appearance_invalidates_maintenance_proof(case):
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
request, project, _ = case
config = project.parent/'PCB/pcb.prj'
config.rename(config.with_name('template.prj'))
with maintenance_target_guard(request) as proof:
before = proof['context']
config.write_text('KEY CentralLibrary "different.lmc"\n')
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
with maintenance_target_guard(request, before): pass
def test_ordinary_verify_still_blocks_existing_address_without_repair(case, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, _, address = case
@@ -114,6 +151,7 @@ def test_maintenance_guard_blocks_before_native(case, monkeypatch, obstacle):
try:
result = runner.run_verify(request)
assert result.status == 'BLOCKED' and not result.safe_to_continue
assert result.error_stage == 'preflight'
finally:
if handle: handle.Close()
+14
View File
@@ -53,6 +53,8 @@ def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(q
assert window.visible_records()[0].name == 'IP101GR'
assert window.visible_records()[0].status == 'UNKNOWN'
assert '未确认' in window.status_label.text()
assert 'ICDB' in window.management_capability_label.text()
assert '会话' in window.add_button.toolTip()
window.select_visible_button.click()
assert window.icdb_repair_button.isEnabled()
assert not any(button.isEnabled() for button in (window.batch_button, window.selected_batch_button,
@@ -65,6 +67,18 @@ def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(q
assert len(calls) == 1 and calls[0].maintenance is True
def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._global_icdb_run = True
detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致'
window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log'))
assert detail in window.summary.text()
assert detail in window.status_label.text()
def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
from cbb_refresh_verify.ui.main_window import MainWindow
+6 -1
View File
@@ -95,9 +95,14 @@ def test_prelaunch_proof_blocks_without_launch(context, monkeypatch, obstacle):
if handle: handle.Close()
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch):
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch, pcb_config):
from cbb_refresh_verify import post_repair_consent as consent
_, _, proof, job = context
if pcb_config == 'legacy_template':
pcb = Path(job['pcb'])
(pcb.parent/'pcb.prj').rename(pcb.parent/'template.prj')
pcb.write_text('KEY ProjectFile "../'+Path(job['project']).name+'"\n')
command = ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']
consent.prepare_launch(job, command)
controller = consent.ConsentController(proof, job)