diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 728a5fb..aeb6232 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -1123,7 +1123,8 @@ Sub QPDiscardFailedBatchProject(ByRef ErrorDescription) If (Not QP_BatchMode And Not QP_SessionMode) Or Not QP_OwnedProject Or QP_App Is Nothing Then Exit Sub HasStagedItems = False If IsObject(QP_SessionItems) Then HasStagedItems = (QP_SessionItems.Count > 0) - If QP_NativeMutationPossible Or QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then + If QP_NativeMutationPossible Or QP_NativeCallActive Or QP_RestoreTransactionOpen Or _ + QP_BatchSaveRequested Or QP_BatchSaveCommitted Or HasStagedItems Then ErrorDescription = "write or save outcome requires reconciliation; owned project retained without automatic save or discard" Exit Sub End If @@ -1658,6 +1659,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath) End If CommandLine = CommandLine & " --native-helper --snapshot " & Chr(34) & SnapshotPath & Chr(34) Set Shell = CreateObject("WScript.Shell") + QP_Stage = "native_replace" QP_NativeCallActive = True QPProgress "native_replace", 0, 1 ExitCode = Shell.Run(CommandLine, 0, True) diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index b94ec25..865b09c 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -292,7 +292,8 @@ def wait_for(callback, description, timeout=15): raise TimeoutError(description) -def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15): +def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_interval=0.15, + scope=lambda: None): deadline = time.monotonic() + timeout previous = None stable_since = None @@ -309,7 +310,7 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in previous = stable_since = None time.sleep(poll_interval) continue - signature = tuple(tuple(str(value) for value in columns) for _, columns in latest) + signature = (scope(), tuple(tuple(str(value) for value in columns) for _, columns in latest)) now = time.monotonic() if signature != previous: previous = signature @@ -321,6 +322,99 @@ def wait_for_library_rows(callback, target, timeout=30, stable_for=0.45, poll_in raise TimeoutError(f"Native DxDataBook did not finish loading target part: {target}") +def load_databook_target(snapshot, report, target, *, controls, browse, filter_part, + list_rows, dialogs, close_dialog): + """Load the target before the native submit boundary and retry a prepared batch once.""" + from .batch_attempt import can_retry_attempt + + diagnostic = report.setdefault('databook', {}) + loads = diagnostic['loads'] = [] + baseline = {row['hwnd'] for row in dialogs()} + initial = snapshot_attempt(snapshot) + warm = controls() is not None + for index in range(2): + timeout = 20 if warm else 45 + started = time.monotonic() + load = {'mode': 'warm' if warm else 'cold', 'timeout_seconds': timeout, + 'attempt_state_before_load': initial[1]['state'] if initial else None} + loads.append(load) + save_report(snapshot, report) + pair = None + + def read(): + nonlocal pair + current = controls() + if current is None: + pair = None + return [] + if current != pair: + filter_part(current[1]) + pair = current + load.update(list_handle=pair[0], filter_handle=pair[1]) + return list_rows(pair[0]) + + try: + if index == 0 or controls() is None: + browse() + rows = wait_for_library_rows(read, target, timeout=timeout, scope=lambda: pair) + except TimeoutError as error: + load['error'] = str(error) + load['elapsed_seconds'] = round(time.monotonic() - started, 3) + load['dialogs'] = [row for row in dialogs() if row['hwnd'] not in baseline] + bound = snapshot_attempt(snapshot) + prepared = initial is not None and initial[1]['state'] == 'prepared' and can_retry_attempt(*initial) + load['attempt_state'] = bound[1]['state'] if bound else None + blockers = [row for row in load['dialogs'] if not row.get('browser')] + candidates = [row for row in blockers if row['dismissible']] + retry = index == 0 and prepared and bool(os.environ.get('DXPART_DESKTOP')) + # A different modal must get its normal operator handling. + retry = retry and (not blockers or len(blockers) == len(candidates) == 1) + load['retry'] = retry + save_report(snapshot, report) + if not retry: + raise + if candidates: + close_dialog(candidates[0]) + load['closed_dialog'] = candidates[0]['hwnd'] + warm = True + else: + load['elapsed_seconds'] = round(time.monotonic() - started, 3) + return pair[0], rows + + +def databook_dialogs(gui, process, pid, replacement, main_handle): + from .cad_dialogs import _text + + replacement_thread, _ = process.GetWindowThreadProcessId(replacement) + rows = [] + + def dialog(handle, _): + if (handle in {replacement, main_handle} or not gui.IsWindowVisible(handle) + or process.GetWindowThreadProcessId(handle)[1] != pid + or gui.GetClassName(handle) != '#32770'): + return + owner = gui.GetWindow(handle, 4) # GW_OWNER + row = {'hwnd': handle, 'owner': owner, 'pid': pid, 'title': '', 'children': [], + 'browser': False, 'dismissible': False} + rows.append(row) + children = [] + try: + row['title'] = _text(handle) + gui.EnumChildWindows(handle, lambda child, _: children.append(child), None) + row['children'] = [{'hwnd': child, 'parent': gui.GetParent(child), 'class': gui.GetClassName(child), + 'id': gui.GetDlgCtrlID(child)} for child in children[:64]] + row['browser'] = {('SysListView32', 4000), ('Edit', 4006)} <= { + (child['class'], child['id']) for child in row['children']} + row['dismissible'] = (not row['title'].strip() and not children and owner == replacement + and process.GetWindowThreadProcessId(handle)[0] == replacement_thread + and not gui.IsWindowEnabled(replacement)) + except (OSError, gui.error) as error: + row['read_error'] = str(error) + + gui.EnumWindows(dialog, None) + return rows + + def target_symbol_matches(displayed, library_symbol, slot_count): actual = str(displayed).casefold() expected = str(library_symbol).casefold() @@ -848,8 +942,8 @@ def run_native(snapshot, report): raise ValueError("Multiple replacement dialogs") return matches[0] if matches else None - def message(handle, code, wparam=0, lparam=0): - return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, 15000) + def message(handle, code, wparam=0, lparam=0, *, timeout=15000): + return win32gui.SendMessageTimeout(handle, code, wparam, lparam, win32con.SMTO_ABORTIFHUNG, timeout) def control_text(control): buffer = ctypes.create_unicode_buffer(2048) @@ -865,9 +959,9 @@ def run_native(snapshot, report): control = dlg_item(dialog, identifier) if not control: raise ValueError(f"Required native option {identifier} is unavailable") - if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1: + if message(control, 0x00F0)[1] != 1: click(control) - if win32gui.SendMessage(control, 0x00F0, 0, 0) != 1: + if message(control, 0x00F0)[1] != 1: raise ValueError(f"Native option {identifier} was not enabled") report.setdefault("native_options", {})[str(identifier)] = { "text": control_text(control), @@ -896,31 +990,63 @@ def run_native(snapshot, report): "main_visible_before_browse": bool(win32gui.IsWindowVisible(main_handle)), "browse_button": int(dlg_item(dialog, 1366)), } - click(dlg_item(dialog, 1366)) - def part_list(): - report["databook"]["main_visible_during_wait"] = bool( - win32gui.IsWindowVisible(main_handle) - ) + def query_message(handle, code, wparam=0, lparam=0): + try: + message(handle, code, wparam, lparam, timeout=5000) + except win32gui.error as error: + if error.winerror == 1460: + raise TimeoutError('Native DxDataBook browse or filter did not respond') from error + raise + + def browse(): + button = dlg_item(dialog, 1366) + if button and win32gui.IsWindowEnabled(dialog) and win32gui.IsWindowEnabled(button): + query_message(button, 0x00F5) # BM_CLICK + + def controls(): + lists, filters = {}, {} for handle in owned_windows(include_hidden=True): - if win32gui.GetClassName(handle) == "SysListView32" and win32gui.GetDlgCtrlID(handle) == 4000: - return handle - return None - list_handle = wait_for(part_list, "Native DxDataBook part list did not open", timeout=30) + try: + kind = (win32gui.GetClassName(handle), win32gui.GetDlgCtrlID(handle)) + if kind == ('SysListView32', 4000): + lists[handle] = win32gui.GetAncestor(handle, 2) + elif kind == ('Edit', 4006): + filters[handle] = win32gui.GetAncestor(handle, 2) + except win32gui.error: + if win32gui.IsWindow(handle): + raise + pairs = [(part_list, part_filter) for part_list, list_root in lists.items() + for part_filter, filter_root in filters.items() if list_root == filter_root] + visible = [pair for pair in pairs if all(win32gui.IsWindowVisible(handle) for handle in pair)] + pairs = visible or pairs + return pairs[0] if len(pairs) == 1 else None + + def filter_part(handle): + query_message(handle, win32con.WM_SETTEXT, 0, metadata[3]) + + def current_library_rows(list_handle): + return [(row, [text.window_text() for text in row.children(control_type="Text")]) + for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")] + + def dialogs(): + return databook_dialogs(win32gui, win32process, process_id, dialog, main_handle) + + def close_dialog(expected): + if expected not in dialogs(): + raise OSError('DxDataBook dialog changed before close') + win32gui.PostMessage(expected['hwnd'], win32con.WM_CLOSE, 0, 0) + wait_for(lambda: not win32gui.IsWindowVisible(expected['hwnd']), + 'Native DxDataBook dialog did not close', timeout=3) + + list_handle, rows = load_databook_target(snapshot, report, metadata[3], controls=controls, + browse=browse, filter_part=filter_part, list_rows=current_library_rows, + dialogs=dialogs, close_dialog=close_dialog) report["databook"].update( list_handle=int(list_handle), list_visible=bool(win32gui.IsWindowVisible(list_handle)), main_visible_after_load=bool(win32gui.IsWindowVisible(main_handle)), ) - filter_handles = [handle for handle in owned_windows(include_hidden=True) - if win32gui.GetDlgCtrlID(handle) == 4006 and win32gui.GetClassName(handle) == "Edit"] - if len(filter_handles) != 1: - raise ValueError("Cannot uniquely identify native Part Number filter") - message(filter_handles[0], win32con.WM_SETTEXT, 0, metadata[3]) - def current_library_rows(): - return [(row, [text.window_text() for text in row.children(control_type="Text")]) - for row in desktop.window(handle=list_handle).descendants(control_type="ListItem")] - rows = wait_for_library_rows(current_library_rows, metadata[3]) row, columns = exact_target(rows, metadata[3]) report["library_row"] = columns symbol_parts = columns[2].split(":", 1) @@ -930,6 +1056,9 @@ def run_native(snapshot, report): report["slot_count"] = slot_count if slot_count < 1: raise ValueError("Library target has no valid slots") + current_pair = controls() + if current_pair is None or current_pair[0] != list_handle: + raise ValueError("DxDataBook controls changed after target selection") rectangle = row.rectangle() list_rectangle = win32gui.GetWindowRect(list_handle) if rectangle.height() <= 0 or rectangle.top < list_rectangle[1] or rectangle.bottom > list_rectangle[3]: diff --git a/tests/v1_1/test_databook_load.py b/tests/v1_1/test_databook_load.py new file mode 100644 index 0000000..a538c97 --- /dev/null +++ b/tests/v1_1/test_databook_load.py @@ -0,0 +1,141 @@ +from types import SimpleNamespace + +import pytest + +from dx_productivity.trial_task_center import native_helper as native +from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, read_attempt + + +@pytest.fixture +def attempt(tmp_path, monkeypatch): + job = 'job' + project = tmp_path / 'board.prj' + record_path = tmp_path / 'attempt.json' + snapshot = tmp_path / f'snapshot-{job}.tsv' + snapshot.write_text(f'M\t{project}\tOLD\tNEW\tMAIN:1\nC\tuid\tR1\t0\t0\t0\t1\t\n', encoding='utf-8') + (tmp_path / 'command.tsv').write_text( + f'job_id\ttask_id\tproject_path\n{job}\ttask\t{project}\n', encoding='utf-8') + record = prepare_attempt(record_path, session_id='session', generation=1, + job_id=job, task_id='task', project_path=project) + for name, value in { + 'DXPART_DESKTOP': 'dx-test', + 'DXPART_ATTEMPT_FILE': record_path, + 'DXPART_ATTEMPT_ID': record['attempt_id'], + 'DXPART_BATCH_GENERATION': record['generation'], + 'DXPART_BATCH_SESSION_ID': record['session_id'], + }.items(): + monkeypatch.setenv(name, str(value)) + return snapshot, record_path + + +@pytest.fixture +def clock(monkeypatch): + now = [0.] + monkeypatch.setattr(native, 'time', SimpleNamespace( + monotonic=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds))) + return now + + +def test_cold_list_recreation_reapplies_filter_and_uses_the_new_handle(attempt, clock): + snapshot, record = attempt + report, filtered = {}, [] + browsing = False + + def browse(): + nonlocal browsing + browsing = True + + def controls(): + if browsing: + return (10, 11) if clock[0] < .3 else (20, 21) + return None + + list_handle, rows = native.load_databook_target(snapshot, report, 'NEW', + controls=controls, browse=browse, filter_part=lambda handle: filtered.append(handle), + list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])], + dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close')) + assert (list_handle, rows[0][0], filtered) == (20, 20, [11, 21]) + assert report['databook']['loads'][0]['mode'] == 'cold' + assert read_attempt(record)['state'] == 'prepared' + + +@pytest.mark.parametrize('already_written', [False, True]) +def test_timeout_reissues_filter_once_only_with_bound_prepared_attempt(attempt, clock, already_written): + snapshot, record = attempt + if already_written: + native.mark_snapshot_mutation(snapshot) + report, filters = {}, [] + + def run(): + return native.load_databook_target(snapshot, report, 'NEW', + controls=lambda: (10, 11), browse=lambda: None, + filter_part=lambda handle: filters.append(handle), list_rows=lambda handle: [], + dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close')) + + with pytest.raises(TimeoutError, match='DxDataBook'): + run() + loads = report['databook']['loads'] + assert [load['mode'] for load in loads] == ['warm'] * (1 if already_written else 2) + assert len(filters) == len(loads) + assert read_attempt(record)['state'] == ('mutation_possible' if already_written else 'prepared') + + +def test_retry_closes_only_new_owned_empty_dialog_and_persists_evidence_first(attempt, clock): + snapshot, record = attempt + report, closed = {}, [] + blank = {'hwnd': 19, 'owner': 7, 'title': '', 'children': [], 'dismissible': True} + previous = dict(blank, hwnd=18) + named = dict(blank, hwnd=20, title='Save', dismissible=False) + + def dialogs(): + return [previous, named] if clock[0] == 0 else [previous, blank, named] + + def close(row): + import json + + evidence = json.loads(snapshot.with_suffix('.tsv.native.json').read_bytes()) + assert evidence['databook']['loads'][0]['dialogs'][0]['hwnd'] == 19 + assert evidence['databook']['loads'][0]['attempt_state'] == 'prepared' + closed.append(row['hwnd']) + + native.load_databook_target(snapshot, report, 'NEW', + controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None, + list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])] if closed else [], + dialogs=dialogs, close_dialog=close) + assert closed == [19] + assert len(report['databook']['loads']) == 2 + assert read_attempt(record)['state'] == 'prepared' + + +def test_named_or_unowned_prompt_keeps_operator_handling(attempt, clock): + snapshot, _ = attempt + report = {} + with pytest.raises(TimeoutError, match='DxDataBook'): + native.load_databook_target(snapshot, report, 'NEW', + controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None, + list_rows=lambda handle: [], + dialogs=lambda: [{'hwnd': 20, 'dismissible': False}] if clock[0] else [], + close_dialog=lambda row: pytest.fail('unrecognized prompt was closed')) + assert len(report['databook']['loads']) == 1 + + +def test_dialog_fingerprint_requires_same_owner_pid_thread_and_empty_controls(monkeypatch): + from dx_productivity.trial_task_center import cad_dialogs + + owner, pid = 7, 8 + windows = {10: (1, pid, owner), 11: (1, pid, 99), 12: (2, pid, owner), + 13: (1, 99, owner), 14: (1, pid, owner), owner: (1, pid, 99)} + monkeypatch.setattr(cad_dialogs, '_text', lambda hwnd: '') + gui = SimpleNamespace( + error=RuntimeError, IsWindowVisible=lambda hwnd: True, IsWindowEnabled=lambda hwnd: False, + EnumWindows=lambda callback, _: [callback(hwnd, None) for hwnd in windows], + GetWindow=lambda hwnd, _: windows[hwnd][2], + EnumChildWindows=lambda hwnd, callback, _: callback(20, None) if hwnd == 14 else None, + GetClassName=lambda hwnd: 'Button' if hwnd == 20 else '#32770', + GetDlgCtrlID=lambda hwnd: 1, GetParent=lambda hwnd: 14, + ) + process = SimpleNamespace(GetWindowThreadProcessId=lambda hwnd: windows[hwnd][:2]) + rows = native.databook_dialogs(gui, process, pid, owner, 99) + assert [row['hwnd'] for row in rows] == [10, 11, 12, 14] + assert [row['hwnd'] for row in rows if row['dismissible']] == [10] + assert rows[-1]['children'] == [{'hwnd': 20, 'parent': 14, 'class': 'Button', 'id': 1}] diff --git a/tests/v1_1/test_nonblocking_value_vbs.py b/tests/v1_1/test_nonblocking_value_vbs.py index 6228e24..c45879e 100644 --- a/tests/v1_1/test_nonblocking_value_vbs.py +++ b/tests/v1_1/test_nonblocking_value_vbs.py @@ -3,7 +3,8 @@ import test_accuracy_vbs_guards as guards @pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native', - 'save_requested', 'save_committed', 'close']) + 'native_unresolved', 'prior_staged_write', 'save_requested', + 'save_committed', 'close']) def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault): output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject', 'QPCloseBatchProject', 'QPReadUtf8'], ''' @@ -33,6 +34,8 @@ Set QP_Fso=CreateObject("Scripting.FileSystemObject") QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0 QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj" QP_NativeMutationPossible=''' + str(fault == 'native') + ''' +QP_NativeCallActive=''' + str(fault == 'native_unresolved') + ''' +If ''' + str(fault == 'prior_staged_write') + ''' Then QP_SessionItems.Add "previous-job", "restored_ok" QP_BatchSaveRequested=''' + str(fault == 'save_requested') + ''' QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + ''' Class FakeApp @@ -85,8 +88,8 @@ End Sub Sub QPLog(ByVal Root,ByVal Level,ByVal Message) End Sub ''') - paused_before = fault != 'native' - paused_after = fault not in {'native', 'transaction'} + paused_before = fault not in {'native', 'native_unresolved'} + paused_after = fault not in {'native', 'native_unresolved', 'transaction'} assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}' diff --git a/tests/v1_1/test_target_cell_execution.py b/tests/v1_1/test_target_cell_execution.py index 10307d9..e475408 100644 --- a/tests/v1_1/test_target_cell_execution.py +++ b/tests/v1_1/test_target_cell_execution.py @@ -152,6 +152,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk elif code == 0xF5 and handle == 1695: submits.append(handle) raise RuntimeError('native submit reached') + return 1, 1 gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows, EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True, GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'), @@ -179,7 +180,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk monkeypatch.setattr(native_helper, 'selection', lambda *args: None) monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977) monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback()) - monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback()) + monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args, **kwargs: callback()) monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback()) report = {} with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'):