fix: validate the hidden owner of a late startup tip

This commit is contained in:
阿白叔 committed 2026-11-17 07:14:54 +08:00
1 parent a64636ba0d
commit d5d1a3deea
3 files changed
+127 -6

No files matched your search

+5 -2
View File
@@ -98,6 +98,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
dismissed_tips = set()
close_handle = None
close_identity = None
close_frame = None
while True:
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records:
@@ -217,6 +218,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
close_frame = main[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.
@@ -231,9 +233,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
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,
dict(pid=pcb_pid, name='ExpeditionPCB.exe', scope_confirmed=True, startup_frame=close_frame,
**close_identity), close_handle, windows,
incomplete=residual_sessions._window_error(snapshot, pcb_pid), dismissed=dismissed_tips)
incomplete=residual_sessions._window_error(snapshot, pcb_pid),
dismissed=dismissed_tips, deadline=deadline)
if dismissed is not None:
dismissed_tips.add(dismissed)
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=dismissed)
+44 -4
View File
@@ -482,9 +482,35 @@ def inspect_residual_sessions(library, *, block_names=()):
'previous_records': previous}
def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=()):
def _hidden_tip_owner(tip, pid):
"""Read only the Tip's direct hidden frame, never arbitrary hidden windows."""
import win32api, win32con, win32gui, win32process
with _window_desktop(tip['desktop']) as desktop:
hwnd = win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER)
if (not hwnd or hwnd not in _desktop_windows(desktop)
or win32process.GetWindowThreadProcessId(hwnd)[1] != pid
or win32gui.IsWindowVisible(hwnd) or win32gui.IsWindowEnabled(hwnd)):
return None
kind, title = win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd)
if not kind.startswith('Afx:') or title.strip() not in (
'Expedition PCB', 'Expedition PCB - Reusable Block'):
return None
children, documents = [], []
def child(control, _):
control_class = win32gui.GetClassName(control)
if control_class.casefold() == 'msctls_progress32':
children.append({'class': control_class})
if control_class == 'MDIClient' and win32gui.GetWindow(control, win32con.GW_CHILD):
documents.append(control)
win32api.SetLastError(0)
win32gui.EnumChildWindows(hwnd, child, None)
return dict(hwnd=hwnd, title=title, **{'class': kind}, desktop=tip['desktop'],
enabled=False, children=children, documents=documents)
def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=(), deadline=None, stop=None):
"""A non-writing startup Tip may finish an already pending normal close."""
import win32con, win32event
import win32con, win32event, win32gui
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'
@@ -498,12 +524,19 @@ def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=())
if len(tips) != 1 or tips[0]['hwnd'] in dismissed:
return None
tip = tips[0]
hidden_owner = None
if not any(w['class'].startswith('Afx:') for w in windows):
hidden_owner = _hidden_tip_owner(tip, row['pid'])
# 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]
if hidden_owner is not None:
rest.append(dict(hidden_owner, enabled=True))
main, _ = close_target(row['name'], rest)
if (main is None or main.get('documents') or main['title'].strip() not in (
if (main is None or main.get('documents')
or row.get('startup_frame', main['hwnd']) != main['hwnd']
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
@@ -515,6 +548,8 @@ def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=())
if active_write_records(row['library']):
return None
with _window_desktop(tip['desktop'], write=True):
if win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']:
return None
current = _startup_snapshot(tip['hwnd'], row['pid'])
target = _tip_target(current)
if (target is None or target.handle != buttons[0]['hwnd']
@@ -524,8 +559,13 @@ def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=())
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 win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']
or hidden_owner is not None and _hidden_tip_owner(tip, row['pid']) != hidden_owner
or _startup_snapshot(tip['hwnd'], row['pid']) != current):
return None
if (deadline is not None and time.monotonic() >= deadline
or stop is not None and stop.is_set()):
return None
_post_window_message(tip, target.handle, row['pid'], win32con.BM_CLICK)
return tip['hwnd']
@@ -544,7 +584,7 @@ def _request_close(row, *, stop=None):
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:
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.
deadline = time.monotonic()+3
+78
View File
@@ -42,6 +42,8 @@ def late_tip_fixture(tmp_path, monkeypatch):
monkeypatch.setattr(sessions, '_post_window_message',
lambda w, hwnd, pid, msg: post(hwnd, msg))
monkeypatch.setattr(sessions, '_window_desktop', lambda *a, **kw: nullcontext())
monkeypatch.setattr(win32gui, 'GetWindow', lambda hwnd, kind:
100 if hwnd == 200 and kind == win32con.GW_OWNER else 0)
# Revalidation reads native controls, independently of the initial snapshot.
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
def snapshot(hwnd, pid):
@@ -172,3 +174,79 @@ def test_release_tip_ack_never_stacks_another_close_while_process_still_exits(tm
assert result['release_status'] == 'WAITING' and records
assert messages == [(201, win32con.BM_CLICK)]
assert 3 <= state['ticks'] < 3.2
@pytest.mark.parametrize('entry', ['startup', 'release'])
@pytest.mark.parametrize('obstacle', ['', 'foreign_owner', 'other_desktop', 'document',
'progress', 'changed_owner', 'enabled_owner', 'wrong_title'])
def test_late_tip_direct_hidden_empty_owner_matches_native_capture(tmp_path, monkeypatch, entry, obstacle):
import win32con, win32gui, win32process
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
frame, tip = deepcopy(windows)
monkeypatch.setattr(sessions, '_process_windows', lambda pids: {
12: [deepcopy(tip)] if state['tip'] else [dict(frame, enabled=True)]})
monkeypatch.setattr(sessions, '_desktop_windows', lambda desktop:
[200] if obstacle == 'other_desktop' else [100, 200])
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: hwnd != 100 if state['tip'] else True)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd:
hwnd != 100 or not state['tip'] or obstacle == 'enabled_owner')
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd:
'Loaded.pcb - Expedition PCB' if state['tip'] and obstacle == 'wrong_title'
else 'Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd:
('msctls_progress32' if obstacle == 'progress' else 'MDIClient') if hwnd == 300
else 'Afx:main')
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
fn(300, arg) if state['tip'] and obstacle in ('document', 'progress') else None)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd:
(1, 99 if hwnd == 100 and state['tip'] and obstacle == 'foreign_owner' else 12))
reads = []
def owner(hwnd, kind):
if hwnd == 300 and kind == win32con.GW_CHILD: return 301
if hwnd == 200 and kind == win32con.GW_OWNER:
reads.append(hwnd)
return 999 if obstacle == 'changed_owner' and len(reads) > 1 else 100
return 0
monkeypatch.setattr(win32gui, 'GetWindow', owner)
if entry == 'release':
state['tip'] = True
result = sessions._request_close(row)
status = result['release_status']
else:
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
status = result['status']
expected = [(100, win32con.WM_CLOSE)] if entry == 'startup' else []
if obstacle:
assert status in ('WAITING', 'RETAINED') and records
else:
expected.append((201, win32con.BM_CLICK))
assert status in ('CLOSED', 'RELEASED') and not records
assert messages == expected
@pytest.mark.parametrize('entry', ['startup_deadline', 'release_stop'])
def test_tip_action_rechecks_budget_or_stop_after_slow_fresh_snapshot(tmp_path, monkeypatch, entry):
from threading import Event
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
stop = Event()
original = sessions._process_windows
reads = []
def snapshot(pids):
value = original(pids)
if state['tip']:
reads.append(1)
if len(reads) >= 2:
state['ticks'] += 2
stop.set()
return value
monkeypatch.setattr(sessions, '_process_windows', snapshot)
if entry == 'startup_deadline':
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED'
assert messages == [(100, win32con.WM_CLOSE)]
else:
state['tip'] = True
assert sessions._request_close(row, stop=stop)['release_status'] in ('WAITING', 'CANCELLED')
assert not messages
assert records