from PySide6.QtCore import Signal, Qt from PySide6.QtWidgets import QWidget from types import SimpleNamespace import pytest from dx_productivity.trial_task_center.errors import TaskCenterError pytestmark = pytest.mark.usefixtures('ai_ready') class HarnessView(QWidget): action_requested = Signal(object) task_creation_requested = Signal(object) task_creation_cancelled = Signal(object) lifecycle_requested = Signal(object) lifecycle_cancelled = Signal(object) stopped = Signal() def __init__(self, parent): super().__init__(parent) self.starts = 0 self.binds = [] self.creation = {} self.lifecycle = {} self.operations = {} self.lifecycle_results = [] self.results = [] def start(self): self.starts += 1 def bind(self, snapshot, **kwargs): self.operations = kwargs.get('operations', {}) self.binds.append(snapshot) self.context = {'task_id': snapshot.task_id, 'revision': 'rev'} def shutdown(self): pass def complete_task_creation(self, value): self.results.append(value) def complete_lifecycle(self, value): self.lifecycle_results.append(value) def test_direct_navigation_opens_harness_and_returns_without_losing_task(ui, monkeypatch, qtbot): window = ui.window monkeypatch.setattr(type(window), '_create_dsh_view', lambda self: HarnessView(self), raising=False) task_id = window._task_id qtbot.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton) assert window.content_stack.currentWidget() is window._dsh_view assert window._dsh_view.binds[-1].task_id == task_id assert window._dsh_view.starts == 1 assert window.dsh_navigation.isChecked() assert window.task_center_navigation.geometry().right() < window.dsh_navigation.geometry().left() qtbot.mouseClick(window.task_center_navigation, Qt.MouseButton.LeftButton) assert window.content_stack.currentIndex() == 0 assert window._task_id == task_id assert window.task_center_navigation.isChecked() qtbot.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton) assert window._dsh_view.starts == 1 def test_dsh_navigation_surfaces_lazy_startup_failure(ui, monkeypatch, qtbot): window = ui.window def fail(_self): raise RuntimeError('controlled missing WebEngine') monkeypatch.setattr(type(window), '_create_dsh_view', fail) qtbot.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton) assert window.ai_status_indicator.property('state') == 'unavailable' assert 'DSH助手不可用' in window.ai_status_indicator.toolTip() def test_cross_task_harness_action_never_reaches_task_service(ui, monkeypatch): window = ui.window monkeypatch.setattr(type(window), '_create_dsh_view', lambda self: HarnessView(self), raising=False) window.dsh_action.trigger() called = [] monkeypatch.setattr(window, '_retry_failed', lambda: called.append('retry')) window._handle_dsh_action({'action': 'retry_failed', 'task_id': 'another', 'revision': 'rev'}) assert not called def test_error_entry_queues_automatic_ai_without_running_synchronous_retry(ui, monkeypatch): window = ui.window events, retried = [], [] window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True) window._dsh.action_handler = lambda proposal: retried.append(proposal) window._show_error(TaskCenterError('worker_error', 'controlled error')) assert len(events) == 1 and events[0][0][:2] == (window._task_id, 'worker_error') assert not retried def test_failed_result_queues_ai_even_when_no_exception_is_raised(ui, monkeypatch): window = ui.window events = [] window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append((args, kwargs)) or True) monkeypatch.setattr(window, '_metadata_changed', lambda _: None) window._active_quick_run_task_id = window._task_id window._show_batch_result(SimpleNamespace(paused=False, progress=SimpleNamespace(failed_items=1, saved_items=0, no_match_items=0))) assert events[0][0][1] == 'execution_failed' def test_cancelled_operation_does_not_start_ai(ui): window = ui.window events = [] window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *args, **kwargs: events.append(args)) window._show_error(TaskCenterError('operation_cancelled', 'cancelled')) assert not events def test_interrupted_incident_restores_as_pending_without_replay(ui, monkeypatch): import json from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation window = ui.window incident_id = '0' * 24 directory = ui.data / 'dsh' / 'incidents' / incident_id directory.mkdir(parents=True) (directory / 'incident.json').write_text(json.dumps({'incident_id': incident_id, 'task_id': window._task_id, 'issue_code': 'worker_error', 'status': 'retrying', 'attempts': 1, 'analyses': []}), encoding='utf8') automation = DshAutomation(window) assert automation.latest['status'] == 'pending_issue' assert not automation.pending and automation.worker is None window._dsh_automation = automation monkeypatch.setattr(type(window), '_create_dsh_view', lambda self: HarnessView(self)) window.dsh_action.trigger() assert window._dsh_view.automation['status'] == 'pending_issue' def test_auto_intervention_toggle_persists_and_disabled_errors_do_not_enqueue(ui, qtbot): from PySide6.QtCore import QSettings window = ui.window events = [] assert window.auto_intervention_check.isChecked() window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append(a), set_enabled=lambda enabled: None) qtbot.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) window._show_error(TaskCenterError('worker_error', 'disabled error')) assert not events settings = QSettings(str(ui.service.layout_settings_path), QSettings.Format.IniFormat) assert settings.value('dsh/auto_intervention', True, type=bool) is False ui.settle() from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow reopened = TrialTaskCenterWindow(ui.service) qtbot.addWidget(reopened) assert not reopened.auto_intervention_check.isChecked() qtbot.waitUntil(lambda: not reopened._task_query.busy and not reopened._resource_status.busy) reopened.close() def test_intervention_switch_has_colored_track_and_supports_keyboard(ui, qtbot): from PySide6.QtCore import QPoint switch = ui.window.auto_intervention_check def track_color(): image = switch.grab().toImage() scale = image.devicePixelRatio() return image.pixelColor(round((switch.width() - 38) * scale), round(switch.height() / 2 * scale)) green = track_color() assert green.green() > green.red() + 30 qtbot.mouseClick(switch, Qt.MouseButton.LeftButton, pos=QPoint(switch.width() - 5, switch.height() // 2)) assert not switch.isChecked() switch.setFocus() qtbot.keyClick(switch, Qt.Key.Key_Space) assert switch.isChecked() def test_taskless_error_automatically_queues_diagnosis(ui): window = ui.window window._task_id = None window._dsh_run_id = 'previous-cad-run' events = [] window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append((a, kw)) or True) window._show_error(TaskCenterError('worker_error', 'taskless error')) assert len(events) == 1 assert events[0][0][:2] == ('', 'worker_error') assert events[0][1]['execution_authorized'] is False assert events[0][1]['run_id'] == 'observation' assert window._dsh.history[-1]['snapshot']['task_id'] == '' def test_native_startup_failure_never_enqueues_itself(ui): events = [] ui.window._dsh_automation = SimpleNamespace(can_cancel=False, cancel=lambda: None, enqueue=lambda *a, **kw: events.append(a)) ui.window._show_error(TaskCenterError('dsh_startup', 'native unavailable')) assert not events def test_disabling_clears_pending_without_stopping_original_execution(ui, monkeypatch): from PySide6.QtWidgets import QApplication from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows') automation = DshAutomation(ui.window) ui.window._dsh_automation = automation from dx_productivity.trial_task_center.stop_control import StopControl original_stop = StopControl() drain = automation._drain monkeypatch.setattr(automation, '_drain', lambda: None) assert automation.enqueue(ui.window._task_id, 'worker_error', 'queued', stop_event=original_stop) retry_permission = automation.execution_enabled ui.window.auto_intervention_check.setChecked(False) assert not automation.pending assert not original_stop.is_set() assert not retry_permission.is_set() drain() assert ui.window._dsh_view is None assert not automation.enqueue('', 'worker_error', 'disabled') ui.window.auto_intervention_check.setChecked(True) assert automation.execution_enabled.is_set() assert not retry_permission.is_set() def test_duplicate_errors_share_pending_incident_but_new_runs_do_not(ui, monkeypatch): from PySide6.QtWidgets import QApplication from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows') automation = DshAutomation(ui.window) monkeypatch.setattr(automation, '_drain', lambda: None) for run in ('first', 'first', 'second'): assert automation.enqueue(ui.window._task_id, 'worker_error', 'error', run_id=run) assert len(automation.pending) == 2 def test_diagnosis_completion_refresh_cannot_retrigger_persistent_read_error(ui, monkeypatch): from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation ui.settle() automation = DshAutomation(ui.window) events = [] monkeypatch.setattr(automation, 'enqueue', lambda *a, **kw: events.append(a)) monkeypatch.setattr(ui.window, '_dsh_automation', automation) def fail(*a, **kw): raise TaskCenterError('task_read_failed', 'persistent failure') monkeypatch.setattr(ui.service, 'task_context', fail) automation._current_identity = (ui.window._task_id, 'task_read_failed', 'observation') automation.seen.add(automation._current_identity) automation._finished() ui.settle() assert not events assert 'persistent failure' in ui.window.run_panel.operator_band.text() def test_taskless_incident_actions_allow_outbox_and_evidence_but_reject_other_tasks(ui, monkeypatch): from PySide6.QtGui import QDesktopServices window = ui.window calls = [] monkeypatch.setattr(window, '_task_id', None) monkeypatch.setattr(window, '_dsh_view', SimpleNamespace(context={'revision': 'r'}, shutdown=lambda: None)) monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace( can_cancel=False, cancel=lambda: None, latest={'task_id': '', 'incident_id': 'a' * 24}, resubmit=lambda value: calls.append(value))) monkeypatch.setattr(QDesktopServices, 'openUrl', lambda url: calls.append(url.toLocalFile())) window._handle_dsh_action({'task_id': '', 'revision': 'r', 'action': 'retry_issue'}) window._handle_dsh_action({'task_id': '', 'revision': 'r', 'action': 'open_evidence'}) window._handle_dsh_action({'task_id': 'other', 'revision': 'r', 'action': 'retry_issue'}) assert len(calls) == 2 assert calls[0] == 'a' * 24 assert calls[1].endswith('a' * 24) def test_passive_taskless_refresh_cannot_retrigger_renderer_error(ui, monkeypatch): ui.settle() events = [] monkeypatch.setattr(ui.window, '_task_id', None) monkeypatch.setattr(ui.window, '_queue_dsh_incident', lambda *a: events.append(a)) def fail(*args): raise TaskCenterError('render_failed', 'persistent render failure') monkeypatch.setattr(ui.window.project_summary, 'populate', fail) ui.window._load_task_data(auto_intervene=False) assert not events assert 'persistent render failure' in ui.window.run_panel.operator_band.text()