merge-main-ui-host-compatibility
Core regression / Python core and release configuration (push) Successful in 16s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python core and release configuration (push) Successful in 16s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
commit
56588a9203
14 files changed
+621
-21
No files matched your search
@@ -31,6 +31,7 @@ def main():
|
||||
parser.add_argument('--output',type=Path,default=Path('build/acrylic-acceptance'))
|
||||
parser.add_argument('--webengine-roundtrip',action='store_true')
|
||||
parser.add_argument('--history',action='store_true')
|
||||
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):
|
||||
@@ -83,6 +84,9 @@ def main():
|
||||
report['native_enabled']=True
|
||||
def capture(name):
|
||||
QCursor.setPos(window.mapToGlobal(QPoint(12,12)))
|
||||
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()
|
||||
@@ -149,6 +153,40 @@ def main():
|
||||
(out/'roundtrip-probe.json').write_text(json.dumps(report,indent=2),encoding='utf8')
|
||||
assert report[f'roundtrip_{index}_sidebar_difference']>2,report
|
||||
assert report[f'roundtrip_{index}_table_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()<deadline:
|
||||
settle(.1)
|
||||
if window._dsh_view is not None and window._dsh_view._started:break
|
||||
assert window._dsh_view is not None and window._dsh_view._started,'DSH did not start'
|
||||
# READY precedes the Chromium load; require the real visible page.
|
||||
loaded=[]
|
||||
window._dsh_view.web.page().runJavaScript("document.body?.innerText?.includes('DSH助手')",loaded.append)
|
||||
deadline=time.monotonic()+60
|
||||
while time.monotonic()<deadline:
|
||||
settle(.1)
|
||||
if loaded and loaded[-1]:break
|
||||
if loaded:
|
||||
loaded.clear()
|
||||
window._dsh_view.web.page().runJavaScript("document.body?.innerText?.includes('DSH助手')",loaded.append)
|
||||
assert loaded and loaded[-1],'Official DSH UI did not load'
|
||||
capture('dsh-before-return')
|
||||
QTest.mouseClick(window.task_center_navigation,Qt.MouseButton.LeftButton)
|
||||
settle(.5)
|
||||
background.phase=0;background.update();capture('returned-backdrop-a')
|
||||
background.phase=1;background.update();capture('returned-backdrop-b')
|
||||
returned=ImageChops.difference(captures['returned-backdrop-a'],captures['returned-backdrop-b'])
|
||||
assert report['surfaces']['native-app-backdrop-a']['hwnd']==report['surfaces']['returned-backdrop-a']['hwnd'],report
|
||||
report['after_dsh_sidebar_difference']=mean(returned.crop(sidebar))
|
||||
report['after_dsh_header_difference']=mean(returned.crop(header))
|
||||
report['after_dsh_table_difference']=mean(returned.crop(table))
|
||||
(out/'surface-probe.json').write_text(json.dumps(report,indent=2),encoding='utf8')
|
||||
assert report['after_dsh_sidebar_difference']>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()
|
||||
@@ -234,15 +272,21 @@ def main():
|
||||
modal.grab().save(str(out/'native-app-history-clear-confirm.png'))
|
||||
QTest.mouseClick(modal.button(QMessageBox.StandardButton.Yes),Qt.MouseButton.LeftButton)
|
||||
QTimer.singleShot(100,confirm_history)
|
||||
assert panel.clear_button.isEnabled(),{'status':panel.status.text(),'mutation_enabled':panel._mutations_enabled}
|
||||
panel.clear_button.click();wait_history()
|
||||
assert panel.table.rowCount()==0
|
||||
assert panel.table.rowCount()==0,{'status':panel.status.text(),'clear_success':panel._clear_success,
|
||||
'mutation_enabled':panel._mutations_enabled,'rows':panel.table.rowCount()}
|
||||
assert len(service.tasks())==2
|
||||
capture('native-app-history-cleared')
|
||||
report['history_search_clear_and_task_preservation']=True
|
||||
window.task_center_action.trigger();settle(.2)
|
||||
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()<deadline:settle(.1)
|
||||
assert not window.isVisible(),'Window did not finish shutdown'
|
||||
settle(.3);store.close();logging.shutdown()
|
||||
background.close();app.processEvents()
|
||||
(out/'acceptance.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print(json.dumps(report,ensure_ascii=True))
|
||||
|
||||
@@ -32,6 +32,7 @@ def main():
|
||||
parser.add_argument('--port', type=int, default=9227)
|
||||
parser.add_argument('--provider-config', type=Path)
|
||||
parser.add_argument('--live-model', action='store_true')
|
||||
parser.add_argument('--model-settings-check', action='store_true', help='Create an isolated custom provider using a local model-list fixture')
|
||||
parser.add_argument('--incident', action='store_true', help='Inject a read-only controlled failure and verify automatic diagnosis and Git escalation')
|
||||
parser.add_argument('--outbox-only', action='store_true', help='Verify failed publication stays in local outbox without creating another real issue')
|
||||
parser.add_argument('--without-git', action='store_true', help='Simulate a client with no Git credentials or executable')
|
||||
@@ -146,6 +147,8 @@ def main():
|
||||
command = ['node', str(REPO / 'tools' / script), str(output), str(args.port), '--confirm-cancel']
|
||||
if args.live_model:
|
||||
command.append('--live-model')
|
||||
if args.model_settings_check:
|
||||
command.append('--model-settings-check')
|
||||
if args.outbox_only:
|
||||
command.append('--outbox-only')
|
||||
state['child'] = subprocess.Popen(command, cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/** Real settings form, provider discovery and persistence against an owned fixture. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {createServer} from 'node:http';
|
||||
import path from 'node:path';
|
||||
|
||||
export async function verifyModelSettings(c, output) {
|
||||
const requests=[];
|
||||
const server=createServer((req,res)=>{
|
||||
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()<end){if(await c.evaluate(expression))return;await new Promise(r=>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;i<target;i++){
|
||||
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'ArrowDown',code:'ArrowDown',windowsVirtualKeyCode:40});
|
||||
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'ArrowDown',code:'ArrowDown',windowsVirtualKeyCode:40});
|
||||
}
|
||||
await c.call('Input.dispatchKeyEvent',{type:'keyDown',key:'Enter',code:'Enter',windowsVirtualKeyCode:13});
|
||||
await c.call('Input.dispatchKeyEvent',{type:'keyUp',key:'Enter',code:'Enter',windowsVirtualKeyCode:13});
|
||||
await wait(`(${visible(protocol)}).value==='openai-completions'`);
|
||||
await c.click(button('获取可用模型'));
|
||||
await wait(`document.body.innerText.includes('issue16-fixture-model')`);
|
||||
assert.deepEqual(requests,[{method:'GET',path:'/v1/models'}]);
|
||||
const candidate=`[...document.querySelectorAll('[role="dialog"] label')].find(e=>e.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));
|
||||
}
|
||||
}
|
||||
@@ -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()==='准备失败项重试')`);
|
||||
|
||||
@@ -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);}
|
||||
@@ -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));}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user