fix: retain unknown startup windows and expose native dispatch errors

This commit is contained in:
阿白叔 committed 2026-11-02 22:19:59 +08:00
1 parent 46c3e72364
commit ffa7e84d43
4 files changed
+154 -8

No files matched your search

+9 -2
View File
@@ -103,7 +103,14 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
and win32gui.GetWindowText(w).strip() in (
'Expedition PCB', 'Expedition PCB - Reusable Block')
and win32gui.IsWindowEnabled(w)]
dialogs = any(win32gui.GetClassName(w) == '#32770' for w in windows)
observed = [{'hwnd': w, 'class': win32gui.GetClassName(w),
'title': win32gui.GetWindowText(w), 'enabled': bool(win32gui.IsWindowEnabled(w))}
for w in windows]
benign = [w for w in observed if w['title'] == '' and w['class'] in (
'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')]
unknown = [w for w in observed if w['hwnd'] not in main and w not in benign]
result.update(owned_windows=observed, unknown_windows=unknown,
benign_auxiliary_windows=benign)
documents = []
def child(hwnd, _):
if (win32gui.GetClassName(hwnd) == 'MDIClient'
@@ -112,7 +119,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
if len(main) == 1:
win32gui.EnumChildWindows(main[0], child, None)
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
if len(main) == 1 and not dialogs and not documents and not addresses:
if len(main) == 1 and not unknown and not documents and not addresses:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
sent = True
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
+39 -6
View File
@@ -218,23 +218,48 @@ def _close_probe_dialogs(desktop, owned_pids):
return # Never close a parent with an unreleased child.
def _probe_add_dialog(app, job, desktop, owned_pids, root):
def _exception_details(error):
import traceback
return {'type': f'{type(error).__module__}.{type(error).__name__}', 'message': str(error),
'args': json.loads(json.dumps(error.args, default=str)),
'hresult': getattr(error, 'hresult', None),
'traceback': ''.join(traceback.format_exception(type(error), error, error.__traceback__))}
def _dispatch_diagnostics(root, stage, app, library, *, paths=None):
"""Read only three known DISPIDs, preserving errors hidden by dynamic COM."""
record = {'stage': stage, 'members': {}}
for label, obj, name in (('application.OnReusableBlocksEditor', app, 'OnReusableBlocksEditor'),
('application.Quit', app, 'Quit'), ('library.Close', library, 'Close')):
try:
record['members'][label] = {'dispid': obj._oleobj_.GetIDsOfNames(name)}
except Exception as error:
record['members'][label] = {'error': _exception_details(error)}
if paths is not None:
record['paths'] = paths
with (Path(root)/'dispatch-diagnostics.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n')
def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
try:
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root)
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root, library=library)
finally:
import gc
gc.collect() # Release UIA wrappers before closing native child dialogs.
_close_probe_dialogs(desktop, owned_pids)
def _probe_add_dialog_impl(app, job, desktop, owned_pids, root):
def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None):
"""Diagnostic only: proven editor/UIA tab and resource1103 controls.
This function has no production capability override. It is called only
after this worker itself creates a new disposable library.
"""
import pythoncom, win32con, win32gui, win32process
_dispatch_diagnostics(root, 'before-pywinauto-import', app, library)
from pywinauto import Desktop
_dispatch_diagnostics(root, 'after-pywinauto-import', app, library)
from .backup_recovery import _align_library
from .management import source_project
source, pcb, top = source_project(job['source'], job.get('top_level_block', ''))
@@ -242,6 +267,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root):
if not source.is_relative_to(Path(root).parent.resolve()/source_folder):
raise ValueError('隔离新增只允许使用本次复制的来源工程。')
_align_library(source, pcb, Path(job['library']))
_dispatch_diagnostics(root, 'after-source-alignment', app, library,
paths={'source': str(source), 'pcb': str(pcb), 'library_argument': job['library']})
validate_name(job['name'])
deadline = time.monotonic() + float(job['timeout_seconds'])
def find_window(title):
@@ -545,7 +572,7 @@ def _catalog_com(job, root):
if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve():
raise RuntimeError('原生返回中心库身份不一致。')
if job['operation'] in ('probe_create_add', 'probe_readd'):
_probe_add_dialog(app, job, desktop, owned_pids, root)
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
entries = []
parts = library.Partitions(7)
for i in range(1, int(parts.Count) + 1):
@@ -569,14 +596,19 @@ def _catalog_com(job, root):
result.update(success=True, library=str(library.FullName), flow=int(library.FlowType), entries=entries)
except Exception as error:
result['detail'] = str(error)
result['exception'] = _exception_details(error)
finally:
if library is not None:
try: library.Close()
except Exception as error: result['close_detail'] = str(error)
except Exception as error:
result['close_detail'] = str(error)
result['close_exception'] = _exception_details(error)
library = None
if app is not None:
try: app.Quit()
except Exception as error: result['quit_detail'] = str(error)
except Exception as error:
result['quit_detail'] = str(error)
result['quit_exception'] = _exception_details(error)
app = None
stop.set()
if watcher:
@@ -630,6 +662,7 @@ def management_worker_main(request_path):
raise ValueError('未验证的原生管理操作')
except Exception as error:
result['detail'] = str(error)
result['exception'] = _exception_details(error)
finally:
_write_json(root/'result.json', result)
return 0 if result['success'] and result['safe_to_continue'] else 2
+44
View File
@@ -186,3 +186,47 @@ def test_startup_exit_does_not_hide_late_database_address(tmp_path, monkeypatch)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED'
assert result['release']['addresses']
@pytest.mark.parametrize('window_class,title', [('CustomPrompt', 'Database action pending'),
('Afx:tool', ''), ('UAC_InputIndicatorOverlayWnd', 'Unknown prompt'), ('UAC Input Indicator', ' ')])
def test_enabled_empty_main_with_unaccounted_owned_window_is_never_closed(tmp_path, monkeypatch, window_class, title):
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)])
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else window_class)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else title)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED' and not result['release']['safe_to_continue']
assert messages == [] and records
assert result['unknown_windows'] == [{'hwnd': 200, 'class': window_class, 'title': title, 'enabled': True}]
assert json.loads((tmp_path/'startup-close.json').read_text(encoding='utf-8'))['unknown_windows'] == result['unknown_windows']
def test_empty_title_known_uac_windows_are_accounted_for_before_normal_close(tmp_path, monkeypatch):
import win32gui, win32con
job, records, messages = startup_fixture(tmp_path, monkeypatch)
classes = {100: 'Afx:main', 200: 'UAC_InputIndicatorOverlayWnd', 201: 'UAC Input Indicator'}
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in classes])
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else '')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)]
assert result['unknown_windows'] == []
assert [entry['hwnd'] for entry in result['benign_auxiliary_windows']] == [200, 201]
def test_custom_prompt_must_disappear_before_main_close(tmp_path, monkeypatch):
from types import SimpleNamespace
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
ticks = [0.0]
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg:
[fn(hwnd, arg) for hwnd in ((100, 200) if ticks[0] == 0 else (100,))])
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else 'CustomPrompt')
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else 'Still processing')
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0],
sleep=lambda seconds: ticks.__setitem__(0, ticks[0] + seconds)))
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'CLOSED' and ticks[0] > 0
assert len(messages) == 1
+62
View File
@@ -0,0 +1,62 @@
import json
from pathlib import Path
from types import ModuleType, SimpleNamespace
import pytest
def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path):
from cbb_refresh_verify.native_management import _dispatch_diagnostics
class Error(RuntimeError):
hresult = -2147221008
class Raw:
def GetIDsOfNames(self, name):
if name == 'Quit': raise Error('COM apartment unavailable')
return 17 if name == 'Close' else 21
obj = SimpleNamespace(_oleobj_=Raw())
_dispatch_diagnostics(tmp_path, 'before-import', obj, obj)
record = json.loads((tmp_path/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8'))
assert record['members']['application.OnReusableBlocksEditor']['dispid'] == 21
assert record['members']['library.Close']['dispid'] == 17
error = record['members']['application.Quit']['error']
assert error['hresult'] == -2147221008 and error['args'] == ['COM apartment unavailable']
assert error['type'].endswith('Error')
def test_probe_records_dispatch_before_after_import_and_after_source_alignment(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import sys
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
'KEY iCDBDir "database"\nKEY CentralLibrary "old.lmc"\n')
(source.parent/'database').mkdir(); (source.parent/'database/icdb.dat').write_bytes(b'fixture')
pcb = source.parent/'PCB/Block.pcb'; (pcb.parent/'Layout').mkdir(parents=True)
pcb.write_text('KEY ProjectFile "../Block.prj"\n')
(pcb.parent/'pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
(pcb.parent/'Layout/LayoutDB.lyt').write_bytes(b'fixture')
root = tmp_path/'native-add'; root.mkdir()
library = root/'fixture/mentor_lib.lmc'; library.parent.mkdir(); library.touch()
phase = ['before']
class Raw:
def GetIDsOfNames(self, name): return 1 if phase[0] == 'before' else 2
class App:
_oleobj_ = Raw()
def OnReusableBlocksEditor(self): raise RuntimeError('stop before native UI')
class Uia(ModuleType):
def __getattr__(self, name):
if name == 'Desktop':
phase[0] = 'after'
return None
raise AttributeError(name)
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
job = {'operation': 'probe_create_add', 'source': str(source), 'library': str(library),
'name': 'Block', 'timeout_seconds': 0}
with pytest.raises(RuntimeError, match='stop before native UI'):
native._probe_add_dialog_impl(App(), job, None, set(), root, library=SimpleNamespace(_oleobj_=Raw()))
records = [json.loads(line) for line in (root/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8').splitlines()]
assert [r['stage'] for r in records] == ['before-pywinauto-import', 'after-pywinauto-import', 'after-source-alignment']
assert records[0]['members']['application.Quit']['dispid'] == 1
assert records[1]['members']['application.Quit']['dispid'] == 2
assert records[2]['paths'] == {'source': str(source), 'pcb': str(pcb), 'library_argument': str(library)}
assert 'old.lmc' not in source.read_text()