feat: add confirmed client release with durable consent and server protection

This commit is contained in:
阿白叔 committed 2026-11-05 23:31:36 +08:00
1 parent 282be7be7f
commit 173dee1980
54 files changed
+3909 -14

No files matched your search

+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.3b1"
__version__ = "0.2.4b1"
+441
View File
@@ -0,0 +1,441 @@
"""Preview and cooperatively close the exact native sessions a user confirms."""
from contextlib import contextmanager
import json
import os
from pathlib import Path
import re
import time
from uuid import uuid4
from .owner_probe import query_process_snapshot
from .native_engineering_identity import _OWNER_NAMES
_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe',
'viewdraw.exe', 'icdbnetserver.exe', 'icdbserver.exe',
'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES
_WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'}
_WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
_FORCE_CLIENT_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'viewdraw.exe', 'icdbprojectbackup.exe'}
def force_block_reason(row):
"""A library path proves scope, never exclusive ownership of a server."""
if row.get('scope_confirmed') is not True:
return '进程归属未确认,不允许强制结束'
name = str(row.get('name', '')).casefold()
if name not in _FORCE_CLIENT_NAMES:
return '服务器或其他受保护进程仅供观察,不允许强制结束'
if (not row.get('created_handle') or not row.get('image')
or Path(row['image']).name.casefold() != name):
return '客户端身份未确认,不允许强制结束'
if (row.get('force_user_confirmed') is not True or not row.get('owner_sid')
or not isinstance(row.get('session_id'), int)):
return '未确认属于当前用户和 Windows 会话,不允许强制结束'
return ''
@contextmanager
def _process_handle(pid, *, terminate=False):
import win32api, win32con
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 | (1 if terminate else 0), False, int(pid))
try:
yield handle
finally:
handle.Close()
def _handle_identity(handle):
import ctypes
from ctypes import wintypes
import win32process
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD,
wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
kernel.QueryFullProcessImageNameW.restype = wintypes.BOOL
buffer = ctypes.create_unicode_buffer(32768)
length = wintypes.DWORD(len(buffer))
if not kernel.QueryFullProcessImageNameW(int(handle), 0, buffer, ctypes.byref(length)):
raise ctypes.WinError(ctypes.get_last_error())
return {'created_handle': win32process.GetProcessTimes(handle)['CreationTime'].isoformat(),
'image': buffer.value}
def _process_identity(row):
with _process_handle(row['pid']) as handle:
identity = _handle_identity(handle)
try:
identity.update(_force_ownership(handle, row['pid']))
except Exception as error:
identity.update(force_user_confirmed=False, owner_error=str(error))
return identity
def _force_ownership(handle, pid):
import win32api, win32con, win32process, win32security, win32ts
if win32process.GetProcessId(handle) != pid:
raise ValueError('进程身份已变化')
def owner(process):
token = win32security.OpenProcessToken(process, win32con.TOKEN_QUERY)
try:
return win32security.ConvertSidToStringSid(
win32security.GetTokenInformation(token, win32security.TokenUser)[0])
finally:
token.Close()
sid = owner(handle)
session = win32ts.ProcessIdToSessionId(pid)
return {'owner_sid': sid, 'session_id': session, 'force_user_confirmed':
sid == owner(win32api.GetCurrentProcess())
and session == win32ts.ProcessIdToSessionId(os.getpid())}
def _process_windows(pids):
if not pids: return {}
import win32api, win32con, win32gui, win32process, win32service
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _=None):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
observed.add(hwnd)
children, documents = [], []
def child(handle, _):
kind = win32gui.GetClassName(handle)
if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD):
documents.append(handle)
if win32gui.IsWindowVisible(handle):
children.append({'hwnd': int(handle), 'class': kind,
'id': win32gui.GetDlgCtrlID(handle) & 0xffff,
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))})
win32api.SetLastError(0)
win32gui.EnumChildWindows(hwnd, child, None)
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))}
if any(c['class'].casefold().startswith('richedit') for c in children):
window['output'] = _native_output([window])
result[pid].append(window)
win32api.SetLastError(0)
def incomplete():
for pid in result:
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
'enabled': False, 'children': []})
try:
win32gui.EnumWindows(capture, None)
except Exception:
incomplete()
try:
desktops = win32service.GetProcessWindowStation().EnumDesktops()
except Exception:
incomplete()
return result
for name in desktops:
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
continue
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
except Exception:
incomplete()
finally:
if desktop is not None: desktop.CloseDesktop()
return result
def _project_name(row, library):
from .failed_session import _command_args
for arg in _command_args(row['command'])[1:]:
try:
relative = Path(arg.split('=', 1)[-1]).relative_to(library.parent/'ReusableBlocksLP')
if len(relative.parts) >= 2 and relative.parts[1].casefold() == 'work':
return relative.parts[0]
except ValueError:
continue
return '当前库关联会话'
def close_target(name, windows):
"""No save/restore approval and no close against an unknown modal/window."""
main = [w for w in windows if w['class'].startswith('Afx:') and (
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
or name.casefold() == 'expeditionpcb.exe' and 'Expedition PCB' in w['title'])]
if len(main) != 1:
return None, '未确认空闲主窗口;有工程时请先在原生窗口保存并关闭'
window = main[0]
for other in windows:
if other is window: continue
benign = (not other['title'] and other['class'] in
('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))
benign = benign or (other['class'] == 'Internet Explorer_Hidden' and not other['title']
and not other.get('children') and other.get('rect', [1, 1, 2, 2])[0:2] == other.get('rect', [1, 1, 2, 2])[2:4])
if not benign: return None, '存在原生弹窗,请先处理该窗口后重新检查'
if not window['enabled']:
return None, '原生程序正在工作,请稍后重新检查'
if any(c['class'].casefold() == 'msctls_progress32' for c in window['children']):
return None, '原生操作尚未结束'
if name.casefold() == 'icdbprojectbackup.exe':
output = window.get('output')
if not isinstance(output, str): return None, '原生输出尚无法确认,请重新检查'
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
last_load = output.rfind('Backup information loaded correctly.')
failure = output.rfind('Repair project error [')
if active and max(last_load, failure) < active[-1].start():
return None, '备份、恢复或修复需要在原生窗口确认结束后再释放'
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
def _save_question(windows):
for window in windows:
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
if (window['class'] == '#32770' and 'Expedition' in window['title']
and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I)
and set(buttons) == {6, 7, 2}):
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
return None
def inspect_residual_sessions(library, *, block_names=()):
from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library
library = Path(library).resolve()
if library.suffix.casefold() != '.lmc' or not library.is_file():
raise ValueError('请选择有效的中心库 .lmc 文件')
blocks = tuple(dict.fromkeys(str(name) for name in block_names))
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
raise ValueError('残留检查的工程名称无效')
roots = tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks) + (library.parent/'SymbolLibs',)
if not blocks: roots = (library.parent,)
candidates = []
for row in query_process_snapshot():
if row['pid'] == os.getpid(): continue
native = row['name'].casefold() in _NAMES
worker = (row['name'].casefold() in _WORKER_NAMES
and any(flag in row['command'].casefold() for flag in _WORKER_FLAGS))
if not (native or worker): continue
scope = _owner_matches_scope(row, library, roots)
if scope is not False:
candidates.append({**row, 'scope_confirmed': scope is True})
windows = _process_windows({r['pid'] for r in candidates})
sessions = []
for row in candidates:
item = dict(row)
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
item.update(can_close=target is not None, detail=detail)
except Exception as error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
item['force_block_reason'] = force_block_reason(item)
item['force_allowed'] = not item['force_block_reason']
if item['force_block_reason']:
item['detail'] += ';'+item['force_block_reason']
sessions.append(item)
previous = []
marker = blocker_path(library)
for path in (marker, marker.with_suffix('.pending')):
if path.exists():
record = checkpoint_record(path)
previous.append({'path': str(path), 'recognized': record is not None,
'status': record.get('status', 'UNRECOGNIZED') if record else 'UNRECOGNIZED',
'time': record.get('time', '') if record else '',
'pid': record.get('pid') if record else None})
if has_retained_library(library):
previous.append({'path': str(library), 'status': 'RETAINED_IN_MEMORY', 'time': '',
'pid': os.getpid(), 'kind': 'in_memory'})
return {'library': str(library), 'block_names': list(blocks), 'sessions': sessions,
'previous_records': previous}
def _request_close(row, *, stop=None):
import win32con, win32event, win32gui, win32process
with _process_handle(row['pid']) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已退出'}
identity = _handle_identity(handle)
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
if row['name'].casefold() == 'expeditionpcb.exe':
from .failed_session import _startup_snapshot, _cancel_target
for window in windows:
if window['class'] != '#32770': continue
target = _cancel_target(_startup_snapshot(window['hwnd'], row['pid']))
if target:
win32gui.PostMessage(target[1].handle, win32con.BM_CLICK, 0, 0)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
if close_target(row['name'], windows)[0] is not None: break
break
target, detail = close_target(row['name'], windows)
if target is None: return {'release_status': 'WAITING', 'detail': detail}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if win32process.GetWindowThreadProcessId(target['hwnd'])[1] != row['pid']:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '窗口归属已变化,未关闭'}
win32gui.PostMessage(target['hwnd'], win32con.WM_CLOSE, 0, 0)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已正常退出'}
if stop is not None and stop.is_set(): break
return {'release_status': 'WAITING', 'detail': '已请求正常关闭;请处理原生窗口,完成后重新检查'}
def _force_close(row, *, stop=None):
"""Separate UI consent permits ending only this exact, scoped process handle."""
import win32api, win32con, win32event
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if reason := force_block_reason(row):
return {'release_status': 'WAITING', 'detail': reason}
with _process_handle(row['pid'], terminate=True) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return {'release_status': 'RELEASED', 'detail': '已退出'}
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'}
ownership = _force_ownership(handle, row['pid'])
if (not ownership['force_user_confirmed'] or
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
win32api.TerminateProcess(handle, 1)
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
return {'release_status': 'RELEASED' if exited else 'WAITING',
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
def _finish_library_release(library, evidence):
from .library_lock import release_retained_library
return release_retained_library(library, evidence)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('释放记录需位于中心库之外')
root.mkdir(parents=True)
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
if force:
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**row, 'force_allowed': not force_block_reason(row),
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
with consent_path.open('x', encoding='utf-8') as stream:
json.dump(consent, stream, ensure_ascii=False, indent=2)
stream.flush(); os.fsync(stream.fileno())
result['consent_path'] = str(consent_path)
fresh = {r['pid']: r for r in query_process_snapshot()}
# Close native children first, so their supervisors can finish and drop leases.
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for original in ordered:
current = fresh.get(original['pid'])
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, (library.parent,)) is True
if original.get('scope_confirmed') is not True or not scoped or original['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(original)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
result['sessions'].append({**original, **outcome})
by_pid = {r['pid']: r for r in result['sessions']}
result['sessions'] = [by_pid[r['pid']] for r in plan['sessions']]
# Launchers may exit only after the GUI child processed its close request.
after = {r['pid']: r for r in query_process_snapshot()}
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
if r['release_status'] == 'WAITING' and r['pid'] in after})
for row in result['sessions']:
if row['release_status'] == 'WAITING' and row['pid'] not in after:
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
row['prompt'] = _save_question(remaining_windows.get(row['pid'], []))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
try:
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).resolve() != library):
raise ValueError('释放证明与当前库不一致')
result['status'] = 'RELEASE_CONFIRMED'
except Exception as error:
result['detail'] = str(error)
try:
(root/'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), 'utf-8')
except OSError as error:
result['evidence_error'] = str(error)
return result
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
import win32con, win32event
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
deadline = time.monotonic()+15
while time.monotonic() < deadline and not (stop and stop.is_set()):
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if acquired: break
time.sleep(.2)
if not acquired:
return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [
{**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'}
for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'}
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
def answer_save_question(row, choice):
"""Only the exact displayed save question receives an explicit user answer."""
import win32con, win32event, win32gui
if choice not in (6, 7, 2): raise ValueError('无效的保存选择')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
mutex.Close()
raise ValueError('其它批次正在执行,请稍后处理保存提示')
try:
_answer_save_question(row, choice)
finally:
win32event.ReleaseMutex(mutex)
mutex.Close()
def _answer_save_question(row, choice):
import win32con, win32gui
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable')):
raise ValueError('进程已变化,请重新检查')
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('进程已变化,请重新检查')
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
if not prompt or prompt != row.get('prompt'):
raise ValueError('原生提示已变化,请重新检查')
button = prompt['buttons'][choice]
import win32process
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('保存按钮归属已变化')
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
+17 -8
View File
@@ -302,7 +302,6 @@ class MainWindow(QWidget):
self.release_library_button = QPushButton('释放残留会话…')
self.release_library_button.clicked.connect(self.check_library_release)
management_buttons.addWidget(self.release_library_button)
self.release_library_button.hide()
self.section_stack.addWidget(management)
layout.addWidget(self.section_stack)
layout.addWidget(self.status_label)
@@ -400,7 +399,7 @@ class MainWindow(QWidget):
self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set())
self.backup_restore_button.setEnabled(ready and bool(
self._eligible_names(checked_only=bool(self.selected_records()))))
self.release_library_button.setEnabled(False)
self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip()))
reasons = []
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
reason = self._management_block_reason(operation)
@@ -447,7 +446,17 @@ class MainWindow(QWidget):
f'{item.get("stage", "")}\n{item["evidence_path"]}')
def check_library_release(self):
return # Release entry arrives with the next review PR.
if self.busy or not self.lmc_edit.text().strip():
return
from .residual_release_dialog import ResidualReleaseDialog
library = Path(self.mentor_lmc_path or self.lmc_edit.text().strip())
self.release_dialog = ResidualReleaseDialog(library, self.data_root/'release-checks', self)
self.release_dialog.native_queue = self.native_queue
self.release_dialog.before_release.connect(self._stop_icdb_check)
self.release_dialog.released.connect(lambda result: self._complete_library_release(self.release_dialog.library, result))
self.release_dialog.finished.connect(self._release_dialog_finished)
self.busy = True; self._update()
self.release_dialog.show()
def _release_dialog_finished(self, _=None):
if self._defer_mapping_finish(self._release_dialog_finished): return
@@ -630,7 +639,7 @@ class MainWindow(QWidget):
result.operation, result.name, result.status, result.safe_to_continue, result.evidence_path, result.detail)
if getattr(self, '_management_is_recovery', False) and result.status == 'UPLOADED_VERIFIED':
self.output.append('副本恢复校验通过,版本待核对。')
if False: # Release entry arrives with the next review PR.
if any(not result.safe_to_continue for result in results):
self._management_unsafe = True
self._management_unsafe_library = self._management_operation_library
self._management_unsafe_libraries.add(_path_key(self._management_operation_library))
@@ -860,7 +869,7 @@ class MainWindow(QWidget):
+(result.stderr or result.stdout or result.status)
for req, result in zip(task.requests, task.results)))
summary.setTextFormat(Qt.PlainText); summary.setAttribute(Qt.WA_ShowWithoutActivating)
if False: # Release entry arrives with the next review PR.
if any(not result.safe_to_continue for result in task.results):
def release_task():
if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease)
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)):
@@ -1425,7 +1434,7 @@ class MainWindow(QWidget):
f'取消 {counts["cancelled"]},队列未执行 {skipped}\n'
f'完整日志:{report}\n仅失败日志:{failure_report}')
self.icdb_phase.setText('批量检查已结束')
if False: # Release entry arrives with the next review PR.
if any(not result.safe_to_continue for result in results):
text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。'
status_text = (f'已结束:通过 {passed},失败/受阻 {failed},'
f'仅检查 {checked},未执行 {skipped + len(self.skipped_names)}。')
@@ -1443,7 +1452,7 @@ class MainWindow(QWidget):
status_text += '\nMentor 不允许对此已验证过的 CBB 反标注,校验未通过。'
else:
status_text += '\n部分项目未完成,请查看详情。'
if False: # Release entry arrives with the next review PR.
if any(not result.safe_to_continue for result in results):
status_text += '\n后续操作已暂停。'
if self._reimport_offers:
guidance = '\n修复未完成,可选择工程副本恢复。'
@@ -1459,7 +1468,7 @@ class MainWindow(QWidget):
self._residual_release_action = None
self._resume_batch_action = None
self._resume_batch = None
if False: # Release entry arrives with the next review PR.
if any(not result.safe_to_continue for result in results):
self._residual_release_action = self.summary.addButton('查看残留并释放…', QMessageBox.ActionRole)
self._residual_release_action.clicked.connect(self.check_library_release)
self._residual_release_action.setEnabled(False)
@@ -0,0 +1,180 @@
"""User-confirmed, asynchronous native-session release."""
from pathlib import Path
from threading import Event
from PySide6.QtCore import QThreadPool, Signal
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
from .workers import ServiceWorker
from ..residual_sessions import force_block_reason
class ResidualReleaseDialog(QDialog):
released = Signal(object)
before_release = Signal()
def __init__(self, library, evidence_dir, parent=None):
super().__init__(parent)
self.library, self.evidence_dir = Path(library), Path(evidence_dir)
self.plan = None
self.native_queue = None
self.busy = False
self.stop = Event()
self._refresh_after = False
self.pool = QThreadPool(self)
self.setWindowTitle('释放残留会话')
self.setModal(True)
self.resize(760, 350)
layout = QVBoxLayout(self)
self.message = QLabel('正在检查当前库关联的会话…')
self.message.setWordWrap(True)
layout.addWidget(self.message)
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态'])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
layout.addWidget(self.table)
buttons = QHBoxLayout()
self.refresh_button = QPushButton('重新检查')
self.confirm_button = QPushButton('确认释放')
self.prompt_button = QPushButton('处理保存提示…')
self.force_button = QPushButton('强制结束客户端…')
self.force_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.close_button = QPushButton('关闭')
for button in (self.refresh_button, self.confirm_button, self.prompt_button, self.force_button, self.close_button): buttons.addWidget(button)
layout.addLayout(buttons)
self.refresh_button.clicked.connect(self.refresh)
self.confirm_button.clicked.connect(self.confirm_release)
self.close_button.clicked.connect(self.close)
self.prompt_button.clicked.connect(self.answer_prompt)
self.force_button.clicked.connect(self.force_release)
self.table.itemSelectionChanged.connect(self._update_prompt)
self.refresh()
def _start(self, action, completed):
self.busy = True
self.confirm_button.setEnabled(False)
self.refresh_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.force_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(action)
self.worker.signals.succeeded.connect(completed)
self.worker.signals.failed.connect(lambda error: self.message.setText(str(error)))
self.worker.signals.finished.connect(self._finished)
self.pool.start(self.worker)
def _finished(self):
self.busy = False
self.refresh_button.setEnabled(True)
self.confirm_button.setEnabled(self.plan is not None)
self.force_button.setEnabled(bool(self.plan and any(
not force_block_reason(r) for r in self.plan['sessions'])))
self.close_button.setText('关闭')
self._update_prompt()
if self._refresh_after:
self._refresh_after = False
self.refresh()
def _rows(self, sessions):
self.table.setRowCount(len(sessions))
for index, session in enumerate(sessions):
for column, value in enumerate((session.get('project', ''), session['name'],
session['pid'], session.get('detail', ''))):
self.table.setItem(index, column, QTableWidgetItem(str(value)))
if sessions: self.table.setCurrentCell(0, 0)
def _update_prompt(self):
row = self.table.currentRow()
rows = self.plan['sessions'] if self.plan else []
self.prompt_button.setEnabled(not self.busy and 0 <= row < len(rows) and bool(rows[row].get('prompt')))
def answer_prompt(self):
if self.busy or not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
prompt = session.get('prompt')
if not prompt: return
choice = QMessageBox.question(self, '关闭工程前保存', prompt['text']+
'\n\n是:保存后关闭;否:放弃未保存更改;取消:保留会话。',
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
code = {QMessageBox.Yes: 6, QMessageBox.No: 7, QMessageBox.Cancel: 2}[choice]
from cbb_refresh_verify.residual_sessions import answer_save_question
self._start(lambda: answer_save_question(session, code),
lambda _: setattr(self, '_refresh_after', True))
def refresh(self):
if self.busy: return
from cbb_refresh_verify.library_lock import inspect_residual_sessions
self.plan = None
self.message.setText('正在检查当前库关联的会话…')
def ready(plan):
self.library = Path(plan['library'])
self.plan = plan
self._rows(plan['sessions'])
text = ('确认后逐项正常关闭下列会话;有未保存更改时,可选择保存或保留。'
if plan['sessions'] else '未发现活跃会话。')
records = plan.get('previous_records', [])
if records:
dates = ', '.join(sorted({r['time'][:10] for r in records if r.get('time')}))
text += f'\n有 {len(records)} 条历史操作记录'+(f'({dates})' if dates else '')+',确认后将复核并清理。'
elif not plan['sessions']:
text += '确认后将复查库占用状态。'
self.message.setText(text)
def inspect():
from cbb_refresh_verify.network_path import select_library_file
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
return inspect_residual_sessions(library)
self._start(inspect, ready)
def force_release(self):
if self.busy or not self.plan or not self.plan['sessions']: return
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
if not targets: return
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
answer = QMessageBox.warning(self, '强制结束客户端',
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
if answer == QMessageBox.Yes: self.confirm_release(force=True)
def confirm_release(self, checked=False, *, force=False):
if self.busy or self.plan is None: return
from cbb_refresh_verify.library_lock import release_residual_sessions
self.stop.clear()
plan = self.plan
self.before_release.emit()
self.message.setText('正在逐项释放,请稍候…')
def done(result):
self.plan = {**plan, 'sessions': result['sessions']}
self._rows(result['sessions'])
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
if result['status'] == 'RELEASE_CONFIRMED':
self.plan = None
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。')
self.released.emit(result['proof'])
else:
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
def execute():
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
self._start(execute, done)
def closeEvent(self, event):
if self.busy:
self.stop.set()
self.message.setText('正在停止释放,等待本次操作返回…')
event.ignore()
else:
super().closeEvent(event)
def reject(self):
if self.busy:
self.stop.set()
else:
super().reject()