fix: reconcile reused identities and protect every native dispatch

This commit is contained in:
阿白叔 committed 2026-11-06 16:21:08 +08:00
1 parent cb11624b68
commit d9a79b6535
8 files changed
+159 -13

No files matched your search

+1
View File
@@ -109,6 +109,7 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
emit(stage='integration_action_unavailable', action=method,
initial_status=state[name], reason='mentor_not_allowed')
raise IntegrationError(f'{name}: required but not allowed')
check_error() # The permission getter itself can block past cancellation.
emit(stage='integration_action', action=method, initial_status=state[name],
reason='required_verification' if name not in executed else 'resynchronize')
started = clock()
+27 -5
View File
@@ -717,10 +717,22 @@ def _set_probe_field(hwnd, control_id, expected, root):
def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
try:
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root, library=library)
except Exception as error:
if job.get('_native_add_pending') and str(error).startswith('NATIVE_ADD_FAILED:'):
try:
failure = json.loads((Path(root)/'native-add-output.json').read_text('utf-8')).get('failure', {})
if failure.get('acknowledged') is True:
job['_native_add_pending'] = False
from .session_record import update_worker_state
update_worker_state(job, 'POSTCALL')
except (OSError, ValueError, AttributeError):
pass
raise
finally:
import gc
gc.collect() # Release UIA wrappers before closing native child dialogs.
_close_probe_dialogs(desktop, owned_pids)
if not job.get('_native_add_pending'):
_close_probe_dialogs(desktop, owned_pids)
def _require_management_continuation(job, root):
@@ -823,6 +835,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
_write_json(root/'native-add-log-baseline.json', log_baseline)
observed_failures = {}
_require_add_supervisor(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
success = None
while time.monotonic() < deadline:
@@ -853,6 +868,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
break
if not success:
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
job['_native_add_pending'] = False
update_worker_state(job, 'POSTCALL')
def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_source=None):
@@ -1125,6 +1142,7 @@ def _catalog_com(job, root):
if int(library.FlowType) != 1:
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
update_worker_state(job, 'CLOSING')
library.Close()
library = None
_require_management_continuation(job, root)
@@ -1169,14 +1187,18 @@ def _catalog_com(job, root):
result['detail'] = str(error)
result['exception'] = _exception_details(error)
finally:
if library is not None:
try: library.Close()
if library is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
library.Close()
except Exception as error:
result['close_detail'] = str(error)
result['close_exception'] = _exception_details(error)
library = None
if app is not None:
try: app.Quit()
if app is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
app.Quit()
except Exception as error:
result['quit_detail'] = str(error)
result['quit_exception'] = _exception_details(error)
+15 -2
View File
@@ -142,6 +142,9 @@ def _reconcile(path, root, handles, stack):
if identity.get('role') == 'supervisor':
continue
key = tuple(identity[k] for k in IDENTITY_KEYS)
changed_key = ('identity_changed', *key)
if changed_key in handles:
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察', session=session, state=state)
if key not in handles:
try:
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000, False, identity['pid'])
@@ -157,6 +160,8 @@ def _reconcile(path, root, handles, stack):
actual = {'pid': identity['pid'], **_handle_identity(handle),
**_force_ownership(handle, identity['pid'])}
if any(actual[k] != identity[k] for k in IDENTITY_KEYS):
handles[key] = handle
handles[changed_key] = True
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察',
session=session, state=state)
handles[key] = handle
@@ -205,6 +210,14 @@ 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':
try:
from .library_lock import release_retained_library
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
if proof.get('status') == 'RELEASE_CONFIRMED':
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
except Exception as error:
result['detail'] += f';资源释放待确认:{error}'
try:
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
except (OSError, ValueError):
@@ -214,14 +227,14 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
progress(result)
except Exception:
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
if result['status'] in ('RELEASED', 'IDENTITY_CHANGED') or stop.is_set():
if result['status'] == 'RELEASED' or stop.is_set():
return result
if not handles and process is not None and process.poll() is None:
stop.wait(1)
continue # The exact owned handle survives a failed journal.
if not handles and process is None:
return result
stop.wait(5 if result['status'] == 'UNCONFIRMED' else 1)
stop.wait(5 if result['status'] in ('UNCONFIRMED', 'IDENTITY_CHANGED') else 1)
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None):
+3 -1
View File
@@ -475,8 +475,10 @@ class MainWindow(QWidget):
f'{item.get("stage", "")}\n{item["evidence_path"]}')
for session in sessions:
if session['status'] != 'RELEASED':
phase = {'NATIVE_CALL': '原生操作进行中', 'CLOSING': '正在关闭', 'POSTCALL': '原生调用已返回',
'PRECALL': '尚未开始', 'UNCONFIRMED': '当前状态无法确认'}.get(session.get('phase'), '待核对')
self.output.append(f'未完成会话:{session.get("block") or ""} · '
f'{session.get("phase", "")} · {session.get("detail", "")}\n{session["path"]}')
f'{phase} · {session.get("detail", "")}\n{session["path"]}')
def check_library_release(self):
if self.busy or not self.lmc_edit.text().strip():