fix: clear late owned startup tips after normal close

This commit is contained in:
阿白叔 committed 2026-11-17 07:07:18 +08:00
1 parent 4402486baa
commit a64636ba0d
4 files changed
+278 -6

No files matched your search

+35 -4
View File
@@ -1,5 +1,6 @@
"""Close only an idle document whose native identity was already established."""
import json
from contextlib import ExitStack
import os
from pathlib import Path
import time
@@ -69,16 +70,18 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
read/write question is declined; no ownership is taken or version restored.
Unknown windows and documents are retained. WM_CLOSE is cooperative.
"""
import win32api, win32con, win32gui, win32process
import win32api, win32con, win32gui, win32process, win32event
from .mentor_adapter import _process_details
from .native_repair_ui import _current_desktop_name
from .icdb_ownership import unreleased_addresses
from . import residual_sessions
root = Path(job['root'])
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
'safe_to_continue': False}
if launcher_process is not None:
result['launcher_pid'] = launcher_process.pid
handles = ExitStack()
try:
desktop = job.get('desktop', '')
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
@@ -93,9 +96,18 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
declined_kind = None
cancelled_open = False
dismissed_tips = set()
close_handle = None
close_identity = None
while True:
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records:
if (close_handle is not None
and win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_OBJECT_0):
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 原进程句柄尚未确认退出'
if time.monotonic() >= deadline:
break
time.sleep(.2)
continue
if declined_hwnd is not None:
cancelled_open = True
result['cancelled_prompt'] = declined_kind
@@ -200,15 +212,32 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
win32gui.EnumChildWindows(main[0], child, None)
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
sent = True
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
# Observe exit even when the caller requested no extra wait.
continue
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
# After the single owned WM_CLOSE, WMI may lose the executable/
# command fields before removing the PID. Only observe exit here;
# never issue another close or treat missing fields as release.
# WMI fields can disappear during teardown. The held identity binds
# any late Tip action to the original process, never a reused PID.
if sent and time.monotonic() < deadline:
if _current_desktop_name() != desktop:
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
snapshot = residual_sessions._process_windows({pcb_pid})
windows = snapshot.get(pcb_pid, [])
if all(w.get('desktop') == desktop for w in windows):
dismissed = residual_sessions._dismiss_startup_tip(
dict(pid=pcb_pid, name='ExpeditionPCB.exe', scope_confirmed=True,
**close_identity), close_handle, windows,
incomplete=residual_sessions._window_error(snapshot, pcb_pid), dismissed=dismissed_tips)
if dismissed is not None:
dismissed_tips.add(dismissed)
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=dismissed)
continue
if time.monotonic() >= deadline:
if sent:
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
@@ -216,6 +245,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
time.sleep(.2)
except Exception as error:
result['detail'] = str(error)
finally:
handles.close()
(root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
emit(stage='startup_close_result', **result)
return result
@@ -482,6 +482,54 @@ def inspect_residual_sessions(library, *, block_names=()):
'previous_records': previous}
def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=()):
"""A non-writing startup Tip may finish an already pending normal close."""
import win32con, win32event
from .failed_session import _startup_snapshot, _tip_target
if (incomplete or row.get('scope_confirmed') is not True
or row.get('name', '').casefold() != 'expeditionpcb.exe'
or row.get('runtime_phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED')
or native_activity(row['name'], windows)['status'] != 'IDLE'):
return None
desktops = {w.get('desktop', '') for w in windows}
if len(desktops) != 1 or not next(iter(desktops), '').startswith('CbbVerify_'):
return None
tips = [w for w in windows if w['class'] == '#32770' and w['title'] == 'Tip of the Day']
if len(tips) != 1 or tips[0]['hwnd'] in dismissed:
return None
tip = tips[0]
# A disabled empty frame is expected behind a modal Tip. No document,
# progress, other dialog, or arbitrary disabled application is admitted.
rest = [dict(w, enabled=True) if w['class'].startswith('Afx:') else w
for w in windows if w is not tip]
main, _ = close_target(row['name'], rest)
if (main is None or main.get('documents') or main['title'].strip() not in (
'Expedition PCB', 'Expedition PCB - Reusable Block')):
return None
buttons = [c for c in tip['children'] if c['class'] == 'Button' and c.get('id') == 1
and c.get('enabled')]
if len(buttons) != 1 or not tip['enabled']:
return None
if row.get('library'):
from .session_record import active_write_records
if active_write_records(row['library']):
return None
with _window_desktop(tip['desktop'], write=True):
current = _startup_snapshot(tip['hwnd'], row['pid'])
target = _tip_target(current)
if (target is None or target.handle != buttons[0]['hwnd']
or current.title != tip['title'] or current.window_class != tip['class']):
return None
fresh = _process_windows({row['pid']})
if (_window_error(fresh, row['pid']) or fresh.get(row['pid']) != windows
or win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_TIMEOUT
or _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}
or _startup_snapshot(tip['hwnd'], row['pid']) != current):
return None
_post_window_message(tip, target.handle, row['pid'], win32con.BM_CLICK)
return tip['hwnd']
def _request_close(row, *, stop=None):
import win32con, win32event
with _process_handle(row['pid']) as handle:
@@ -494,6 +542,18 @@ def _request_close(row, *, stop=None):
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
if _dismiss_startup_tip(row, handle, windows) is not None:
# Legacy startup cleanup may already have sent WM_CLOSE. Only wait
# for it here; never stack another close behind this acknowledgement.
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': '已停止释放'}
return {'release_status': 'WAITING', 'detail': '已关闭启动提示,等待原生退出后重新检查'}
if row['name'].casefold() == 'expeditionpcb.exe':
from .failed_session import _startup_snapshot, _cancel_target
for window in windows: