diff --git a/README.md b/README.md index 5212bde..50446ed 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ DSH助手围绕真实任务中心工作,支持: - 用自然语言创建任务、修改规则、复制或归档任务;工程选择和提交仍由原生窗口确认。 - 查询任务快照、执行预检、影响范围和实际执行历史。 - 在原生确认后按冻结范围执行任务,支持安全暂停、原队列恢复和排期授权。 -- 发生异常时自动介入,收集脱敏证据链、保留诊断记录,并在需要时提交受限 Git 工单。 +- 顶部 **AI 自动介入** 开关默认开启并记住设置;发生异常时自动打开 DSH、新建诊断对话,收集脱敏证据链,并在需要时提交受限 Git 工单。 - 在右侧任务监管中查看运行、影响、排期、经验、工单和用量;审计损坏、证据缺失和未知计数会明确显示。 AI 不能直接写入 CAD、运行 Shell 或绕过确认门禁。普通对话可按用户要求读取本地文件;自动异常诊断为只读事件快照。不确定执行不会自动重放,恢复必须重新核对冻结计划、检查点和业务证据。未配置模型时仍可使用任务监管和本地恢复功能,但不会产生真实模型回复。 diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index 3cabe56..e02efcf 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -58,8 +58,12 @@ DSH 使用独立原生子窗口承载 WebEngine,切回任务中心后保留原 ### 自动异常介入 +顶部常驻 **AI 自动介入** 开关,默认开启,重启后保留设置。关闭后不再接收新的自动异常介入,并清空尚未处理的队列;当前诊断继续保存证据,但不再发起自动重试。已经开始的工程执行继续遵循原来的暂停和强制结束按钮,关闭 AI 开关不会停止工程。 + 任务操作报错、单任务收尾有失败项,或批次包含失败/阻断任务时,会自动切入 DSH助手并创建专属诊断会话,不需要手动提问。原执行收尾后,AI 读取出错任务绑定的快照和脱敏事件;即使切换任务,诊断也不会串到另一个任务。 +没有关联任务的应用异常也会创建诊断对话、保留日志证据,但不会自动执行工程操作。用户取消和助手自身启动失败不触发自动介入,避免取消被误判或启动错误循环。不同事件使用独立会话,同一事件的诊断和复盘沿用该会话。 + 已经由用户确认执行的任务,遇到已知可重试错误且现有服务确认“可重试、没有待核验结果”时,AI 可建议一次自动重试。程序通过原服务准备失败项、执行并重新读取真实进度;只有队列完成、失败为零且没有中断标记,才显示处理通过。模型建议或重试准备成功都不算解决;暂停请求会阻止继续重试。 未解决时,AI 再做一轮复盘,保存结论、依据、未知项和后续验证方法,并尝试提交 Git 工单。事件以任务、原执行轮次和错误码去重;同一任务同一原执行轮次的不同错误码共享一次重试额度,执行前持久记录,重启不重置。未知错误、未授权执行和未核验状态仅诊断取证,不自动重放工程写入。 diff --git a/integration/dsh/task-plugin/client.js b/integration/dsh/task-plugin/client.js index 481f277..428b98e 100644 --- a/integration/dsh/task-plugin/client.js +++ b/integration/dsh/task-plugin/client.js @@ -9,7 +9,7 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ h('h2',null,'DSH工具'), h('p',null,'面向 DxDesigner 器件替换任务的异常分析与执行监管。发现报错后自动介入,直接使用当前任务上下文,无需另外登录。'), h('h3',null,'工作方式'), - h('p',null,'在顶部切换任务中心和 DSH助手。会话、任务选择和未发送草稿会保留。'), + h('p',null,'在顶部切换任务中心和 DSH助手。“AI 自动介入”默认开启并记住设置,异常会自动新建诊断对话;关闭后不再接收自动诊断或发起自动重试。会话、任务选择和未发送草稿会保留。'), h('h3',null,'任务能力'), h('ul',null,...['在对话中创建和修改任务;具体工程与执行范围由原生窗口确认','实时监管当前执行、阶段、耗时与保存/失败/未命中计数','保存执行回执,重启后核对原队列并手动确认恢复','预览精确位号影响;仅有料号映射时明确标记未知匹配数量','检索历史异常经验,仅将持久化核验通过的记录标为已验证','只读同步已有 Git 工单状态与评论,查看本地证据','查看会话 Token、耗时与超时状态,配置响应时限并停止模型生成','设置任务优先级、执行时间与依赖,通过原生窗口确认排期'].map(text=>h('li',{key:text},text))), h('h3',null,'模型与数据'), diff --git a/integration/dsh/task-plugin/host.mjs b/integration/dsh/task-plugin/host.mjs index fce0e6c..1f67f07 100644 --- a/integration/dsh/task-plugin/host.mjs +++ b/integration/dsh/task-plugin/host.mjs @@ -63,7 +63,8 @@ export async function apply(ctx){ let request; try{request=JSON.parse(text);}catch{res.writeHead(400);res.end();return;} const current=await readContext(); - if(!actions.has(request.action)||request.task_id!==current.task_id||request.revision!==current.revision||!current.task_id|| + if(!actions.has(request.action)||request.task_id!==current.task_id||request.revision!==current.revision|| + (!current.task_id&&!['retry_issue','open_evidence'].includes(request.action))|| Object.keys(request).some(key=>!['action','task_id','revision'].includes(key))){res.writeHead(409);res.end();return;} const identity=request.task_id+':'+request.revision+':'+request.action; if(pending.has(identity)){res.writeHead(409);res.end();return;} diff --git a/src/dx_productivity/dsh/incidents.py b/src/dx_productivity/dsh/incidents.py index f526a4b..9e9a444 100644 --- a/src/dx_productivity/dsh/incidents.py +++ b/src/dx_productivity/dsh/incidents.py @@ -60,12 +60,14 @@ class IncidentRunner: record['decision_log_status'] = 'unavailable' evidence.event('decision_log_unavailable', error=type(error).__name__) - def run(self, task_id, issue_code, message, *, run_id='observation', execution_authorized=False, stop_event=None): + def run(self, task_id, issue_code, message, *, run_id='observation', execution_authorized=False, stop_event=None, + execution_enabled=None): with _RUN_LOCK: return self._run(task_id, issue_code, message, run_id=run_id, - execution_authorized=execution_authorized, stop_event=stop_event or Event()) + execution_authorized=execution_authorized, stop_event=stop_event or Event(), + execution_enabled=execution_enabled) - def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event): + def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event, execution_enabled): incident_id = sha256(f'{task_id}:{run_id}:{issue_code}'.encode()).hexdigest()[:24] evidence = IncidentEvidence(self.data_root, incident_id) state_path = evidence.directory / 'incident.json' @@ -119,6 +121,7 @@ class IncidentRunner: gates = {'context_available': context is not None, 'no_unverified_result': context is not None and not context.interrupted, 'retry_phase': context is not None and context.phase == 'retry', 'known_retryable_error': issue_code in RETRYABLE_CODES, 'execution_authorized': bool(execution_authorized), 'not_stopped': not stop_event.is_set(), + 'auto_intervention_enabled': execution_enabled is None or execution_enabled.is_set(), 'retry_budget_available': budget_available, 'model_requested_retry': bool(suggestion and suggestion['action'] == 'retry_failed'), 'failure_policy': policy} @@ -143,14 +146,16 @@ class IncidentRunner: try: # Re-read at the actual mutation boundary; the model never supplies parameters. current = self.service.task_context(task_id) - if current.interrupted or current.phase != 'retry' or stop_event.is_set(): + if (current.interrupted or current.phase != 'retry' or stop_event.is_set() + or (execution_enabled is not None and not execution_enabled.is_set())): raise ValueError('retry_gate_changed') self.service.prepare_failed_quick_run(task_id) prepared = self.service.task_context(task_id) p = prepared.progress expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number, 'part_label' if prepared.task.copy_part_number_to_value else 'preserve') - if prepared.interrupted or not p.next_project_path or stop_event.is_set(): + if (prepared.interrupted or not p.next_project_path or stop_event.is_set() + or (execution_enabled is not None and not execution_enabled.is_set())): raise ValueError('retry_execution_gate_changed') outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event) update('verifying') diff --git a/src/dx_productivity/trial_task_center/ui/dsh_automation.py b/src/dx_productivity/trial_task_center/ui/dsh_automation.py index 8a110e5..27a3052 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_automation.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_automation.py @@ -27,6 +27,10 @@ class DshAutomation(QObject): self.latest = {} self.waiters = {} self.worker = None + self.execution_enabled = Event() + if window.auto_intervention_check.isChecked(): + self.execution_enabled.set() + self._current_identity = None self._connected_view = None self._native_unavailable = False self.model_requested.connect(self._request_model) @@ -47,11 +51,22 @@ class DshAutomation(QObject): except (OSError, ValueError, KeyError): continue + def set_enabled(self, enabled): + self.execution_enabled.clear() + if enabled: + # Old workers retain a revoked permission even after re-enabling. + self.execution_enabled = Event() + self.execution_enabled.set() + else: + for task_id, code, _message, _authorized, run_id, _stop in self.pending: + self.seen.discard((task_id, code, run_id)) + self.pending.clear() + def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation', stop_event=None): # Offscreen UI unit tests have no Chromium surface or local provider. if QApplication.platformName().casefold() == 'offscreen': return False - if issue_code == 'operation_cancelled' or not task_id: + if not self.window.auto_intervention_check.isChecked() or issue_code in {'operation_cancelled', 'dsh_startup'}: return False item = (task_id, issue_code, message, execution_authorized, run_id, stop_event) identity = (task_id, issue_code, run_id) @@ -64,13 +79,16 @@ class DshAutomation(QObject): def _drain(self): w = self.window - if w._closed or self.worker is not None or not self.pending: + if w._closed or not w.auto_intervention_check.isChecked() or self.worker is not None or not self.pending: return if (w._workers or w._loading or (w._dsh_lifecycle and w._dsh_lifecycle.dialog) or (w._dsh_task_creation and w._dsh_task_creation.dialog) or w._dsh_operations.busy): QTimer.singleShot(200, self._drain) return task_id, code, message, authorized, run_id, original_stop = self.pending.pop(0) + self._current_identity = (task_id, code, run_id) + if run_id == 'observation': + run_id = uuid4().hex self.latest = {} self._native_unavailable = False try: @@ -88,12 +106,13 @@ class DshAutomation(QObject): stop = original_stop if original_stop is not None else StopControl() # The same worker gate reserves the mutation lane throughout diagnosis. w._batch_stop = stop - w._active_quick_run_task_id = task_id + w._active_quick_run_task_id = task_id or None runner = IncidentRunner(self.root, w.service, self._analyze, GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit) allow_execution = authorized and not w.plan_panel.has_unsaved_plans() + permission = self.execution_enabled worker = ServiceWorker(lambda: runner.run(task_id, code, message, run_id=run_id, - execution_authorized=allow_execution, stop_event=stop)) + execution_authorized=allow_execution, stop_event=stop, execution_enabled=permission)) self._start_worker(worker) def _start_worker(self, worker): @@ -192,8 +211,12 @@ class DshAutomation(QObject): w = self.window w._workers.discard(self.worker) self.worker = None + if self._current_identity and self._current_identity[2] == 'observation': + self.seen.discard(self._current_identity) + self._current_identity = None w._finish_run() - w._load_task_data() + # A passive refresh must not create an incident about this diagnosis. + w._load_task_data(auto_intervene=False) w._update_gates() if w._close_pending: QTimer.singleShot(0, w.close) diff --git a/src/dx_productivity/trial_task_center/ui/main_window.py b/src/dx_productivity/trial_task_center/ui/main_window.py index b8bc651..dbe1503 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -80,6 +80,9 @@ class TrialTaskCenterWindow(MaterialMainWindow): setattr(self, name, button) self.task_center_action.setChecked(True) navigation_layout.addStretch() + self.auto_intervention_check = QCheckBox('AI 自动介入', objectName='dshAutoIntervention') + self.auto_intervention_check.setToolTip('开启后异常自动新建诊断对话。关闭后不再接收异常或发起自动重试;当前诊断继续保存证据,已开始的执行不受影响。') + navigation_layout.addWidget(self.auto_intervention_check) self.reduced_transparency_button = QToolButton(objectName='reduceTransparency') self.reduced_transparency_button.setText('减少透明度') self.reduced_transparency_button.setCheckable(True) @@ -163,6 +166,9 @@ class TrialTaskCenterWindow(MaterialMainWindow): self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。') self._build_layout() self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat) + self.auto_intervention_check.setChecked(self._layout_settings.value( + 'dsh/auto_intervention', True, type=bool)) + self.auto_intervention_check.toggled.connect(self._set_auto_intervention) self.reduced_transparency_button.setChecked(self._layout_settings.value( 'appearance/reduced_transparency', False, type=bool)) self._material.set_reduced_transparency(self.reduced_transparency_button.isChecked()) @@ -410,7 +416,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._log_presenter.bind(task_id) self._load_task_data() - def _load_task_data(self): + def _load_task_data(self, *, auto_intervene=True): self._context = None self._context_phase = ContextReadPhase.LOADING if self._task_id else ContextReadPhase.IDLE self._update_gates() @@ -418,19 +424,20 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._log_presenter.bind(task_id) if not task_id: self._context_query.invalidate() - self._apply_task_context(None) + self._apply_task_context(None, auto_intervene=auto_intervene) return self.project_summary.state.setText('正在读取任务…') self._context_query.request(lambda control: self.service.task_context(task_id, read_control=control), - self._apply_task_context, self._task_context_failed, cancellable=True) + lambda context: self._apply_task_context(context, auto_intervene=auto_intervene), + lambda error: self._task_context_failed(error, auto_intervene=auto_intervene), cancellable=True) - def _task_context_failed(self, error): + def _task_context_failed(self, error, *, auto_intervene=True): self._context_phase = ContextReadPhase.FAILED self._context = None self.project_summary.state.setText('任务读取失败,请点击“重试读取任务”。') - self._show_error(error) + self._show_error(error, auto_intervene=auto_intervene) - def _apply_task_context(self, context): + def _apply_task_context(self, context, *, auto_intervene=True): try: self._context_phase = ContextReadPhase.READY if context else ContextReadPhase.IDLE self._context = context @@ -453,7 +460,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._update_gates() self._bind_dsh_context() except Exception as error: - self._task_context_failed(error) + self._task_context_failed(error, auto_intervene=auto_intervene) def _update_gates(self): busy = bool(self._workers) or self._loading or self.history_panel._worker is not None @@ -1124,12 +1131,12 @@ class TrialTaskCenterWindow(MaterialMainWindow): def _handle_dsh_action(self, request): view = self._dsh_view - if view is None or not view.context or request.get('task_id') != self._task_id or request.get('revision') != view.context['revision']: + if view is None or not view.context or request.get('task_id') != (self._task_id or '') or request.get('revision') != view.context['revision']: return action = request.get('action') if action in {'retry_issue', 'open_evidence'} and self._dsh_automation: incident = self._dsh_automation.latest - if incident.get('task_id') != self._task_id: + if incident.get('task_id') != (self._task_id or ''): return if action == 'retry_issue': self._dsh_automation.resubmit(incident['incident_id']) @@ -1142,6 +1149,8 @@ class TrialTaskCenterWindow(MaterialMainWindow): if action == 'refresh_snapshot': self._bind_dsh_context('任务上下文已刷新') return + if not self._task_id: + return if self._workers and action != 'pause_task': self._bind_dsh_context('任务操作尚未结束,请等待当前步骤收尾。') return @@ -1245,7 +1254,7 @@ class TrialTaskCenterWindow(MaterialMainWindow): self._update_gates() QThreadPool.globalInstance().start(worker) - def _show_error(self, error, *, owner_task_id=None, **_unused): + def _show_error(self, error, *, owner_task_id=None, auto_intervene=True, **_unused): stable = error if isinstance(error, TaskCenterError) else self.service.report_ui_error(error) message = format_operation_error(stable) if owner_task_id: @@ -1253,27 +1262,36 @@ class TrialTaskCenterWindow(MaterialMainWindow): message = f'任务「{name}」:{message}' self._set_operator_message(message, 'error') task_id = owner_task_id or self._task_id - if task_id and not (isinstance(error, TaskCenterError) and error.code == 'operation_cancelled'): - issue_code = getattr(error, 'code', error.__class__.__name__).lower() + issue_code = getattr(stable, 'code', stable.__class__.__name__).lower() + if issue_code not in {'operation_cancelled', 'dsh_startup'}: try: - self._dsh.observe(TaskSnapshot(task_id, 'failed', issue_code=issue_code, issue=message), auto=False) + self._dsh.observe(TaskSnapshot(task_id or '', 'failed', issue_code=issue_code, issue=message), auto=False) except Exception: # DSH must never hide or replace the original operation error. pass self._bind_dsh_context() - managed = self._queue_dsh_incident(task_id, issue_code, message) + managed = auto_intervene and self._queue_dsh_incident(task_id or '', issue_code, message) else: managed = False if owner_task_id is None or owner_task_id == self._task_id: self._append_log(message) self._update_gates() - if not managed and self.isVisible() and QApplication.platformName().casefold() != 'offscreen': + if auto_intervene and not managed and self.isVisible() and QApplication.platformName().casefold() != 'offscreen': QMessageBox.warning(self, '操作未完成', message) + def _set_auto_intervention(self, enabled): + self._layout_settings.setValue('dsh/auto_intervention', enabled) + self._layout_settings.sync() + if self._dsh_automation is not None: + self._dsh_automation.set_enabled(enabled) + def _queue_dsh_incident(self, task_id, issue_code, message): + if not self.auto_intervention_check.isChecked(): + return False if self._dsh_automation is None: from .dsh_automation import DshAutomation self._dsh_automation = DshAutomation(self) return self._dsh_automation.enqueue(task_id, issue_code, message, - execution_authorized=task_id in self._dsh_authorized_tasks, run_id=self._dsh_run_id, + execution_authorized=task_id in self._dsh_authorized_tasks, + run_id=self._dsh_run_id if task_id else 'observation', stop_event=self._batch_stop if self._batch_stop is not None else self._dsh_run_stop) diff --git a/tests/dsh/test_incidents.py b/tests/dsh/test_incidents.py index f0bb1b6..6976e44 100644 --- a/tests/dsh/test_incidents.py +++ b/tests/dsh/test_incidents.py @@ -155,3 +155,34 @@ def test_different_error_codes_share_one_retry_budget_for_original_run(tmp_path) second = runner.run('t', 'execution_failed', 'same run, different code', execution_authorized=True, run_id='original') assert second['attempts'] == 0 assert service.calls == ['prepare', 'execute'] + + +def test_disabling_intervention_during_analysis_prevents_retry_without_stopping_run(tmp_path): + permission, stop = Event(), Event() + permission.set() + service = Service() + def model(*args): + permission.clear() + return analyze() + result = make_runner(tmp_path, service, model).run('t', 'worker_error', 'failure', + execution_authorized=True, stop_event=stop, execution_enabled=permission) + assert not service.calls + assert not stop.is_set() + assert result['gates']['auto_intervention_enabled'] is False + assert (Path(result['evidence_dir']) / 'evidence.zip').is_file() + + +def test_disabling_at_prepare_boundary_prevents_execution(tmp_path): + permission = Event() + permission.set() + service = Service() + prepare = service.prepare_failed_quick_run + def prepare_and_disable(task_id): + prepare(task_id) + permission.clear() + service.prepare_failed_quick_run = prepare_and_disable + result = make_runner(tmp_path, service).run('t', 'worker_error', 'failure', + execution_authorized=True, execution_enabled=permission) + assert service.calls == ['prepare'] + assert result['status'] == 'escalated' + assert result['retry_error']['detail'] == 'retry_execution_gate_changed' diff --git a/tests/ui/test_dsh_native_menu.py b/tests/ui/test_dsh_native_menu.py index c85e1fb..ff619cf 100644 --- a/tests/ui/test_dsh_native_menu.py +++ b/tests/ui/test_dsh_native_menu.py @@ -122,3 +122,128 @@ def test_interrupted_incident_restores_as_pending_without_replay(ui, monkeypatch 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(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_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(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(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( + 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() diff --git a/tools/accept_dsh_desktop.py b/tools/accept_dsh_desktop.py index 86a6a73..56ecfbe 100644 --- a/tools/accept_dsh_desktop.py +++ b/tools/accept_dsh_desktop.py @@ -35,10 +35,13 @@ def main(): parser.add_argument('--model-settings-check', action='store_true', help='Create an isolated custom provider using a local model-list fixture') parser.add_argument('--file-check', action='store_true', help='Pick and upload a real local text file and ZIP in the official UI') parser.add_argument('--incident', action='store_true', help='Inject a read-only controlled failure and verify automatic diagnosis and Git escalation') + parser.add_argument('--auto-intervention-check', action='store_true', help='Click the intervention switch off/on and diagnose a second taskless incident (requires --incident)') parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue') parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable') parser.add_argument('--create-task', action='store_true', help='Create real project tasks from a live native model conversation') args = parser.parse_args() + if args.auto_intervention_check and not args.incident: + parser.error('--auto-intervention-check requires --incident') output = args.output.resolve() output.mkdir(parents=True, exist_ok=True) if args.file_check: @@ -82,7 +85,7 @@ def main(): report = {'driver': 'Qt QTest mouse clicks + Chromium CDP Input events', 'checks': []} state = {'phase': 'select', 'child': None, 'creation_step': 'input', - 'deadline': time.monotonic() + (600 if args.file_check else 420 if args.incident else 300 if args.create_task else 240 if args.live_model else 150)} + 'deadline': time.monotonic() + (840 if args.auto_intervention_check else 600 if args.file_check else 420 if args.incident else 300 if args.create_task else 240 if args.live_model else 150)} def build_window(service): if not args.create_task: @@ -183,6 +186,22 @@ def main(): window.grab().save(str(output / 'task-center.png')) if args.incident: from dx_productivity.trial_task_center.errors import TaskCenterError + if args.auto_intervention_check: + state['phase'] = 'toggle-disabled' + assert window.auto_intervention_check.isChecked() + QTest.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + assert not window.auto_intervention_check.isChecked() + def dismiss_disabled_error(): + modal = QApplication.activeModalWidget() + assert isinstance(modal, QMessageBox) + QTest.mouseClick(modal.button(QMessageBox.StandardButton.Ok), Qt.MouseButton.LeftButton) + QTimer.singleShot(100, dismiss_disabled_error) + window._show_error(TaskCenterError('dsh_acceptance_disabled', '关闭 AI 自动介入受控验收')) + assert window._dsh_view is None and window._dsh_automation is None + report['checks'].append('clicked intervention off: error remained visible without starting AI') + QTest.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + assert window.auto_intervention_check.isChecked() + report['checks'].append('clicked intervention on before injecting an error') window._show_error(TaskCenterError('dsh_acceptance_failure', 'DSH 自动介入受控验收:模拟不可重试错误,任务没有工程数据,不执行 CAD 写入。')) report['checks'].append('injected controlled failure in real error entry without opening assistant manually') @@ -228,12 +247,34 @@ def main(): row = window._dsh_automation.latest assert row['issue_code'] == 'dsh_acceptance_failure', 'Unexpected UI error replaced controlled incident' assert row['status'] == ('pending_issue' if args.outbox_only else 'escalated') and row['attempts'] == 0 + if args.outbox_only: + timeline = data / 'dsh/incidents' / row['incident_id'] / 'timeline.jsonl' + submissions = [json.loads(line) for line in timeline.read_text(encoding='utf8').splitlines()] + assert sum(event['stage'] == 'issue_submission' for event in submissions) >= 2, 'Resubmit did not reach the desktop publisher' if not args.outbox_only: assert row['ticket']['attachment_status'] == 'uploaded' if args.without_git: assert row['ticket']['credential_source'] == 'prefilled_issue_token' report['checks'].append('client without Git used only the prefilled issue reporter token') report['incident'] = row + if args.auto_intervention_check: + incidents = report.setdefault('incidents', []) + assert row.get('session_id') + if incidents: + assert row['session_id'] != incidents[0]['session_id'] + assert row['incident_id'] != incidents[0]['incident_id'] + assert row['task_id'] == '' + report['checks'].append('second taskless error created and opened a distinct native conversation automatically') + incidents.append(dict(row)) + if len(incidents) == 1: + state['phase'] = 'ready' + click_navigation(window.task_center_action) + window._task_id = None + window._context = None + from dx_productivity.trial_task_center.errors import TaskCenterError + window._show_error(TaskCenterError('dsh_acceptance_failure', + 'DSH 无关联任务异常验收:新建独立诊断对话,不执行 CAD 写入。')) + return report['checks'].append('real native automatic diagnosis and reflection, evidence and ' + ('retryable local issue outbox' if args.outbox_only else 'Git issue attachment') + ' completed without CAD mutations') if args.create_task: diff --git a/tools/verify_dsh_incident_ui.mjs b/tools/verify_dsh_incident_ui.mjs index 87cc001..0d1cd83 100644 --- a/tools/verify_dsh_incident_ui.mjs +++ b/tools/verify_dsh_incident_ui.mjs @@ -26,14 +26,18 @@ try{ assert.match(value.automation.ticket.url,/git\.simgreek\.com\/Skyworth_Digital_Hardware\/dxdesigner-part-replacement\/issues\/\d+/); } await wait(`document.body.innerText.includes('DSH自动诊断')`); - await wait(`document.querySelector('[data-chat-group-part="response"]')?.innerText.length>40`); + await wait(`[...document.querySelectorAll('[data-chat-group-part="response"]')].some(e=>e.innerText.length>40)`); report.checks.push('native auto-created diagnostic conversation visible without manual send'); report.checks.push(outboxOnly?'unresolved incident reflected and local outbox retained after publication unavailable': 'unresolved incident reflected, evidence saved and real Git issue with attachment submitted'); report.ticket=value.automation.ticket; if(outboxOnly){ + await wait(`[...document.querySelectorAll('button')].some(e=>e.textContent==='重新提交工单')`); + await c.evaluate(`(()=>{window.__dshAcceptanceActions=[];const original=window.fetch;window.fetch=async(...args)=>{const response=await original(...args);if(args[0]==='/dx/action')window.__dshAcceptanceActions.push(response.status);return response;};})()`); const before=await c.evaluate(`fetch('/dx/context').then(r=>r.json()).then(d=>d.revision)`); await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent==='重新提交工单')`); + await wait(`window.__dshAcceptanceActions.length>0`); + assert.equal(await c.evaluate(`window.__dshAcceptanceActions.at(-1)`),200,'real resubmit action accepted'); await wait(`fetch('/dx/context').then(r=>r.json()).then(d=>d.revision!==${JSON.stringify(before)}&&d.automation.status==='pending_issue')`); report.checks.push('clicked resubmit and retained pending evidence without replaying CAD'); }else await wait(`!!document.querySelector('[data-testid="dx-auto-ticket"]')`); diff --git a/tools/verify_dsh_runtime.mjs b/tools/verify_dsh_runtime.mjs index bd62c90..65fc4f4 100644 --- a/tools/verify_dsh_runtime.mjs +++ b/tools/verify_dsh_runtime.mjs @@ -84,6 +84,15 @@ try { assert.equal(response.status,409); } report.invalidActionsDenied=true; + await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'',revision:'taskless-revision', + status:'observe',automation:{task_id:'',incident_id:'a'.repeat(24)}})); + for(const [action,expected] of [['retry_issue',200],['open_evidence',200],['retry_failed',409],['pause_task',409]]){ + const response=await fetch(base+'/dx/action',{method:'POST',headers:{...auth,'Content-Type':'application/json'}, + body:JSON.stringify({action,task_id:'',revision:'taskless-revision'})}); + assert.equal(response.status,expected,action); + } + report.tasklessEvidenceAndOutboxAllowed=true; + report.tasklessEngineeringActionsDenied=true; report.status='passed'; await writeFile(path.join(output,'report.json'),JSON.stringify(report,null,2)); console.log(JSON.stringify(report));