feat(dsh): show AI readiness and prevent repeated intervention on status changes
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-05 16:09:41 +08:00
1 parent bd06bbc7d2
commit cf6e3f9d2a
28 files changed
+1159 -37

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
"""Read-only local model readiness; it never probes a remote model service."""
from __future__ import annotations
import json
import os
from pathlib import Path
import re
import subprocess
from .native_runtime import integration_root, node_executable
from .provider_config import load_provider
_MESSAGES = {
'available': 'AI 模型已配置(未测试服务连接)。',
'missing_configuration': '未配置 AI 模型或 API Key;AI 功能已停用。',
'missing_credential': 'AI 模型缺少凭据;AI 功能已停用。',
'invalid_configuration': 'AI 模型配置不可用;AI 功能已停用。',
'runtime_unavailable': 'AI 运行时不可用;AI 功能已停用。',
}
_HOST_KEYS = ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY')
def _result(code: str) -> dict:
return {'available': code == 'available', 'code': code, 'message': _MESSAGES[code]}
def check_availability(data_root: Path) -> dict:
"""Check task-center-root/dsh without creating profiles or exposing secrets."""
directory = Path(data_root) / 'dsh'
home = directory / 'harness-home'
native = any((home / name).is_file() for name in (
'profiles/dx-task/cordis.patch.yml', 'profiles/dx-task/package.json', '.credentials.yaml'))
native = native or bool(os.environ.get('DEEPSEEK_API_KEY', '').strip())
env = dict(os.environ)
host_error = False
if not all(env.get(key, '').strip() for key in _HOST_KEYS):
try:
env.update(load_provider(directory))
except Exception:
host_error = True
configured = all(isinstance(env.get(key), str) and env[key].strip() for key in _HOST_KEYS)
if not native and not configured:
return _result('invalid_configuration' if host_error else 'missing_configuration')
root = integration_root()
if not (root / 'node_modules/@deepseek-ai/dsh/package.json').is_file():
return _result('runtime_unavailable')
try:
node = node_executable()
except Exception:
return _result('runtime_unavailable')
if not native:
return _result('available') | {'source': 'host', 'environment_refs': ['DSH_API_KEY']}
env.update(DSH_HOME=str(home), DX_DSH_HOME=str(home), DSH_TELEMETRY_DISABLED='1')
try:
completed = subprocess.run([node, str(root / 'model_availability.mjs'), str(home)],
cwd=str(directory if directory.is_dir() else root), env=env, capture_output=True, text=True, encoding='utf8',
errors='replace', timeout=3, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
value = json.loads(completed.stdout)
code = value['code']
if completed.returncode != 0 or code not in _MESSAGES or value['available'] is not (code == 'available'):
return _result('runtime_unavailable')
if code == 'available':
source, refs = value.get('source'), value.get('environment_refs')
if source not in {'native', 'host'} or not isinstance(refs, list) or len(refs) > 1 or any(
not isinstance(ref, str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', ref) for ref in refs):
return _result('runtime_unavailable')
return _result(code) | {'source': source, 'environment_refs': refs}
return _result(code)
except Exception:
# Parser/OS errors can include paths or text containing credentials.
return _result('runtime_unavailable')
+6 -9
View File
@@ -7,6 +7,7 @@ from pathlib import Path
from .evidence import scrub
from .issue_credentials import load_bootstrap, issue_target
from .availability import check_availability
def _now():
@@ -34,15 +35,11 @@ class HealthStore:
return scrub({"status": status, "checked_utc": checked, "checks": checks})
def _provider(self):
path = self.data_root / "dsh" / "provider.json"
try:
value = json.loads(path.read_text(encoding="utf8"))
configured = isinstance(value, dict) and bool(value.get("base_url")) and bool(value.get("default_model"))
except (OSError, ValueError, TypeError):
configured = False
return {"name": "provider", "status": "ok" if configured else "degraded",
"code": "ready" if configured else "provider_unconfigured",
"message": "模型提供方已配置" if configured else "尚未配置模型提供方"}
value = check_availability(self.data_root)
return {"name": "provider", "status": "ok" if value['available'] else "degraded",
"code": "ready" if value['available'] else (
"provider_unconfigured" if value['code'] == 'missing_configuration' else value['code']),
"message": value['message']}
def _stores(self):
dsh = self.data_root / "dsh"
+9 -2
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import os
import re
from pathlib import Path
import shutil
import sys
@@ -28,14 +29,20 @@ def node_executable() -> str:
return value
def launch_environment(data_root: Path) -> dict[str, str]:
def launch_environment(data_root: Path, *, native_model=False, credential_refs=()) -> dict[str, str]:
allowed = {'SystemRoot', 'WINDIR', 'ComSpec', 'PATHEXT', 'PATH', 'TEMP', 'TMP',
'APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMFILES', 'PROGRAMFILES(X86)',
'DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY'}
allowed.update(ref for ref in credential_refs
if isinstance(ref, str) and re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', ref))
env = {key: value for key, value in os.environ.items() if key.upper() in {s.upper() for s in allowed}}
if not all(env.get(key) for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY')):
from .provider_config import load_provider
env.update(load_provider(data_root))
try:
env.update(load_provider(data_root))
except Exception:
if not native_model:
raise
env.update(DX_DSH_HOME=str(data_root / 'harness-home'),
DX_DSH_CONTEXT_FILE=str(data_root / 'task-context.json'),
DSH_TELEMETRY_DISABLED='1', DX_DSH_PARENT_PIPE='1', NO_COLOR='1')
+1 -1
View File
@@ -45,9 +45,9 @@ def save_provider(directory: Path, *, base_url: str, models: list[str], default_
def load_provider(directory: Path) -> dict[str, str]:
import win32crypt
if not (directory / 'provider.json').is_file():
return {}
import win32crypt
metadata = json.loads((directory / 'provider.json').read_text(encoding='utf8'))
if not isinstance(metadata, dict):
raise ValueError('invalid_provider_configuration')
@@ -53,6 +53,7 @@ class DshAutomation(QObject):
if window.auto_intervention_check.isChecked():
self.execution_enabled.set()
self._current_identity = None
self.current_request = None
self._owns_execution_lane = True
self._uses_cad_controls = False
self.cancel_event = Event()
@@ -96,8 +97,19 @@ class DshAutomation(QObject):
self._forget((item.task_id, item.code, item.run_id))
self.pending.remove(item)
def resume_available(self):
if not self.window.auto_intervention_check.isChecked():
return
if not self.execution_enabled.is_set():
self.execution_enabled = Event()
self.execution_enabled.set()
QTimer.singleShot(0, self._drain)
def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation', stop_event=None,
trigger=None, snapshot_override=None, read_only=False, cleanup_allowed=False):
status = getattr(self.window, '_dsh_status', None)
if status is not None and not status.available:
return False
# Offscreen UI unit tests have no Chromium surface or local provider.
if QApplication.platformName().casefold() == 'offscreen':
return False
@@ -113,11 +125,15 @@ class DshAutomation(QObject):
while len(self._seen_order) > 256:
self.seen.discard(self._seen_order.popleft())
self.pending.append(item)
if status is not None:
status.update()
QTimer.singleShot(0, self._drain)
return True
def _drain(self):
w = self.window
if w._dsh_status is not None and not w._dsh_status.available:
return
if w._closed or not w.auto_intervention_check.isChecked() or self.worker is not None or not self.pending:
return
busy = (w._workers or w._loading or (w._dsh_lifecycle and w._dsh_lifecycle.dialog)
@@ -127,6 +143,7 @@ class DshAutomation(QObject):
QTimer.singleShot(200, self._drain)
return
item = self.pending.pop(index)
self.current_request = item
task_id, code, message, authorized, run_id, original_stop = (
item.task_id, item.code, item.message, item.authorized, item.run_id, item.stop)
self._owns_execution_lane = not item.read_only and (item.authorized or item.cleanup_allowed)
@@ -145,6 +162,12 @@ class DshAutomation(QObject):
except Exception as error:
self._native_unavailable = True
w.service.report_ui_error(error)
if w._dsh_status is not None and not w._dsh_status.available:
self.pending.insert(0, item)
self._current_identity = None
self.current_request = None
w._dsh_status.update()
return
view = w._dsh_view
if view is not None and view is not self._connected_view:
view.diagnosis_event.connect(self._diagnosis_event)
@@ -258,6 +281,11 @@ class DshAutomation(QObject):
if self.window._closed or self.cancel_event.is_set():
self._diagnosis_event({'request_id': request['request_id'], 'status': 'cancelled', 'error': 'diagnosis_cancelled'})
return
status = self.window._dsh_status
if status is not None and not status.available and not (
self.current_request is not None and status.can_continue):
self._diagnosis_event({'request_id': request['request_id'], 'status': 'failed', 'error': 'model_configuration_unavailable'})
return
view = self.window._dsh_view
if view is None or not view.is_running:
self._diagnosis_event({'request_id': request['request_id'], 'status': 'failed', 'error': 'native_harness_unavailable'})
@@ -297,6 +325,8 @@ class DshAutomation(QObject):
def _publish_context(self):
w = self.window
if not w._closed and w._dsh_status is not None:
w._dsh_status.update()
if not w._dsh_view or w._closed:
return
row = self.latest
@@ -339,6 +369,7 @@ class DshAutomation(QObject):
if self._current_identity[2] == 'observation' or self._current_identity[2].startswith('blocker-'):
self._forget(self._current_identity)
self._current_identity = None
self.current_request = None
self._publish_context()
if w._closed:
return
@@ -31,6 +31,7 @@ class NativeHarnessView(QWidget):
ready = Signal()
stopped = Signal()
diagnosis_event = Signal(object)
availability_failed = Signal(str)
task_creation_requested = Signal(object)
task_creation_cancelled = Signal(object)
lifecycle_requested = Signal(object)
@@ -58,6 +59,7 @@ class NativeHarnessView(QWidget):
self._started = False
self._stopping = False
self.last_error = ''
self.environment_refs = set()
# QObject child order must release the page before its profile.
self.web = QWebEngineView(self)
self.profile = QWebEngineProfile('DxPartReplaceDSH', self)
@@ -159,7 +161,13 @@ class NativeHarnessView(QWidget):
self._show_official_loading(root)
env = QProcessEnvironment()
try:
for key, value in launch_environment(self.data_root).items():
status = getattr(self.window(), '_dsh_status', None)
model = status.availability if status is not None else {}
environment = launch_environment(self.data_root,
native_model=model.get('available') is True and model.get('source') == 'native',
credential_refs=model.get('environment_refs', ()))
self.environment_refs = set(environment)
for key, value in environment.items():
env.insert(key, value)
node = node_executable()
except Exception:
@@ -246,6 +254,7 @@ class NativeHarnessView(QWidget):
self.status.show()
self.web.hide()
self.retry.show()
self.availability_failed.emit(text)
def _finished(self, *_):
self._started = False
@@ -0,0 +1,144 @@
"""Non-blocking model readiness and visible automatic-intervention state."""
from PySide6.QtCore import QObject, QSize, Qt, QTimer
from PySide6.QtGui import QColor, QIcon, QPainter, QPixmap
from PySide6.QtWidgets import QToolButton
from ...dsh.availability import check_availability
from ...dsh.evidence import scrub
from .queries import LatestQuery
class DshStatusIndicator(QToolButton):
def __init__(self, parent=None):
super().__init__(parent, objectName='dshAiStatus')
self.setAutoRaise(True)
self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.setIconSize(QSize(18, 18))
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setStyleSheet('QToolButton#dshAiStatus, QToolButton#dshAiStatus:hover, '
'QToolButton#dshAiStatus:pressed {border: none; background: transparent; padding: 0 2px;}')
self.set_state('checking', '检查配置', '正在检查本地 AI 配置,普通任务不受影响。')
def set_state(self, state, label, details):
colors = {'idle': '#2bb673', 'working': '#e7ad21', 'checking': '#e7ad21',
'unavailable': '#e04b5a', 'attention': '#e04b5a', 'silent': '#929aa6'}
if self.property('state') != state:
pixmap = QPixmap(36, 36)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
color = QColor(colors[state])
painter.setBrush(color)
painter.drawEllipse(8, 8, 20, 20)
painter.end()
self.setIcon(QIcon(pixmap))
self.setProperty('state', state)
self.setText('AI · ' + label)
self.setToolTip(details)
self.setAccessibleName('AI 自动介入:' + label)
self.setAccessibleDescription(details)
class DshStatusController(QObject):
def __init__(self, window):
super().__init__(window)
self.window = window
self.availability = {'available': False, 'code': 'checking', 'message': '正在检查本地 AI 配置。'}
self._runtime_error = ''
self.query = LatestQuery(self)
self.timer = QTimer(self)
self.timer.setInterval(5000)
self.timer.timeout.connect(self.refresh)
self.timer.start()
self.update()
self.refresh()
@property
def available(self):
return bool(self.availability.get('available') and not self._runtime_error)
@property
def can_continue(self):
return self.available or (self.availability.get('code') == 'runtime_unavailable' and not self._runtime_error)
def refresh(self):
if not self.window._closed and not self.query.busy:
root = self.window.service.layout_settings_path.parent
self.query.request(lambda: check_availability(root), self._received,
lambda _: self._received({'available': False, 'code': 'invalid_configuration',
'message': 'AI 配置暂不可用,普通任务不受影响。'}))
def _received(self, value):
before = self.available
self.availability = dict(value)
view = self.window._dsh_view
launched_refs = getattr(view, 'environment_refs', None)
if (value.get('available') and getattr(view, 'is_running', False) and launched_refs is not None
and not set(value.get('environment_refs', ())).issubset(launched_refs)):
self.availability.update(available=False, code='restart_required',
message='新模型的环境凭据尚未加载,请重启软件后启用 AI。')
self._sync(before)
def runtime_failed(self, message):
before = self.available
self._runtime_error = message
self.window._cancel_dsh_diagnosis()
self._sync(before)
def runtime_ready(self):
before = self.available
self._runtime_error = ''
self._sync(before)
self.refresh()
def _sync(self, before):
window = self.window
if window._closed:
return
if not before and self.available and window.auto_intervention_check.isChecked():
automation = window._dsh_automation
if automation is not None:
resume = getattr(automation, 'resume_available', None)
if resume is not None:
resume()
# A background check is not an explicit user request to retry a
# completed blocker; preserve its episode and deduplication key.
window._dsh_blockers.replay_pending()
self.update()
def update(self):
window = self.window
indicator = window.ai_status_indicator
automation = window._dsh_automation
active = getattr(automation, 'worker', None) is not None
row = getattr(automation, 'latest', {})
if not window.auto_intervention_check.isChecked():
indicator.set_state('silent', '静默', 'AI 自动介入已关闭,不会接管新的异常。手动对话仍可使用。')
elif not self.available and not active:
checking = self.availability.get('code') == 'checking' and not self._runtime_error
message = self._runtime_error or self.availability['message']
indicator.set_state('checking' if checking else 'unavailable', '检查配置' if checking else '不可用',
message + '\n普通任务不受影响;点击进入 DSH助手配置模型。')
elif active or getattr(automation, 'pending', None):
if not active:
row = {}
request = getattr(automation, 'current_request', None)
if (not active or request is None) and getattr(automation, 'pending', None):
request = automation.pending[0]
reason = scrub(str(row.get('message') or getattr(request, 'message', '') or '任务异常'))[:500]
owner = row.get('task_name') or row.get('task_id') or getattr(request, 'task_id', '')
stages = {'collecting': '收集证据', 'analyzing': '分析异常', 'reflecting': '复盘与补充证据',
'retrying': '按规则重试', 'cleaning_resources': '清理自有资源', 'verifying': '核验处理结果'}
stage = stages.get(row.get('status'), '准备介入' if getattr(automation, 'worker', None) else '等待介入')
indicator.set_state('working', '介入中',
f'AI 因以下异常介入:{reason}\n' + (f'所属任务:{owner}\n' if owner else '') +
f'当前阶段:{stage}\n点击查看 DSH助手,或右键指示灯取消本次介入。')
elif row.get('status') in {'pending_issue', 'escalated'}:
indicator.set_state('attention', '待处理', 'AI 诊断已结束,异常尚未自动解决,证据已保留。\n点击进入 DSH助手查看原因和工单状态。')
else:
indicator.set_state('idle', '待机', 'AI 自动介入已就绪,待机,等待异常。\n点击进入 DSH助手。')
def close(self):
self.timer.stop()
self.query.close()
@@ -26,6 +26,7 @@ from .workers import ServiceWorker
from .toggle_switch import ToggleSwitch
from .queries import LatestQuery
from .resource_status import ResourceStatus
from .dsh_status import DshStatusController, DshStatusIndicator
from .task_log import TaskLogPresenter
from .execution_feedback import format_feedback
from .operation_state import ContextReadPhase, OperationPhase, OperationState
@@ -45,6 +46,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh_operations = None
self._dsh_stopping = False
self._dsh_automation = None
self._dsh_status = None
self._dsh_run_id = 'observation'
self._dsh_live_run = {'active': False}
self._dsh_last_execution = {}
@@ -84,10 +86,14 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.auto_intervention_check = ToggleSwitch('AI 自动介入', objectName='dshAutoIntervention')
self.auto_intervention_check.setToolTip('异常时自动新建对话,诊断后按规则尝试修复并核验;未解决则保留证据、转工单。关闭后不接收新异常或发起自动重试,当前诊断继续保存证据,已开始的执行不受影响。')
navigation_layout.addWidget(self.auto_intervention_check)
self.cancel_diagnosis_button = QPushButton('取消 AI 诊断', objectName='dshCancelDiagnosis')
self.cancel_diagnosis_button.hide()
self.cancel_diagnosis_button.clicked.connect(self._cancel_dsh_diagnosis)
navigation_layout.addWidget(self.cancel_diagnosis_button)
self.ai_status_indicator = DshStatusIndicator(navigation)
self.ai_status_indicator.clicked.connect(self._open_dsh)
self.ai_cancel_action = QAction('取消本次 AI 介入', self)
self.ai_cancel_action.triggered.connect(self._cancel_dsh_diagnosis)
self.ai_cancel_action.setVisible(False)
self.ai_status_indicator.addAction(self.ai_cancel_action)
self.ai_status_indicator.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)
navigation_layout.addWidget(self.ai_status_indicator)
self.reduced_transparency_button = QToolButton(objectName='reduceTransparency')
self.reduced_transparency_button.setText('减少透明度')
self.reduced_transparency_button.setCheckable(True)
@@ -208,6 +214,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if (self.service.layout_settings_path.parent / 'dsh' / 'incidents').is_dir():
from .dsh_automation import DshAutomation
self._dsh_automation = DshAutomation(self)
self._dsh_status = DshStatusController(self)
if getattr(service, '_supervised', False):
QTimer.singleShot(0, self._startup_resource_recheck)
@@ -389,6 +396,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
self._closed = True
self._dsh_status.close()
self._dsh_stall_timer.stop()
self.history_panel.shutdown()
if self._dsh_operations:
@@ -485,8 +493,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _update_gates(self):
cancellable = bool(self._dsh_automation and getattr(self._dsh_automation, 'can_cancel', False))
self.cancel_diagnosis_button.setVisible(cancellable)
self.cancel_diagnosis_button.setEnabled(cancellable)
self.ai_cancel_action.setVisible(cancellable)
self.ai_cancel_action.setEnabled(cancellable)
if self._dsh_status is not None:
self._dsh_status.update()
busy = bool(self._workers) or self._loading or self.history_panel._worker is not None
resources_pending = self._resource_status.blocked
self.history_panel.set_mutations_enabled(not busy and not resources_pending and self._batch_stop is None)
@@ -1116,12 +1126,15 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.service.report_ui_error(error)
except Exception:
pass
self._show_error(TaskCenterError(
'dsh_startup', 'DSH助手启动失败,请检查发布包中的运行时和 Node.js。'))
self._dsh_status.runtime_failed('DSH助手不可用,请检查运行时或模型设置。')
def _ensure_dsh_view(self):
if self._dsh_view is None:
self._dsh_view = self._create_dsh_view()
if getattr(self._dsh_view, 'ready', None) is not None:
self._dsh_view.ready.connect(self._dsh_status.runtime_ready)
if getattr(self._dsh_view, 'availability_failed', None) is not None:
self._dsh_view.availability_failed.connect(self._dsh_status.runtime_failed)
from .dsh_task_creation import DshTaskCreationController
self._dsh_task_creation = DshTaskCreationController(self, self._dsh_view)
from .dsh_task_lifecycle import DshTaskLifecycleController
@@ -1326,7 +1339,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if owner_task_id is None or owner_task_id == self._task_id:
self._append_log(message)
self._update_gates()
if auto_intervene and not managed and self.isVisible() and QApplication.platformName().casefold() != 'offscreen':
ai_unavailable = self.auto_intervention_check.isChecked() and not self._dsh_status.available
if auto_intervene and not managed and not ai_unavailable and self.isVisible() and QApplication.platformName().casefold() != 'offscreen':
QMessageBox.warning(self, '操作未完成', message)
def _cancel_dsh_diagnosis(self):
@@ -1338,10 +1352,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
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)
self._dsh_automation.set_enabled(enabled and self._dsh_status.available)
if enabled:
self._observe_dsh_resource_blockers()
self._dsh_blockers.set_enabled(enabled)
self._dsh_status.update()
def _observe_dsh_resource_blockers(self):
status = self._resource_status
@@ -1397,7 +1412,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _enqueue_dsh_blocker(self, *, source, task_id, issue_code, run_id, message, details,
read_only, cleanup_allowed, snapshot):
if self._closed or not self.auto_intervention_check.isChecked():
if self._closed or not self.auto_intervention_check.isChecked() or not self._dsh_status.available:
return False
from ...dsh.evidence import scrub
if self._dsh_automation is None:
@@ -1418,7 +1433,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
read_only=read_only or not cleanup_allowed, cleanup_allowed=cleanup_allowed)
def _queue_dsh_incident(self, task_id, issue_code, message):
if not self.auto_intervention_check.isChecked():
if not self.auto_intervention_check.isChecked() or not self._dsh_status.available:
return False
if self._dsh_automation is None:
from .dsh_automation import DshAutomation