fix: apply reviewed ownership and release follow-up to umbrella

This commit is contained in:
阿白叔 committed 2026-11-06 12:08:59 +08:00
1 parent 9970635f7e
commit 32d7a63828
21 files changed
+1313 -83

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ def maintenance_counts(results):
'checked_without_repair': sum(r.status == 'CHECKED' for r in results),
'issues_found': sum(r.error_category == 'ICDB_REPAIR_REQUIRED' for r in results),
'in_use': sum(r.error_category == 'ICDB_DATABASE_IN_USE' for r in results),
'unconfirmed': sum(r.status not in ('CHECKED', 'SKIPPED', 'CANCELLED')
'unconfirmed': sum(r.status not in ('PASS', 'CHECKED', 'SKIPPED', 'CANCELLED')
and r.error_category not in ('ICDB_REPAIR_REQUIRED', 'ICDB_DATABASE_IN_USE') for r in results),
'cancelled': sum(r.status == 'CANCELLED' for r in results),
'skipped': sum(r.status == 'SKIPPED' for r in results),
+23 -1
View File
@@ -82,6 +82,28 @@ def has_retained_library(library):
return bool(owner and owner['retained'])
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None):
"""Historical records trigger fresh proof, never process termination or repair."""
if not (required or has_blocker(library) or has_retained_library(library)):
return None
def notify(stage, **details):
if progress is not None:
try:
progress({'stage': stage, 'block': block_name or '', **details})
except Exception:
import logging
logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True)
notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
try:
proof = release_retained_library(library, evidence_dir, block_name=block_name)
except Exception as error:
notify('previous_release_unconfirmed', detail=str(error))
raise
notify('previous_release_confirmed', release_proof=proof,
detail='已确认会话释放并归档历史记录;这不表示历史数据已恢复')
return proof
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, block_name=None):
import win32api, win32process
path = blocker_path(library)
@@ -499,7 +521,7 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
def release_retained_library(library, evidence_dir, *, block_name=None):
"""Explicit user-requested release, after fresh owner/address/access proof.
"""Reconcile historical leases after fresh owner/address/access proof.
The upload sidecar is never deleted. This acknowledges process release,
not the correctness of a partially changed library or its recovery state.
+34 -5
View File
@@ -73,6 +73,7 @@ class ManagementResult:
detail: str = ''
evidence_path: Path | None = None
release_proof: dict | None = None
change_report: dict | None = None
def validate_name(value):
@@ -186,6 +187,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
mutex = None
acquired = False
release_proof = None
original = None
change_report = None
def invoke(callback, *args):
nonlocal owner_safe
owner_safe = False
@@ -206,8 +209,32 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
if progress:
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
def finish(status, detail='', safe=True):
nonlocal change_report
if mutated and original is not None and change_report is None:
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
'unrelated_cbb_content_checked': False,
'detail': '原生会话尚未释放,未读取写后内容'}
if safe:
try:
after = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
_write_json(root/'library-after-manifest.json', after)
before_files, after_files = original['files'], after['files']
change_report.update(status='RECORDED', detail='目标工程及共享依赖的内容差分',
added=sorted(after_files.keys()-before_files.keys()),
deleted=sorted(before_files.keys()-after_files.keys()),
modified=sorted(path for path in before_files.keys() & after_files.keys()
if before_files[path] != after_files[path]))
except Exception as error:
change_report['detail'] = f'写后内容未确认:{error}'
try:
_write_json(root/'library-changes.json', change_report)
except OSError as error:
change_report.update(status='UNCONFIRMED', evidence_error=str(error),
detail=f'变更记录保存失败:{error}')
if change_report['status'] != 'RECORDED':
detail = (detail+'\n'+change_report['detail']).strip()
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof)
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)
if report:
try:
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
@@ -256,10 +283,12 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。')
from .library_lock import has_blocker, has_retained_library, release_retained_library
if (has_blocker(library) or has_retained_library(library) or request.check_previous_release
or unfinished_target and unfinished_target.get('safe_to_continue') is not True):
release_proof = release_retained_library(library, root/'previous-release')
from .library_lock import recheck_previous_release
release_proof = recheck_previous_release(library, root/'previous-release', block_name=request.name,
required=request.check_previous_release or bool(unfinished_target
and unfinished_target.get('safe_to_continue') is not True), progress=progress)
if release_proof is not None:
checkpoint('release_check', release_proof=release_proof)
if unfinished_target:
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
if hasattr(adapter, 'bind_library_mapping'):
+178 -55
View File
@@ -31,9 +31,33 @@ def force_block_reason(row):
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 会话,不允许强制结束'
activity = row.get('native_activity', {})
if activity.get('status') in ('ACTIVE', 'UNCONFIRMED'):
return activity.get('detail', '原生操作状态未确认')+';请查看进展或请求原生取消后重新检查'
if name == 'icdbprojectbackup.exe' and activity.get('status') != 'IDLE':
return '备份/恢复/修复状态未确认,请重新检查'
return ''
def native_activity(name, windows):
if any(w['class'] == 'UNCONFIRMED' for w in windows):
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
return {'status': 'ACTIVE', 'detail': '原生窗口显示操作进行中'}
if name.casefold() == 'icdbprojectbackup.exe':
main = [w for w in windows if w['class'].startswith('Afx:')
and w['title'].startswith('iCDB Project Backup')]
output = main[0].get('output') if len(main) == 1 else None
if not isinstance(output, str) or not output.strip():
return {'status': 'UNCONFIRMED', 'detail': '无法确认备份/恢复/修复输出'}
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
if active and max(output.rfind('Backup information loaded correctly.'),
output.rfind('Repair project error [')) < active[-1].start():
return {'status': 'ACTIVE', 'detail': '原生备份/恢复/修复尚未确认结束', 'output': output}
return {'status': 'IDLE', 'detail': '未观察到进行中的原生操作'}
@contextmanager
def _process_handle(pid, *, terminate=False):
import win32api, win32con
@@ -94,7 +118,7 @@ def _process_windows(pids):
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _=None):
def capture(hwnd, _=None, *, desktop_name='Default'):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
@@ -111,6 +135,7 @@ def _process_windows(pids):
win32api.SetLastError(0)
win32gui.EnumChildWindows(hwnd, child, None)
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
'desktop': desktop_name,
'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):
@@ -136,7 +161,7 @@ def _process_windows(pids):
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd), desktop_name=name)
except Exception:
incomplete()
finally:
@@ -194,15 +219,36 @@ def _save_question(windows):
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 {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons,
'desktop': window.get('desktop', '')}
return None
def _cancel_question(name, windows):
if name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows)['status'] != 'ACTIVE':
return None
candidates = []
for window in windows:
if not (window['class'].startswith('Afx:') or window['class'] == '#32770'):
continue
if not window['title'].startswith('iCDB Project Backup') or not window['enabled']:
continue
for button in window['children']:
if (button['class'] == 'Button' and button.get('id') == 2 and button.get('enabled')
and button.get('text', '').replace('&', '').strip() in ('Cancel', '取消')):
candidates.append({'hwnd': window['hwnd'], 'button': button,
'title': window['title'],
'desktop': window.get('desktop', '')})
return candidates[0] if len(candidates) == 1 else 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 文件')
if library.suffix.casefold() != '.lmc':
raise ValueError('请选择中心库 .lmc 文件')
if not library.is_file():
raise ValueError('中心库路径当前不可见,请检查文件是否存在及网络盘映射后重新检查')
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('残留检查的工程名称无效')
@@ -231,6 +277,14 @@ def inspect_residual_sessions(library, *, block_names=()):
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
observed = windows.get(row['pid'], [])
item['windows'] = observed
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
item['native_activity'] = native_activity(row['name'], observed)
item['cancel_prompt'] = (_cancel_question(row['name'], observed)
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
item['force_block_reason'] = force_block_reason(item)
item['force_allowed'] = not item['force_block_reason']
if item['force_block_reason']:
@@ -308,6 +362,11 @@ def _force_close(row, *, stop=None):
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 会话已变化,未结束'}
activity = native_activity(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
if reason := force_block_reason({**row, 'native_activity': activity}):
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放,未强制结束'}
win32api.TerminateProcess(handle, 1)
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
return {'release_status': 'RELEASED' if exited else 'WAITING',
@@ -319,75 +378,139 @@ def _finish_library_release(library, evidence):
return release_retained_library(library, evidence)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
def _request_native_cancel(row, *, stop=None):
"""Only click the exact currently visible Cancel control the user confirmed."""
import win32con, win32gui, win32process
if row.get('scope_confirmed') is not True:
raise ValueError('取消目标归属未确认,请重新检查')
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', 'name')):
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('取消目标身份已变化,请重新检查')
owner = _force_ownership(handle, row['pid'])
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
raise ValueError('取消目标用户/会话已变化')
prompt = _cancel_question(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
if not prompt or prompt != row.get('cancel_prompt'):
raise ValueError('原生取消按钮已变化,请重新检查')
button = prompt['button']
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('原生取消按钮归属已变化')
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止,未请求原生取消'}
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
return {'release_status': 'WAITING', 'detail': '已请求原生取消,需重新检查实际结果;未强制结束'}
def request_native_cancel(row, library, evidence_dir, *, stop=None):
# Reuse serialized admission, consent and incremental evidence for cancellation.
plan = {'library': str(library), 'sessions': [row]}
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=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,
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [
{**row, 'release_status': 'NOT_STARTED', 'detail': '尚未执行',
'consent_allowed': not force_block_reason(row) if force else row.get('scope_confirmed') is True}
for row in plan['sessions']], 'force': force, 'cancel_native': cancel_native,
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
if force:
def save():
from .management import _write_json
try:
result['report_saved'] = True
_write_json(root/'result.json', result)
return True
except OSError as error:
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
return False
if not save():
return result # No native actions without the initial checkpoint.
if force or cancel_native:
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**row, 'force_allowed': not force_block_reason(row),
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
'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:
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())
except OSError as error:
result['detail'] = f'确认记录保存失败,未执行:{error}'
save()
raise
result['consent_path'] = str(consent_path)
try:
fresh = {r['pid']: r for r in query_process_snapshot()}
blocks = plan.get('block_names', ())
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
# Close native children first; keep output rows in the original preview order.
ordered = sorted(result['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for row in ordered:
current = fresh.get(row['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, roots) is True
if row.get('scope_confirmed') is not True or not scoped or row['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif not row.get('created') or any(current.get(key) != row.get(key)
for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(row)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
row.update(release_status='REQUESTING', detail='正在请求原生操作,结果待确认')
if not save():
return result
try:
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
(_force_close if force else _request_close)(row, stop=stop))
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
row.update(outcome)
if not save():
return result # Preserve completed facts; stop further actions on storage failure.
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':
windows = remaining_windows.get(row['pid'], [])
row.update(prompt=_save_question(windows), windows=windows,
cancel_prompt=(_cancel_question(row['name'], windows)
if row.get('force_user_confirmed') is True else None),
native_activity=native_activity(row['name'], windows))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
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)
except BaseException as error:
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
if not isinstance(error, Exception):
raise
finally:
save()
return result
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
import win32con, win32event
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
@@ -401,7 +524,7 @@ def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
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)
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force, cancel_native=cancel_native)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
+16 -1
View File
@@ -14,7 +14,7 @@ from ..management import run_management_batch, validate_name
RESULT_LABELS = {
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过',
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复 / 队列已停止',
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复',
'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持',
}
STAGE_LABELS = {
@@ -25,6 +25,9 @@ STAGE_LABELS = {
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
'hash': '正在校验主要文件',
'release_check': '正在检查工程是否被占用',
'previous_release_check': '正在复核历史占用',
'previous_release_confirmed': '历史会话已确认释放',
'previous_release_unconfirmed': '占用复核未通过',
}
@@ -203,6 +206,18 @@ class ManagementDialog(QDialog):
for result in results:
summary = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)}'
text = f'{summary} — {result.detail}'
changes = getattr(result, 'change_report', None)
if changes:
if changes.get('status') == 'RECORDED':
text += (f'\n变更:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、'
f'修改 {len(changes["modified"])} 个主要文件。')
else:
summary += ',变更清单待核对'
text += '\n'+changes.get('detail', '变更清单未确认')
if getattr(result, 'release_proof', None):
text += '\n历史会话已释放;历史工程数据的恢复状态需另行核对。'
if not result.safe_to_continue:
summary += ',原生会话释放待确认'
if self.recovery_from and result.status == 'UPLOADED_VERIFIED':
summary += ',版本待核对。'
elif result.status not in ('UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED'):
@@ -25,13 +25,13 @@ class ResidualReleaseDialog(QDialog):
self.pool = QThreadPool(self)
self.setWindowTitle('释放残留会话')
self.setModal(True)
self.resize(760, 350)
self.resize(1040, 400)
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 = QTableWidget(0, 6)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径'])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
@@ -40,17 +40,22 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button = QPushButton('重新检查')
self.confirm_button = QPushButton('确认释放')
self.prompt_button = QPushButton('处理保存提示…')
self.details_button = QPushButton('查看原生提示…')
self.cancel_native_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)
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
self.cancel_native_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.details_button.clicked.connect(self.show_native_details)
self.cancel_native_button.clicked.connect(self.cancel_native)
self.table.itemSelectionChanged.connect(self._update_prompt)
self.refresh()
@@ -60,6 +65,7 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.force_button.setEnabled(False)
self.cancel_native_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(action)
self.worker.signals.succeeded.connect(completed)
@@ -83,7 +89,8 @@ class ResidualReleaseDialog(QDialog):
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', ''))):
session['pid'], session.get('detail', ''), ', '.join(session.get('desktops', [])),
session.get('image', session.get('executable', '')))):
self.table.setItem(index, column, QTableWidgetItem(str(value)))
if sessions: self.table.setCurrentCell(0, 0)
@@ -91,6 +98,65 @@ class ResidualReleaseDialog(QDialog):
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')))
self.cancel_native_button.setEnabled(not self.busy and 0 <= row < len(rows)
and bool(rows[row].get('cancel_prompt')))
self.details_button.setEnabled(0 <= row < len(rows))
def show_native_details(self):
if not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
box = QMessageBox(self); self.native_details = box
box.setWindowTitle('原生会话状态')
box.setText(f'{session["name"]} (PID {session["pid"]})\n'+session.get('detail', ''))
details = ['程序路径:'+session.get('image', session.get('executable', '')),
'窗口位置:'+', '.join(session.get('desktops', [])),
session.get('native_activity', {}).get('detail', '')]
for window in session.get('windows', []):
details.extend(['', window.get('title', ''), window.get('output', '') or ''])
details.extend(c.get('text', '') for c in window.get('children', [])
if c.get('class') == 'Static')
box.setDetailedText('\n'.join(details))
box.show()
def cancel_native(self):
if self.busy or not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
if not session.get('cancel_prompt'): return
answer = QMessageBox.question(self, '请求原生取消',
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
'取消后的工程状态仍需核对;不会强制结束进程。',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if answer != QMessageBox.Yes: return
from cbb_refresh_verify.residual_sessions import request_native_cancel
self.before_release.emit(); self.stop.clear()
def execute():
action = lambda: request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
def done(result):
self.message.setText(result.get('detail') or '\n'.join(r.get('detail', '') for r in result['sessions']))
confirmed = self._accept_release_proof(result)
if confirmed:
self.message.setText('已确认原生会话结束,当前库已释放。')
if result.get('evidence_error'):
self.message.setText(self.message.text()+'\n记录保存失败:'+result['evidence_error'])
elif not confirmed:
self._refresh_after = True
self._start(execute, done)
def _accept_release_proof(self, result):
proof = result.get('proof', {})
# Both paths were canonicalized by the worker; GUI comparison must not touch SMB.
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).absolute() != self.library.absolute()
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
return False
self.plan = None
self.released.emit(proof)
return True
def answer_prompt(self):
if self.busy or not self.plan: return
@@ -153,13 +219,13 @@ class ResidualReleaseDialog(QDialog):
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'])
if self._accept_release_proof(result):
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。'
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
else:
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
+ ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。')
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') 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()
+10 -2
View File
@@ -102,6 +102,7 @@ class VerifyResult:
timings_seconds: dict[str, float] = field(default_factory=dict)
incomplete_timing_phases: tuple[str, ...] = ()
recovery_attempts: tuple[dict, ...] = ()
release_proof: dict | None = None
def resolve_importer(mentor_bin: str | None = None) -> Path:
@@ -550,6 +551,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None
previous_release = None
release_confirmed = True
remaining_clients = ()
def clients_released():
@@ -566,16 +568,18 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if request.maintenance:
from .maintenance_entry import run_icdb_check
return run_icdb_check(request, progress=progress, stop=stop)
from .library_lock import LibraryLock, LibraryBusy
from .library_lock import LibraryLock, LibraryBusy, recheck_previous_release
import pywintypes
if Path(request.lmc_file).is_file():
try:
previous_release = recheck_previous_release(request.lmc_file,
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, progress=progress)
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
safe_to_release=clients_released)
library_lock.__enter__()
except LibraryBusy as error:
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
except (OSError, pywintypes.error) as error:
except (OSError, ValueError, RuntimeError, pywintypes.error) as error:
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_ACCESS_FAILED')
release_confirmed = False
result = _run_verify_serialized(
@@ -674,6 +678,10 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if type(pid) is int and pid > 0)
except (OSError, ValueError, KeyError):
pass
if previous_release is not None:
result = replace(result, release_proof=previous_release)
if result.evidence_path:
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
return result
finally:
try: