diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index be42ef2..95005ac 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -40,10 +40,13 @@ jobs: tests/dsh/test_experience.py tests/dsh/test_issue_broker.py tests/dsh/test_incidents.py + tests/dsh/test_availability.py + tests/dsh/test_health.py tests/ui/test_dsh_native_menu.py tests/ui/test_dsh_blockers.py tests/ui/test_dsh_blocker_sources.py tests/ui/test_dsh_diagnosis_lifecycle.py + tests/ui/test_dsh_status_indicator.py tests/ui/test_pr10_review_edges.py tests/ui/test_query_observability.py tests/packaging/test_dsh_runtime_staging.py @@ -75,6 +78,7 @@ jobs: node --check integration/dsh/start.mjs node --check integration/dsh/task-plugin/host.mjs node --check integration/dsh/task-plugin/client.js + node --check integration/dsh/model_availability.mjs - name: Intervention panel and bounded model views (no model or network) run: | node tools/verify_dsh_incident_panel.mjs diff --git a/README.md b/README.md index 2f2a37f..2fcd859 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,10 @@ DSH助手围绕真实任务中心工作,支持: - 查询任务快照、执行预检、影响范围和实际执行历史。 - 在原生确认后按冻结范围执行任务,支持安全暂停、原队列恢复和排期授权。 - 顶部 **AI 自动介入** 开关默认开启并记住设置;异常、BOM 校验失败、预检阻断、资源释放问题和后台操作长期无进展时自动新建诊断对话,收集脱敏证据,按规则重试或清理自有资源并核验,未解决则转受限 Git 工单。 -- 只读诊断期间可继续选择、创建任务,也可正常关闭窗口。顶部和助手面板均提供 **取消 AI 诊断**:停止模型请求、保存本地证据并转人工接管;已进入执行的 CAD 步骤仍按原暂停/强停机制安全收尾。拒绝关闭或取消未保存计划的关闭确认时,诊断继续。诊断与复盘从原生会话准备好后共享等待预算,默认 180 秒,随模型超时设置调整为 90–300 秒;运行时启动和会话创建另有最多 300 秒的等待上限,不挤占分析时间。 +- 右上角使用无外框的 **AI 状态灯**:绿色待机、黄色介入中、红色未配置/不可用或待人工处理;关闭 **AI 自动介入** 后显示灰色静默。悬浮可查看介入原因、所属任务和当前阶段。未配置模型或 API Key 时,仅提示状态,不自动启动诊断、复盘或工单流程,也不弹窗、锁住任务操作;仍可手动打开助手配置模型。 +- 只读诊断期间可继续选择、创建任务,也可正常关闭窗口。在助手面板取消诊断,或右键状态灯选择 **取消本次 AI 介入**,会停止模型请求、保存本地证据并转人工接管;已进入执行的 CAD 步骤仍按原暂停/强停机制安全收尾。拒绝关闭或取消未保存计划的关闭确认时,诊断继续。诊断与复盘从原生会话准备好后共享等待预算,默认 180 秒,随模型超时设置调整为 90–300 秒;运行时启动和会话创建另有最多 300 秒的等待上限,不挤占分析时间。 - 后台读取异常先在约 200 毫秒后复查,连续失败才介入;同一持续阻塞不会周期性重复建会话,关闭再开启自动介入可主动重新诊断。面板分别显示清理次数及独立核验结果;资源自行释放显示“自行解除”,不会计作 AI 修复。资源清理使用独立控制,不显示 CAD 暂停或强停按钮。 +- 模型配置的后台检查不会取消健康的在途诊断,也不会把“配置恢复”当成用户重新开启开关。同一异常保持原事件编号,完成后不因配置状态波动重新发诊断;只恢复此前尚未开始的待处理项。仅新异常、用户重新导入或主动关闭再开启允许再次介入。 - 在右侧任务监管中查看运行、影响、排期、经验、工单和用量;审计损坏、证据缺失和未知计数会明确显示。 AI 不能直接写入 CAD、运行 Shell 或绕过确认门禁。普通对话可按用户要求读取本地文件;自动异常诊断为只读事件快照。不确定执行不会自动重放,恢复必须重新核对冻结计划、检查点和业务证据。未配置模型时仍可使用任务监管和本地恢复功能,但不会产生真实模型回复。 diff --git a/docs/testing/2026-11-05-dsh-status-and-no-loop.md b/docs/testing/2026-11-05-dsh-status-and-no-loop.md new file mode 100644 index 0000000..a571341 --- /dev/null +++ b/docs/testing/2026-11-05-dsh-status-and-no-loop.md @@ -0,0 +1,35 @@ +# AI 状态灯、无密钥路径与重复诊断回归 + +## 最终行为 + +- 右上角使用与相邻组件对齐的小圆灯和文字,无外框、底色或卡片。绿色为待机,黄色为当前介入,红色为配置不可用或待人工处理;自动介入开关关闭时优先显示灰色静默。 +- 悬浮显示异常原因、任务和阶段;等待中的新任务使用自身原因,不沿用上一事件。取消操作保留在原生面板及指示灯右键菜单。 +- 空配置不会拉起原生运行时、创建事件或发起诊断/复盘/工单;任务错误仍留在任务中心。配置检查不占用任务执行通道,不触发 QMessageBox。 +- 配置检查同时覆盖环境变量、DPAPI 和原生 Harness 提供商/凭据。原生配置与凭据使用实际 Harness 合并及解析语义,不写配置、不访问远程模型,输出不含密钥。故意不要求凭据的本地路由仍可用。新增环境凭据尚未进入已运行的子进程时显示需重启,不宣称已可用。 +- 发布定义包含新的只读配置检查脚本;健康状态不再仅凭 provider.json 存在就宣称正常。 + +## 测试中暴露并修复的严重回归 + +用户观察到同一条 BOM 异常反复诊断。失败实机记录中存在 **22 个相同 bom_import 错误、不同 blocker run_id 的取消事件**,该轮未通过,已停止,后续没有再调用真实模型。 + +根因在新增的状态控制器:可用性检查失败/恢复时调用了 `set_enabled(False/True)`。该 API 原本表示用户主动切换开关,会为已完成事件生成新的重试编号;轮询错误复用了这层语义,同时取消在途诊断,形成“取消→恢复→新会话”的循环。 + +现修复为: + +1. 后台检查不重置协调器、不刷新事件编号,也不取消健康的在途会话。 +2. 恢复时仅唤醒未开始的待处理项,原编号、去重状态和原执行许可保持一致;已完成的同一阻塞不重发。 +3. 只有用户主动切换开关走原重试语义;新导入/新异常仍可形成新事件。 +4. 不确定的本地检查超时不会截断已准入会话的诊断到复盘交接;真正缺少配置或原生运行时失败仍阻止新请求。 +5. 原生同步启动失败时保留原待处理项,不丢失它,也不换新编号;可恢复后只执行一次。 +6. 实模型验收工具增加重复事件检测,发现同一测试异常第二次建事件即停止,防止再以无限诊断方式等待验收。 + +## 验证 + +- DSH 状态、生命周期、原生导航、阻塞来源、既有协议边界、配置、健康及发布资产相关测试:**165 passed,78.10 秒**,报告 `build/dsh-status-feature-tests.xml`。没有运行旧全量测试。 +- 最终追加的离线回归:**11 passed,5.61 秒**,报告 `build/dsh-status-no-loop-tests.xml`。覆盖无 Key、关闭灰色、排队原因、已运行子进程缺少新环境凭据、后台状态抖动、初次配置、启动失败恢复及保存的静默设置。 +- 其中一次完成事件经 25 轮不可用/恢复仍只入队一次;修复前同一测试入队 26 次。用户明确关闭再开启后仅增加一次新事件。 +- 实际 IncidentRunner 与 Qt 线程/信号使用受控 Harness 响应,连续 75 轮状态波动(含诊断到复盘时仍不可用)后,只产生 **一个事件、一次诊断和一次复盘**,本地工单发布替身一次,远程请求为 0。 +- 实际 Harness 配置/凭据读取的无网络 Node 验证:**20 场景通过**,包含 malformed records、不可迁移 flat YAML、原生/环境凭据优先级以及文件字节不变。 +- 未配置环境的真实 Qt/QTest 通过实际文件对话框导入错误 XLSX:红灯、不弹窗、不启动 AI、事件数量 0、任务控件可用;点击关闭开关变灰。记录 `build/dsh-status-desktop/20261105-152808/report.json`。绿色/黄色的截图是受控视觉状态,并非真实模型调用。 + +实模型测试未作为通过证据。发现循环后只做离线和受控模型验证;没有重跑真实模型、创建远程测试工单、构建 EXE 或合并 PR。 diff --git a/integration/dsh/model_availability.mjs b/integration/dsh/model_availability.mjs new file mode 100644 index 0000000..e97a08a --- /dev/null +++ b/integration/dsh/model_availability.mjs @@ -0,0 +1,101 @@ +/** Read-only Harness model composition. Never starts services or writes a profile. */ +import {createRequire} from 'node:module'; +import {readFile} from 'node:fs/promises'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {isDeepStrictEqual} from 'node:util'; +import {overlay,refreshApplicationModels} from './start.mjs'; + +const require=createRequire(import.meta.url); +const result=code=>({available:code==='available',code}); +const ready=(source,ref)=>({...result('available'),source,environment_refs:ref?[ref]:[]}); + +async function optional(filename,parse) { + try{return parse(await readFile(filename,'utf8'));} + catch(error){if(error.code==='ENOENT')return undefined;throw error;} +} + +function entry(rows,id) { + const matches=rows.filter(row=>row.id===id); + if(matches.length>1)throw Error('duplicate_entry'); + return matches[0]?.disabled===true?undefined:matches[0]; +} + +export async function checkModelAvailability(home) { + try { + const {composeEntries,loadOverlayPatches}=await import('@deepseek-ai/dsh-app-boot'); + const {resolveDshHome}=await import('@deepseek-ai/dsh-home-paths'); + const {load}=require('js-yaml'); + const directory=path.join(home,'profiles/dx-task'); + // Startup owns these exact bundle layers; loadProfileDirectory may migrate + // a manifest, so the status check reads only their installed patch files. + const base=loadOverlayPatches('dx-availability',require.resolve('@deepseek-ai/dsh-base/cordis.patch.yml')); + const web=loadOverlayPatches('dx-availability',require.resolve('@deepseek-ai/dsh-web-app/cordis.patch.yml')); + const application=overlay(); + const layers=[base,web,application]; + const original=await optional(path.join(directory,'cordis.patch.yml'),load)??[]; + if(!Array.isArray(original))return result('invalid_configuration'); + const legacy=original.some(row=>Array.isArray(row?.insert) + &&row.insert.some(item=>item.id==='dx-task'&&item.name==='@dx/dsh-task') + &&row.insert.some(item=>item.id==='preset-dx-task')); + const editable=new Set(['llm-pi-ai','llm-deepseek','agent-default-model']); + const rows=legacy?original.filter(row=>editable.has(row?.id)&&row.config):original; + const initial=composeEntries([...layers,rows]); + const credentials=entry(initial,'credentials'); + let refs={}; + if(credentials){ + if(credentials.name!=='@deepseek-ai/dsh-credentials-local')return result('invalid_configuration'); + const config=credentials.config??{}; + const credentialHome=resolveDshHome(config.dshHome,{DSH_HOME:home}); + const filename=path.resolve(config.path??path.join(credentialHome,'.credentials.yaml')); + const text=await optional(filename,value=>value); + if(text!==undefined){ + const {parseCredentialsDocument,renderFlatLayoutMigration}=await import('@deepseek-ai/dsh-credentials-local'); + // Match native admission and migration rules without writing the store. + const parsed=parseCredentialsDocument(renderFlatLayoutMigration(text)??text,filename); + refs=Object.fromEntries(parsed.refs); + } + } + const withoutHost=[base,web,application.filter(row=>row.id!=='llm-pi-ai')]; + const boundDx=entry(composeEntries([...withoutHost,rows]),'llm-pi-ai')?.config?.providers?.dx; + const previousApplication=await optional(path.join(directory,'node_modules/@dx/dsh-policy/cordis.patch.yml'),load)??[]; + const storedHostKey=typeof refs.DSH_API_KEY==='string'&&refs.DSH_API_KEY.length>0; + const refreshed=refreshApplicationModels(rows,application,{legacy,storedHostKey,previousApplication,boundDx}); + const effective=composeEntries([...layers,refreshed]); + const selection=entry(effective,'agent-default-model')?.config; + if(selection?.provider==='deepseek-official'){ + const official=entry(effective,'llm-deepseek'); + if(official?.name!=='@deepseek-ai/dsh-llm-deepseek-api-key')return result('invalid_configuration'); + const ref=official.config?.apiKeyEnv??'DEEPSEEK_API_KEY'; + if(typeof ref!=='string'||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(ref))return result('invalid_configuration'); + const key=refs[ref]??process.env[ref]; + return typeof key==='string'&&key.trim()?ready('native',refs[ref]===undefined?ref:undefined):result('missing_credential'); + } + const adapter=entry(effective,'llm-pi-ai'); + if(adapter&&adapter.name!=='@deepseek-ai/dsh-llm-pi-ai')return result('invalid_configuration'); + const profile=adapter?.config?.providers?.[selection?.provider]; + if(!profile)return result('missing_configuration'); + if(profile.apiKeyEnv==='DSH_API_KEY'){ + const current=application.find(row=>row.id==='llm-pi-ai')?.config.providers.dx; + if(storedHostKey&&(!boundDx||!isDeepStrictEqual(profile,boundDx)))return result('invalid_configuration'); + if(!storedHostKey&&!isDeepStrictEqual(profile,current))return result('invalid_configuration'); + } + if(!selection.model||profile.models&&!profile.models.some(model=>model.id===selection.model)) + return result('invalid_configuration'); + if(profile.apiKeyEnv!==undefined){ + if(typeof profile.apiKeyEnv!=='string'||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(profile.apiKeyEnv)) + return result('invalid_configuration'); + const key=refs[profile.apiKeyEnv]??process.env[profile.apiKeyEnv]; + const source=selection.provider==='dx'&&!storedHostKey&&profile.apiKeyEnv==='DSH_API_KEY'?'host':'native'; + return typeof key==='string'&&key.trim() + ?ready(source,refs[profile.apiKeyEnv]===undefined?profile.apiKeyEnv:undefined):result('missing_credential'); + } + // Native routes may explicitly omit credentials for local/public endpoints. + return ready('native'); + }catch{return result('invalid_configuration');} +} + +if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){ + const checked=await checkModelAvailability(path.resolve(process.argv[2])); + process.stdout.write(JSON.stringify(checked)); +} diff --git a/integration/dsh/start.mjs b/integration/dsh/start.mjs index a8a058d..77e4531 100644 --- a/integration/dsh/start.mjs +++ b/integration/dsh/start.mjs @@ -85,7 +85,7 @@ function modelEntry(rows,id) { return entries[0]; } -function refreshApplicationModels(rows,application,{legacy=false,storedHostKey=false,previousApplication=[],boundDx}={}) { +export function refreshApplicationModels(rows,application,{legacy=false,storedHostKey=false,previousApplication=[],boundDx}={}) { const current=application.find(row=>row.id==='llm-pi-ai')?.config.providers.dx; let userLlm=rows.filter(row=>row.id==='llm-pi-ai'&&row.config).at(-1); if(current&&storedHostKey&&!boundDx){ diff --git a/packaging/DxPartReplace.spec b/packaging/DxPartReplace.spec index 00d25e4..233f4d1 100644 --- a/packaging/DxPartReplace.spec +++ b/packaging/DxPartReplace.spec @@ -34,7 +34,7 @@ legacy_runtime_datas = [ # The native assistant loads the official web UI; include its pinned Node runtime. dsh_root = project_root / 'integration' / 'dsh' for required in ('node_modules/@deepseek-ai/dsh/package.json', 'issue-bootstrap.json', - 'start.mjs', 'package.json', 'task-plugin/host.mjs'): + 'start.mjs', 'model_availability.mjs', 'package.json', 'task-plugin/host.mjs'): if not (dsh_root / required).is_file(): raise RuntimeError(f'Complete DSH release runtime is required; missing: {required}') if shutil.which('node') is None: @@ -49,6 +49,7 @@ if (dsh_root / 'node_modules' / '@deepseek-ai' / 'dsh' / 'package.json').is_file staged_node_modules = dsh_root / 'node_modules' legacy_runtime_datas.extend([ (str(dsh_root / 'start.mjs'), 'dsh-runtime'), + (str(dsh_root / 'model_availability.mjs'), 'dsh-runtime'), (str(dsh_root / 'package.json'), 'dsh-runtime'), (str(dsh_root / 'task-plugin'), 'dsh-runtime/task-plugin'), (str(staged_node_modules), 'dsh-runtime/node_modules'), diff --git a/src/dx_productivity/dsh/availability.py b/src/dx_productivity/dsh/availability.py new file mode 100644 index 0000000..d023b4c --- /dev/null +++ b/src/dx_productivity/dsh/availability.py @@ -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') diff --git a/src/dx_productivity/dsh/health.py b/src/dx_productivity/dsh/health.py index 8cf1d1e..9fb61db 100644 --- a/src/dx_productivity/dsh/health.py +++ b/src/dx_productivity/dsh/health.py @@ -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" diff --git a/src/dx_productivity/dsh/native_runtime.py b/src/dx_productivity/dsh/native_runtime.py index e745fdf..8801a7c 100644 --- a/src/dx_productivity/dsh/native_runtime.py +++ b/src/dx_productivity/dsh/native_runtime.py @@ -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') diff --git a/src/dx_productivity/dsh/provider_config.py b/src/dx_productivity/dsh/provider_config.py index f468123..f540174 100644 --- a/src/dx_productivity/dsh/provider_config.py +++ b/src/dx_productivity/dsh/provider_config.py @@ -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') 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 0be4a0a..e5105ed 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_automation.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_automation.py @@ -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 diff --git a/src/dx_productivity/trial_task_center/ui/dsh_native.py b/src/dx_productivity/trial_task_center/ui/dsh_native.py index aa62c14..46b7881 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_native.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_native.py @@ -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 diff --git a/src/dx_productivity/trial_task_center/ui/dsh_status.py b/src/dx_productivity/trial_task_center/ui/dsh_status.py new file mode 100644 index 0000000..1c84001 --- /dev/null +++ b/src/dx_productivity/trial_task_center/ui/dsh_status.py @@ -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() 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 3ec1c72..48b2452 100644 --- a/src/dx_productivity/trial_task_center/ui/main_window.py +++ b/src/dx_productivity/trial_task_center/ui/main_window.py @@ -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 diff --git a/tests/dsh/test_availability.py b/tests/dsh/test_availability.py new file mode 100644 index 0000000..05f17f0 --- /dev/null +++ b/tests/dsh/test_availability.py @@ -0,0 +1,154 @@ +import json +import sys +from types import SimpleNamespace + +import pytest + +from dx_productivity.dsh import availability + + +@pytest.fixture(autouse=True) +def isolated_environment(monkeypatch): + for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY', 'DX_DSH_MODELS', 'DEEPSEEK_API_KEY', 'FIXTURE_NATIVE_KEY'): + monkeypatch.delenv(key, raising=False) + + +def host_env(monkeypatch): + for key, value in {'DSH_API_BASE': 'https://example.test/v1', 'DSH_MODEL': 'fixture', + 'DSH_API_KEY': 'fake-credential-never-return'}.items(): + monkeypatch.setenv(key, value) + + +def test_fresh_install_is_disabled_without_files_or_node(tmp_path, monkeypatch): + def unexpected(*args, **kwargs): + pytest.fail('Fresh configuration must not spawn a process') + monkeypatch.setattr(availability.subprocess, 'run', unexpected) + monkeypatch.setitem(sys.modules, 'win32crypt', None) + assert availability.check_availability(tmp_path) == { + 'available': False, 'code': 'missing_configuration', 'message': '未配置 AI 模型或 API Key;AI 功能已停用。'} + assert list(tmp_path.iterdir()) == [] + + +def test_environment_host_configuration_is_available_and_never_returned(tmp_path, monkeypatch): + host_env(monkeypatch) + result = availability.check_availability(tmp_path) + assert result['available'] is True, result + assert result['code'] == 'available' + assert result['source'] == 'host' + assert result['environment_refs'] == ['DSH_API_KEY'] + assert 'fake-credential' not in json.dumps(result) + assert list(tmp_path.iterdir()) == [] + + +def test_corrupt_host_configuration_returns_safe_error(tmp_path): + config = tmp_path / 'dsh' + config.mkdir() + (config / 'provider.json').write_text('{fake-secret: invalid', encoding='utf8') + result = availability.check_availability(tmp_path) + assert result['available'] is False + assert result['code'] == 'invalid_configuration' + assert 'fake-secret' not in json.dumps(result) + + +def test_native_profile_is_checked_without_host_key(tmp_path, monkeypatch): + patch = tmp_path / 'dsh/harness-home/profiles/dx-task/cordis.patch.yml' + patch.parent.mkdir(parents=True) + patch.write_text('[]', encoding='utf8') + def native_check(*args, **kwargs): + return SimpleNamespace(returncode=0, stdout='{"available":true,"code":"available","source":"native","environment_refs":["NATIVE_API_KEY"]}', stderr='') + monkeypatch.setattr(availability.subprocess, 'run', native_check) + assert availability.check_availability(tmp_path)['available'] is True + assert patch.read_text(encoding='utf8') == '[]' + + +def test_host_configuration_requires_node(tmp_path, monkeypatch): + host_env(monkeypatch) + def missing_node(): + raise RuntimeError('private error text') + monkeypatch.setattr(availability, 'node_executable', missing_node) + assert availability.check_availability(tmp_path)['code'] == 'runtime_unavailable' + + +def test_native_only_credential_store_is_checked_without_profile_patch(tmp_path, monkeypatch): + credentials = tmp_path / 'dsh/harness-home/.credentials.yaml' + credentials.parent.mkdir(parents=True) + credentials.write_text('version: 1\nrefs: {}', encoding='utf8') + monkeypatch.setattr(availability.subprocess, 'run', lambda *a, **k: SimpleNamespace(returncode=0, + stdout='{"available":true,"code":"available","source":"native","environment_refs":[]}', stderr='')) + assert availability.check_availability(tmp_path)['source'] == 'native' + + +def test_dpapi_host_configuration_is_available_without_writes(tmp_path): + from dx_productivity.dsh.provider_config import save_provider + directory = tmp_path / 'dsh' + save_provider(directory, base_url='https://example.test/v1', models=['fixture'], + default_model='fixture', api_key='fake-protected-key') + before = {path.name: path.read_bytes() for path in directory.iterdir()} + result = availability.check_availability(tmp_path) + assert result['source'] == 'host' + assert 'fake-protected-key' not in json.dumps(result) + assert {path.name: path.read_bytes() for path in directory.iterdir()} == before + + +def test_real_native_route_survives_corrupt_unused_host_metadata(tmp_path): + directory = tmp_path / 'dsh' + patch = directory / 'harness-home/profiles/dx-task/cordis.patch.yml' + patch.parent.mkdir(parents=True) + (directory / 'provider.json').write_text('{invalid-unused-host', encoding='utf8') + patch.write_text(json.dumps([ + {'id': 'llm-pi-ai', 'config': {'providers': {'native': {'api': 'openai-completions', + 'baseURL': 'https://example.invalid/v1', 'apiKeyEnv': 'FIXTURE_NATIVE_KEY', + 'models': [{'id': 'fixture-model'}]}}}}, + {'id': 'agent-default-model', 'config': {'provider': 'native', 'model': 'fixture-model'}}]), encoding='utf8') + credentials = directory / 'harness-home/.credentials.yaml' + credentials.write_text(json.dumps({'version': 1, 'refs': {'FIXTURE_NATIVE_KEY': 'fake-native-key'}}), encoding='utf8') + before = {path: path.read_bytes() for path in directory.rglob('*') if path.is_file()} + result = availability.check_availability(tmp_path) + assert result['available'] is True, result + assert result['source'] == 'native' + assert result['environment_refs'] == [] + assert 'fake-native-key' not in json.dumps(result) + assert {path: path.read_bytes() for path in directory.rglob('*') if path.is_file()} == before + + +def test_ambient_official_native_key_works_before_dsh_directory_exists(tmp_path, monkeypatch): + monkeypatch.setenv('DEEPSEEK_API_KEY', 'fake-official-native-key') + result = availability.check_availability(tmp_path) + assert result['available'] is True, result + assert result['source'] == 'native' + assert result['environment_refs'] == ['DEEPSEEK_API_KEY'] + assert not (tmp_path / 'dsh').exists() + + +def test_native_extra_child_fields_are_discarded(tmp_path, monkeypatch): + credentials = tmp_path / 'dsh/harness-home/.credentials.yaml' + credentials.parent.mkdir(parents=True) + credentials.write_text('{}', encoding='utf8') + output = json.dumps({'available': True, 'code': 'available', 'source': 'native', + 'environment_refs': ['FIXTURE_NATIVE_KEY'], 'key': 'fake-do-not-return'}) + monkeypatch.setattr(availability.subprocess, 'run', lambda *a, **k: + SimpleNamespace(returncode=0, stdout=output, stderr='')) + assert 'fake-do-not-return' not in json.dumps(availability.check_availability(tmp_path)) + + +@pytest.mark.parametrize('output', ['secret not json', '{"available":true,"code":"secret"}']) +def test_native_invalid_output_is_fixed_safe_message(tmp_path, monkeypatch, output): + patch = tmp_path / 'dsh/harness-home/profiles/dx-task/cordis.patch.yml' + patch.parent.mkdir(parents=True) + patch.write_text('[]', encoding='utf8') + monkeypatch.setattr(availability.subprocess, 'run', lambda *a, **k: + SimpleNamespace(returncode=0, stdout=output, stderr='another-secret')) + result = availability.check_availability(tmp_path) + assert result['code'] == 'runtime_unavailable' + assert 'secret' not in json.dumps(result) + + +def test_native_timeout_is_safe_and_bounded(tmp_path, monkeypatch): + patch = tmp_path / 'dsh/harness-home/profiles/dx-task/cordis.patch.yml' + patch.parent.mkdir(parents=True) + patch.write_text('[]', encoding='utf8') + def timeout(*args, **kwargs): + assert kwargs['timeout'] <= 10 + raise availability.subprocess.TimeoutExpired('fake-secret', 8) + monkeypatch.setattr(availability.subprocess, 'run', timeout) + assert availability.check_availability(tmp_path)['code'] == 'runtime_unavailable' diff --git a/tests/dsh/test_health.py b/tests/dsh/test_health.py index 5c03813..75ac3e0 100644 --- a/tests/dsh/test_health.py +++ b/tests/dsh/test_health.py @@ -37,3 +37,12 @@ def test_health_snapshot_reports_stale_ticket_cache(tmp_path): value = HealthStore(tmp_path).snapshot(_Service()) checks = {row['name']: row for row in value['checks']} assert checks['tickets']['status'] == 'ok' + + +def test_provider_metadata_without_a_key_does_not_claim_ready(tmp_path, monkeypatch): + for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY', 'DEEPSEEK_API_KEY'): + monkeypatch.delenv(key, raising=False) + provider = tmp_path / 'dsh' / 'provider.json' + provider.parent.mkdir(parents=True) + provider.write_text(json.dumps({'base_url': 'https://example.test/v1', 'default_model': 'm'}), encoding='utf8') + assert HealthStore(tmp_path)._provider()['status'] == 'degraded' diff --git a/tests/dsh/test_native_runtime.py b/tests/dsh/test_native_runtime.py index 4eb63ad..6799339 100644 --- a/tests/dsh/test_native_runtime.py +++ b/tests/dsh/test_native_runtime.py @@ -1,4 +1,5 @@ import json +import pytest from dx_productivity.dsh.native_runtime import launch_environment, write_context from dx_productivity.dsh.snapshot import TaskSnapshot @@ -19,6 +20,34 @@ def test_launch_does_not_inherit_unrelated_credentials_or_user_harness_home(tmp_ assert env['DX_DSH_HOME'].startswith(str(tmp_path)) +def test_selected_native_credential_is_forwarded_without_unrelated_secrets(tmp_path, monkeypatch): + monkeypatch.setenv('FIXTURE_SELECTED_API_KEY', 'fake-selected-key') + monkeypatch.setenv('FIXTURE_UNRELATED_API_KEY', 'fake-unrelated-key') + monkeypatch.setenv('OPENAI_API_KEY', 'fake-openai-key') + env = launch_environment(tmp_path, native_model=True, credential_refs=['FIXTURE_SELECTED_API_KEY']) + assert env['FIXTURE_SELECTED_API_KEY'] == 'fake-selected-key' + assert 'FIXTURE_UNRELATED_API_KEY' not in env + assert 'OPENAI_API_KEY' not in env + + +def test_proven_native_route_can_launch_with_corrupt_unused_host_metadata(tmp_path, monkeypatch): + for name in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY'): + monkeypatch.delenv(name, raising=False) + (tmp_path / 'provider.json').write_text('{invalid-metadata', encoding='utf8') + monkeypatch.setenv('FIXTURE_SELECTED_API_KEY', 'fake-native-key') + env = launch_environment(tmp_path, native_model=True, credential_refs=['FIXTURE_SELECTED_API_KEY']) + assert env['FIXTURE_SELECTED_API_KEY'] == 'fake-native-key' + assert env['DX_DSH_HOME'] == str(tmp_path / 'harness-home') + with pytest.raises(Exception): + launch_environment(tmp_path) + + +def test_invalid_native_credential_reference_does_not_expand_environment_allowlist(tmp_path, monkeypatch): + monkeypatch.setenv('FIXTURE_UNRELATED_API_KEY', 'fake-unrelated-key') + env = launch_environment(tmp_path, native_model=True, credential_refs=[None, 'invalid-ref', 'A' * 129]) + assert 'FIXTURE_UNRELATED_API_KEY' not in env + + def test_context_publication_survives_a_real_windows_reader_lock(tmp_path): import ctypes from ctypes import wintypes diff --git a/tests/packaging/test_release_configuration.py b/tests/packaging/test_release_configuration.py index 3c2a438..14a2ceb 100644 --- a/tests/packaging/test_release_configuration.py +++ b/tests/packaging/test_release_configuration.py @@ -24,7 +24,7 @@ def test_release_spec_includes_all_assets_and_complete_runtime(): assert not any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'stage_node_modules' for node in ast.walk(tree)) assert {'dsh-runtime/node_modules', 'dsh-runtime/task-plugin', - 'issue-bootstrap.json', 'PySide6.QtWebEngineCore', + 'issue-bootstrap.json', 'model_availability.mjs', 'PySide6.QtWebEngineCore', 'PySide6.QtWebEngineWidgets'} <= constants analysis = next(node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'Analysis') diff --git a/tests/ui/conftest.py b/tests/ui/conftest.py index 24f64b3..3895f59 100644 --- a/tests/ui/conftest.py +++ b/tests/ui/conftest.py @@ -13,6 +13,14 @@ from dx_productivity.trial_task_center.quick_run import QuickRunPreparer from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow +@pytest.fixture +def ai_ready(monkeypatch): + """AI flow tests supply readiness explicitly; normal fixtures remain unconfigured.""" + from dx_productivity.trial_task_center.ui import dsh_status + monkeypatch.setattr(dsh_status, 'check_availability', lambda root: + {'available': True, 'code': 'available', 'message': 'Controlled configured model'}) + + @pytest.fixture def ui(qtbot, tmp_path): root = tmp_path/'projects' diff --git a/tests/ui/test_dsh_blocker_sources.py b/tests/ui/test_dsh_blocker_sources.py index 545525d..d8a88a7 100644 --- a/tests/ui/test_dsh_blocker_sources.py +++ b/tests/ui/test_dsh_blocker_sources.py @@ -6,6 +6,7 @@ from dx_productivity.trial_task_center.bom_import_report import BomImportReport, from dx_productivity.trial_task_center.errors import TaskCenterError from .test_dsh_operations import setup_view +pytestmark = pytest.mark.usefixtures('ai_ready') @pytest.fixture def blockers(ui, monkeypatch): diff --git a/tests/ui/test_dsh_blockers.py b/tests/ui/test_dsh_blockers.py index 7a2dda9..d1a7886 100644 --- a/tests/ui/test_dsh_blockers.py +++ b/tests/ui/test_dsh_blockers.py @@ -3,6 +3,7 @@ import pytest from dx_productivity.trial_task_center.ui.dsh_blockers import DshBlockerCoordinator +pytestmark = pytest.mark.usefixtures('ai_ready') def test_blocker_report_is_deduplicated_until_cleared(): events = [] diff --git a/tests/ui/test_dsh_diagnosis_lifecycle.py b/tests/ui/test_dsh_diagnosis_lifecycle.py index b22781d..6fcc99e 100644 --- a/tests/ui/test_dsh_diagnosis_lifecycle.py +++ b/tests/ui/test_dsh_diagnosis_lifecycle.py @@ -8,6 +8,7 @@ from PySide6.QtWidgets import QApplication from dx_productivity.trial_task_center.ui import dsh_automation as module from .test_dsh_native_menu import HarnessView +pytestmark = pytest.mark.usefixtures('ai_ready') class SlowHarness(HarnessView): diagnosis_event = Signal(object) @@ -64,13 +65,14 @@ def test_readonly_diagnosis_keeps_task_controls_usable_and_can_be_cancelled(slow assert automation.worker not in window._workers assert window.task_list.list.isEnabled() assert window.task_list.new_button.isEnabled() - assert window.cancel_diagnosis_button.isVisible() - qtbot.mouseClick(window.cancel_diagnosis_button, Qt.MouseButton.LeftButton) + assert window.ai_status_indicator.property('state') == 'working' + assert window.ai_cancel_action.isVisible() + window.ai_cancel_action.trigger() qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) assert view.cancellations assert automation.latest['status'] == 'cancelled' assert not published - assert not window.cancel_diagnosis_button.isVisible() + assert not window.ai_cancel_action.isVisible() ui.settle() @@ -108,7 +110,7 @@ def test_resource_diagnosis_has_no_cad_pause_or_force_controls(slow_diagnosis, q assert window._batch_stop is None assert not window.run_panel.stop_queue_button.isVisible() assert not window.run_panel.force_stop_button.isVisible() - qtbot.mouseClick(window.cancel_diagnosis_button, Qt.MouseButton.LeftButton) + window.ai_cancel_action.trigger() qtbot.waitUntil(lambda: automation.worker is None, timeout=5000) assert view.cancellations and not published ui.settle() @@ -199,7 +201,7 @@ def test_completed_incident_removes_embedded_cancel_action(slow_diagnosis, qtbot automation._start_worker(ServiceWorker(lambda: {'status': 'observed_cleared', 'task_id': ''})) qtbot.waitUntil(lambda: automation.worker is None) assert window._dsh_view.automation['can_cancel'] is False - assert not window.cancel_diagnosis_button.isVisible() + assert not window.ai_cancel_action.isVisible() ui.settle() @@ -208,7 +210,7 @@ def test_optional_automation_without_cancel_api_keeps_gates_and_close_usable(ui, window = ui.window monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(enqueue=lambda *a, **kw: True)) window._update_gates() - assert not window.cancel_diagnosis_button.isVisible() + assert not window.ai_cancel_action.isVisible() window._cancel_dsh_diagnosis() window.close() qtbot.waitUntil(lambda: window._closed) diff --git a/tests/ui/test_dsh_native_menu.py b/tests/ui/test_dsh_native_menu.py index be8a8c5..cbdfddc 100644 --- a/tests/ui/test_dsh_native_menu.py +++ b/tests/ui/test_dsh_native_menu.py @@ -1,8 +1,10 @@ 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) @@ -64,7 +66,8 @@ def test_dsh_navigation_surfaces_lazy_startup_failure(ui, monkeypatch, qtbot): raise RuntimeError('controlled missing WebEngine') monkeypatch.setattr(type(window), '_create_dsh_view', fail) qtbot.mouseClick(window.dsh_navigation, Qt.MouseButton.LeftButton) - assert 'DSH助手启动失败' in window.run_panel.operator_band.text() + 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): diff --git a/tests/ui/test_dsh_status_indicator.py b/tests/ui/test_dsh_status_indicator.py new file mode 100644 index 0000000..6a29294 --- /dev/null +++ b/tests/ui/test_dsh_status_indicator.py @@ -0,0 +1,256 @@ +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QApplication, QMessageBox + +from dx_productivity.trial_task_center.errors import TaskCenterError + + +@pytest.fixture +def no_model(monkeypatch): + for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY'): + monkeypatch.delenv(key, raising=False) + + +def test_fresh_install_without_key_is_red_and_task_error_never_starts_ai(no_model, ui, monkeypatch, qtbot): + from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation + window = ui.window + ui.settle() + warnings = [] + monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows') + monkeypatch.setattr(QMessageBox, 'warning', lambda *args: warnings.append(args)) + monkeypatch.setattr(DshAutomation, '_drain', lambda self: None) + window._show_error(TaskCenterError('worker_error', 'Controlled task failure')) + qtbot.wait(20) + assert window._dsh_automation is None, 'Unconfigured AI must not start an incident workflow' + assert window._dsh_view is None + assert not warnings + assert window.task_list.list.isEnabled() and window.task_list.new_button.isEnabled() + assert not list(ui.data.glob('dsh/incidents/*')) + assert hasattr(window, 'ai_status_indicator'), 'AI needs persistent visible state feedback' + qtbot.waitUntil(lambda: window.ai_status_indicator.property('state') == 'unavailable') + assert '未配置' in window.ai_status_indicator.toolTip() + + +def test_switch_off_shows_grey_silent_even_without_key(no_model, ui, qtbot): + window = ui.window + assert hasattr(window, 'ai_status_indicator'), 'Silent mode needs a grey status lamp' + qtbot.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + assert window.ai_status_indicator.property('state') == 'silent' + assert '静默' in window.ai_status_indicator.text() + assert '已关闭' in window.ai_status_indicator.toolTip() + + +def test_indicator_tooltip_explains_live_intervention_reason_and_stage(no_model, ui, monkeypatch): + window = ui.window + assert hasattr(window, 'ai_status_indicator'), 'The old cancel button does not explain intervention' + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured'}) + assert window.ai_status_indicator.property('state') == 'idle' + assert '待机' in window.ai_status_indicator.toolTip() + automation = SimpleNamespace(worker=object(), pending=[], can_cancel=True, + latest={'status': 'reflecting', 'message': 'BOM 表头缺少旧料号', 'task_name': 'Board-A'}, + current_request=None, cancel=lambda: None) + monkeypatch.setattr(window, '_dsh_automation', automation) + window._update_gates() + assert window.ai_status_indicator.property('state') == 'working' + assert 'BOM 表头缺少旧料号' in window.ai_status_indicator.toolTip() + assert 'Board-A' in window.ai_status_indicator.toolTip() + assert '复盘' in window.ai_status_indicator.toolTip() + + +def test_pending_intervention_tooltip_uses_new_request_instead_of_old_incident(no_model, ui, monkeypatch): + window = ui.window + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured'}) + monkeypatch.setattr(window, '_dsh_automation', SimpleNamespace(worker=None, + pending=[SimpleNamespace(message='新任务的 BOM 缺列', task_id='new-task')], current_request=None, + latest={'status': 'resolved', 'message': '旧任务错误', 'task_name': 'Old board'}, cancel=lambda: None)) + window._update_gates() + assert '新任务的 BOM 缺列' in window.ai_status_indicator.toolTip() + assert 'new-task' in window.ai_status_indicator.toolTip() + assert '旧任务错误' not in window.ai_status_indicator.toolTip() + + +def test_running_harness_without_new_environment_ref_does_not_claim_ready(no_model, ui, monkeypatch): + from .test_dsh_native_menu import HarnessView + window = ui.window + view = HarnessView(window) + view.is_running = True + view.environment_refs = set() + view.shutdown = lambda: (setattr(view, 'is_running', False), view.stopped.emit()) + monkeypatch.setattr(window, '_dsh_view', view) + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured', + 'source': 'native', 'environment_refs': ['NEW_MODEL_KEY']}) + assert not window._dsh_status.available + assert window.ai_status_indicator.property('state') == 'unavailable' + assert '重启' in window.ai_status_indicator.toolTip() + + +def test_availability_polling_never_reopens_completed_blocker(no_model, ui, monkeypatch, qtbot): + window = ui.window + window._dsh_status.timer.stop() + window._dsh_status.query.close() + ready = {'available': True, 'code': 'available', 'message': 'Configured'} + window._dsh_status._received(ready) + submitted = [] + coordinator = window._dsh_blockers + monkeypatch.setattr(coordinator, 'enqueue', lambda **value: submitted.append(value.copy()) or True) + coordinator.report('bom:controlled', window._task_id, 'bom_import', 'One persistent BOM failure', read_only=True) + coordinator.completed(submitted[0]['run_id']) + for _ in range(25): + window._dsh_status._received({'available': False, 'code': 'runtime_unavailable', 'message': 'Local probe timeout'}) + window._dsh_status._received(ready) + assert len(submitted) == 1, 'Background configuration polling must never restart the same diagnosis' + qtbot.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + qtbot.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + assert len(submitted) == 2, 'Explicit user off/on may request one new diagnosis' + assert submitted[0]['run_id'] != submitted[1]['run_id'] + + +def test_local_readiness_probe_does_not_cancel_or_revoke_running_diagnosis(no_model, ui, monkeypatch): + from dx_productivity.trial_task_center.ui.dsh_automation import DshAutomation + window = ui.window + window._dsh_status.timer.stop() + window._dsh_status.query.close() + ready = {'available': True, 'code': 'available', 'message': 'Configured'} + window._dsh_status._received(ready) + automation = DshAutomation(window) + monkeypatch.setattr(window, '_dsh_automation', automation) + automation.worker = object() + automation._current_identity = ('owner', 'bom_import', 'blocker-one') + permission = automation.execution_enabled + try: + for _ in range(10): + window._dsh_status._received({'available': False, 'code': 'runtime_unavailable', 'message': 'Local probe timeout'}) + window._dsh_status._received(ready) + assert not automation.cancel_event.is_set() + assert permission.is_set() and automation.execution_enabled is permission + finally: + automation.worker = None + automation._current_identity = None + + +def test_actual_incident_sends_one_diagnosis_and_one_reflection_despite_readiness_flaps(no_model, ui, monkeypatch, qtbot): + from PySide6.QtCore import Signal + from .test_dsh_native_menu import HarnessView + from dx_productivity.trial_task_center.ui import dsh_automation + + class ControlledHarness(HarnessView): + diagnosis_event = Signal(object) + is_running = True + + def __init__(self, parent): + super().__init__(parent) + self.requests = [] + + def request_diagnosis(self, request): + self.requests.append(request) + + def shutdown(self): + self.is_running = False + self.stopped.emit() + + window = ui.window + ui.settle() + window._dsh_status.timer.stop() + window._dsh_status.query.close() + ready = {'available': True, 'code': 'available', 'message': 'Controlled configured model'} + window._dsh_status._received(ready) + monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows') + monkeypatch.setattr(window, '_create_dsh_view', lambda: ControlledHarness(window)) + publications = [] + monkeypatch.setattr(dsh_automation, 'GitIssuePublisher', lambda path: + lambda *args: publications.append(1) or {'status': 'unavailable'}) + window._dsh_blockers.report('bom:one-attempt', window._task_id, 'bom_import', + 'Controlled malformed BOM', read_only=True) + qtbot.waitUntil(lambda: window._dsh_view is not None and len(window._dsh_view.requests) == 1) + view = window._dsh_view + for phase in ('diagnose', 'reflect'): + qtbot.waitUntil(lambda: len(view.requests) == (1 if phase == 'diagnose' else 2)) + request = view.requests[-1] + assert request['phase'] == phase + view.diagnosis_event.emit({'status': 'started', 'request_id': request['request_id'], 'session_id': 'controlled-session'}) + for _ in range(25): + window._dsh_status._received({'available': False, 'code': 'runtime_unavailable', 'message': 'Controlled local probe timeout'}) + window._dsh_status._received(ready) + # Keep the uncertain local check through the next phase boundary. + window._dsh_status._received({'available': False, 'code': 'runtime_unavailable', 'message': 'Controlled local probe timeout'}) + view.diagnosis_event.emit({'status': 'completed', 'request_id': request['request_id'], + 'session_id': 'controlled-session', 'reply': '{"action":"none","summary":"Controlled BOM validation failure"}'}) + qtbot.waitUntil(lambda: window._dsh_automation.worker is None, timeout=5000) + for _ in range(25): + window._dsh_status._received({'available': False, 'code': 'runtime_unavailable', 'message': 'Controlled local probe timeout'}) + window._dsh_status._received(ready) + qtbot.wait(20) + assert [request['phase'] for request in view.requests] == ['diagnose', 'reflect'] + assert len({request['incident_id'] for request in view.requests}) == 1 + assert len(list(ui.data.glob('dsh/incidents/*/incident.json'))) == 1 + assert len(publications) == 1 + ui.settle() + + +def test_configuring_ai_replays_only_previously_unstarted_blocker_once(no_model, ui, monkeypatch): + window = ui.window + window._dsh_status.timer.stop() + window._dsh_status.query.close() + coordinator = window._dsh_blockers + started = [] + + def enqueue(**value): + if not window._dsh_status.available: + return False + started.append(value.copy()) + return True + + monkeypatch.setattr(coordinator, 'enqueue', enqueue) + coordinator.report('bom:unconfigured-attempt', window._task_id, 'bom_import', 'Persistent failure', read_only=True) + original = next(iter(coordinator.pending.values()))['run_id'] + for _ in range(20): + window._dsh_status._received({'available': False, 'code': 'missing_configuration', 'message': 'No key'}) + assert not started and window._dsh_automation is None + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured'}) + assert len(started) == 1 and started[0]['run_id'] == original + coordinator.completed(original) + for _ in range(20): + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured'}) + assert len(started) == 1 + + +def test_saved_silent_preference_is_grey_before_any_background_check(no_model, ui, qtbot): + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + ui.window.auto_intervention_check.setChecked(False) + reopened = TrialTaskCenterWindow(ui.service) + qtbot.addWidget(reopened) + assert reopened.ai_status_indicator.property('state') == 'silent' + qtbot.waitUntil(lambda: not reopened._task_query.busy and not reopened._resource_status.busy + and not reopened._dsh_status.query.busy) + reopened.close() + + +def test_failed_runtime_start_keeps_unstarted_request_identity_for_recovery(no_model, ui, monkeypatch, qtbot): + from dx_productivity.trial_task_center.ui import dsh_automation + window = ui.window + ui.settle() + window._dsh_status.timer.stop() + window._dsh_status.query.close() + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Configured'}) + monkeypatch.setattr(QApplication, 'platformName', lambda: 'windows') + automation = dsh_automation.DshAutomation(window) + monkeypatch.setattr(window, '_dsh_automation', automation) + monkeypatch.setattr(window, '_open_dsh', lambda: window._dsh_status.runtime_failed('Controlled startup failure')) + automation.enqueue(window._task_id, 'bom_import', 'Controlled failure', run_id='blocker-startup-once', read_only=True) + automation._drain() + assert len(automation.pending) == 1 + assert automation.pending[0].run_id == 'blocker-startup-once' + assert (window._task_id, 'bom_import', 'blocker-startup-once') in automation.seen + assert automation.worker is None and not list(ui.data.glob('dsh/incidents/*')) + starts = [] + monkeypatch.setattr(window, '_open_dsh', lambda: None) + monkeypatch.setattr(automation, '_start_worker', lambda worker: starts.append(automation.current_request.run_id)) + monkeypatch.setattr(dsh_automation, 'GitIssuePublisher', lambda path: lambda *args: {'status': 'unavailable'}) + window._dsh_status.runtime_ready() + qtbot.waitUntil(lambda: bool(starts)) + assert starts == ['blocker-startup-once'] + assert not automation.pending + automation._current_identity = None + automation.current_request = None diff --git a/tests/ui/test_pr10_review_edges.py b/tests/ui/test_pr10_review_edges.py index 5a83013..5d20ad9 100644 --- a/tests/ui/test_pr10_review_edges.py +++ b/tests/ui/test_pr10_review_edges.py @@ -6,6 +6,8 @@ from threading import Event from types import SimpleNamespace import pytest + +pytestmark = pytest.mark.usefixtures('ai_ready') from PySide6.QtCore import Signal from PySide6.QtWidgets import QMessageBox,QWidget @@ -210,7 +212,8 @@ def test_runtime_restart_discards_partial_protocol_and_utf8_characters(qtbot,tmp package.parent.mkdir(parents=True);package.write_text('{}') monkeypatch.setattr(dsh_native,'integration_root',lambda:tmp_path) monkeypatch.setattr(dsh_native,'node_executable',lambda:'test-node') - monkeypatch.setattr(dsh_native,'launch_environment',lambda *args:{}) + state.window=lambda:None + monkeypatch.setattr(dsh_native,'launch_environment',lambda *args,**kwargs:{}) dsh_native.NativeHarnessView.start(state) new={'name':'新请求'} chunks.append(('DX_DSH_CREATE_REQUEST '+json.dumps(new,ensure_ascii=False)+'\n').encode('utf8')) diff --git a/tools/accept_dsh_blockers.py b/tools/accept_dsh_blockers.py index 5cc32b3..c637e33 100644 --- a/tools/accept_dsh_blockers.py +++ b/tools/accept_dsh_blockers.py @@ -178,6 +178,10 @@ def main(): if state['phase'] == 'closing': window.close() return + codes = [json.loads(path.read_text(encoding='utf8')).get('issue_code') + for path in (data / 'dsh/incidents').glob('*/incident.json')] + if any(codes.count(code) > 1 for code in {'bom_import', 'batch_resources_pending'}): + raise AssertionError('Duplicate automatic incident detected; live acceptance stopped') if time.monotonic() > state['deadline']: raise TimeoutError('Desktop blocker acceptance exceeded nine minutes') if state['phase'] == 'select' and window.task_list.list.count() and not window._task_query.busy: diff --git a/tools/accept_dsh_status.py b/tools/accept_dsh_status.py new file mode 100644 index 0000000..0a213e7 --- /dev/null +++ b/tools/accept_dsh_status.py @@ -0,0 +1,148 @@ +"""Click a real unconfigured desktop through a BOM failure and capture lamp states.""" +from pathlib import Path +import json +import os +import sys +import time +from types import SimpleNamespace + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / 'src')) + + +def main(): + for key in ('QT_QPA_PLATFORM', 'DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY', 'DEEPSEEK_API_KEY'): + os.environ.pop(key, None) + output = REPO / 'build' / 'dsh-status-desktop' / time.strftime('%Y%m%d-%H%M%S') + output.mkdir(parents=True) + project = output / 'fixtures/Board-A/board.prj' + project.parent.mkdir(parents=True) + project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n', encoding='utf8') + workbook_path = output / 'fixtures/invalid-bom.xlsx' + from openpyxl import Workbook + workbook = Workbook() + workbook.active.append(['invalid_required_headers']) + workbook.active.append(['controlled invalid BOM row']) + workbook.save(workbook_path) + workbook.close() + + from PySide6.QtCore import QEvent, QPoint, QThreadPool, QTimer, Qt + from PySide6.QtGui import QHelpEvent + from PySide6.QtTest import QTest + from PySide6.QtWidgets import QApplication, QDialogButtonBox, QFileDialog, QLineEdit, QMessageBox, QToolTip + from dx_productivity.trial_task_center.bom_import_state import BomImportPhase + from dx_productivity.trial_task_center.logging_setup import configure_logging + from dx_productivity.trial_task_center.service import TaskCenterService + from dx_productivity.trial_task_center.store import TaskStore + from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow + + QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontUseNativeDialogs) + app = QApplication([]) + popups = [] + QMessageBox.warning = lambda *args, **kwargs: popups.append('warning') or QMessageBox.StandardButton.Ok + QMessageBox.critical = lambda *args, **kwargs: popups.append('critical') or QMessageBox.StandardButton.Ok + data = output / 'data' + store = TaskStore(data / 'tasks.db') + service = TaskCenterService(store, configure_logging(data)) + service._supervised = True + tasks = service.create_project_tasks(project.parent.parent) + window = TrialTaskCenterWindow(service, close_plan_confirmer=lambda: 'discard') + window.resize(1380, 880) + window.setAttribute(Qt.WidgetAttribute.WA_AlwaysShowToolTips, True) + window.show() + window.open_task(tasks[0].task_id) + report = {'status': 'running', 'driver': 'real Qt/QTest; no API keys', 'output': str(output), 'checks': []} + state = {'phase': 'ready', 'deadline': time.monotonic() + 60} + + def capture(name): + window.menuWidget().grab().save(str(output / (name + '-navigation.png'))) + lamp = window.ai_status_indicator + point = lamp.rect().center() + QTest.mouseMove(lamp, point) + QApplication.sendEvent(lamp, QHelpEvent(QEvent.Type.ToolTip, point, lamp.mapToGlobal(point))) + QToolTip.showText(lamp.mapToGlobal(point), lamp.toolTip(), lamp) + app.processEvents() + tips = [widget for widget in app.topLevelWidgets() if widget.windowType() == Qt.WindowType.ToolTip and widget.isVisible()] + assert tips, 'Actual Qt hover tooltip was not shown: ' + str([(w.metaObject().className(), str(w.windowType()), w.isVisible()) for w in app.topLevelWidgets()]) + tips[0].grab().save(str(output / (name + '-tooltip.png'))) + QToolTip.hideText() + + def finish(error=None): + state['phase'] = 'closing' + report.update(status='failed' if error else 'passed', popups=popups, + automaticRuntimeStarted=window._dsh_view is not None, + incidentCount=len(list(data.glob('dsh/incidents/*')))) + if error: + report['error'] = type(error).__name__ + ': ' + str(error) + (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8') + window._dsh_automation = None + window.close() + QTimer.singleShot(100, app.quit) + + def pick_file(): + try: + picker = app.activeModalWidget() + assert isinstance(picker, QFileDialog) + edit = picker.findChild(QLineEdit, 'fileNameEdit') + QTest.keyClicks(edit, str(workbook_path)) + buttons = picker.findChild(QDialogButtonBox) + QTest.mouseClick(buttons.button(QDialogButtonBox.StandardButton.Open), Qt.MouseButton.LeftButton) + state['phase'] = 'failed-bom' + except Exception as error: + finish(error) + + def tick(): + try: + if state['phase'] == 'closing': + return + if time.monotonic() > state['deadline']: + raise TimeoutError('status acceptance deadline') + if state['phase'] == 'ready' and window._context and not window._loading and not window._resource_status.blocked and window._dsh_status.availability['code'] != 'checking': + assert window.ai_status_indicator.property('state') == 'unavailable' + assert 'API Key' in window.ai_status_indicator.toolTip() + capture('red-unconfigured') + tabs = window.mapping_tabs.tabBar() + QTest.mouseClick(tabs, Qt.MouseButton.LeftButton, pos=tabs.tabRect(1).center()) + state['phase'] = 'picker' + QTimer.singleShot(200, pick_file) + QTest.mouseClick(window.plan_panel.import_bom_button, Qt.MouseButton.LeftButton) + elif state['phase'] == 'failed-bom' and not window._workers and window.plan_panel.bom_import_state.phase is BomImportPhase.FAILED: + assert not popups and window._dsh_view is None and window._dsh_automation is None + assert not list(data.glob('dsh/incidents/*')) + assert window.task_list.list.isEnabled() and window.task_list.new_button.isEnabled() + report['checks'].append('Unconfigured model + real BOM parser failure: red lamp, no dialog/runtime/incident, task controls usable') + QTest.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + assert window.ai_status_indicator.property('state') == 'silent' + capture('grey-silent') + report['checks'].append('Clicked automatic-intervention switch off: grey silent state and hover explanation') + # The remaining captures exercise visual states only, with no model calls. + window._dsh_status.timer.stop() + window._dsh_status.query.close() + window._dsh_blockers.pending.clear() + window._dsh_status._received({'available': True, 'code': 'available', 'message': 'Controlled visual fixture'}) + QTest.mouseClick(window.auto_intervention_check, Qt.MouseButton.LeftButton) + capture('green-idle') + window._dsh_automation = SimpleNamespace(worker=object(), pending=[], can_cancel=True, + latest={'status': 'reflecting', 'message': 'BOM 表头缺少旧料号、新料号和位号', 'task_name': 'Board-A'}, + current_request=None, cancel=lambda: None) + window._update_gates() + assert window.ai_status_indicator.property('state') == 'working' + capture('yellow-intervening') + report['checks'].append('Controlled visual-only ready/working states: hover shows task, BOM reason and reflection stage') + finish() + except Exception as error: + finish(error) + + timer = QTimer(window) + timer.setInterval(100) + timer.timeout.connect(tick) + timer.start() + app.exec() + QThreadPool.globalInstance().waitForDone() + store.close() + print(json.dumps(report, ensure_ascii=True)) + return 0 if report['status'] == 'passed' else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/verify_dsh_model_availability.mjs b/tools/verify_dsh_model_availability.mjs new file mode 100644 index 0000000..9bc7886 --- /dev/null +++ b/tools/verify_dsh_model_availability.mjs @@ -0,0 +1,86 @@ +/** Offline fixtures: real Harness composition, no runtime boot or model requests. */ +import assert from 'node:assert/strict'; +import {mkdtemp,mkdir,writeFile,readFile,readdir,rm} from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import {checkModelAvailability} from '../integration/dsh/model_availability.mjs'; + +const home=await mkdtemp(path.join(os.tmpdir(),'dx-model-availability-')); +const directory=path.join(home,'profiles/dx-task'); +await mkdir(directory,{recursive:true}); +const names=['DSH_API_BASE','DSH_MODEL','DSH_API_KEY','DX_DSH_MODELS','FIXTURE_NATIVE_KEY','DEEPSEEK_API_KEY']; +const saved=Object.fromEntries(names.map(key=>[key,process.env[key]])); +for(const key of names)delete process.env[key]; +const route={api:'openai-completions',baseURL:'https://fixture.invalid/v1', + apiKeyEnv:'FIXTURE_NATIVE_KEY',models:[{id:'fixture-model'}]}; +const rows=profile=>[{id:'llm-pi-ai',config:{providers:{custom:profile}}}, + {id:'agent-default-model',config:{provider:'custom',model:'fixture-model'}}]; +let cases=0; + +async function snapshot(directory){ + const entries=await readdir(directory,{withFileTypes:true}); + const result={}; + for(const entry of entries){ + const filename=path.join(directory,entry.name); + result[entry.name]=entry.isDirectory()?await snapshot(filename):(await readFile(filename)).toString('base64'); + } + return result; +} + +async function verify(patch,credentials,code,environmentRefs){ + await writeFile(path.join(directory,'cordis.patch.yml'),JSON.stringify(patch)); + await writeFile(path.join(home,'.credentials.yaml'),typeof credentials==='string'?credentials:JSON.stringify(credentials),{mode:0o600}); + const before=await snapshot(home); + const started=performance.now(); + const checked=await checkModelAvailability(home); + assert.equal(checked.code,code); + assert.equal(checked.available,code==='available'); + if(checked.available){ + assert.ok(['native','host'].includes(checked.source)); + assert.ok(Array.isArray(checked.environment_refs)); + assert.ok(checked.environment_refs.every(name=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))); + if(environmentRefs!==undefined)assert.deepEqual(checked.environment_refs,environmentRefs); + } + assert.deepEqual(await snapshot(home),before,'status check must not change files'); + assert.ok(performance.now()-started<3000,'native read-only check must fit desktop worker deadline'); + cases++; +} + +try{ + await verify([],{},'missing_credential'); + await verify([],{version:1,refs:{DEEPSEEK_API_KEY:'fake-official-native-key'}},'available',[]); + assert.equal((await checkModelAvailability(home)).source,'native'); + assert.deepEqual((await checkModelAvailability(home)).environment_refs,[]); + await verify([{id:'llm-deepseek',config:{apiKeyEnv:'FIXTURE_NATIVE_KEY'}}], + {version:1,refs:{FIXTURE_NATIVE_KEY:'fake-custom-official-key'}},'available',[]); + await verify(rows(route),{},'missing_credential'); + await verify(rows(route),{version:1,refs:{FIXTURE_NATIVE_KEY:'fake-offline-key'}},'available',[]); + await verify(rows(route),{version:1,refs:{FIXTURE_NATIVE_KEY:'fake-offline-key'},records:[]},'invalid_configuration'); + await verify(rows(route),{FIXTURE_NATIVE_KEY:'fake-flat-offline-key'},'available',[]); + await verify(rows(route),'%YAML 1.2\n---\nFIXTURE_NATIVE_KEY: fake-flat-offline-key\n','invalid_configuration'); + await verify(rows(route),'version: 1\nrefs: [fake-secret', 'invalid_configuration'); + await verify(rows(route),{version:99,refs:{FIXTURE_NATIVE_KEY:'fake-offline-key'}},'invalid_configuration'); + process.env.FIXTURE_NATIVE_KEY='fake-environment-key'; + await verify(rows(route),{},'available',['FIXTURE_NATIVE_KEY']); + await verify(rows(route),{version:1,refs:{FIXTURE_NATIVE_KEY:'fake-stored-wins'}},'available',[]); + await verify([{id:'llm-deepseek',config:{apiKeyEnv:'FIXTURE_NATIVE_KEY'}}],{},'available',['FIXTURE_NATIVE_KEY']); + delete process.env.FIXTURE_NATIVE_KEY; + await verify(rows({...route,apiKeyEnv:undefined}),{},'available'); + const ignored=rows(route);ignored[0].name='@deepseek-ai/not-the-configured-plugin'; + await verify(ignored,{version:1,refs:{FIXTURE_NATIVE_KEY:'fake-offline-key'}},'missing_configuration'); + await verify([...rows(route),{insert:[{id:'llm-pi-ai',name:'@deepseek-ai/dsh-llm-pi-ai'}]}], + {version:1,refs:{FIXTURE_NATIVE_KEY:'fake-offline-key'}},'invalid_configuration'); + Object.assign(process.env,{DSH_API_BASE:'https://host.invalid/v1',DSH_MODEL:'host-model',DSH_API_KEY:'fake-host-key'}); + await verify([],{},'available',['DSH_API_KEY']); + await verify(rows(route),{version:1,refs:{FIXTURE_NATIVE_KEY:'fake-offline-key'}},'available'); + await verify([],{version:1,refs:{DSH_API_KEY:'fake-unbound-key'}},'invalid_configuration'); + // Independently stored native dx refs are valid even with no host provider. + for(const key of ['DSH_API_BASE','DSH_MODEL','DSH_API_KEY'])delete process.env[key]; + await verify([{id:'llm-pi-ai',config:{providers:{dx:{...route,apiKeyEnv:'DSH_API_KEY'}}}}, + {id:'agent-default-model',config:{provider:'dx',model:'fixture-model'}}], + {version:1,refs:{DSH_API_KEY:'fake-bound-native-key'}},'available',[]); + console.log(JSON.stringify({status:'passed',cases,realHarnessComposition:true,readOnly:true,remoteModelCalls:false})); +}finally{ + for(const key of names){if(saved[key]===undefined)delete process.env[key];else process.env[key]=saved[key];} + await rm(home,{recursive:true,force:true}); +}