From 374e1cd5bf2713bb4afcb648ee2f714a12804ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Tue, 3 Nov 2026 11:41:50 +0800 Subject: [PATCH 1/2] fix(dsh): preserve acrylic and restore durable native model settings --- README.md | 2 +- docs/testing/2026-11-03-dsh-issue16.md | 28 ++++++++ docs/user/dsh-ai-supervision.md | 8 ++- integration/dsh/start.mjs | 56 ++++++++++++--- integration/dsh/task-plugin/client.js | 2 +- .../trial_task_center/ui/dsh_native.py | 7 +- tools/accept_acrylic_ui.py | 44 +++++++++++- tools/accept_dsh_desktop.py | 3 + tools/verify_dsh_model_settings.mjs | 69 +++++++++++++++++++ tools/verify_dsh_native_ui.mjs | 20 ++++-- tools/verify_dsh_profile_settings.mjs | 40 +++++++++++ 11 files changed, 262 insertions(+), 17 deletions(-) create mode 100644 docs/testing/2026-11-03-dsh-issue16.md create mode 100644 tools/verify_dsh_model_settings.mjs create mode 100644 tools/verify_dsh_profile_settings.mjs diff --git a/README.md b/README.md index 730479c..85b3af0 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ DSH助手围绕真实任务中心工作,支持: AI 不能直接写入 CAD、运行 Shell、访问任意文件或绕过确认门禁。自动异常诊断为只读;不确定执行不会自动重放,恢复必须重新核对冻结计划、检查点和业务证据。未配置模型时仍可使用任务监管和本地恢复功能,但不会产生真实模型回复。 -模型配置保存在本机任务中心数据目录,密钥使用 Windows DPAPI 保护,不写入仓库或环境变量。首次接入可在 **工具设置 → DSH工具** 中配置 OpenAI 兼容端点和模型;开发环境也可通过 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY` 临时提供配置。不要把 API key、Git 凭据或 `integration/dsh/issue-bootstrap.json` 提交到 Git。 +首次接入打开 **工具设置 → 模型 → 添加模型提供商 → 自定义模型 API**,填写 API 地址、协议和密钥,点击 **获取可用模型** 并选择需要的模型,也可手动填写模型 ID。保存后在输入框下方选择模型。设置保存在任务中心数据目录的专用 Harness profile,重启会保留;主工具预配置的密钥继续由 Windows DPAPI 保护,模型设置页新增的密钥使用 Harness 本地凭据存储。开发环境也可通过 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY` 临时提供配置。不要把数据目录、API key 或 Git 凭据提交到 Git。 详细的能力边界、异常介入、证据链、排期和工单说明见 [DSH助手使用与监管说明](docs/user/dsh-ai-supervision.md)。源码环境可用下面的命令检查运行时门禁: diff --git a/docs/testing/2026-11-03-dsh-issue16.md b/docs/testing/2026-11-03-dsh-issue16.md new file mode 100644 index 0000000..df43085 --- /dev/null +++ b/docs/testing/2026-11-03-dsh-issue16.md @@ -0,0 +1,28 @@ +# 工单 #16:DSH 切换材质与模型设置 + +基线:`main@3cec9ad`。工单:[切换DSH工具遇到的一些问题](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/issues/16)。 + +## 修复内容 + +首次展示 WebEngine 时,Qt 将透明主窗口重建为 RHI 图形合成表面。返回任务中心后,重新调用 Acrylic API 或预设 alpha buffer 均不能恢复玻璃效果。DSH 现在通过 `WA_DontCreateNativeAncestors` 和 `WA_NativeWindow` 独立承载 Chromium 原生表面,保留任务中心的原 HWND 与 Acrylic。未改变系统透明度策略及“减少透明度”回退。 + +恢复官方 `ui-settings-models` 插件,提供模型提供商、自定义模型 API、手动模型列表和“获取可用模型”。通过上游公开的配置项关闭凭据引导,并使用固定 Harness 版本对应的欢迎说明配置,保留无账户/充值入口的任务工具界面。 + +重启验收发现旧启动脚本还会覆盖原生用户 `cordis.patch.yml`。应用配置现放在独立 `@dx/dsh-policy` bundle 中,原生用户配置作为上层保留。识别到旧应用生成的 overlay 时,先保存包含 SHA256 的逐字节备份,再迁移提供商与默认模型配置。原生模型页新增密钥使用 Harness 本地凭据存储,主工具预配置继续使用 DPAPI,文档分别说明。 + +## Windows 实际显示与点击 + +- 修复前屏幕截图:进入 DSH 再返回后,侧栏和右侧摘要对两种自有底图的差异均为 **0**;Acrylic 属性仍显示 true,因此属性不能作为显示成功证明。 +- 最终材质验收:`build/dsh-issue16-acrylic-final/acceptance.json`。主 HWND 全程相同,切换前后侧栏差异均为 **21.82**,右侧摘要差异均约 **9.30**;数据表差异为 **0**,保持实色。减少透明度、紧凑布局和正常关闭通过。 +- 模型页面实际输入/点击:`build/dsh-issue16-model-final/desktop-report.json`。添加自定义 API、调用自有本机测试服务器的 `GET /v1/models`、选择模型、保存提供商、重新打开编辑器读回模型均通过。未调用真实模型生成、CAD 或远端工单接口。 +- 独立新进程重启报告:`build/dsh-issue16-model-final/restart-report.json`。重启真实 Harness 后读取到页面创建的 `issue16-fixture-model`,未发起模型请求。 +- 同轮桌面验收还通过无登录/首次引导、官方页面、侧栏、SVG 动画、模型选择器、原生取消确认、导航后草稿保留及清洁退出。 + +## 回归 + +- DSH、UI、打包、队列与安全停止:412 passed(在原生子窗口修复后运行)。 +- `node tools/verify_dsh_profile_settings.mjs`:原生设置重复初始化不改写、真实提供方加载、旧配置迁移与原字节备份通过。 +- 官方 runtime CLI 门禁、模型结果裁剪与 dock 启动检查通过。 +- 独立代码审查未发现新增阻断问题。 + +本轮没有构建冻结 EXE;发布包须从修复分支重新构建,源码验收不替代发布包验收。 diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index 4db769c..ad649ec 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -6,7 +6,13 @@ 这里直接运行 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 的官方前端与运行时,固定 npm 版本 `0.2.1-rc.5`,通过 Qt WebEngine 嵌入主窗口。官方三栏框架、原生 SVG、鲸鱼悬停动画、输入编辑器、模型选择、侧栏与停靠交互均由上游代码提供。项目增加任务监管插件和“DSH助手”名称,不再使用 Qt 控件重画聊天页面。上游许可见 `licenses/DeepSeek-Harness-MIT.txt`。 -不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页中的“DSH工具”说明;首页提示和任务监管面板围绕器件替换任务。输入框下方仍可选择主工具已经配置的模型。 +不显示上游账户登录、注册、充值和首次产品引导,也不注册其账户模型提供方。左下角 **工具设置** 单击打开原生设置页,包含“DSH工具”“通用设置”和“模型”;首页提示和任务监管面板围绕器件替换任务。输入框下方选择已配置的模型。 + +在 **模型 → 添加模型提供商 → 自定义模型 API** 中填写 Provider ID、API 地址、协议及可选密钥,点击 **获取可用模型**,勾选后点 **添加所选**,最后 **创建提供商**。也可手动添加模型 ID。获取失败会保留表单,便于修正地址或手动填写。已有提供方点击 **编辑** 可修改其模型目录;保存后即时生效。 + +模型页面使用官方 Harness 设置与凭据服务:用户设置保存在 `dsh/harness-home/profiles/dx-task/cordis.patch.yml`,新增的密钥通过官方本地凭据服务保存在 `dsh/harness-home/.credentials.yaml`;此文件不使用主工具的 DPAPI 格式。主工具预配置的 `provider.json` 和 DPAPI 密钥仍可加载。应用固定策略作为独立 bundle 提供,不会在启动时覆盖用户模型设置。旧版应用生成的配置升级时先逐字节备份,再保留提供方和默认模型设置;请一并备份整个数据目录,不要将凭据文件分发或提交到仓库。 + +DSH 使用独立原生子窗口承载 WebEngine,切回任务中心后保留原有 Acrylic 玻璃材质;“减少透明度”与系统高对比度等回退规则继续生效。 模型由本机保存的主工具配置加载;也支持启动进程的 `DSH_API_BASE`、`DSH_MODEL`、`DSH_API_KEY`。未配置模型时可查看任务上下文和操作面板,不能获得真实模型回复。 diff --git a/integration/dsh/start.mjs b/integration/dsh/start.mjs index 5ae7026..6f5e211 100644 --- a/integration/dsh/start.mjs +++ b/integration/dsh/start.mjs @@ -1,7 +1,8 @@ /** Application-owned composition around the unmodified official Harness web UI. */ import {createRequire} from 'node:module'; import {fileURLToPath} from 'node:url'; -import {mkdir, writeFile, readFile, cp} from 'node:fs/promises'; +import {mkdir, writeFile, readFile, cp, rename} from 'node:fs/promises'; +import {createHash,randomUUID} from 'node:crypto'; import path from 'node:path'; import {createInterface} from 'node:readline'; @@ -28,12 +29,14 @@ export const DISABLED = [ // This embedded tool uses its application-owned API configuration, without // upstream accounts, billing, credential onboarding or product feedback. 'ui-settings-account','account-controller','deepseek-account','llm-deepseek-account', - 'ui-settings-models','ui-message-feedback','message-feedback','command-feedback', + 'ui-message-feedback','message-feedback','command-feedback', ]; export function overlay() { const rows = DISABLED.map(id => ({id, disabled:true})); rows.push({id:'agent-preset-registry',config:{default:'dx-task'}}); + rows.push({id:'ui-settings-general',config:{welcomeNoticeVersion:'2026-09-28.1'}}); + rows.push({id:'ui-settings-models',config:{credentialOnboarding:false}}); rows.push({id:'web-runtime',config:{openBrowser:false,printUrl:false,surfaceContext:false}}); rows.push({id:'sandbox-policy',config:{mode:'read-only',workspaceRoot:process.env.DX_DSH_WORKSPACE}}); rows.push({id:'permission',config:{presets:{'read-only':{sandbox:'read-only',approval:'ask'}}}}); @@ -55,6 +58,48 @@ export function overlay() { return rows; } +async function replaceJson(filename,value) { + const temporary=filename+'.'+randomUUID()+'.tmp'; + const {unlink}=await import('node:fs/promises'); + try{await writeFile(temporary,JSON.stringify(value,null,2));await rename(temporary,filename);} + finally{await unlink(temporary).catch(error=>{if(error.code!=='ENOENT')throw error;});} +} + +export async function prepareProfileDirectory(dir) { + // The official settings page writes the user patch. Application defaults + // belong to a bundle below that patch, so rebooting must never overwrite it. + await mkdir(dir,{recursive:true}); + const userPatch=path.join(dir,'cordis.patch.yml'); + let prior; + try{prior=await readFile(userPatch,'utf8');}catch(error){if(error.code!=='ENOENT')throw error;} + if(prior!==undefined){ + const {load}=require('js-yaml'); + const rows=load(prior); + const legacy=Array.isArray(rows)&&rows.some(row=>Array.isArray(row?.insert) + &&row.insert.some(entry=>entry.id==='dx-task'&&entry.name==='@dx/dsh-task') + &&row.insert.some(entry=>entry.id==='preset-dx-task')); + if(legacy){ + const digest=createHash('sha256').update(prior).digest('hex'); + const backup=userPatch+'.legacy-'+digest+'.bak'; + try{await writeFile(backup,prior,{flag:'wx'});}catch(error){ + if(error.code!=='EEXIST'||await readFile(backup,'utf8')!==prior)throw error; + } + const editable=new Set(['llm-pi-ai','llm-deepseek','agent-default-model']); + await replaceJson(userPatch,rows.filter(row=>editable.has(row?.id)&&row.config) + .map(({id,config})=>({id,config}))); + } + } + const policyDir=path.join(dir,'node_modules','@dx','dsh-policy'); + await mkdir(policyDir,{recursive:true}); + await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true}); + await replaceJson(path.join(policyDir,'package.json'),{name:'@dx/dsh-policy',version:VERSION, + private:true,dsh:{bundle:{patch:'./cordis.patch.yml'}}}); + await replaceJson(path.join(policyDir,'cordis.patch.yml'),overlay()); + await replaceJson(path.join(dir,'package.json'),{private:true,type:'module', + dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin'),'@dx/dsh-policy':'file:'+policyDir}, + dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app','@dx/dsh-policy']}}}); +} + export async function bootRuntime({announce=true} = {}) { const installed = require('@deepseek-ai/dsh/package.json'); if (installed.version !== VERSION) throw Error('Unsupported Harness version: ' + installed.version); @@ -73,12 +118,7 @@ export async function bootRuntime({announce=true} = {}) { process.env.DX_DSH_WORKSPACE = path.join(process.env.DX_DSH_HOME,'workspace'); await mkdir(process.env.DX_DSH_WORKSPACE,{recursive:true}); const dir = path.join(process.env.DX_DSH_HOME,'profiles','dx-task'); - await mkdir(path.join(dir,'node_modules','@dx'),{recursive:true}); - await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true}); - await writeFile(path.join(dir,'package.json'), JSON.stringify({private:true,type:'module', - dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin')}, - dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app']}}})); - await writeFile(path.join(dir,'cordis.patch.yml'),JSON.stringify(overlay(),null,2)); + await prepareProfileDirectory(dir); const {runProfile, INSTALL_ANCHOR} = await import('@deepseek-ai/dsh/profile-boot'); const {loadProfileDirectory,composeEntries} = await import('@deepseek-ai/dsh-app-boot'); const {createLaunchEnvironmentSnapshot} = await import('@deepseek-ai/dsh-launch-environment'); diff --git a/integration/dsh/task-plugin/client.js b/integration/dsh/task-plugin/client.js index 19707aa..d29167a 100644 --- a/integration/dsh/task-plugin/client.js +++ b/integration/dsh/task-plugin/client.js @@ -13,7 +13,7 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{ h('h3',null,'任务能力'), h('ul',null,...['在对话中创建和修改任务;具体工程与执行范围由原生窗口确认','实时监管当前执行、阶段、耗时与保存/失败/未命中计数','保存执行回执,重启后核对原队列并手动确认恢复','预览精确位号影响;仅有料号映射时明确标记未知匹配数量','检索历史异常经验,仅将持久化核验通过的记录标为已验证','只读同步已有 Git 工单状态与评论,查看本地证据','查看会话 Token、耗时与超时状态,配置响应时限并停止模型生成','设置任务优先级、执行时间与依赖,通过原生窗口确认排期'].map(text=>h('li',{key:text},text))), h('h3',null,'模型与数据'), - h('p',null,'使用主工具配置的模型,在输入框下方选择。会话保存在本机任务中心数据目录。'), + h('p',null,'在“模型”设置页添加模型提供商或自定义模型 API,填写地址后可获取可用模型,也可手动填写模型 ID。保存后在输入框下方选择,模型设置和会话在重启后保留。'), h('h3',null,'异常工单'), h('p',null,'随工具预置专用工单上报身份,无需安装 Git 或登录。未解决的异常自动提交项目工单,并上传脱敏诊断证据。'), h('p',null,'工程修改与执行核验由任务中心完成。模型不直接访问工程文件或执行命令。')); 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 826a4eb..65eacd7 100644 --- a/src/dx_productivity/trial_task_center/ui/dsh_native.py +++ b/src/dx_productivity/trial_task_center/ui/dsh_native.py @@ -5,7 +5,7 @@ import json import codecs from pathlib import Path -from PySide6.QtCore import QProcess, QProcessEnvironment, QTimer, QUrl, Signal +from PySide6.QtCore import QProcess, QProcessEnvironment, QTimer, QUrl, Signal, Qt from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineSettings from PySide6.QtWebEngineWidgets import QWebEngineView from PySide6.QtWidgets import QLabel, QPushButton, QVBoxLayout, QWidget @@ -37,6 +37,11 @@ class NativeHarnessView(QWidget): def __init__(self, data_root: Path, parent=None): super().__init__(parent) + # Isolate Chromium's RHI surface in this child HWND. Otherwise showing + # WebEngine recreates the translucent task-center HWND as an opaque + # graphics surface and Acrylic stays white after the view is hidden. + self.setAttribute(Qt.WidgetAttribute.WA_DontCreateNativeAncestors) + self.setAttribute(Qt.WidgetAttribute.WA_NativeWindow) self.setObjectName('dshNativeWorkspace') self.setStyleSheet('QWidget#dshNativeWorkspace {background:white;}') self.data_root = Path(data_root) diff --git a/tools/accept_acrylic_ui.py b/tools/accept_acrylic_ui.py index 3fe01bb..8211bdf 100644 --- a/tools/accept_acrylic_ui.py +++ b/tools/accept_acrylic_ui.py @@ -29,6 +29,7 @@ from dx_productivity.trial_task_center.target_plan import ComponentTarget,Target def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--output',type=Path,default=Path('build/acrylic-acceptance')) + parser.add_argument('--dsh-switch',action='store_true',help='Measure live Acrylic after entering the actual DSH WebEngine page') args=parser.parse_args();out=args.output.resolve();out.mkdir(parents=True,exist_ok=True) app=QApplication([]);app.setFont(QFont('Microsoft YaHei UI',9)) def settle(seconds=.2): @@ -80,6 +81,9 @@ def main(): assert window.property('acrylicEnabled'),'Native Acrylic not available under current system policy' report['native_enabled']=True def capture(name): + report.setdefault('surfaces',{})[name]={ + 'hwnd':int(window.winId()),'translucent':window.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground), + 'alpha':window.windowHandle().format().alphaBufferSize(),'acrylic':window.property('acrylicEnabled')} settle(.7) QToolTip.hideText();settle(.12) geo=window.geometry();scale=screen.devicePixelRatio() @@ -121,6 +125,40 @@ def main(): assert report['right_header_backdrop_difference']>2,report assert report['right_execution_backdrop_difference']>2,report assert report['opaque_table_backdrop_difference']<1.5,report + if args.dsh_switch: + from PySide6.QtTest import QTest + QTest.mouseClick(window.dsh_navigation,Qt.MouseButton.LeftButton) + deadline=time.monotonic()+120 + while time.monotonic()2,report + assert report['after_dsh_header_difference']>2,report + assert report['after_dsh_table_difference']<1.5,report + report['real_dsh_switch_restored_acrylic']=True window.plan_panel.find_text.setText('RV');window.plan_panel.find() report['visible_search_feedback']=window.plan_panel.find_result.isVisible() assert '2 / 6'in window.plan_panel.find_result.text() @@ -158,7 +196,11 @@ def main(): window._finish_run();window._update_gates() window.project_options_button.setChecked(True);settle(.2) report['options_exposed']=window.run_panel.copy_value_check.isVisible() - window.plan_panel.discard_all();window.close();settle(.3);store.close();logging.shutdown() + window.plan_panel.discard_all();window.close() + deadline=time.monotonic()+15 + while window.isVisible() and time.monotonic(){ + requests.push({method:req.method,path:req.url}); + res.writeHead(req.url==='/v1/models'?200:404,{'Content-Type':'application/json'}); + res.end(JSON.stringify({object:'list',data:[{id:'issue16-fixture-model',object:'model',owned_by:'acceptance'}]})); + }); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + const endpoint=`http://127.0.0.1:${server.address().port}/v1`; + const visible=selector=>`[...document.querySelectorAll(${JSON.stringify(selector)})].find(e=>e.getBoundingClientRect().width>0)`; + const button=text=>`[...document.querySelectorAll('button')].find(e=>e.getBoundingClientRect().width>0&&e.textContent.trim()===${JSON.stringify(text)})`; + async function wait(expression){ + const end=Date.now()+20000; + while(Date.now()setTimeout(r,100));} + throw Error('Models acceptance timed out: '+expression); + } + async function type(selector,text){ + await c.click(visible(selector)); + await c.call('Input.insertText',{text}); + await wait(`(${visible(selector)})?.value===${JSON.stringify(text)}`); + } + try{ + // The caller has reached the actual upstream Custom model API form. + await type('input[aria-label="Provider ID"]','issue16-fixture'); + await type('input[aria-label="API 地址"]',endpoint); + const protocol='select[aria-label="API 协议"]'; + // This is a native keyboard selection, not a direct settings RPC. + const choices=await c.evaluate(`[...(${visible(protocol)}).options].map(x=>x.value)`); + const target=choices.indexOf('openai-completions'); + assert.ok(target>=0); + await c.click(visible(protocol)); + await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Home',code:'Home',windowsVirtualKeyCode:36}); + await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Home',code:'Home',windowsVirtualKeyCode:36}); + for(let i=0;ie.textContent.includes('issue16-fixture-model'))?.querySelector('input[type="checkbox"]')`; + if(!await c.evaluate(`(${candidate})?.checked`))await c.click(candidate); + assert.equal(await c.evaluate(`(${candidate})?.checked`),true); + await c.click(button('添加所选')); + await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`); + await c.screenshot(path.join(output,'custom-model-discovery.png')); + await c.click(button('创建提供商')); + await wait(`!document.querySelector('input[aria-label="Provider ID"]')`); + await wait(`document.body.innerText.includes('issue16-fixture')`); + // Reopen the real editor to read committed fields, not the submitted draft. + await c.click(`[...document.querySelectorAll('li')].find(e=>e.textContent.includes('issue16-fixture'))?.querySelector('button')`); + await wait(`document.body.innerText.includes('自定义设置')`); + await c.click(`[...document.querySelectorAll('summary')].find(e=>e.textContent.includes('自定义设置'))`); + await wait(`!![...document.querySelectorAll('input')].find(x=>x.value==='issue16-fixture-model')`); + await c.screenshot(path.join(output,'custom-model-persisted.png')); + return {status:'passed',provider:'issue16-fixture',model:'issue16-fixture-model',requests, + credentialsUsed:false,remoteModelCalls:false}; + }finally{ + server.closeAllConnections();await new Promise(resolve=>server.close(resolve)); + } +} diff --git a/tools/verify_dsh_native_ui.mjs b/tools/verify_dsh_native_ui.mjs index 53580e4..3688a3a 100644 --- a/tools/verify_dsh_native_ui.mjs +++ b/tools/verify_dsh_native_ui.mjs @@ -33,9 +33,21 @@ try { assert.equal(await c.evaluate(`${accountEntries}.length`),0); report.checks.push('one click opens native tool settings with DSH capabilities and no account entry'); await c.screenshot(path.join(output,'dsh-tool-settings.png')); - await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape'}); - await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape'}); - await wait(`!document.querySelector('[data-testid="dx-tool-settings-panel"]')`); + await c.click(`[...document.querySelectorAll('[data-shortcut-modal="settings"] nav button')].find(e=>e.textContent.trim()==='模型')`); + await wait(`document.body.innerText.includes('自定义模型 API')||document.body.innerText.includes('添加模型提供商')`); + if(!await c.evaluate(`document.body.innerText.includes('自定义模型 API')`)) + await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent.includes('添加模型提供商'))`); + await wait(`document.body.innerText.includes('自定义模型 API')`); + await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='自定义模型 API')`); + await wait(`!!document.querySelector('input[aria-label="Provider ID"]')&&document.body.innerText.includes('获取可用模型')`); + report.checks.push('actual model settings clicks reveal custom API and fetch-model controls'); + await c.screenshot(path.join(output,'dsh-custom-model-settings.png')); + if(process.argv.includes('--model-settings-check')){ + const {verifyModelSettings}=await import('./verify_dsh_model_settings.mjs'); + report.modelSettings=await verifyModelSettings(c,output); + } + await c.click(`[...document.querySelectorAll('[data-shortcut-modal="settings"] button')].find(e=>e.textContent.trim()==='关闭')`); + await wait(`!document.querySelector('[role="dialog"]')`); await c.screenshot(path.join(output,'dsh-tool-home.png')); const context=await c.evaluate(`fetch('/dx/context').then(r=>r.json())`); assert.ok(context.task_id,'Select a task in the task center before running this test.'); @@ -92,7 +104,7 @@ try { report.checks.push('real API reply rendered through the official Harness conversation'); await c.click(`document.querySelector('[contenteditable="true"]')`); await c.call('Input.insertText',{text:'请分析当前任务的下一步。'}); - } else report.reason='No model credential configured in this isolated acceptance profile.'; + } else report.reason='Live model generation was not requested for this acceptance run.'; await c.screenshot(path.join(output,'dsh-native-final.png')); if(process.argv.includes('--confirm-cancel')) { await c.click(`[...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='准备失败项重试')`); diff --git a/tools/verify_dsh_profile_settings.mjs b/tools/verify_dsh_profile_settings.mjs new file mode 100644 index 0000000..964dc82 --- /dev/null +++ b/tools/verify_dsh_profile_settings.mjs @@ -0,0 +1,40 @@ +/** Boot the actual Harness over native user settings and a legacy profile. */ +import assert from 'node:assert/strict'; +import {mkdtemp,mkdir,readFile,writeFile,readdir} from 'node:fs/promises'; +import path from 'node:path'; +import {bootRuntime,overlay,prepareProfileDirectory} from '../integration/dsh/start.mjs'; + +const output=path.resolve('build/dsh-profile-settings-verification'); +await mkdir(output,{recursive:true}); +const base=await mkdtemp(path.join(output,'run-')); +process.env.DX_DSH_HOME=path.join(base,'home'); +process.env.DX_DSH_CONTEXT_FILE=path.join(base,'context.json'); +await writeFile(process.env.DX_DSH_CONTEXT_FILE,JSON.stringify({task_id:'',revision:'settings-test',status:'observe'})); +const dir=path.join(process.env.DX_DSH_HOME,'profiles/dx-task'); +await mkdir(dir,{recursive:true}); +const profile=[{id:'llm-pi-ai',config:{providers:{'profile-fixture':{ + api:'openai-completions',baseURL:'http://127.0.0.1:1/v1',models:[{id:'persisted-fixture-model'}]}}}}]; +const patch=path.join(dir,'cordis.patch.yml'); +const original='# Native user settings\n'+JSON.stringify(profile,null,2)+'\n'; +await writeFile(patch,original); +await prepareProfileDirectory(dir);await prepareProfileDirectory(dir); +assert.equal(await readFile(patch,'utf8'),original,'application preparation must not rewrite a native user layer'); +const legacyDir=path.join(base,'legacy'); +await mkdir(legacyDir,{recursive:true}); +const old=JSON.stringify([...overlay(),...profile],null,2); +await writeFile(path.join(legacyDir,'cordis.patch.yml'),old); +await prepareProfileDirectory(legacyDir); +const migrated=await readFile(path.join(legacyDir,'cordis.patch.yml'),'utf8'); +assert.ok(JSON.parse(migrated).some(x=>x.id==='llm-pi-ai'&&x.config.providers['profile-fixture'])); +const backups=(await readdir(legacyDir)).filter(x=>x.includes('.legacy-')); +assert.equal(backups.length,1); +assert.equal(await readFile(path.join(legacyDir,backups[0]),'utf8'),old); +await prepareProfileDirectory(legacyDir); +assert.equal(await readFile(path.join(legacyDir,'cordis.patch.yml'),'utf8'),migrated); +const {ctx,shutdown}=await bootRuntime({announce:false}); +try{ + assert.deepEqual((await ctx.llm.listModels('profile-fixture')).map(x=>x.id),['persisted-fixture-model']); + assert.equal(ctx.tools.schemas().length,7); + console.log(JSON.stringify({status:'passed',nativeSettingsPreserved:true,actualProviderRestored:true, + legacyMigrationPreservedModels:true,byteBackup:true,modelRequests:0})); +}finally{await shutdown.shutdown(0);} From af46ee16175785972e78103a51df41b65ac891ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Tue, 3 Nov 2026 17:28:22 +0800 Subject: [PATCH 2/2] fix(dsh): bind migrated model routes to credential sources --- .../2026-11-03-dsh-provider-migration.md | 18 ++ docs/testing/2026-11-03-dsh-issue16.md | 24 ++- docs/user/dsh-ai-supervision.md | 4 +- integration/dsh/start.mjs | 140 ++++++++++-- tools/verify_dsh_provider_switch.mjs | 200 ++++++++++++++++++ 5 files changed, 368 insertions(+), 18 deletions(-) create mode 100644 docs/plans/2026-11-03-dsh-provider-migration.md create mode 100644 tools/verify_dsh_provider_switch.mjs diff --git a/docs/plans/2026-11-03-dsh-provider-migration.md b/docs/plans/2026-11-03-dsh-provider-migration.md new file mode 100644 index 0000000..6dd32b9 --- /dev/null +++ b/docs/plans/2026-11-03-dsh-provider-migration.md @@ -0,0 +1,18 @@ +# PR #17 提供方迁移修复 + +目标:修复 PR #17 评论 #168 的旧地址与新密钥错配,保留原生自定义提供方及其独立凭据。 + +设计:`dx` 且引用启动环境 `DSH_API_KEY` 的配置归主工具管理,每次启动从当前主工具配置完整刷新;独立凭据的提供方保留。Harness 的插件 config 整块替换,因此用户 providers 存在时须同时纳入当前主工具提供方。迁移旧生成配置时,生成的 dx 默认模型回到当前主工具默认值;原生用户选定的有效 dx 模型和自定义提供方默认模型继续保留。没有主工具配置时清除旧应用管理的路由与默认选择。修改前保存原文件备份,重复初始化不重复改写。 + +凭据来源补充:上游本地保存的引用优先于环境变量。显式 dx 使用本地保存的 DSH_API_KEY 时,整条路由和密钥作为原生用户覆盖保留。启用了主工具模型、却只有孤立本地密钥时拒绝启动,不从历史 policy 猜测地址;没有主工具模型时不阻断其他独立提供方。首次正常启动即在原生用户配置中物化完整的应用 dx,确保此后模型页仅修改密钥也能保留它所属的地址和模型。配置准备不修改凭据文件,解析错误不包含密钥原文。 + +绑定证明以 Harness 真实 composition 为准,保留 name assertion / insert 语义,拒绝凭据、模型适配器和默认模型的重复 ID。从有效 credentials 配置解析实际文件路径。启动前确认最终应用路由与当前配置一致;桌面接入前再次核对实际凭据来源和仅在内存中的密钥摘要,避免环境与文件来源互换。 + +不采用只删除旧 dx 的方案:用户的 providers 整块覆盖会遮住新的应用提供方。不采用保留旧地址并换密钥的方案:会破坏凭据绑定。 + +执行步骤: + +- [x] 新增真实 Harness/本机 HTTP 回归,覆盖旧 overlay、更换提供方、已有迁移结果、自定义提供方/默认模型、重复启动及主工具配置清除;先确认当前代码失败。 +- [x] 在启动配置准备阶段按来源刷新应用提供方,保留其他原生配置及凭据文件。 +- [x] 跑 HTTP 回归、现有 runtime/profile 检查、Python 回归和实际 Qt 模型设置点击;未复现点击失败,保留原脚本。 +- [x] 更新验收记录与 PR 描述,检查 diff 和秘密泄露后提交、推送到现有 PR;不合并。 diff --git a/docs/testing/2026-11-03-dsh-issue16.md b/docs/testing/2026-11-03-dsh-issue16.md index df43085..0a2fa0f 100644 --- a/docs/testing/2026-11-03-dsh-issue16.md +++ b/docs/testing/2026-11-03-dsh-issue16.md @@ -23,6 +23,28 @@ - DSH、UI、打包、队列与安全停止:412 passed(在原生子窗口修复后运行)。 - `node tools/verify_dsh_profile_settings.mjs`:原生设置重复初始化不改写、真实提供方加载、旧配置迁移与原字节备份通过。 - 官方 runtime CLI 门禁、模型结果裁剪与 dock 启动检查通过。 -- 独立代码审查未发现新增阻断问题。 +- 首轮独立代码审查未发现新增阻断问题;后续 PR 评论 #168 发现的提供方迁移缺陷及补充验证见下文。 + +## PR #17 评论 #168:提供方与凭据绑定 + +原迁移按插件 ID 整行保存 `llm-pi-ai`,把旧版自动生成的 dx 地址、模型和默认选择提升为用户覆盖。更换主工具提供方后,旧地址/模型覆盖新策略,环境中的密钥却已经换新。原有 412 项回归及模型列表读取没有覆盖真正请求的地址与认证头。 + +修复后,引用启动环境 DSH_API_KEY 的应用 dx 每次完整刷新,并与同一插件中的自定义提供方共同保留。旧生成默认选择迁移到当前主工具默认值;原生有效选择和自定义默认模型保留。已迁移过一次的数据也会纠正;没有主工具配置时移除旧应用路由。改写前备份,重复准备不会再次改写原生配置。 + +上游本地凭据优先于环境变量,因此进一步按真实来源区分:显式 dx 使用已保存的 DSH_API_KEY 时,整条用户路由保留;主工具模型启用时,孤立保存密钥没有有效提供方地址证据便拒绝启动,不猜测历史地址。没有主工具模型时,无关孤立引用不阻断其他独立提供方。正常首次准备就物化应用 dx 的完整配置,确保原生模型页只保存密钥后仍有地址和模型绑定。配置准备不改写凭据文件,元数据解析错误不引用密钥原文。 + +凭据绑定使用 Harness 真正的 composition 结果校验,不能把被 name assertion 跳过或只执行 insert 的行当成绑定;保留旧模型行的原有语义。对 credentials、llm-pi-ai、agent-default-model 的重复 ID 明确拒绝,避免 Loader 的最后项挂载语义与检查结果不同。实际凭据路径从有效 credentials 配置解析,兼容备用 path / dshHome。桌面接入前通过真正挂载的凭据服务再次核对来源和仅内存保存的值摘要,环境管理路由也必须完整等于当前主工具配置。 + +验证: + +- `node tools/verify_dsh_provider_switch.mjs`:先在旧地址断言处观察失败,再验证修复。最终 **18 个场景通过、14 次真实 Harness 本机 HTTP 请求**;逐一核对 `/v1/chat/completions` 目的服务器、模型与虚构认证头,含旧 overlay、自定义默认模型、已迁移数据、原生自定义提供方、有效 dx 选择、独立凭据 dx、本地保存密钥、只修改密钥、孤立密钥拒绝、被跳过的配置行、重复插件 ID、备用凭据路径及主配置移除。报告:`build/dsh-provider-switch-verification/run-HgwLis/report.json`。 +- 额外的本地保存密钥与孤立密钥用例均在修复前观察失败。孤立密钥拒绝不改变原用户补丁,也不发起模型请求。 +- `node tools/verify_dsh_profile_settings.mjs`:原生独立配置保留、真实提供方加载、迁移与逐字节备份通过。 +- `python -m pytest -q tests/v1_1 tests/ui tests/dsh tests/packaging --tb=short`:**1353 passed**,1 条 pywinauto COM 模式警告。 +- `python -X utf8 tools/accept_dsh_desktop.py --output build/pr17-review168-final --port 9290 --provider-config <本机配置目录> --model-settings-check`:最终源码的真实 Qt/CDP 点击、输入、获取模型、创建、编辑器读回和正常关闭通过,未复现评论中的 API 地址点击被遮挡。未修改点击脚本,本机验收通过不作为已定位该次失败原因的证明。 +- runtime 七项工具门禁、模型结果和 dock 启动验证通过。JS 语法与 `git diff --check` 通过。 +- 最终独立复审重新验证了备用文件显式绑定与重复 ID 的拒绝,未发现新增已验证 P1/P2;5 个提交文件扫描本机已知凭据,无匹配。 + +所有新增模型请求仅到 127.0.0.1 自有测试端点,使用虚构密钥;没有外部模型生成、CAD 写入、远端工单写入或 EXE 构建。 本轮没有构建冻结 EXE;发布包须从修复分支重新构建,源码验收不替代发布包验收。 diff --git a/docs/user/dsh-ai-supervision.md b/docs/user/dsh-ai-supervision.md index ad649ec..af196c1 100644 --- a/docs/user/dsh-ai-supervision.md +++ b/docs/user/dsh-ai-supervision.md @@ -10,7 +10,9 @@ 在 **模型 → 添加模型提供商 → 自定义模型 API** 中填写 Provider ID、API 地址、协议及可选密钥,点击 **获取可用模型**,勾选后点 **添加所选**,最后 **创建提供商**。也可手动添加模型 ID。获取失败会保留表单,便于修正地址或手动填写。已有提供方点击 **编辑** 可修改其模型目录;保存后即时生效。 -模型页面使用官方 Harness 设置与凭据服务:用户设置保存在 `dsh/harness-home/profiles/dx-task/cordis.patch.yml`,新增的密钥通过官方本地凭据服务保存在 `dsh/harness-home/.credentials.yaml`;此文件不使用主工具的 DPAPI 格式。主工具预配置的 `provider.json` 和 DPAPI 密钥仍可加载。应用固定策略作为独立 bundle 提供,不会在启动时覆盖用户模型设置。旧版应用生成的配置升级时先逐字节备份,再保留提供方和默认模型设置;请一并备份整个数据目录,不要将凭据文件分发或提交到仓库。 +模型页面使用官方 Harness 设置与凭据服务:用户设置保存在 `dsh/harness-home/profiles/dx-task/cordis.patch.yml`,新增的密钥通过官方本地凭据服务保存在 `dsh/harness-home/.credentials.yaml`;此文件不使用主工具的 DPAPI 格式。主工具预配置的 `provider.json` 和 DPAPI 密钥仍可加载。应用固定策略作为独立 bundle 提供;应用管理的 `dx` 提供方随主工具配置完整更新,自定义提供方及其独立凭据保留。旧版生成的 `dx` 默认模型在迁移时回到当前主工具默认值;原生用户选定且仍有效的模型及自定义提供方默认选择保留。改写配置前逐字节备份,重复启动不重复改写。 + +在原生模型页为现有 `dx` 保存密钥后,该提供方作为用户覆盖保留其地址、模型和本地密钥,不再随主工具自动切换。如果当前启用了主工具模型,但旧数据中存在本地 `DSH_API_KEY` 密钥、却没有对应的有效 `dx` 配置,DSH 会明确拒绝启动,避免把未知来源的密钥发到当前地址。恢复时先备份整个数据目录,将密钥配置为具有独立凭据引用的自定义提供方;不要只搬运密钥文件。主工具模型未启用时,无关的孤立引用不会阻断独立提供方。不要将凭据文件分发或提交到仓库。 DSH 使用独立原生子窗口承载 WebEngine,切回任务中心后保留原有 Acrylic 玻璃材质;“减少透明度”与系统高对比度等回退规则继续生效。 diff --git a/integration/dsh/start.mjs b/integration/dsh/start.mjs index 6f5e211..fd51513 100644 --- a/integration/dsh/start.mjs +++ b/integration/dsh/start.mjs @@ -3,6 +3,7 @@ import {createRequire} from 'node:module'; import {fileURLToPath} from 'node:url'; import {mkdir, writeFile, readFile, cp, rename} from 'node:fs/promises'; import {createHash,randomUUID} from 'node:crypto'; +import {isDeepStrictEqual} from 'node:util'; import path from 'node:path'; import {createInterface} from 'node:readline'; @@ -65,11 +66,111 @@ async function replaceJson(filename,value) { finally{await unlink(temporary).catch(error=>{if(error.code!=='ENOENT')throw error;});} } +async function readOptionalModelMetadata(filename) { + let text; + try{text=await readFile(filename,'utf8');}catch(error){if(error.code==='ENOENT')return;throw error;} + try{return require('js-yaml').load(text);}catch{ + // YAML parser errors can quote the line containing a credential. + throw Error('Cannot parse stored model metadata: '+path.basename(filename)); + } +} + +function modelEntry(rows,id) { + const entries=rows.filter(row=>row.id===id); + if(entries.length>1)throw Error('Duplicate '+id+' prevents verifying model binding; startup refused.'); + return entries[0]; +} + +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){ + // A generated policy alone cannot prove which endpoint a saved key belongs + // to. Never attach an unbound local credential to today's host endpoint. + throw Error('Stored DSH_API_KEY has no provider binding; configure a native provider with its own credential reference before starting DSH.'); + } + if(!userLlm&¤t){ + userLlm={id:'llm-pi-ai',config:{providers:{dx:current}}}; + rows=[...rows,userLlm]; + } + const prior=boundDx; + if(storedHostKey&&prior?.apiKeyEnv==='DSH_API_KEY'&&!rows.some(row=>row.id==='agent-default-model')){ + const saved=previousApplication.find(row=>row.id==='agent-default-model')?.config; + const config=saved?.provider==='dx'&&prior.models?.some(model=>model.id===saved.model) + ?saved:{provider:'dx',model:prior.models[0].id}; + rows=[...rows,{id:'agent-default-model',config}]; + } + // A native provider with its own credential reference (or deliberately no + // credential) owns its complete route. Only an environment-sourced + // DSH_API_KEY belongs to the host; a saved native key owns its user route. + const managed=prior===undefined||(prior.apiKeyEnv==='DSH_API_KEY'&&!storedHostKey); + return rows.flatMap(row=>{ + if(row.id==='agent-default-model'&&row.config?.provider==='dx'&&managed + &&(legacy||!current?.models.some(model=>model.id===row.config.model)))return []; + if(row.id!=='llm-pi-ai'||!row.config)return [row]; + const providers={...row.config.providers}; + if(providers.dx===undefined||(providers.dx.apiKeyEnv==='DSH_API_KEY'&&!storedHostKey)){ + if(current)providers.dx=current;else delete providers.dx; + } + // Harness replaces an entire plugin config, rather than deep-merging it. + // Keep the host route beside custom routes in any overriding user row. + return [{...row,config:{...row.config,providers}}]; + }); +} + export async function prepareProfileDirectory(dir) { // The official settings page writes the user patch. Application defaults - // belong to a bundle below that patch, so rebooting must never overwrite it. + // belong to a bundle below it. Only host-owned model routes are refreshed; + // independent native providers and their credential references remain intact. await mkdir(dir,{recursive:true}); + const application=overlay(); const userPatch=path.join(dir,'cordis.patch.yml'); + const previousApplication=await readOptionalModelMetadata(path.join(dir,'node_modules/@dx/dsh-policy/cordis.patch.yml'))??[]; + const policyDir=path.join(dir,'node_modules','@dx','dsh-policy'); + await mkdir(policyDir,{recursive:true}); + await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true}); + await replaceJson(path.join(policyDir,'package.json'),{name:'@dx/dsh-policy',version:VERSION, + private:true,dsh:{bundle:{patch:'./cordis.patch.yml'}}}); + await replaceJson(path.join(policyDir,'cordis.patch.yml'),application); + await replaceJson(path.join(dir,'package.json'),{private:true,type:'module', + dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin'),'@dx/dsh-policy':'file:'+policyDir}, + dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app','@dx/dsh-policy']}}}); + const {loadProfileDirectory,composeEntries}=await import('@deepseek-ai/dsh-app-boot'); + const profile=loadProfileDirectory('dx-dsh',dir,require.resolve('@deepseek-ai/dsh/package.json'),{userLayer:false}); + const layers=profile.layers.map(layer=>layer.patches); + // Remove only the generated host route when testing whether a user binding + // actually applies. Use Harness semantics, including name assertions/inserts. + const withoutHost=profile.layers.map(layer=>layer.packageName==='@dx/dsh-policy' + ?layer.patches.filter(row=>row.id!=='llm-pi-ai'):layer.patches); + let hostCredentialBinding; + const refresh=async(rows,legacy=false)=>{ + const effective=composeEntries([...layers,rows]); + const credentials=modelEntry(effective,'credentials'); + modelEntry(effective,'llm-pi-ai');modelEntry(effective,'agent-default-model'); + let storedHostKey=false,savedKey; + if(credentials?.disabled!==true){ + if(credentials?.name!=='@deepseek-ai/dsh-credentials-local') + throw Error('Cannot verify the configured model credential provider; startup refused.'); + const {resolveDshHome}=await import('@deepseek-ai/dsh-home-paths'); + const config=credentials.config??{}; + const home=resolveDshHome(config.dshHome,{DSH_HOME:path.resolve(dir,'../..')}); + const stored=await readOptionalModelMetadata(path.resolve(config.path??path.join(home,'.credentials.yaml'))); + savedKey=stored?.version===undefined?stored?.DSH_API_KEY:stored?.refs?.DSH_API_KEY; + storedHostKey=typeof savedKey==='string'&&savedKey.length>0; + } + const boundDx=modelEntry(composeEntries([...withoutHost,rows]),'llm-pi-ai')?.config?.providers?.dx; + const next=refreshApplicationModels(rows,application,{legacy,storedHostKey,previousApplication,boundDx}); + const actual=modelEntry(composeEntries([...layers,next]),'llm-pi-ai')?.config?.providers?.dx; + if(storedHostKey&&actual?.apiKeyEnv==='DSH_API_KEY' + &&(!boundDx||!isDeepStrictEqual(actual,boundDx))) + throw Error('Stored DSH_API_KEY has no provider binding after Harness composition; startup refused.'); + if(!storedHostKey&&actual?.apiKeyEnv==='DSH_API_KEY' + &&!isDeepStrictEqual(actual,application.find(row=>row.id==='llm-pi-ai')?.config.providers.dx)) + throw Error('Application model route did not match the current provider; startup refused.'); + if(actual?.apiKeyEnv==='DSH_API_KEY')hostCredentialBinding={source:storedHostKey?'file':'env', + digest:createHash('sha256').update((storedHostKey?savedKey:process.env.DSH_API_KEY)??'').digest('hex')}; + return next; + }; let prior; try{prior=await readFile(userPatch,'utf8');}catch(error){if(error.code!=='ENOENT')throw error;} if(prior!==undefined){ @@ -78,26 +179,22 @@ export async function prepareProfileDirectory(dir) { const legacy=Array.isArray(rows)&&rows.some(row=>Array.isArray(row?.insert) &&row.insert.some(entry=>entry.id==='dx-task'&&entry.name==='@dx/dsh-task') &&row.insert.some(entry=>entry.id==='preset-dx-task')); - if(legacy){ + const editable=new Set(['llm-pi-ai','llm-deepseek','agent-default-model']); + const userRows=legacy?rows.filter(row=>editable.has(row?.id)&&row.config):rows; + const next=Array.isArray(userRows)?await refresh(userRows,legacy):userRows; + if(legacy||JSON.stringify(next)!==JSON.stringify(rows)){ const digest=createHash('sha256').update(prior).digest('hex'); - const backup=userPatch+'.legacy-'+digest+'.bak'; + const backup=userPatch+(legacy?'.legacy-':'.models-')+digest+'.bak'; try{await writeFile(backup,prior,{flag:'wx'});}catch(error){ if(error.code!=='EEXIST'||await readFile(backup,'utf8')!==prior)throw error; } - const editable=new Set(['llm-pi-ai','llm-deepseek','agent-default-model']); - await replaceJson(userPatch,rows.filter(row=>editable.has(row?.id)&&row.config) - .map(({id,config})=>({id,config}))); + await replaceJson(userPatch,next); } + }else if(application.some(row=>row.id==='llm-pi-ai')){ + const next=await refresh([]); + await replaceJson(userPatch,next); } - const policyDir=path.join(dir,'node_modules','@dx','dsh-policy'); - await mkdir(policyDir,{recursive:true}); - await cp(path.join(root,'task-plugin'),path.join(dir,'node_modules','@dx','dsh-task'),{recursive:true}); - await replaceJson(path.join(policyDir,'package.json'),{name:'@dx/dsh-policy',version:VERSION, - private:true,dsh:{bundle:{patch:'./cordis.patch.yml'}}}); - await replaceJson(path.join(policyDir,'cordis.patch.yml'),overlay()); - await replaceJson(path.join(dir,'package.json'),{private:true,type:'module', - dependencies:{'@dx/dsh-task':'file:'+path.join(root,'task-plugin'),'@dx/dsh-policy':'file:'+policyDir}, - dsh:{profile:{bundles:['@deepseek-ai/dsh-base','@deepseek-ai/dsh-web-app','@dx/dsh-policy']}}}); + return {hostCredentialBinding}; } export async function bootRuntime({announce=true} = {}) { @@ -118,7 +215,7 @@ export async function bootRuntime({announce=true} = {}) { process.env.DX_DSH_WORKSPACE = path.join(process.env.DX_DSH_HOME,'workspace'); await mkdir(process.env.DX_DSH_WORKSPACE,{recursive:true}); const dir = path.join(process.env.DX_DSH_HOME,'profiles','dx-task'); - await prepareProfileDirectory(dir); + const modelBinding=await prepareProfileDirectory(dir); const {runProfile, INSTALL_ANCHOR} = await import('@deepseek-ai/dsh/profile-boot'); const {loadProfileDirectory,composeEntries} = await import('@deepseek-ai/dsh-app-boot'); const {createLaunchEnvironmentSnapshot} = await import('@deepseek-ai/dsh-launch-environment'); @@ -133,6 +230,17 @@ export async function bootRuntime({announce=true} = {}) { patchFiles:[],args:['--no-open','--host','127.0.0.1','--port','0'], environment:createLaunchEnvironmentSnapshot([{source:'process',values:process.env}])}); await ctx.loader.await(); + // Check the mounted service as well as its composition: an unexpected + // credential source must fail before exposing the runtime to the desktop. + if(modelBinding.hostCredentialBinding){ + const actual=ctx.get('credentials')?await ctx.credentials.resolve('DSH_API_KEY') + :{source:'env',value:process.env.DSH_API_KEY}; + if(actual?.source!==modelBinding.hostCredentialBinding.source||typeof actual?.value!=='string' + ||createHash('sha256').update(actual.value).digest('hex')!==modelBinding.hostCredentialBinding.digest){ + await shutdown.shutdown(1); + throw Error('Host model credential source changed during startup; startup refused.'); + } + } const names=ctx.tools.schemas().map(tool=>tool.name); if(names.length!==7 || !['dx_task_snapshot','dx_task_create','dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations'].every(name=>names.includes(name))) { await shutdown.shutdown(1); diff --git a/tools/verify_dsh_provider_switch.mjs b/tools/verify_dsh_provider_switch.mjs new file mode 100644 index 0000000..9d47f2d --- /dev/null +++ b/tools/verify_dsh_provider_switch.mjs @@ -0,0 +1,200 @@ +/** Real Harness requests must keep each provider endpoint, model and credential together. */ +import assert from 'node:assert/strict'; +import {createServer} from 'node:http'; +import {spawn} from 'node:child_process'; +import {mkdir,mkdtemp,readFile,writeFile,readdir} from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {bootRuntime,overlay,prepareProfileDirectory} from '../integration/dsh/start.mjs'; + +const script=fileURLToPath(import.meta.url); +const require=createRequire(new URL('../integration/dsh/start.mjs',import.meta.url)); +const {load}=require('js-yaml'); +const appKeys=['DSH_API_BASE','DSH_MODEL','DSH_API_KEY','DX_DSH_MODELS','DSH_HOME','DX_DSH_HOME','DX_DSH_CONTEXT_FILE','DX_DSH_PARENT_PIPE']; +const selection=ctx=>ctx.agentDefaultModel.currentSelection(); + +async function runChild(specPath,env){ + return new Promise(resolve=>{ + const child=spawn(process.execPath,[script,'--child',specPath],{env,stdio:['ignore','pipe','pipe'],windowsHide:true}); + let stdout='',stderr='';child.stdout.on('data',x=>stdout+=x);child.stderr.on('data',x=>stderr+=x); + const timeout=setTimeout(()=>child.kill(),60000); + child.on('close',code=>{clearTimeout(timeout);resolve({code,stdout,stderr});}); + }); +} + +async function stream(ctx,provider,model){ + const chunks=[]; + for await(const chunk of ctx.llm.stream({provider,model,messages:[{role:'user',content:[{type:'text',text:'fixture request'}]}], + maxTokens:8,signal:AbortSignal.timeout(15000)}))chunks.push(chunk); + assert.equal(chunks.find(x=>x.type==='finish')?.reason.kind,'stop','owned fixture stream must finish successfully'); + assert.equal(chunks.filter(x=>x.type==='text-delta').map(x=>x.text).join(''),'ok'); +} + +if(process.argv[2]==='--child'){ + const spec=JSON.parse(await readFile(process.argv[3],'utf8')); + if(spec.orphanKey){ + await assert.rejects(bootRuntime({announce:false}),/Stored DSH_API_KEY has no provider binding|Duplicate .* prevents verifying model binding|Application model route did not match/); + console.log('DX_SWITCH_REPORT '+JSON.stringify({status:'passed',unboundCredentialRefused:true})); + process.exit(0); + } + const {ctx,shutdown}=await bootRuntime({announce:false}); + try{ + if(spec.hostAbsent){ + assert.ok(!ctx.llm.listProviders().some(x=>x.id==='dx')); + await stream(ctx,'custom','custom-model'); + console.log('DX_SWITCH_REPORT '+JSON.stringify({status:'passed',customWorksWithoutHost:true})); + }else{ + // Send even when the model catalogue is stale: detect the actual HTTP credential destination. + const dxModels=(await ctx.llm.listModels('dx')).map(x=>x.id); + await stream(ctx,'dx',dxModels[0]); + if(spec.custom){ + assert.deepEqual((await ctx.llm.listModels('custom')).map(x=>x.id),['custom-model']); + await stream(ctx,'custom','custom-model'); + } + assert.deepEqual(dxModels,spec.customDx?['custom-dx-model']:['new-model','alternate-model']); + assert.deepEqual(selection(ctx),spec.expectedDefault); + console.log('DX_SWITCH_REPORT '+JSON.stringify({status:'passed',dxModels,selection:selection(ctx)})); + } + }finally{await shutdown.shutdown(0);} +}else{ + const output=path.resolve('build/dsh-provider-switch-verification');await mkdir(output,{recursive:true}); + const base=await mkdtemp(path.join(output,'run-')); + const requests=[]; + async function endpoint(name){ + const server=createServer(async(req,res)=>{ + let text='';for await(const chunk of req)text+=chunk; + const body=text?JSON.parse(text):{}; + requests.push({server:name,path:req.url,authorization:req.headers.authorization,model:body.model}); + res.writeHead(200,{'Content-Type':'text/event-stream'}); + res.end('data: '+JSON.stringify({id:'fixture',object:'chat.completion.chunk',created:1,model:body.model, + choices:[{index:0,delta:{role:'assistant',content:'ok'},finish_reason:null}]})+'\n\n'+ + 'data: '+JSON.stringify({id:'fixture',object:'chat.completion.chunk',created:1,model:body.model, + choices:[{index:0,delta:{},finish_reason:'stop'}]})+'\n\ndata: [DONE]\n\n'); + }); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + return {server,url:`http://127.0.0.1:${server.address().port}/v1`}; + } + const old=await endpoint('old'),next=await endpoint('new'),custom=await endpoint('custom'); + const cleanEnv={...process.env};for(const key of appKeys)delete cleanEnv[key]; + const nextEnv={DSH_API_BASE:next.url,DSH_MODEL:'new-model',DSH_API_KEY:'fixture-new-key',DX_DSH_MODELS:'["new-model","alternate-model"]'}; + const cases=[ + {name:'legacy-switch',legacy:true}, + {name:'legacy-custom-default',legacy:true,custom:true,expectedDefault:{provider:'custom',model:'custom-model'}}, + {name:'already-migrated-switch',custom:true}, + {name:'native-custom-provider',custom:true,omitDx:true}, + {name:'native-dx-selection',expectedDefault:{provider:'dx',model:'alternate-model'},selected:'alternate-model'}, + {name:'native-independent-dx',customDx:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}}, + {name:'native-stored-dx-key',customDx:true,storedHostKey:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}}, + {name:'legacy-stored-dx-key',legacy:true,customDx:true,storedHostKey:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}}, + {name:'native-key-only-edit',customDx:true,storedHostKey:true,keyOnly:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}}, + {name:'unbound-stored-key',storedHostKey:true,orphanKey:true}, + {name:'ignored-name-binding',storedHostKey:true,orphanKey:true,ignoredName:true}, + {name:'legacy-ignored-name-binding',legacy:true,storedHostKey:true,orphanKey:true,ignoredName:true}, + {name:'insert-is-not-a-binding',storedHostKey:true,orphanKey:true,insertOnly:true}, + {name:'alternate-unbound-key',alternateCredentials:true,storedHostKey:true,orphanKey:true}, + {name:'alternate-bound-key',alternateCredentials:true,customDx:true,storedHostKey:true,expectedDefault:{provider:'dx',model:'custom-dx-model'}}, + {name:'duplicate-credentials',storedHostKey:true,orphanKey:true,duplicate:'credentials'}, + {name:'duplicate-model-adapter',orphanKey:true,duplicate:'llm-pi-ai'}, + ]; + const reports=[]; + try{ + for(const spec of cases){ + if(process.argv[2]==='--case'&&process.argv[3]!==spec.name)continue; + const home=path.join(base,spec.name),dir=path.join(home,'profiles/dx-task');await mkdir(dir,{recursive:true}); + const credentialsFile=path.join(home,spec.alternateCredentials?'alternate-credentials.yaml':'.credentials.yaml'); + Object.assign(process.env,{DSH_API_BASE:old.url,DSH_MODEL:'old-model',DSH_API_KEY:'fixture-old-key',DX_DSH_MODELS:'["old-model"]'}); + let rows=overlay(); + if(!spec.legacy)rows=rows.filter(x=>['llm-pi-ai','agent-default-model'].includes(x.id)); + const llm=rows.find(x=>x.id==='llm-pi-ai'); + if(spec.omitDx)delete llm.config.providers.dx; + if(spec.custom)llm.config.providers.custom={api:'openai-completions',baseURL:custom.url,apiKeyEnv:'FIXTURE_CUSTOM_KEY',models:[{id:'custom-model'}]}; + if(spec.customDx)llm.config.providers.dx={api:'openai-completions',baseURL:custom.url, + apiKeyEnv:spec.storedHostKey?'DSH_API_KEY':'FIXTURE_CUSTOM_KEY',models:[{id:'custom-dx-model'}]}; + if(spec.keyOnly){ + rows=[]; + Object.assign(process.env,{DSH_API_BASE:custom.url,DSH_MODEL:'custom-dx-model',DX_DSH_MODELS:'["custom-dx-model"]'}); + } + if(spec.orphanKey&&!spec.ignoredName&&!spec.insertOnly&&!spec.duplicate)rows=[]; + if(spec.ignoredName)llm.name='@deepseek-ai/previous-llm-name'; + if(spec.insertOnly)llm.insert=[]; + if(spec.alternateCredentials)rows.push({id:'credentials',config:{path:credentialsFile}}); + if(spec.duplicate)rows.push({insert:[{id:spec.duplicate, + name:spec.duplicate==='credentials'?'@deepseek-ai/dsh-credentials-local':'@deepseek-ai/dsh-llm-pi-ai', + config:spec.duplicate==='credentials'?{path:path.join(home,'empty-store.yaml')}:structuredClone(llm.config)}]}); + const defaultRow=rows.find(x=>x.id==='agent-default-model'); + if(defaultRow)defaultRow.config=spec.expectedDefault??{provider:'dx',model:spec.selected??'old-model'}; + const patch=path.join(dir,'cordis.patch.yml'); + if(spec.keyOnly){ + await writeFile(patch,'[]');await prepareProfileDirectory(dir); + rows=load(await readFile(patch,'utf8')); + assert.equal(rows.find(x=>x.id==='llm-pi-ai').config.providers.dx.baseURL,custom.url, + 'host route must be materialized before the official UI can save a key-only edit'); + } + const original=JSON.stringify(rows,null,2); + await writeFile(patch,original); + const refs={FIXTURE_CUSTOM_KEY:'fixture-custom-key',...spec.storedHostKey?{DSH_API_KEY:'fixture-custom-key'}:{}}; + const credentials=JSON.stringify({version:1,refs}); + await writeFile(credentialsFile,credentials,{mode:0o600}); + const context=path.join(home,'context.json');await writeFile(context,'{"status":"observe","revision":"switch-fixture"}'); + spec.expectedDefault??={provider:'dx',model:'new-model'}; + const specPath=path.join(home,'spec.json');await writeFile(specPath,JSON.stringify(spec)); + const env={...cleanEnv,...nextEnv,DX_DSH_HOME:home,DX_DSH_CONTEXT_FILE:context}; + const firstRequest=requests.length; + const result=await runChild(specPath,env); + const calls=requests.slice(firstRequest); + if(spec.orphanKey){ + assert.deepEqual(calls,[],'unbound stored key must not make requests'); + assert.equal(result.code,0,spec.name+': '+result.stderr); + assert.equal(await readFile(patch,'utf8'),original,'refused profile must stay unchanged'); + reports.push({name:spec.name,status:'passed',unboundCredentialRefused:true}); + continue; + } + assert.equal(calls.length,spec.custom?2:1,spec.name+': request count; '+result.stderr); + const dx=calls[0]; + assert.equal(dx.server,spec.customDx?'custom':'new',spec.name+': wrong server received the current key'); + assert.equal(dx.authorization,spec.customDx?'Bearer fixture-custom-key':'Bearer fixture-new-key',spec.name+': credential source'); + assert.equal(dx.model,spec.customDx?'custom-dx-model':'new-model'); + assert.equal(dx.path,'/v1/chat/completions'); + if(spec.custom)assert.deepEqual(calls[1],{server:'custom',path:'/v1/chat/completions',authorization:'Bearer fixture-custom-key',model:'custom-model'}); + assert.equal(result.code,0,spec.name+': '+result.stderr+'\n'+result.stdout); + // Harness itself adds a browser-session record; model references must survive unchanged. + assert.deepEqual(load(await readFile(credentialsFile,'utf8')).refs, + refs,'stored provider credentials must be untouched'); + Object.assign(process.env,nextEnv); + const migrated=await readFile(patch,'utf8'); + const credentialsAfterBoot=await readFile(credentialsFile,'utf8'); + await prepareProfileDirectory(dir); + assert.equal(await readFile(credentialsFile,'utf8'),credentialsAfterBoot,'profile preparation must not rewrite credentials'); + assert.equal(await readFile(patch,'utf8'),migrated,'second boot must not rewrite the same profile'); + if(spec.legacy){ + const backup=(await readdir(dir)).find(x=>x.includes('.legacy-')); + assert.equal(await readFile(path.join(dir,backup),'utf8'),original); + } + reports.push({name:spec.name,status:'passed',calls:calls.map(({authorization,...rest})=>({...rest,credentialMatched:true}))}); + } + // Removing host configuration must not leave a stale application route backed by a new key later. + if(process.argv[2]!=='--case'){ + const dir=path.join(base,'already-migrated-switch/profiles/dx-task'); + for(const key of ['DSH_API_BASE','DSH_API_KEY','DSH_MODEL','DX_DSH_MODELS'])delete process.env[key]; + await prepareProfileDirectory(dir); + const cleared=load(await readFile(path.join(dir,'cordis.patch.yml'),'utf8')); + assert.equal(cleared.find(x=>x.id==='llm-pi-ai')?.config.providers.dx,undefined); + assert.ok(cleared.find(x=>x.id==='llm-pi-ai').config.providers.custom); + assert.equal(cleared.find(x=>x.id==='agent-default-model'),undefined); + const home=path.resolve(dir,'../..'),credentialsFile=path.join(home,'.credentials.yaml'); + const stored=load(await readFile(credentialsFile,'utf8'));stored.refs.DSH_API_KEY='fixture-orphan-key'; + await writeFile(credentialsFile,JSON.stringify(stored)); + const specPath=path.join(home,'no-host-spec.json');await writeFile(specPath,'{"hostAbsent":true}'); + const count=requests.length; + const result=await runChild(specPath,{...cleanEnv,DX_DSH_HOME:home,DX_DSH_CONTEXT_FILE:path.join(home,'context.json')}); + assert.equal(result.code,0,'independent provider must work without host configuration: '+result.stderr); + assert.deepEqual(requests.slice(count),[{server:'custom',path:'/v1/chat/completions',authorization:'Bearer fixture-custom-key',model:'custom-model'}]); + reports.push({name:'no-host-with-unused-stored-key',status:'passed',calls:[{server:'custom',path:'/v1/chat/completions',model:'custom-model',credentialMatched:true}]}); + } + const report={status:'passed',realHarness:true,externalModelCalls:false,cases:reports,hostRemoval:process.argv[2]!=='--case'}; + await writeFile(path.join(base,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report)); + }finally{ + for(const {server} of [old,next,custom]){server.closeAllConnections();await new Promise(resolve=>server.close(resolve));} + } +}