fix: serialize ready diagnostic close and exact native prompt handling

This commit is contained in:
阿白叔 committed 2026-11-17 04:20:05 +08:00
1 parent eaff46e50e
commit fd50805380
6 files changed
+233 -16

No files matched your search

+61 -12
View File
@@ -138,10 +138,14 @@ def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True):
return None
def _target_frame(windows, name):
def _target_frame(windows, name, *, require_ready=True):
matches = []
for window in windows:
if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True):
if not window['class'].casefold().startswith('afx:'):
continue
if require_ready and (not window.get('enabled', True) or any(
child['class'].casefold() == 'msctls_progress32' and child.get('visible', False)
for child in window['children'])):
continue
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
continue
@@ -170,6 +174,23 @@ def _windows(pid):
# Custom controls may have no cached text; missing evidence fails closed.
user.GetWindowTextW(hwnd, buffer, len(buffer))
return buffer.value
def owner_chain(hwnd):
import win32service
desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(
win32api.GetCurrentThreadId()), 2)
chain, seen = [], {hwnd}
for _ in range(8):
hwnd = int(win32gui.GetWindow(hwnd, 4) or 0)
if not hwnd or hwnd in seen: break
seen.add(hwnd)
thread, owner_pid = win32process.GetWindowThreadProcessId(hwnd)
same_desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(thread), 2) == desktop
chain.append({'hwnd': hwnd, 'pid': owner_pid, 'class': win32gui.GetClassName(hwnd),
'text': text(hwnd), 'visible': bool(win32gui.IsWindowVisible(hwnd)),
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'same_desktop': same_desktop,
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
if owner_pid != pid or not same_desktop or chain[-1]['visible']: break
return chain
result = []
seen = 0
def collect(hwnd, _):
@@ -191,10 +212,10 @@ def _windows(pid):
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls')
child_cls = win32gui.GetClassName(ch)
if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden'
or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')):
or child_cls.casefold() in ('mdiclient', 'msctls_progress32') or child_cls.casefold().startswith('afx:')):
children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch),
'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch),
'enabled': bool(win32gui.IsWindowEnabled(ch))})
'enabled': bool(win32gui.IsWindowEnabled(ch)), 'visible': bool(win32gui.IsWindowVisible(ch))})
return True
if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden':
win32gui.EnumChildWindows(hwnd, child, None)
@@ -205,7 +226,8 @@ def _windows(pid):
return True
result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption,
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children,
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
'owner': int(win32gui.GetWindow(hwnd, 4) or 0),
'owner_chain': owner_chain(hwnd) if cls == '#32770' else []})
return True
win32api.SetLastError(0)
try:
@@ -261,6 +283,24 @@ def _cancel(job):
raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled')
def _owned_by_frame(window, frame):
if frame is None or window['pid'] != frame['pid']: return False
if window.get('owner') == frame['hwnd']: return True
chain = window.get('owner_chain', ())
expected, seen = window.get('owner'), {window['hwnd']}
if not chain or len(chain) > 8: return False
for index, owner in enumerate(chain):
if (owner['hwnd'] != expected or owner['hwnd'] in seen or owner['pid'] != frame['pid']
or owner.get('same_desktop') is not True): return False
seen.add(owner['hwnd'])
if owner['hwnd'] == frame['hwnd']:
return (index == len(chain)-1 and owner['class'] == frame['class'] and owner['text'] == frame['text'])
if (owner['class'] != '#32770' or owner['text'] != 'Expedition PCB'
or owner['visible'] or owner['enabled']): return False
expected = owner['owner']
return False
def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''):
for window in windows:
known_titles = {'expedition pcb', 'expedition pcb - reusable block'}
@@ -276,14 +316,21 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked
and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold()
for child in window['children'])
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7})
if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text):
forward = (window['class'] == '#32770' and window['text'] == 'Expedition PCB'
and any(child['class'].casefold() == 'static' and child.get('id') == 6172
and ' '.join(child['text'].split()) == 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
for child in window['children'])
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} in ({6,7}, {6,7,6171}))
if _owned_by_frame(window, frame) and (forward or closing and (standard_save or 'do you want to save the reusable block cell' in text)):
targets = [child for child in window['children'] if child['class'].casefold() == 'button'
and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'}
and child.get('enabled', True)]
if len(targets) == 1:
if session is None: return True
if window['hwnd'] not in clicked:
session.post(targets[0]['hwnd'], 0xF5)
clicked.add(window['hwnd'])
if not closing: return True
continue
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; '
f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} "
@@ -317,6 +364,7 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
time.sleep(min(.1, max(0, deadline-time.monotonic())))
try:
deadline = time.monotonic() + max(.01, float(job['timeout']))
startup_clicked = set()
while True:
_cancel(job)
error = _read_bounded(error_reader) if error_reader else None
@@ -327,14 +375,14 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
windows = scan(deadline)
if any(window['pid'] != int(pcb_pid) for window in windows):
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
frame = _target_frame(windows, Path(job['pcb']).stem)
frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
# Startup splash/control windows are transient. Unknown windows
# veto closing only once the target actually has loaded evidence.
pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
if frame is not None else True)
evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False)
if frame is not None and not pending else None)
if evidence is not None:
if frame is not None else None)
pending = (_pending_prompt(windows, frame=frame, session=session if evidence else None,
clicked=startup_clicked, pcb_name=Path(job['pcb']).name) if frame is not None else True)
if evidence is not None and not pending and _target_frame(windows, Path(job['pcb']).stem) is not None:
emit(stage='diagnostic_native_loaded_candidate', **evidence)
break
if time.monotonic() >= deadline:
@@ -348,7 +396,8 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
if current is None or current['hwnd'] != frame['hwnd']:
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
session.post(frame['hwnd'], 0x10)
emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd'])
emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd'],
operation_id=job.get('operation_id'), desktop=job.get('desktop'), project=job['project'], pcb=job['pcb'])
close_deadline = time.monotonic() + 30
clicked = set()
last_pending = ''
+7 -2
View File
@@ -116,7 +116,7 @@ def _read_document(path: Path) -> list[dict[str, Any]]:
return rules
def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]:
def load_rules(default_path: Path, override_path: Path | None = None, *, diagnostic_only=False) -> tuple[DialogRule, ...]:
ordered: list[str] = []
raw_by_id: dict[str, dict[str, Any]] = {}
for raw in _read_document(default_path):
@@ -137,7 +137,12 @@ def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[D
else:
ordered.append(rule_id)
raw_by_id[rule_id] = dict(override)
return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
rules = tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
if diagnostic_only:
# The process-bound diagnostic checker declines this prompt after proving the loaded project.
rules = tuple(replace(rule, category='OBSERVE_PROGRESS', action='', channels=(), target=())
if rule.rule_id == 'forward-annotation-confirm' else rule for rule in rules)
return rules
def _semantic_text(snapshot: WindowSnapshot) -> str:
+17 -2
View File
@@ -412,6 +412,14 @@ def phase_for_event(event, current=None):
return mapping.get(stage, current or DialogPhase.PCB_STARTING)
def _diagnostic_close_event(job, event, target_pid):
return (job.get('diagnostic_only') is True and event.get('stage') == 'diagnostic_wm_close'
and target_pid is not None and event.get('pcb_pid') == target_pid
and type(event.get('hwnd')) is int and event['hwnd'] > 0
and bool(job.get('operation_id')) and event.get('operation_id') == job['operation_id']
and all(event.get(key) == job.get(key) for key in ('project', 'pcb', 'desktop')))
def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation):
"""Classify a returned Verify command that never started its PCB.
@@ -951,6 +959,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
events = root/'events.jsonl'
offset = 0
target_pid = None
diagnostic_closing = False
launcher_pid = None
lm_pid = None
verify_invoked = False
@@ -1002,7 +1011,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
dialog_supervisor = DialogSupervisor(
AgentDialogBackend(dialog_agent, pids=lambda: {
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
rules=load_rules(default_rules_path()),
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
)
else:
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
@@ -1045,6 +1054,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except json.JSONDecodeError:
break
timing.record(event)
if _diagnostic_close_event(job, event, target_pid):
diagnostic_closing = True
if event.get('pcb_pid'): target_pid = event['pcb_pid']
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
if event.get('lm_pid'): lm_pid = event['lm_pid']
@@ -1083,7 +1094,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception as error:
observation = {'error': str(error)}
last_post_verify_observation = observation
if dialog_agent is not None and target_pid is None:
if diagnostic_closing:
# The exact diagnostic worker owns its bounded close/No sequence.
from .dialog_supervisor import DialogPollResult
dialog_result = DialogPollResult(activity=False)
elif dialog_agent is not None and target_pid is None:
# The Library Manager Verify route starts its own window
# before it launches Expedition PCB. Do not feed that
# large MFC main window to the PCB dialog probe; it can
+53
View File
@@ -0,0 +1,53 @@
import json
from pathlib import Path
import pytest
from test_verify_runner import fixture, request, PORTS_OK
@pytest.mark.parametrize('fault', ['', 'no_event', 'wrong_pid', 'wrong_operation', 'wrong_project', 'wrong_desktop', 'ordinary'])
def test_only_current_diagnostic_close_leaves_prompt_actions_to_checker(tmp_path, monkeypatch, fault):
from cbb_refresh_verify import desktop_worker
from cbb_refresh_verify.verify_runner import run_verify
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
fixture(tmp_path); polls = []
class Worker:
desktop = None
pid = 700
companion_pids = []
returncode = None
count = 0
def __init__(self, command, name):
self.name = name
path = Path(command[-1]); job = json.loads(path.read_text())
event = dict(stage='diagnostic_wm_close', pcb_pid=901, hwnd=900,
operation_id=job['operation_id'], desktop=job['desktop'], project=job['project'], pcb=job['pcb'])
for condition, key, value in [('wrong_pid','pcb_pid',999),('wrong_operation','operation_id','foreign'),
('wrong_project','project','foreign.prj'),('wrong_desktop','desktop','Default')]:
if fault == condition: event[key] = value
events = [dict(stage='pcb_worker_started', pcb_pid=901)]
if fault != 'no_event': events.append(event)
path.with_name('events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
path.with_name('outcome.json').write_text(json.dumps({'status':'FAIL','safe_to_continue':False,
'stderr':'DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown prompt retained'}))
def poll(self):
self.count += 1
if self.count > 2: self.returncode = 1
return self.returncode
def close(self): pass
def wait(self, timeout=5): self.returncode = 1; return 1
class Supervisor:
def poll(self, *args):
polls.append(True)
return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='competing save prompt')
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK,
dialog_supervisor_factory=lambda **kwargs:Supervisor())
assert result.status == 'FAIL'
assert json.loads(result.evidence_path.with_name('outcome.json').read_text())['safe_to_continue'] is False
if not fault:
assert polls == []
assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr
else:
assert polls and 'UNKNOWN_DIALOG' in result.stderr
+86
View File
@@ -83,6 +83,58 @@ def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
def test_visible_loading_progress_is_not_ready_for_diagnostic_close(diagnostic, job):
window = frame(job)
progress = {'hwnd': 13, 'class': 'msctls_progress32', 'text': '', 'visible': True}
window['children'].append(progress)
assert diagnostic._target_frame([window], 'IP101GR') is None
progress['visible'] = False
assert diagnostic._target_frame([window], 'IP101GR') == window
@pytest.mark.parametrize('cancel', [False, True])
def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic, job, monkeypatch, cancel):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
signal = Path(job['root']).parent/'cancel-progress'
job['cancel_signal'] = str(signal)
target = frame(job)
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
def windows(pid):
if cancel: signal.touch()
return [target]
monkeypatch.setattr(diagnostic,'_NativeSession',Session)
monkeypatch.setattr(diagnostic,'_windows',windows)
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if cancel else 'DIAGNOSTIC_OPEN_UNCONFIRMED'):
diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)
assert Session.instances[-1].posted == []
def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job); job['timeout'] = 1
class ForwardSession(Session):
declined = False
def post(self, hwnd, message):
self.posted.append((hwnd,message))
if hwnd == 31: self.declined = True
else: self.alive = False
def windows(pid):
state = Session.instances[-1]
target = frame(job)
if state.declined: return [target] if state.alive else []
target['enabled'] = False
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
return [target, {'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10,
'children':[{'hwnd':30,'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'},
{'hwnd':31,'class':'Button','id':7,'text':'&No','enabled':True},
{'hwnd':32,'class':'Button','id':6,'text':'&Yes','enabled':True}]}]
monkeypatch.setattr(diagnostic,'_NativeSession',ForwardSession)
monkeypatch.setattr(diagnostic,'_windows',windows)
assert diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)['status']=='PASS'
assert Session.instances[-1].posted == [(31,0xF5),(10,0x10)]
class Session:
instances = []
def __init__(self, job, pid, launcher):
@@ -417,3 +469,37 @@ def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monke
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
session.post(10, 0x10)
@pytest.mark.parametrize('fault', ['', 'foreign_pid', 'cycle', 'other_frame', 'visible', 'enabled', 'class', 'title', 'desktop', 'incomplete', 'filename'])
def test_diagnostic_save_accepts_only_complete_hidden_owner_chain(diagnostic, job, fault):
target = frame(job)
owner = {'hwnd': 15, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
'owner': 10, 'visible': False, 'enabled': False, 'same_desktop': True}
end = {**target, 'same_desktop': True}
window = {'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
'owner': 15, 'owner_chain': [owner, end], 'children': [
{'hwnd': 30, 'class': 'Static', 'text': 'Save changes to IP101GR.pcb?', 'id': -1},
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}
if fault == 'foreign_pid': owner['pid'] = 99
if fault == 'cycle': owner['owner'] = 15
if fault == 'other_frame': end['hwnd'] = 99
if fault == 'visible': owner['visible'] = True
if fault == 'enabled': owner['enabled'] = True
if fault == 'class': owner['class'] = 'VendorDialog'
if fault == 'title': owner['text'] = 'Unknown recovery'
if fault == 'desktop': owner['same_desktop'] = False
if fault == 'incomplete': window['owner_chain'] = [owner]
if fault == 'filename': window['children'][0]['text'] = 'Save changes to Foreign.pcb?'
session = Session(job, 42, None)
action = lambda:diagnostic._pending_prompt([window], closing=True, frame=target,
session=session, clicked=set(), pcb_name='IP101GR.pcb')
if not fault:
assert action() is False
assert session.posted == [(31, 0xF5)]
else:
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
action()
assert session.posted == []
+9
View File
@@ -15,6 +15,15 @@ from cbb_refresh_verify.dialog_rules import (
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
def test_diagnostic_forward_prompt_is_observed_while_ordinary_verify_still_confirms():
text = 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
snapshot = prompt(text)
ordinary = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
diagnostic = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json', diagnostic_only=True))
assert ordinary.action == 'confirm_forward_annotation'
assert diagnostic.category == 'OBSERVE_PROGRESS' and not diagnostic.action
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
control_types=("Text", "Button")):
controls = tuple(