fix: serialize ready diagnostic close and exact native prompt handling
This commit is contained in:
1 parent
eaff46e50e
commit
fd50805380
6 files changed
+233
-16
No files matched your search
@@ -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 = ''
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user