fix: complete confirmed legacy cleanup from one release intent

This commit is contained in:
阿白叔 committed 2026-11-17 09:44:49 +08:00
1 parent 7cc65f78da
commit a3f69de201
7 files changed
+189 -20

No files matched your search

+9 -5
View File
@@ -151,8 +151,9 @@ def _target_frame(windows, name, *, require_ready=True):
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
continue
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold()
and child['class'].casefold().startswith('afx:') for child in window['children']):
documents = [child for child in window['children'] if child.get('parent') in mdi
and child['class'].casefold().startswith('afx:')]
if len(documents) == 1 and documents[0]['text'].casefold() == name.casefold():
matches.append(window)
return matches[0] if len(matches) == 1 else None
@@ -408,9 +409,12 @@ def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post,
raise
actions = []
def act(hwnd, message):
if (read_windows() != windows or identity_check is not None and not identity_check()
or time.monotonic() >= deadline):
raise RuntimeError('STARTUP_ACTION_UNCONFIRMED: native state or deadline changed')
if read_windows() != windows:
raise RuntimeError('STARTUP_WINDOW_CHANGED: native snapshot changed before action')
if identity_check is not None and not identity_check():
raise RuntimeError('STARTUP_IDENTITY_UNCONFIRMED: registered cleanup binding changed')
if time.monotonic() >= deadline:
raise RuntimeError('STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached')
post(hwnd, message)
actions.append((hwnd, message))
if message == 0xF5:
+24 -5
View File
@@ -676,7 +676,7 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
from .diagnostic_open import cancelled_startup_step
from .operation_queue import check_active
job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop'])
deadline = time.monotonic()+3
deadline = time.monotonic()+30 # One diagnostic cleanup intent; ordinary close still uses 3 seconds.
def active_owner():
check_active()
if stop is not None and stop.is_set():
@@ -716,9 +716,15 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
return {'release_status':'RELEASED','detail':'已关闭启动提示并正常退出'}
if stop is not None and stop.is_set():break
break # Never stack another Close after a legacy Tip acknowledgement.
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
post=post,emit=lambda **event:None,read_windows=lambda:_legacy_diagnostic_windows(bound),
identity_check=confirmed)
try:
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
post=post,emit=lambda **event:None,read_windows=lambda:_legacy_diagnostic_windows(bound),
identity_check=confirmed)
except RuntimeError as error:
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
raise
# No may remove a modal and enable the target while the next
# snapshot is being read. Revalidate anew inside the same budget.
time.sleep(.1)
except (OSError, pywintypes.error, ValueError, RuntimeError) as error:
return {'release_status':'WAITING','detail':str(error)}
@@ -740,7 +746,20 @@ def _request_close(row, *, stop=None):
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if proof := _cancelled_diagnostic_record(row):
return _close_registered_startup(row, handle, proof, stop=stop)
owner = _force_ownership(handle,row['pid'])
if (owner.get('force_user_confirmed') is not True
or any(owner.get(k) != row.get(k) for k in ('owner_sid','session_id'))):
return {'release_status':'WAITING','detail':'取消启动会话的用户或 Windows 会话未确认'}
if stop is not None and stop.is_set():
return {'release_status':'CANCELLED','detail':'已停止释放'}
from .session_record import handoff_session
record_path = Path(proof['record_path'])
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False)
from .operation_queue import native_phase
# This confirmed no-write native cleanup has its own single bounded
# budget; metadata inactivity must not abandon it between No and Close.
with native_phase(read_only=True):
return _close_registered_startup(row, handle, proof, stop=stop)
if _dismiss_startup_tip(row, handle, windows, stop=stop) is not None:
# Legacy startup cleanup may already have sent WM_CLOSE. Only wait
# for it here; never stack another close behind this acknowledgement.
+18 -5
View File
@@ -387,15 +387,17 @@ def inspect_session_record(path, *, evidence_root):
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None,
observe_only=False):
stop = stop if stop is not None else threading.Event()
read_only = observe_only if callable(observe_only) else lambda: observe_only
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
with ExitStack() as stack:
handles = {}
while True:
observation_only = read_only()
try:
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only)
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observation_only)
except Exception as error:
result = _result('UNCONFIRMED', str(error))
if (not observe_only and process is not None and process.poll() is not None
if (not observation_only and process is not None and process.poll() is not None
and getattr(process, 'cbb_library', None)):
try:
from .library_lock import release_retained_library
@@ -405,7 +407,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
session={'library': str(process.cbb_library)}, proof=proof)
except Exception:
pass
if result['status'] == 'IDENTITY_CHANGED' and not observe_only:
if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
try:
from .library_lock import release_retained_library
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
@@ -427,7 +429,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
except Exception:
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
if (result['status'] == 'RELEASED' or stop.is_set()
or observe_only and result['status'] != 'ACTIVE'):
or read_only() and result['status'] != 'ACTIVE'):
return result
if not handles and process is not None and process.poll() is None:
stop.wait(1)
@@ -449,6 +451,9 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
with _observer_guard:
if key in _observers:
if (observe_only is False and session.get('operation_id')
and _retained_results.get(key, {}).get('operation_id') == session['operation_id']):
_retained_results[key]['release_operation_id'] = session['operation_id']
return
_retained_libraries[key] = aliases
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
@@ -466,11 +471,19 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
'block': value.get('block') or previous['block']}
if progress is not None:
progress(value)
def observation_only():
if not observe_only:
return False
with _observer_guard:
value = _retained_results.get(key, {})
return not (session.get('operation_id') and _retained_libraries.get(key) is aliases
and value.get('operation_id') == session.get('operation_id')
and value.get('release_operation_id') == session.get('operation_id'))
def observe():
result = None
try:
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
stop=stop, process=process, observe_only=observe_only)
stop=stop, process=process, observe_only=observation_only)
if process is not None and process.poll() is not None:
process.close()
return result
@@ -68,7 +68,7 @@ class ResidualReleaseDialog(QDialog):
self.table.itemSelectionChanged.connect(self._update_prompt)
self.refresh()
def _start(self, action, completed):
def _start(self, action, completed, *, metadata_only=False):
context = BatchTaskContext(str(self.library))
self.context, self.stop = context, context.stop
self.busy = True
@@ -78,7 +78,7 @@ class ResidualReleaseDialog(QDialog):
self.force_button.setEnabled(False)
self.cancel_native_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(lambda:context.run(action))
self.worker = ServiceWorker(lambda:context.run(action, metadata_only=metadata_only))
worker = self.worker
self._workers.add(worker)
self.worker.signals.succeeded.connect(context.guard_callback(completed, current=lambda:self.context))
@@ -238,7 +238,7 @@ class ResidualReleaseDialog(QDialog):
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
discover_sessions(self.evidence_dir.parent, library=library)})
return {**plan, 'runtime_sessions': list(states.values())}
self._start(inspect, ready)
self._start(inspect, ready, metadata_only=True)
def force_release(self):
if self.busy or not self.plan or not self.plan['sessions']: return