diff --git a/src/cbb_refresh_verify/failed_session.py b/src/cbb_refresh_verify/failed_session.py index 8f60548..6f233fb 100644 --- a/src/cbb_refresh_verify/failed_session.py +++ b/src/cbb_refresh_verify/failed_session.py @@ -108,6 +108,15 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: for w in windows] benign = [w for w in observed if w['title'] == '' and w['class'] in ( 'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')] + for window in observed: + if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '': + window['rect'] = list(win32gui.GetWindowRect(window['hwnd'])) + window['children'] = [] + win32gui.EnumChildWindows(window['hwnd'], + lambda hwnd, _: window['children'].append(int(hwnd)), None) + left, top, right, bottom = window['rect'] + if left == right and top == bottom and not window['children']: + benign.append(window) 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) diff --git a/src/cbb_refresh_verify/native_management.py b/src/cbb_refresh_verify/native_management.py index 1721f9a..5bb908f 100644 --- a/src/cbb_refresh_verify/native_management.py +++ b/src/cbb_refresh_verify/native_management.py @@ -241,6 +241,47 @@ def _dispatch_diagnostics(root, stage, app, library, *, paths=None): stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n') +def _set_probe_field(hwnd, control_id, expected, root): + """Set/read a remote Edit with a one-second total message budget.""" + from ctypes import wintypes + record = {'control_id': control_id, 'hwnd': int(hwnd), 'expected': expected, + 'actual': None, 'matched': False} + deadline = time.monotonic() + 1.0 + try: + user32 = ctypes.WinDLL('user32', use_last_error=True) + send = user32.SendMessageTimeoutW + send.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM, + wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)] + send.restype = wintypes.LPARAM + def message(code, count, buffer): + remaining = min(1000, int((deadline - time.monotonic()) * 1000)) + if remaining <= 0: + raise TimeoutError(f'原生字段消息超时:{control_id}') + returned = ctypes.c_size_t() + if not send(int(hwnd), code, count, ctypes.addressof(buffer), 0x0002, + remaining, ctypes.byref(returned)): + raise TimeoutError(f'原生字段消息超时或失败:{control_id}, Windows={ctypes.get_last_error()}') + return returned.value + text = ctypes.create_unicode_buffer(expected) + if not message(0x000C, 0, text): # WM_SETTEXT + raise RuntimeError(f'原生字段拒绝写入:{control_id}') + buffer = ctypes.create_unicode_buffer(32768) + copied = message(0x000D, len(buffer), buffer) # WM_GETTEXT, remote Edit marshalled by Windows. + record['actual'] = buffer.value + if copied >= len(buffer) - 1: + raise RuntimeError(f'原生字段复读可能截断:{control_id}') + if record['actual'] != expected: + raise RuntimeError(f'原生新增字段回读失败:{control_id}') + record['matched'] = True + return record['actual'] + except Exception as error: + record['exception'] = _exception_details(error) + raise + finally: + with (Path(root)/'native-field-readback.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, library=library) @@ -309,9 +350,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None) hwnd = win32gui.GetDlgItem(dialog, control) if not hwnd or win32gui.GetClassName(hwnd) != 'Edit': raise RuntimeError(f'原生新增字段身份不匹配:{control}') - win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, 0, value) - if win32gui.GetWindowText(hwnd) != value: - raise RuntimeError(f'原生新增字段回读失败:{control}') + _set_probe_field(hwnd, control, value, root) _write_json(root/'submitted-fields.json', fields) ok = win32gui.GetDlgItem(dialog, 1083) if not ok: diff --git a/tests/test_failed_startup.py b/tests/test_failed_startup.py index c01fb0f..0062239 100644 --- a/tests/test_failed_startup.py +++ b/tests/test_failed_startup.py @@ -230,3 +230,26 @@ def test_custom_prompt_must_disappear_before_main_close(tmp_path, monkeypatch): result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) assert result['status'] == 'CLOSED' and ticks[0] > 0 assert len(messages) == 1 + + +@pytest.mark.parametrize('obstacle', ['', 'title', 'area', 'children', 'near_class']) +def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_path, monkeypatch, obstacle): + import win32gui, win32con + 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 + 'Internet Explorer_Hidden_other' if obstacle == 'near_class' else 'Internet Explorer_Hidden') + monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else + 'Active prompt' if obstacle == 'title' else '') + monkeypatch.setattr(win32gui, 'GetWindowRect', lambda hwnd: (0, 0, 100, 50) if obstacle == 'area' else (0, 0, 0, 0)) + monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: + fn(201, arg) if hwnd == 200 and obstacle == 'children' else None) + result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) + if obstacle: + assert result['status'] == 'RETAINED' and messages == [] + assert result['unknown_windows'][0]['hwnd'] == 200 + else: + assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)] + entry = result['benign_auxiliary_windows'][0] + assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0] + assert entry['children'] == [] diff --git a/tests/test_native_management_fields.py b/tests/test_native_management_fields.py new file mode 100644 index 0000000..0e4a731 --- /dev/null +++ b/tests/test_native_management_fields.py @@ -0,0 +1,58 @@ +import ctypes +import json +from types import SimpleNamespace + +import pytest + + +@pytest.mark.parametrize('expected,actual', [('S:\\source\\项目.prj', 'S:\\source\\项目.prj'), ('', '')]) +def test_field_uses_bounded_set_and_remote_gettext_with_exact_readback(tmp_path, monkeypatch, expected, actual): + from cbb_refresh_verify import native_management as native + calls = [] + class Send: + def __call__(self, hwnd, message, wparam, lparam, flags, timeout, result): + calls.append((hwnd, message, flags, timeout)) + if message == 0x000C: + assert ctypes.wstring_at(lparam) == expected + result._obj.value = 1 + elif message == 0x000D: + buffer = ctypes.create_unicode_buffer(actual) + ctypes.memmove(lparam, ctypes.addressof(buffer), ctypes.sizeof(buffer)) + result._obj.value = len(actual) + else: + pytest.fail('unproven field message') + return 1 + monkeypatch.setattr(native.ctypes, 'WinDLL', lambda *a, **k: SimpleNamespace(SendMessageTimeoutW=Send())) + assert native._set_probe_field(123, 1217, expected, tmp_path) == actual + assert [item[1] for item in calls] == [0x000C, 0x000D] + assert all(item[0] == 123 and item[2] == 0x0002 and 0 < item[3] <= 1000 for item in calls) + record = json.loads((tmp_path/'native-field-readback.jsonl').read_text(encoding='utf-8')) + assert record['expected'] == expected and record['actual'] == actual and record['matched'] + + +@pytest.mark.parametrize('failure', ['empty', 'mismatch', 'set_timeout', 'read_timeout', 'set_rejected', 'truncated']) +def test_field_failure_is_recorded_before_rejection_without_foreground_fallback(tmp_path, monkeypatch, failure): + from cbb_refresh_verify import native_management as native + calls = [] + class Send: + def __call__(self, hwnd, message, wparam, lparam, flags, timeout, result): + calls.append(message) + if message == 0x000C: + result._obj.value = 0 if failure == 'set_rejected' else 1 + return 0 if failure == 'set_timeout' else 1 + if failure == 'read_timeout': return 0 + actual = '' if failure == 'empty' else 'other project' + buffer = ctypes.create_unicode_buffer(actual) + ctypes.memmove(lparam, ctypes.addressof(buffer), ctypes.sizeof(buffer)) + result._obj.value = wparam - 1 if failure == 'truncated' else len(actual) + return 1 + monkeypatch.setattr(native.ctypes, 'WinDLL', lambda *a, **k: SimpleNamespace(SendMessageTimeoutW=Send())) + with pytest.raises((RuntimeError, TimeoutError)): + native._set_probe_field(123, 1217, 'expected project', tmp_path) + record = json.loads((tmp_path/'native-field-readback.jsonl').read_text(encoding='utf-8')) + assert record['expected'] == 'expected project' and not record['matched'] + assert record['control_id'] == 1217 and record['exception']['type'] + if failure in ('empty', 'mismatch'): + assert record['actual'] == ('' if failure == 'empty' else 'other project') + if failure in ('set_timeout', 'set_rejected'): + assert calls == [0x000C]