feat(dsh): add persistent automatic AI intervention switch
Core regression / Python core and release configuration (push) Successful in 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 17s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-04 21:52:58 +08:00
1 parent 9316cf4fc4
commit e28c6d0d6e
12 files changed
+292 -31

No files matched your search

+10 -5
View File
@@ -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')
@@ -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)
@@ -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)