fix(dsh): bind migrated model routes to credential sources
Core regression / Python core and release configuration (push) Successful in 18s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 15s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-03 17:28:22 +08:00
1 parent 374e1cd5bf
commit af46ee1617
5 files changed
+368 -18

No files matched your search

@@ -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;不合并。
+23 -1
View File
@@ -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;发布包须从修复分支重新构建,源码验收不替代发布包验收。
+3 -1
View File
@@ -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 玻璃材质;“减少透明度”与系统高对比度等回退规则继续生效。
+124 -16
View File
@@ -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&&current){
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);
+200
View File
@@ -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));}
}
}