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:
+9 -2
View File
@@ -7,8 +7,9 @@ from cbb_refresh_verify import failed_session, mentor_adapter
def startup_fixture(tmp_path, monkeypatch):
import win32gui, win32process
from cbb_refresh_verify import native_repair_ui
from contextlib import nullcontext
import win32gui, win32process, win32event, win32con
from cbb_refresh_verify import native_repair_ui, residual_sessions
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
'desktop': 'CbbVerify_test'}
@@ -20,6 +21,12 @@ def startup_fixture(tmp_path, monkeypatch):
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
monkeypatch.setattr(residual_sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(residual_sessions, '_handle_identity', lambda h:
{'created_handle': 'original', 'image': r'C:\Mentor\wg\ExpeditionPCB.exe'})
monkeypatch.setattr(residual_sessions, '_process_windows', lambda pids: {12: []})
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a:
win32con.WAIT_TIMEOUT if records else win32con.WAIT_OBJECT_0)
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
+174
View File
@@ -0,0 +1,174 @@
"""A late, owned Tip must not strand the single pending normal close."""
from contextlib import nullcontext
from copy import deepcopy
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import failed_session, residual_sessions as sessions
from test_failed_startup import startup_fixture
def late_tip_fixture(tmp_path, monkeypatch):
import win32con, win32event, win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
identity = {'created_handle': 'original', 'image': records[0][1]}
state = {'ticks': 0., 'tip': False, 'exited': False}
windows = [dict(hwnd=100, title='Expedition PCB', **{'class': 'Afx:main'},
desktop=job['desktop'], enabled=False, children=[], documents=[]),
dict(hwnd=200, title='Tip of the Day', **{'class': '#32770'},
desktop=job['desktop'], enabled=True, documents=[], children=[
{'hwnd': 201, 'class': 'Button', 'id': 1, 'text': 'OK', 'enabled': True}])]
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda h: dict(identity))
def wait(handle, ms):
state['ticks'] += ms/1000
return win32con.WAIT_OBJECT_0 if state['exited'] else win32con.WAIT_TIMEOUT
monkeypatch.setattr(win32event, 'WaitForSingleObject', wait)
def advance(seconds):
state['ticks'] += seconds
if state['ticks'] >= .2: state['tip'] = True
clock = SimpleNamespace(monotonic=lambda: state['ticks'], sleep=advance)
monkeypatch.setattr(failed_session, 'time', clock)
monkeypatch.setattr(sessions, 'time', clock)
monkeypatch.setattr(sessions, '_process_windows', lambda pids: {
12: deepcopy(windows if state['tip'] else [dict(windows[0], enabled=True)])})
def post(hwnd, message, *_):
messages.append((hwnd, message))
if hwnd == 201 and message == win32con.BM_CLICK:
state['exited'] = True
records.clear()
monkeypatch.setattr(win32gui, 'PostMessage', post)
monkeypatch.setattr(sessions, '_post_window_message',
lambda w, hwnd, pid, msg: post(hwnd, msg))
monkeypatch.setattr(sessions, '_window_desktop', lambda *a, **kw: nullcontext())
# Revalidation reads native controls, independently of the initial snapshot.
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
def snapshot(hwnd, pid):
w = next(w for w in windows if w['hwnd'] == hwnd)
return WindowSnapshot(hwnd, pid, 'ExpeditionPCB.exe', 'pcb', w['class'], w['title'],
DialogPhase.PCB_STARTING, tuple(ControlSnapshot(c['hwnd'], c['id'], c['class'],
c['text'], enabled=c['enabled']) for c in w['children']))
monkeypatch.setattr(failed_session, '_startup_snapshot', snapshot)
row = dict(pid=12, name='ExpeditionPCB.exe', scope_confirmed=True,
library=job['lmc_file'], **identity)
return job, row, records, messages, windows, state, identity
@pytest.mark.parametrize('launcher_exits', [True, False])
def test_late_tip_after_first_close_exits_without_a_second_close(tmp_path, monkeypatch, launcher_exits):
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
launcher = SimpleNamespace(pid=11, poll=lambda:
0 if launcher_exits and state['exited'] and state['ticks'] >= .6 else None)
events = []
result = failed_session.close_failed_startup(job, 12, launcher_process=launcher,
timeout_seconds=1, emit=lambda **event: events.append(event))
assert messages == [(100, win32con.WM_CLOSE), (201, win32con.BM_CLICK)]
assert result['release']['pcb_exited'] and not records
assert result['status'] == ('CLOSED' if launcher_exits else 'RETAINED')
assert result['release']['safe_to_continue'] is launcher_exits
assert .6 <= state['ticks'] <= 1.2
assert sum(e['stage'] == 'startup_tip_dismissed' for e in events) == 1
def test_normal_release_clears_owned_tip_and_waits_for_existing_close(tmp_path, monkeypatch):
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True # Earlier cancelled startup has already posted WM_CLOSE.
result = sessions._request_close(row)
assert result['release_status'] == 'RELEASED'
assert messages == [(201, win32con.BM_CLICK)]
@pytest.mark.parametrize('obstacle', ['foreign_desktop', 'unknown', 'document', 'progress',
'write', 'identity', 'scope', 'changed_prompt', 'disabled_tip', 'incomplete'])
def test_release_tip_never_overrides_unconfirmed_or_writing_state(tmp_path, monkeypatch, obstacle):
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True
if obstacle == 'foreign_desktop': windows[1]['desktop'] = 'Default'
if obstacle == 'unknown': windows.append(dict(windows[1], hwnd=300, title='Unknown action'))
if obstacle == 'document': windows[0]['documents'] = [300]
if obstacle == 'progress': windows[0]['children'] = [{'class': 'msctls_progress32'}]
if obstacle == 'write': row['runtime_phase'] = 'NATIVE_CALL'
if obstacle == 'identity': identity['created_handle'] = 'replacement'
if obstacle == 'scope': row['scope_confirmed'] = False
if obstacle == 'changed_prompt':
original = failed_session._startup_snapshot
from dataclasses import replace
monkeypatch.setattr(failed_session, '_startup_snapshot',
lambda h, p: replace(original(h, p), title='New question'))
if obstacle == 'disabled_tip': windows[1]['children'][0]['enabled'] = False
if obstacle == 'incomplete':
captured = sessions._WindowSnapshot({12}); captured[12] = windows
captured.incomplete[12] = 'unreadable'
monkeypatch.setattr(sessions, '_process_windows', lambda pids: captured)
assert sessions._request_close(row)['release_status'] in ('WAITING', 'IDENTITY_CHANGED')
assert not messages and records
def test_startup_late_tip_does_not_extend_original_close_budget(tmp_path, monkeypatch):
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
# Tip survives acknowledgement; no re-click and no second WM_CLOSE.
import win32gui, win32con
def record(hwnd, message, *_): messages.append((hwnd, message))
monkeypatch.setattr(win32gui, 'PostMessage', record)
monkeypatch.setattr(sessions, '_post_window_message', lambda w,h,p,m: record(h,m))
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED'
assert messages == [(100, win32con.WM_CLOSE), (201, win32con.BM_CLICK)]
assert 1 <= state['ticks'] <= 1.2
@pytest.mark.parametrize('obstacle', ['identity', 'desktop', 'document', 'progress', 'unknown'])
def test_late_tip_after_close_preserves_changed_or_busy_owner(tmp_path, monkeypatch, obstacle):
import win32con, win32gui
from cbb_refresh_verify import native_repair_ui
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
original = win32gui.PostMessage
if obstacle == 'desktop':
monkeypatch.setattr(native_repair_ui, '_current_desktop_name',
lambda: 'Default' if messages else job['desktop'])
def post(hwnd, message, *args):
original(hwnd, message, *args)
if message != win32con.WM_CLOSE: return
if obstacle == 'identity': identity['created_handle'] = 'replacement'
if obstacle == 'document': windows[0]['documents'] = [300]
if obstacle == 'progress': windows[0]['children'] = [{'class': 'msctls_progress32'}]
if obstacle == 'unknown': windows.append(dict(windows[1], hwnd=300, title='Unknown action'))
monkeypatch.setattr(win32gui, 'PostMessage', post)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED' and records
assert messages == [(100, win32con.WM_CLOSE)]
def test_transient_missing_wmi_pid_is_not_exit_of_held_startup_process(tmp_path, monkeypatch):
import win32gui
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: records.clear())
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED'
assert not result['release']['safe_to_continue']
def test_release_rechecks_live_write_record_before_tip_action(tmp_path, monkeypatch):
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True
monkeypatch.setattr('cbb_refresh_verify.session_record.active_write_records',
lambda _: [{'phase': 'NATIVE_CALL'}])
assert sessions._request_close(row)['release_status'] == 'WAITING'
assert not messages
def test_release_tip_ack_never_stacks_another_close_while_process_still_exits(tmp_path, monkeypatch):
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True
def dismiss(window, hwnd, pid, message):
messages.append((hwnd, message))
state['tip'] = False
monkeypatch.setattr(sessions, '_post_window_message', dismiss)
result = sessions._request_close(row)
assert result['release_status'] == 'WAITING' and records
assert messages == [(201, win32con.BM_CLICK)]
assert 3 <= state['ticks'] < 3.2