feat(models): expose connection affinity and native-state provenance
This commit is contained in:
@@ -4,12 +4,14 @@
|
||||
|
||||
1. [complete] 固定当前官方缓存/状态来源、复用 I15 原件并核SHA;8份来源清单见 tests/fixtures/native-cache-state/SOURCE.json 与 docs/NATIVE-CACHE-STATE-SOURCES.md。保留原丢注解、跨 Run 选线和状态身份缺项观察。Mnemo新结果只读登记,不作为本地验收。
|
||||
2. [complete] 保留 Messages 系统/用户/工具块及工具元数据;新增原生状态身份绑定和会话/Task/Run亲和,修复纯Chat混池仅换model造成旧状态误用,optional亲和存储失败不改变原响应。原用户设置、完整历史和未知原件保留,默认不添加缓存参数。source-5最终16/16,源码类型检查通过。
|
||||
3. [in_progress] 自有 HTTP JSON/SSE、混池、跨 Run、手选换模、修订/停用、停止/恢复/重启与所有工具结果不重放的确定性核对;上游原错误保留。核心专项已验证,接续独立候选相关回归。
|
||||
4. [pending] 复用 Orven 模型中心/原生参数/上下文,完成真实保存恢复与宽窄网页/实际Electron验收、独立构建及逐输入/编译核对。
|
||||
5. [pending] 每阶段回顾、限定本地提交、最终证据清单与普通GitAtlas增量推送;旧封存根只读,原失败保留。
|
||||
3. [complete] 自有 HTTP JSON/SSE、混池、跨 Run、手选换模、修订/停用、停止/恢复/重启与所有工具结果不重放的确定性核对;上游原错误保留。source-5为16/16;首候选127/129,两项旧亲和假设准确修正后两文件26/26。最终178后端输入与首候选一致、213测试输入中211未改,按SHA复用103原通过项,不冒称最终单轮全套全绿。
|
||||
4. [complete] 复用 Orven 模型中心/原生参数/上下文,四范围保存/重载、跨Run沿用/自动重选/手选与原错通过。build-5/candidate-5为880输入/29编译/74runtime,逐SHA核对;web-ui-5与electron-ui-1各实际8组/10图/三配色/1280及390、原metadata/cipher/存储快照/原历史exact。实际Electron保持隐藏窗口原生capturePage,正常关闭后独立宿主恢复。
|
||||
5. [in_progress] 来源71f18055、核心9e1feeeb已限定本地提交,UI及两旧测试的准确契约修正完成两端验收。接续最终证据清单、输入/Git/来源与自有进程核对、回顾提交和普通GitAtlas增量推送;旧封存根只读,原失败保留。
|
||||
|
||||
本批不委派、不读真实Key、不请求真实模型、不操作正式数据/配置/安装/重启,不续旧实验或用户工程。默认 unrestricted/passthrough/preserve 与持久 ask/auto/full 保持,不增加预算、上下文、输出、头或历史额度。工具权限以当前模式为准,不能把状态核对做成新增审批。缓存使用与供应商命中由原 usage 表示,保留 unknown;稳定前缀/亲和或相同指纹不是缓存收益证明。
|
||||
|
||||
W/AD/AE/AG 网络/unknown、重复读取普遍收益未证明、R/W v2真实排除边界与 Purge收益unknown保持。M3须真实 schema2迁移增量及新处理器产生结果后的回退,不能删新账本或直接移除逐表全等守卫。新证据只写 `.qa/m2-native-cache-state-2026-11-07/`。
|
||||
|
||||
接续保留原 source-1/source-2/source-3:首夹具错误、亲和来源断言失败和跨线状态整正文搜索失败仍待准确核对,不能把接续摘要当全绿。首次接续 mkdir 遇既有目录即停止;改为读取已有原件并使用新文件名,未覆盖证据。规划辅助只读路径/输出错误见 progress.md。
|
||||
|
||||
source-4纯Chat混池问题已修后source-5通过,原source-1至4保留。网页1精确标签、2宽屏缩到手机后抽屉隐藏、3误期待失效亲和仍选A、4手机抽屉挡后方工具箱的原失败/图/驱动分别保留;已按真实UI返回路径和自动选线结果修正,新增手选A一次原400验收。最后文本规范化检查0项改动,来源原尾空白保持。
|
||||
|
||||
+10
@@ -1,5 +1,15 @@
|
||||
# 汇总发现
|
||||
|
||||
I09/I11最终Electron通过且实际复看1280新池编辑与390任务上下文:现有Orven布局/中文/长SHA/下拉与真实保存保留,输出“本次不限/不附加上限/由上游处理”与冻结状态分别呈现。网页绿/紫状态图亦复看,三配色和窄屏保持一致。两个端各5本机POST、3成功/2原400,6账本含原unknown;完成工具1、不重放,原metadata/cipher/snapshot/history全部exact。本批不证明真实缓存命中/上游普遍兼容。
|
||||
|
||||
最终网页两图实看:web-ui-5 new-session-pool-1280的连接保持下拉、真实成员及保存动作布局完整;state-blue-390原400/状态数量/地址可读且无文档横溢,顶部当前A与历史B请求分别保留,没有倒改旧请求型号。手机横向导航为既有必要滚动,不误记为文档溢出。实际Electron仍在独立运行,桌面及紫/绿色最终图另验。
|
||||
|
||||
I09/I11最终输入首核对通过:880输入/300产品源码/178后端/213测试/29编译/74runtime。178后端全与首候选相同;213测试输入中211未改,两改测试文件与26/26候选一致,复用103原通过项。8官方原件/source清单与Git原字节一致,来源正文6尾空白不修剪。web-ui-5实际8组/10图、5本机请求+1原unknown账本、原metadata/cipher/snapshot/history exact、三配色被测文字对比≥5.46;实际Electron与清理仍待,不把网页通过当桌面或真实供应商通过。
|
||||
|
||||
I09/I11 web-ui-3四组通过后仍失败:实际第4次选中owned-b,未发送A修改的X-Owned-Scope;原驱动误以为失效亲和仍应选A。原requests.json核对前三次A及相符reasoning,第四次B且无旧reasoning。按实际自动重选保留400,并新增实际模型中心手选A一次核对修改头、原错与不重放;最终应5本机请求/6账本而非旧4/5。候选3产品不变,另冻最后验收输入,避免重复编译与runtime复制。实际已查看web-ui-3的1280账本与390上下文:中文/长地址与状态SHA可读,手机没有文档溢出;最终三配色和Electron仍需验。
|
||||
|
||||
I09/I11接续:candidate-backend-1为127/129,两项旧假设已核对。跨Run权重轮询测试必须显式选run,默认新池应session;关闭保持时不再暗存连接,重新启用run后应先按权重选择,再沿用本次记录。web-ui-2先完成3组/3本机请求,在宽屏打开检视后直接缩到手机触发App已有关闭wide行为,失败现场只显示会话;改为先设390再由真实任务入口打开,不修改已有布局行为。上下文候选状态不能把同一原状态跨连接相加,改为候选连接数,各连接单独列状态数量。
|
||||
|
||||
I09/I11 source-4为14/15:收窄断言后确认真实纯Chat混池缺陷,不是整正文误命中。completionBody在所有成员均无native/streaming时只构造首成员body,actualRequest只换model,旧reasoning_content进入后备连接。现有状态时必须逐成员投影,连同型号相同但凭据不同的池验证。原source-3/4失败保留;原生Messages/Responses SSE、停止续同Task与可选亲和存储故障均在source-4通过。未知亲和记录保留不重写,optional存储失败不改变已完成上游响应的结果。
|
||||
|
||||
I09/I11接续决策:新池可默认会话保持,但旧池必须保留原Run范围;亲和只来自完成的真实响应且诊断路径独立。状态身份要核对实际请求路径/认证模板/版本头/型号/连接与凭据修订,改变原生普通生成参数不应误认凭据变化。状态无法适用时保留原件和原因、以常规文本/原调用构造新历史,不丢用户数据或自动重放工具。沿既有Orven池编辑与上下文/请求账本补真实控制和反馈,不另立页面。
|
||||
|
||||
+12
@@ -1,5 +1,17 @@
|
||||
# 统一执行进度
|
||||
|
||||
I09/I11实际Electron独立8组/10图完成:5本机请求、原metadata/cipher/snapshot/history exact、合成Claude凭据重载、1工具不重放;窗口保持隐藏,原生capturePage,正常关闭并独立宿主重启,三配色/1280及390和外部/页面错误0。已复看网页绿/紫及Electron宽表单/窄上下文,真实字体与结构可读;最终源/界面审查、限定提交与封存收尾,正式未写入/重启。
|
||||
|
||||
I09/I11 web-ui-5完成8组/10图,5本机请求及6账本、所有原metadata/cipher/snapshot/history exact、1工具未重放;外部页面/错误0,三配色/1280及390通过。最终880输入/300源码/178后端/213测试/29编译/74runtime首身份复核通过,规范化0项;source-5为16/16,原127/129加两文件26/26按SHA覆盖129(103未变复用)。实际Electron独立运行中;随后限定UI/回归提交及最终封存,不作正式部署/缓存/Purge收益声明。
|
||||
|
||||
I09/I11 web-ui-4在手机任务抽屉打开后直接点后方工具箱,被可见检视区截住,4组/4请求的原失败与failure-center保留。open辅助先按用户Escape返回,再打开模型中心;不force点击后方元素,不改产品布局。最终按.gitattributes只规范化本批变更文本CRLF为LF、保留原冻结字节和来源正文,另冻build-5验最终源码/桌面。
|
||||
|
||||
I09/I11 build-3/candidate-3为880输入/29编译/74runtime,相关两文件26/26通过。web-ui-3通过4组,原第4次确实自动重选B,因驱动误期待A修改头而失败;保留4请求/原图/原日志。最新驱动分别验证自动B和UI手选A(新增一请求),不修改产品选线;最后使用build-4冻结验收输入及不变candidate-3,产品编译输入逐SHA复用。实际宽窄两图已复看,最终两端/三配色和原件保持仍待。
|
||||
|
||||
I09/I11接续已读原计划/未提交diff并取web-ui-2结果:3组通过后窄屏截图等待失败(3本机请求),candidate-backend-1为127/129。核源码确认两项为旧亲和假设、检视跨手机边界会关闭已有wide状态;按显式run/关闭不暗存更新旧测试,验收器先设390再打开真实任务入口。候选状态汇总改显示连接数,避免跨连接重复加原状态。两次文档patch使用错误findings/progress标题,均整体未应用,第三次按真实锚点完成;原错误保留。下一另冻build-3,只重验受改测试文件和两端核心路径,复用需逐SHA核对的未变后端结果。
|
||||
|
||||
I09/I11独立build-1通过:880输入、29编译、74runtime逐复制SHA;相关候选回归进行中。web-ui-1在第一个旧池编辑的精确标签定位失败,实看1280截图和原DOM已确认下拉存在且显示原Run范围;嵌套select选项参与label文本,新增与可见文案一致的aria-label后另冻build-2。0模型请求,原失败截图/文本/日志保留。旧metadata、密文和快照尚待最终两端验收,不抢先宣称exact。
|
||||
|
||||
I09/I11阶段2核心完成:source-5最终16/16、typecheck-2退出0。纯Chat状态逐成员投影已通过相同型号/不同凭据、实际停用/改头边界;原生块TTL/工具元数据、JSON/SSE签名/加密reasoning/phase、跨Run/Store与Provider重启、手选、同Task停止恢复和optional保存故障保持。原source-1/2/3/4失败原件不动。核心限定本地提交后独立构建与相关回归/两端UI继续;未发行或触正式服务。
|
||||
|
||||
I09/I11 source-4完整新15项为14过1失败:纯Chat池只换型号、误用首成员推理状态已定位并修复,新增相同型号/不同凭据的独立投影边界,下一source-5不覆盖原轮。原生JSON/SSE及phase/cache块、停止恢复不重放、unknown亲和和可选保存故障通过。额外只读调查误猜两个.d.mts路径以及rg参数放在--后均保留为工具使用错误,无产品或正式数据改变。
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { chromium, _electron } from 'playwright';
|
||||
import { expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, until, completion, call } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
|
||||
import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs';
|
||||
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
|
||||
if (process.argv.includes('--help')) {
|
||||
console.log('AGENT_WORKBENCH_QA_APP_ROOT=<independent candidate> AGENT_WORKBENCH_QA_EVIDENCE_ROOT=<new evidence directory> node scripts/verify-native-cache-state-ui.mjs [--desktop]. Owned HTTP only; no production or real model calls.');
|
||||
process.exit(0);
|
||||
}
|
||||
const desktop = process.argv.includes('--desktop');
|
||||
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use an independent candidate');
|
||||
const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
|
||||
const directory = path.resolve(process.env.AGENT_WORKBENCH_QA_EVIDENCE_ROOT ?? '.qa/m2-native-cache-state-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID());
|
||||
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
|
||||
const disposers = [], t = { after: value => disposers.push(value) }, f = fixture(t, { modernDefaults: true });
|
||||
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const requests = [], checks = [], screenshots = [], errors = [], externalBlocked = [], contrast = [];
|
||||
const cache = { type: 'ephemeral', ttl: '1h', owned_extension: { preserved: true } };
|
||||
const native = { thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high' }, cache_control: cache,
|
||||
metadata: { preserved: ['owned', { nested: true }] } };
|
||||
const legacyAttempt = { id: 'owned-original-unknown', model: 'owned-original', status: 'unknown', usage: null,
|
||||
original_extension: { keep: ['network failure', 'unknown usage', 'repeated reads'] } };
|
||||
const originalHistory = [{ role: 'user', content: '原用户内容完整保留。' }, { role: 'assistant', content: '原答复完整保留。',
|
||||
providerState: { schemaVersion: 999, protocol: 'chat-completions', endpoint: 'https://original.invalid/v1', model: 'original', reasoningContent: 'owned-original-opaque' } }];
|
||||
let reject = false;
|
||||
const model = http.createServer(async (request, response) => {
|
||||
try {
|
||||
const chunks = []; for await (const chunk of request) chunks.push(chunk);
|
||||
const body = JSON.parse(Buffer.concat(chunks));
|
||||
requests.push({ path: request.url, body, headers: Object.fromEntries(Object.entries(request.headers).map(([name, value]) => [name, credentialHeader(name) ? '{{credential}}' : value])) });
|
||||
if (reject) {
|
||||
response.writeHead(400, { 'Content-Type': 'application/json', 'x-request-id': 'owned-original-cache-state-error' });
|
||||
response.end(JSON.stringify({ error: { type: 'invalid_request_error', message: 'owned-original-header-scope-error' } })); return;
|
||||
}
|
||||
const value = completion(requests.length === 1 ? [call('owned-first-tool', 'list_files', { path: '', depth: 1 })] : [], '完成');
|
||||
value.model = body.model; value.choices[0].message.reasoning_content = 'owned-current-reasoning-' + requests.length;
|
||||
value.usage.prompt_tokens_details = { cached_tokens: 2 };
|
||||
response.writeHead(200, { 'Content-Type': 'application/json', 'x-request-id': 'owned-cache-state-' + requests.length }); response.end(JSON.stringify(value));
|
||||
} catch (cause) { response.writeHead(500); response.end(cause.message); }
|
||||
});
|
||||
|
||||
let host, browser, application, controller, page, window, result, memberA, memberB, claude, legacyPool, disabledPool, newPool;
|
||||
let originalMetadata, originalCipher, originalSnapshotMetadata, desktopStdout = '', desktopStderr = '';
|
||||
const center = () => page.getByRole('dialog', { name: '模型中心', exact: true });
|
||||
const poolForm = () => center().getByRole('form', { name: '编辑模型池', exact: true });
|
||||
const poolCard = id => center().locator('.mc-pool[data-pool-id="' + id + '"]');
|
||||
const mark = text => { checks.push(text); console.log('PASS ' + text); };
|
||||
async function resize(width, height = 960) {
|
||||
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(width => innerWidth === width, width)); }
|
||||
else await page.setViewportSize({ width, height });
|
||||
}
|
||||
async function open(tab = '模型池') {
|
||||
if (!await center().count()) { await page.keyboard.press('Escape'); await openWorkbenchTool(page, '打开模型中心'); }
|
||||
await expect(center()).toBeVisible(); await center().getByRole('button', { name: tab, exact: true }).click();
|
||||
}
|
||||
async function capture(file) {
|
||||
if (!window) { await page.screenshot({ path: file, scale: 'css' }); return { method: 'playwright-page' }; }
|
||||
const picture = await window.evaluate(async win => {
|
||||
const [width, height] = win.getContentSize(), image = await win.capturePage({ x: 0, y: 0, width, height }, { stayHidden: true, stayAwake: true });
|
||||
return { png: image.toPNG().toString('base64'), empty: image.isEmpty(), size: image.getSize(), hidden: !win.isVisible() };
|
||||
});
|
||||
assert.equal(picture.empty, false); assert.equal(picture.hidden, true); fs.writeFileSync(file, Buffer.from(picture.png, 'base64'), { flag: 'wx' });
|
||||
return { method: 'electron-native-stay-hidden', size: picture.size };
|
||||
}
|
||||
async function shot(name, anchor) {
|
||||
if (anchor) await anchor.scrollIntoViewIfNeeded();
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No document overflow');
|
||||
const file = path.join(directory, name + '.png'), evidence = await capture(file);
|
||||
screenshots.push({ file: path.basename(file), sha256: sha(fs.readFileSync(file)), ...evidence });
|
||||
fs.writeFileSync(path.join(directory, name + '.txt'), await (await center().count() ? center() : page.locator('body')).innerText(), { flag: 'wx' });
|
||||
}
|
||||
async function sampleContrast(locator, label) {
|
||||
const sample = await locator.evaluate(element => {
|
||||
const style = getComputedStyle(element); let ancestor = element, background;
|
||||
while (ancestor) { const color = getComputedStyle(ancestor).backgroundColor; if (!['rgba(0, 0, 0, 0)', 'transparent'].includes(color)) { background = color; break; } ancestor = ancestor.parentElement; }
|
||||
return { color: style.color, background, fontSize: style.fontSize };
|
||||
});
|
||||
const luminance = text => text.match(/[\d.]+/g).slice(0, 3).map(Number).map(value => value / 255).map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
|
||||
const a = luminance(sample.color), b = luminance(sample.background), ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
|
||||
contrast.push({ label, ...sample, ratio }); assert.ok(ratio >= 4.5, label + ': ' + ratio);
|
||||
}
|
||||
async function editPool(id) { await open(); await poolCard(id).getByRole('button', { name: '编辑', exact: true }).click(); await expect(poolForm()).toBeVisible(); }
|
||||
async function savePool() { await poolForm().getByRole('button', { name: '保存模型池', exact: true }).click(); await expect(poolForm()).toHaveCount(0); }
|
||||
async function run(content, count) {
|
||||
await host.api('/sessions/' + f.session.id + '/messages', { content });
|
||||
await until(async () => { const value = await host.api('/sessions/' + f.session.id); return ['completed', 'failed', 'paused'].includes(value.status) && requests.length === count; }, 40000);
|
||||
await until(async () => (await host.api('/model-center')).attempts.filter(value => value.sessionId === f.session.id).every(value => value.status !== 'running'), 20000);
|
||||
}
|
||||
async function entryFor(id) {
|
||||
await open('请求账本'); const ledger = center().locator('.mc-ledger'); await ledger.getByRole('button', { name: '刷新记录', exact: true }).click();
|
||||
const records = await host.api('/model-center/attempts'), index = records.items.findIndex(value => value.id === id); assert.ok(index >= 0);
|
||||
const entry = ledger.locator('article[data-ledger-sequence="' + records.references[index].sequence + '"]'); await expect(entry).toBeVisible(); return entry;
|
||||
}
|
||||
try {
|
||||
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
|
||||
const baseUrl = 'http://127.0.0.1:' + model.address().port + '/v1';
|
||||
f.store.saveConfig({ mode: 'compatible', approvalMode: 'full' });
|
||||
f.store.storage.setMeta('modelAttempts', [legacyAttempt]); originalMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
|
||||
const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), hub = provider.modelHub(f.store);
|
||||
memberA = hub.upsert({ name: '自有 Chat A', model: 'owned-a', baseUrl, requiresKey: false });
|
||||
memberB = hub.upsert({ name: '自有 Chat B', model: 'owned-b', baseUrl, requiresKey: false });
|
||||
claude = hub.upsert({ name: '自有 Claude 缓存设置', model: 'claude-opus-5-5', protocol: 'anthropic-messages', baseUrl,
|
||||
apiKey: 'owned-cache-state-synthetic-key', persistKey: true, nativeParameters: native });
|
||||
legacyPool = hub.pool({ name: '原模型池 · 运行保持', members: [{ connectionId: memberA.id }], sticky: true });
|
||||
disabledPool = hub.pool({ name: '原模型池 · 关闭保持', members: [{ connectionId: memberB.id }], sticky: false });
|
||||
delete legacyPool.affinityScope; delete disabledPool.affinityScope; hub.save();
|
||||
legacyPool = structuredClone(legacyPool); disabledPool = structuredClone(disabledPool);
|
||||
hub.select({ type: 'pool', id: legacyPool.id });
|
||||
const snapshot = modelSnapshot(hub.prepare({ ...f.store.config, mode: 'compatible' })); f.store.storage.setMeta('ownedModelSnapshot', snapshot);
|
||||
originalSnapshotMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
|
||||
originalCipher = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
|
||||
f.session.providerMessages = structuredClone(originalHistory); f.store.save(f.session);
|
||||
fs.writeFileSync(path.join(directory, 'retention-before.json'), JSON.stringify({ metadata: originalMetadata, cipher: originalCipher, snapshot: originalSnapshotMetadata, legacyPool, disabledPool, originalHistory }, null, 2));
|
||||
f.store.close();
|
||||
if (desktop) {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
|
||||
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
|
||||
cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page);
|
||||
} else {
|
||||
host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318');
|
||||
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage();
|
||||
}
|
||||
page.setDefaultTimeout(15000); page.on('pageerror', cause => errors.push(cause.message));
|
||||
await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); externalBlocked.push(url.origin); return route.abort(); });
|
||||
await resize(1280); await page.goto(host.url); await page.waitForLoadState('networkidle'); await open();
|
||||
fs.writeFileSync(path.join(directory, 'initial-dom.html'), await page.content(), { flag: 'wx' }); await shot('existing-pools-1280');
|
||||
await editPool(legacyPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('run'); await poolForm().getByRole('button', { name: '取消', exact: true }).click();
|
||||
await editPool(disabledPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('none'); await poolForm().getByRole('button', { name: '取消', exact: true }).click();
|
||||
let current = await host.api('/model-center'); assert.deepEqual(current.pools.find(value => value.id === legacyPool.id), legacyPool); assert.deepEqual(current.pools.find(value => value.id === disabledPool.id), disabledPool);
|
||||
assert.equal(requests.length, 0); mark('Existing pools retain their original Run/disabled scope without saving new defaults or issuing model requests');
|
||||
|
||||
await center().locator('.mc-section-title').getByRole('button').click(); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('session');
|
||||
await poolForm().getByLabel('模型池名称', { exact: true }).fill('自有会话模型池');
|
||||
for (const name of [memberA.name, memberB.name]) await poolForm().locator('fieldset label').filter({ hasText: name }).getByRole('checkbox').check();
|
||||
await shot('new-session-pool-1280', poolForm()); await savePool();
|
||||
newPool = (await host.api('/model-center')).pools.find(value => value.name === '自有会话模型池'); assert.equal(newPool.affinityScope, 'session');
|
||||
for (const scope of ['task', 'run', 'none', 'session']) {
|
||||
await editPool(newPool.id); await poolForm().getByLabel('连接保持范围', { exact: true }).selectOption(scope); await savePool();
|
||||
await page.reload(); await page.waitForLoadState('networkidle'); await editPool(newPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue(scope);
|
||||
if (scope === 'task') { await resize(390, 844); await shot('task-pool-390', poolForm().getByLabel('连接保持范围', { exact: true })); }
|
||||
await poolForm().getByRole('button', { name: '取消', exact: true }).click();
|
||||
}
|
||||
await poolCard(newPool.id).getByRole('button', { name: '使用此模型池', exact: true }).click();
|
||||
await until(async () => (await host.api('/model-center')).selected.id === newPool.id); await page.keyboard.press('Escape');
|
||||
mark('All four pool scopes save through the real form and survive reload; new pools start with session affinity and explicit selection persists');
|
||||
|
||||
await run('读取工程目录然后结束', 2); await run('追加一句说明然后结束', 3);
|
||||
current = await host.api('/model-center'); const lastSuccess = current.attempts.find(value => value.sessionId === f.session.id && value.nativeStateAudit?.applied === 2);
|
||||
assert.ok(lastSuccess); assert.equal(lastSuccess.routingDecision.affinity.source, 'saved-completed-response'); assert.equal(lastSuccess.routingDecision.affinity.scope, 'session');
|
||||
assert.ok(requests.every(value => value.body.model === memberA.model)); assert.ok(requests[2].body.messages.some(value => value.reasoning_content === 'owned-current-reasoning-1'));
|
||||
assert.ok(requests.every(value => value.body.max_tokens === undefined && value.body.max_completion_tokens === undefined));
|
||||
let entry = await entryFor(lastSuccess.id); await entry.locator('.mc-routing-decision > summary').click(); await expect(entry).toContainText('当前会话 · 沿用连接');
|
||||
await entry.locator('.model-provider-state > summary').click(); await expect(entry.locator('.model-provider-state')).toContainText('可续接 2 / 仅保留 1');
|
||||
await expect(entry.locator('.model-provider-state')).toContainText('原状态版本尚未支持');
|
||||
await resize(1280); await shot('continued-history-1280', entry.locator('.model-provider-state > summary'));
|
||||
mark('The request ledger shows completed-response affinity and applicable native states separately from the retained original unknown state and cache usage');
|
||||
|
||||
await page.keyboard.press('Escape'); await resize(390, 844); await openWorkbenchTool(page, '查看任务记录');
|
||||
const context = page.getByRole('region', { name: '请求上下文', exact: true }); await expect(context).toBeVisible();
|
||||
await context.locator('.model-provider-state > summary').click(); await expect(context).toContainText('发送前冻结的各连接历史投影');
|
||||
await expect(context.locator('.model-provider-state > summary')).toContainText('2 条候选连接');
|
||||
await shot('context-state-390', context.locator('.model-provider-state > summary'));
|
||||
mark('The actual task inspector exposes the frozen state projection and upstream-owned context limits at 390px');
|
||||
|
||||
const changedConnection = (await host.api('/model-center')).connections.find(value => value.id === memberA.id);
|
||||
await host.api('/model-center/connections', { ...changedConnection, requestContract: { ...changedConnection.requestContract, headers: { 'X-Owned-Scope': 'changed' } } });
|
||||
reject = true; await run('继续任务并返回原错误', 4);
|
||||
current = await host.api('/model-center'); const failed = current.attempts.find(value => value.sessionId === f.session.id && value.status === 'failed'); assert.ok(failed);
|
||||
assert.equal(failed.nativeStateAudit.retainedOnly, 4); assert.equal(failed.routingDecision.affinity.reason, 'saved-provider-scope-changed');
|
||||
assert.equal(failed.connectionId, memberB.id); assert.equal(requests[3].body.model, memberB.model);
|
||||
assert.ok(requests[3].body.messages.every(value => value.reasoning_content === undefined)); assert.equal(requests[3].headers['x-owned-scope'], undefined);
|
||||
entry = await entryFor(failed.id); await entry.locator('.model-provider-state > summary').click(); await expect(entry).toContainText('可续接 0 / 仅保留 4');
|
||||
await entry.locator('.mc-routing-decision > summary').click(); await expect(entry).toContainText('连接身份或请求范围已变化');
|
||||
await expect(entry).toContainText('owned-original-header-scope-error'); await shot('changed-state-original-error-390', entry.locator('.model-provider-state > summary'));
|
||||
const old = await entryFor(legacyAttempt.id); await expect(old).toContainText('用量未知'); assert.equal(await old.locator('.model-provider-state').count(), 0);
|
||||
mark('Changed provider scope reselects the next eligible pool member, retains old states and one original upstream 400, and fabricates no old metadata');
|
||||
|
||||
await open('模型连接');
|
||||
await center().locator('.mc-connection[data-connection-id="' + memberA.id + '"]').getByRole('button', { name: '用于新任务', exact: true }).click();
|
||||
await until(async () => (await host.api('/model-center')).selected.id === memberA.id); await page.keyboard.press('Escape');
|
||||
await run('显式选择连接并保留原错误', 5);
|
||||
current = await host.api('/model-center'); const manualFailure = current.attempts.find(value => value.sessionId === f.session.id && value.status === 'failed' && value.connectionId === memberA.id);
|
||||
assert.ok(manualFailure); assert.equal(manualFailure.nativeStateAudit.retainedOnly, 4); assert.equal(manualFailure.routingDecision.reason, 'explicit-selection');
|
||||
assert.equal(requests[4].body.model, memberA.model); assert.equal(requests[4].headers['x-owned-scope'], 'changed');
|
||||
assert.ok(requests[4].body.messages.every(value => value.reasoning_content === undefined));
|
||||
entry = await entryFor(manualFailure.id); await entry.locator('.model-provider-state > summary').click();
|
||||
await expect(entry).toContainText('显式选择:按原配置透传'); await expect(entry).toContainText('owned-original-header-scope-error');
|
||||
await shot('manual-selection-original-error-390', entry.locator('.model-provider-state > summary'));
|
||||
mark('Manual model selection takes precedence, transmits its changed header and preserves the original 400 once without applying old opaque history or replaying tools');
|
||||
|
||||
for (const [palette, name] of [['green', '深青绿'], ['blue', '雾蓝'], ['purple', '鸢尾紫']]) {
|
||||
await page.keyboard.press('Escape'); await page.getByRole('button', { name: '外观', exact: true }).click();
|
||||
await page.getByRole('dialog', { name: '外观', exact: true }).getByRole('radio', { name, exact: true }).check(); await page.keyboard.press('Escape');
|
||||
entry = await entryFor(failed.id); await entry.locator('.model-provider-state > summary').click();
|
||||
await sampleContrast(entry.locator('.model-provider-state > summary'), palette + ' summary'); await sampleContrast(entry.locator('.model-provider-state > p').first(), palette + ' note');
|
||||
await shot('state-' + palette + '-390', entry.locator('.model-provider-state > summary'));
|
||||
}
|
||||
await open(); await editPool(newPool.id); await poolForm().getByLabel('连接保持范围', { exact: true }).selectOption('task'); await savePool();
|
||||
await poolCard(newPool.id).getByRole('button', { name: '使用此模型池', exact: true }).click();
|
||||
await until(async () => (await host.api('/model-center')).selected.id === newPool.id);
|
||||
mark('State details and scope settings remain readable and usable in the three existing palettes without narrow-screen document overflow');
|
||||
|
||||
const finalCenter = await host.api('/model-center'); fs.writeFileSync(path.join(directory, 'center-final.json'), JSON.stringify(finalCenter, null, 2));
|
||||
fs.writeFileSync(path.join(directory, 'session-export.json'), JSON.stringify(await host.api('/sessions/' + f.session.id + '/export'), null, 2));
|
||||
assert.equal(finalCenter.attemptCount, 6); assert.deepEqual(finalCenter.attempts.find(value => value.id === legacyAttempt.id), legacyAttempt);
|
||||
assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []);
|
||||
if (application) { await application.close(); application = null; } if (browser) { await browser.close(); browser = null; }
|
||||
if (controller) { await controller.stop(); controller = null; } await host.close?.(); host = null;
|
||||
host = await launchWorkbench(t, f.data, {}, { appRoot }); const restoredHostUrl = host.url;
|
||||
const restored = await host.api('/model-center'); assert.equal(restored.attemptCount, 6); assert.equal(restored.selected.id, newPool.id);
|
||||
assert.equal(restored.pools.find(value => value.id === newPool.id).affinityScope, 'task');
|
||||
assert.deepEqual(restored.pools.find(value => value.id === legacyPool.id), legacyPool); assert.deepEqual(restored.pools.find(value => value.id === disabledPool.id), disabledPool);
|
||||
const restoredClaude = restored.connections.find(value => value.id === claude.id); assert.equal(restoredClaude.hasKey, true); assert.deepEqual(restoredClaude.nativeParameters, native);
|
||||
await host.close(); host = null;
|
||||
const storage = new Store(f.data);
|
||||
try {
|
||||
const metadata = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
|
||||
const cipher = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
|
||||
const snapshot = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
|
||||
fs.writeFileSync(path.join(directory, 'retention-after.json'), JSON.stringify({ metadata, cipher, snapshot, history: storage.session(f.session.id).providerMessages, affinity: storage.session(f.session.id).modelAffinity }, null, 2));
|
||||
assert.equal(metadata, originalMetadata); assert.equal(cipher, originalCipher); assert.equal(snapshot, originalSnapshotMetadata);
|
||||
assert.deepEqual(storage.session(f.session.id).providerMessages.slice(0, originalHistory.length), originalHistory); assert.equal(storage.core.tool.size, 1);
|
||||
for (const plan of storage.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(storage, storage.session(f.session.id), plan));
|
||||
} finally { storage.close(); }
|
||||
mark('Candidate host restart retains saved scope, original pools, native cache settings, original metadata/cipher/snapshot and history; no tool or request is replayed');
|
||||
result = { success: true, appRoot, actualElectron: desktop, hostUrl: restoredHostUrl, checks, screenshots, contrast, errors, externalBlocked,
|
||||
syntheticRequests: requests.length, originalUnknownAttempts: 1, originalMetadataExact: true, originalCipherExact: true, originalSnapshotExact: true, originalHistoryExact: true,
|
||||
realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] };
|
||||
} catch (cause) {
|
||||
if (page) { await capture(path.join(directory, 'failure.png')).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); }
|
||||
if (host) { const state = await host.api('/model-center').catch(() => null); if (state) fs.writeFileSync(path.join(directory, 'failure-center.json'), JSON.stringify(state, null, 2), { flag: 'wx' }); }
|
||||
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, contrast, errors, externalBlocked, error: cause.stack,
|
||||
syntheticRequests: requests.length, realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0 };
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2));
|
||||
if (application) await application.close(); if (browser) await browser.close();
|
||||
if (controller && await controller.health()) await controller.stop(); await host?.close?.();
|
||||
if (model.listening) await new Promise(resolve => { model.closeAllConnections(); model.close(resolve); });
|
||||
for (const dispose of disposers.reverse()) await dispose();
|
||||
if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); }
|
||||
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
|
||||
}
|
||||
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
|
||||
@@ -21,6 +21,8 @@
|
||||
.mc-routing-decision li{border-left:2px solid var(--line);padding-left:10px}
|
||||
.mc-routing-decision li>span{display:block}
|
||||
.mc-routing-decision summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.mc-affinity-record{margin:10px 0;padding-left:10px;border-left:2px solid var(--line)}.mc-affinity-record>p{margin:5px 0}.mc-affinity-record code{white-space:normal;overflow-wrap:anywhere}
|
||||
.mc-affinity-setting{margin:16px 0;min-width:0}.mc-affinity-setting>label{display:grid;gap:7px;font-size:13px;color:var(--ink)}.mc-affinity-setting select{min-height:44px;padding:10px 12px;border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--ink);font:inherit;width:100%;min-width:0}.mc-affinity-setting select:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.mc-affinity-setting .mc-help{margin:8px 0;color:var(--muted);line-height:1.7}
|
||||
.mc-stream-receipt { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 8px; }
|
||||
.mc-stream-receipt code { display: block; overflow-wrap: anywhere; font-size: 11px; line-height: 1.7; }
|
||||
.mc-stream-receipt .button { margin-top: 8px; }
|
||||
|
||||
@@ -32,7 +32,10 @@ const protocolOutput = (value: ModelSpecConnection & { maxOutputTokens?: number
|
||||
|
||||
type Connection = NativeConnection & { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel;
|
||||
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
|
||||
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
|
||||
type AffinityScope = 'none' | 'run' | 'task' | 'session';
|
||||
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; affinityScope?: AffinityScope; maxAttempts: number; revision?: number; queueTimeoutMs: number };
|
||||
const affinityLabels: Record<AffinityScope, string> = { none: '每次请求重新选择', run: '当前运行保持连接', task: '当前任务保持连接', session: '当前会话保持连接' };
|
||||
const poolAffinity = (pool: Pool): AffinityScope => pool.sticky === false ? 'none' : pool.affinityScope ?? 'run';
|
||||
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
|
||||
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: ModelAttempt[]; waiting: number };
|
||||
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
|
||||
@@ -44,7 +47,7 @@ const states: Record<string, string> = { configured: '已配置', needs_key: '
|
||||
const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, ...DEFAULT_MODEL_CAPACITY, concurrency: 1 };
|
||||
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
|
||||
const capabilityStates: Record<string, string> = { protocol_declared: '声明支持', verified: '已验证', unknown: '待验证', unsupported: '不支持' };
|
||||
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
|
||||
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, affinityScope: 'session', maxAttempts: 3, queueTimeoutMs: 15000 };
|
||||
export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Config, selection?: ModelSelection) => void; busy: boolean; runModel?: ModelSnapshot }) {
|
||||
const [view, setView] = useState<Center | null>(null);
|
||||
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
|
||||
@@ -213,8 +216,8 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
|
||||
</section>}
|
||||
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>自动选择优先已知适配成员,能力未知时保留后备尝试。明确不支持的成员不参与自动选择,仍可手动选用。透传请求失败后保留原错,等待处理。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
|
||||
{!view.pools.length && <p className="mc-empty">添加多个连接后建立模型池,设置轮询或权重与连接亲和。</p>}
|
||||
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
|
||||
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><label className="mc-checkbox"><input type="checkbox" checked={pool.sticky} onChange={event => setPool({ ...pool, sticky: event.target.checked })} />同一运行优先保持连接;明确失败后才切换</label>
|
||||
{view.pools.map(value => <article className="mc-pool" key={value.id} data-pool-id={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {affinityLabels[poolAffinity(value)]}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
|
||||
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><div className="mc-affinity-setting"><label>连接保持范围<select aria-label="连接保持范围" value={poolAffinity(pool)} onChange={event => { const affinityScope = event.target.value as AffinityScope; setPool({ ...pool, affinityScope, sticky: affinityScope !== 'none' }); }}><option value="session">当前会话 · 跨任务与运行</option><option value="task">当前任务 · 跨运行</option><option value="run">当前运行</option><option value="none">关闭 · 每次请求重新选择</option></select></label><p className="mc-help">优先沿用此范围内上次完成响应的连接。停用、身份变化或不适配时重新选择;手动选模优先,上游错误按原结果保留。</p></div>
|
||||
<fieldset><legend>模型池成员与权重</legend>{connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
|
||||
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
|
||||
</>}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
.model-provider-state { min-width: 0; margin-top: 12px; border-top: 1px solid var(--line); padding-top: 8px; color: var(--muted); font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
|
||||
.model-provider-state > summary { cursor: pointer; min-height: 42px; padding: 10px 0; color: var(--ink); font-weight: 600; }
|
||||
.model-provider-state > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
.model-provider-state p { margin: 6px 0 10px; }
|
||||
.model-provider-state section { padding: 8px 0; }
|
||||
.model-provider-state h4 { margin: 4px 0 8px; color: var(--ink); font-size: 12px; }
|
||||
.model-provider-state dl { display: grid; grid-template-columns: 108px minmax(0, 1fr); gap: 6px 12px; margin: 0; }
|
||||
.model-provider-state dt, .model-provider-state dd { margin: 0; min-width: 0; }
|
||||
.model-provider-state code { font: 11px/1.7 var(--font-mono, Consolas, monospace); white-space: normal; overflow-wrap: anywhere; }
|
||||
.model-provider-state ul { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 12px; }
|
||||
.model-provider-state li { border-left: 2px solid var(--line); padding-left: 10px; }
|
||||
.model-provider-state li strong { color: var(--ink); }
|
||||
.model-provider-state li > span, .model-provider-state li > code { display: block; }
|
||||
@media (max-width: 620px) { .model-provider-state dl { grid-template-columns: 1fr; gap: 3px; } .model-provider-state dd { margin-bottom: 7px; } }
|
||||
@@ -0,0 +1,35 @@
|
||||
import { protocolLabel } from '../shared/contracts/model-endpoint.mjs';
|
||||
import './ModelProviderStateDetails.css';
|
||||
|
||||
export type ProviderStateVariant = {
|
||||
connectionId: string | null; model: string; protocol: string; applied: number; retainedOnly: number;
|
||||
binding: { requestUrl: string | null; credentialRevision: number | null; fingerprint: string; headers: [string, string][] };
|
||||
states: { index: number; protocol: string; responseId: string | null; stateSchemaVersion: number; applicable: boolean; reason: string; stateSha256: string }[];
|
||||
};
|
||||
export type ProviderStateAuditView = Partial<ProviderStateVariant> & { schemaVersion?: number; source?: string; requestPlanId?: string; variants?: ProviderStateVariant[] };
|
||||
const reasons: Record<string, string> = { 'same-provider-scope': '当前供应商范围一致', 'provider-scope-changed': '连接、凭据、型号或请求头范围已变化',
|
||||
'unknown-state-schema': '原状态版本尚未支持', 'legacy-chat-identity-match': '原 Chat 连接与凭据身份一致',
|
||||
'legacy-provider-changed': '原连接或型号已变化', 'legacy-direct-protocol': '原直接协议历史', 'legacy-identity-unavailable': '旧状态未保存完整身份' };
|
||||
|
||||
export function ModelProviderStateDetails({ audit }: { audit?: ProviderStateAuditView }) {
|
||||
if (!audit) return null;
|
||||
const variants = audit.variants ?? (audit.binding && audit.states ? [audit as ProviderStateVariant] : []);
|
||||
if (!variants.length) return null;
|
||||
const summary = audit.variants ? `${variants.length} 条候选连接` : `可续接 ${variants[0].applied} / 仅保留 ${variants[0].retainedOnly}`;
|
||||
return <details className="model-provider-state"><summary>原生历史状态 · {summary}</summary>
|
||||
<p>{audit.variants ? '发送前冻结的各连接历史投影。' : '本次选中连接对应的冻结历史投影。'}按协议、地址、型号、凭据和请求头核对;原历史保留,是否被上游接受以原响应为准。</p>
|
||||
{variants.map((variant, index) => <section key={variant.connectionId ?? index}>
|
||||
<h4>{variant.model} · {protocolLabel(variant.protocol)}</h4>
|
||||
<dl><dt>可续接 / 仅保留</dt><dd>{variant.applied} / {variant.retainedOnly}</dd>
|
||||
<dt>请求地址</dt><dd>{variant.binding.requestUrl ?? '原记录未保存'}</dd>
|
||||
<dt>凭据修订</dt><dd>{variant.binding.credentialRevision ?? '原记录未保存'}</dd>
|
||||
<dt>状态范围指纹</dt><dd><code>{variant.binding.fingerprint}</code></dd></dl>
|
||||
{variant.states.length ? <ul>{variant.states.map(state => <li key={state.index}>
|
||||
<strong>{state.applicable ? '可续接' : '仅保留原件'} · {reasons[state.reason] ?? state.reason}</strong>
|
||||
<span>原状态版本 {state.stateSchemaVersion}{state.responseId ? ' · 响应 ' + state.responseId : ''}</span>
|
||||
<code>原状态 SHA256 {state.stateSha256}</code>
|
||||
</li>)}</ul> : <p>本次没有待续接的原生助手状态。</p>}
|
||||
</section>)}
|
||||
<p>连接保持与指纹一致不代表缓存命中。缓存读写和未报告用量在本次用量记录中分别显示。</p>
|
||||
</details>;
|
||||
}
|
||||
@@ -10,9 +10,11 @@ import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
|
||||
import type { RuntimeFailure } from './types';
|
||||
import './ModelRequestLedger.css';
|
||||
import { ModelRequestDetails } from './ModelRequestDetails';
|
||||
import { ModelProviderStateDetails, type ProviderStateAuditView } from './ModelProviderStateDetails';
|
||||
import type { PreparedRequestMetadata } from './types';
|
||||
|
||||
export type ModelAttempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; requestMetadata?: PreparedRequestMetadata;
|
||||
nativeStateAudit?: ProviderStateAuditView; affinityPersistence?: { status: string; reason?: string };
|
||||
upstreamResponse?: { requestId?: string | null; responseUrl?: string | null; headers?: Record<string, string> }; id: string; connectionId?: string; model?: string; protocol?: string; streaming?: boolean;
|
||||
rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal?: number; usageStatus: string; reason?: string;
|
||||
taskId?: string; sessionId?: string; runId?: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean;
|
||||
@@ -73,6 +75,8 @@ export function ModelRequestLedger({ connections, refreshVersion }: { connection
|
||||
{value.requestMetadata && <ModelRequestDetails request={value.requestMetadata} responseHeaders={value.upstreamResponse?.headers} />}
|
||||
{value.reason && <p className="mc-card-warning">{value.reason}</p>}
|
||||
<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model ?? '原记录未保存'} />
|
||||
<ModelProviderStateDetails audit={value.nativeStateAudit} />
|
||||
{value.affinityPersistence && ['unknown', 'retained-unknown'].includes(value.affinityPersistence.status) && <p className="mc-card-warning">连接保持记录{value.affinityPersistence.status === 'unknown' ? '保存结果未知' : '暂不能解释,原件保留'};本次模型响应仍按原结果处理。{value.affinityPersistence.reason}</p>}
|
||||
{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}
|
||||
{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={disabled} onClick={() => void act(() => downloadArtifact(value.sessionId!, value.requestArtifactId!, 'model-request-' + value.id + '.json'))}>下载实际请求</button>}
|
||||
{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + item.capability + ' · ' + item.reason).join(';')}</p>}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export type RoutingDecision = {
|
||||
schemaVersion: number; mode: string; reason: string; selectedConnectionId: string | null; selectedBy?: string;
|
||||
affinity?: { scope: string; reason: string; continued: boolean; source: string; previousConnectionId: string | null; sourceRunId: string | null; selectedConnectionId: string };
|
||||
candidates: { connectionId: string; connectionName: string; model: string; connectionRevision: number; credentialRevision: number;
|
||||
disposition: string; tier: string; unavailable?: string | null; requirements: string[];
|
||||
capabilities: Record<string, { state: string; source: string }>;
|
||||
@@ -12,11 +13,18 @@ const labels: Record<string, string> = { text: '文本', tools: '工具', stream
|
||||
'revision-bound-observation': '对应连接及凭据修订的观测', 'connection-declaration': '连接声明', 'upstream-model-list': '相符上游目录', 'official-model-spec': '官方精确型号规格', 'explicit-compatibility': '用户显式兼容覆盖', 'protocol-declaration': '协议声明' };
|
||||
const reasons: Record<string, string> = { 'known-capabilities': '自动适配:已知能力满足请求', 'unverified-fallback': '自动适配:未知能力后备尝试(未验证)',
|
||||
'no-eligible-candidate': '自动适配:没有可用适配成员', 'explicit-selection': '显式选择:按原配置透传', 'restricted-capabilities': '按手动限制模式核对能力' };
|
||||
const affinityScopes: Record<string, string> = { none: '关闭', run: '当前运行', task: '当前任务', session: '当前会话' };
|
||||
const affinityReasons: Record<string, string> = { disabled: '按当前调度规则选择', 'no-saved-affinity': '此范围尚无完成响应的连接记录',
|
||||
'saved-provider-scope-match': '上次连接及供应商状态范围一致', 'saved-provider-scope-changed': '连接身份或请求范围已变化',
|
||||
'saved-member-not-eligible': '上次成员当前停用或不适配', 'independent-run-path': '独立诊断使用自己的运行范围', 'unknown-affinity-state': '旧连接记录无法解释,原件保留' };
|
||||
|
||||
export function ModelRoutingDetails({ decision }: { decision?: RoutingDecision }) {
|
||||
if (!decision) return null;
|
||||
return <details className="mc-routing-decision"><summary>{reasons[decision.reason] ?? '本次模型选择依据'}</summary>
|
||||
<p>这是本次请求的选择记录。声明支持与实际验证分别记录;请求发出后的上游错误仍按原结果保留。</p>
|
||||
{decision.affinity && <div className="mc-affinity-record"><strong>连接保持:{affinityScopes[decision.affinity.scope] ?? decision.affinity.scope} · {decision.affinity.continued ? '沿用连接' : '本次重新选择'}</strong>
|
||||
<p>{affinityReasons[decision.affinity.reason] ?? decision.affinity.reason}{decision.affinity.source === 'current-run' ? ' · 当前运行的连接记录' : decision.affinity.source === 'saved-completed-response' ? ' · 上次完成响应的记录' : ''}</p>
|
||||
{decision.affinity.sourceRunId && <p>来源 Run <code>{decision.affinity.sourceRunId}</code></p>}</div>}
|
||||
<ul>{decision.candidates.map(candidate => <li key={candidate.connectionId}>
|
||||
<strong>{candidate.connectionName} · {labels[candidate.disposition] ?? candidate.disposition}</strong>
|
||||
<span>{candidate.model} · 连接修订 {candidate.connectionRevision} / 凭据修订 {candidate.credentialRevision}</span>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Modal } from './components';
|
||||
import { ModelUsageDetails } from './ModelUsageDetails';
|
||||
import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types';
|
||||
import { ModelRequestDetails } from './ModelRequestDetails';
|
||||
import { ModelProviderStateDetails } from './ModelProviderStateDetails';
|
||||
|
||||
const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN');
|
||||
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
|
||||
@@ -57,6 +58,7 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
|
||||
{!!plan.skillCatalogEntries && <><dt>技能目录</dt><dd>{plan.skillCatalogEntries} 项本次目录记录</dd></>}
|
||||
<dt>发送内容</dt><dd>{number(plan.requestBytes)} B<code className="context-sha" title={plan.requestSha256}>{plan.requestSha256.slice(0, 16)}</code></dd>
|
||||
</dl>
|
||||
<ModelProviderStateDetails audit={plan.nativeStateAudit} />
|
||||
<ModelUsageDetails key={'usage-' + plan.id} usage={plan.actualUsage} expanded />
|
||||
{surface && <details className="context-tool-surface" key={plan.id}><summary>本轮工具 · 可见 {surface.entries.filter(entry => entry.visible).length} / 已登记 {surface.entries.length}</summary>
|
||||
<p className="record-footnote">这是本次实际发送的工具范围。资源和权限在执行时重新核对;登记不代表本轮可用。</p>
|
||||
|
||||
@@ -210,6 +210,7 @@ export interface ContextPlan {
|
||||
blocks?: { path: string; role: string | null; sha256: string; bytes: number }[];
|
||||
}[] };
|
||||
requestContractAudit?: { schemaVersion: number; previousPlanId: string | null; variants: PreparedRequestMetadata[] };
|
||||
nativeStateAudit?: import('./ModelProviderStateDetails').ProviderStateAuditView;
|
||||
requestObservation?: { schemaVersion: number; path: { kind: string; key: string }; providerHistorySha256: string;
|
||||
userMessageInstances: { id: string; providerIndex: number; origin: string; sha256: string }[];
|
||||
toolSurface: { generation: string; execution: string; entries: { name: string; group: string; registered: boolean; assembled: boolean; visible: boolean; reason: string; schemaSha256: string; definitionSha256: string; definitionBytes: number; generation: string }[] } | null };
|
||||
|
||||
@@ -82,10 +82,10 @@ test('real HTTP pool fails over 429 to another model and never repeats completed
|
||||
assert.equal(bad.requests[0].headers.authorization, 'Bearer owned-rate-limited');
|
||||
});
|
||||
|
||||
test('pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests', async t => {
|
||||
test('explicit Run affinity rotates weighted pool members on new Runs; disabled and missing credentials are excluded without requests', async t => {
|
||||
const f = fixture(t), a = await compatibleFixture(t, () => completion()), b = await compatibleFixture(t, () => completion());
|
||||
const provider = new Provider(), hub = provider.modelHub(f.store), first = add(hub, a, 'A'), second = add(hub, b, 'B');
|
||||
const pool = hub.pool({ name: 'Weighted', strategy: 'weighted', members: [{ connectionId: first.id, weight: 2 }, { connectionId: second.id, weight: 1 }] });
|
||||
const pool = hub.pool({ name: 'Weighted', strategy: 'weighted', affinityScope: 'run', members: [{ connectionId: first.id, weight: 2 }, { connectionId: second.id, weight: 1 }] });
|
||||
hub.select({ type: 'pool', id: pool.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
|
||||
for (let index = 0; index < 3; index++) { runtime.start(f.session.id, 'Finish ' + index); await until(() => !runtime.isActive(f.session.id)); }
|
||||
assert.equal(a.requests.length, 2); assert.equal(b.requests.length, 1);
|
||||
|
||||
@@ -51,7 +51,10 @@ test('automatic requirement ranking includes each member stream choice and respe
|
||||
const choices = [];
|
||||
for (let i = 0; i < 3; i++) { const lease = await f.acquire(config); choices.push(lease.member.id); assert.equal(lease.decision.candidates[0].reasons[0].capability, 'streaming'); lease.release(); }
|
||||
assert.deepEqual(choices, [a.id, a.id, b.id]);
|
||||
config.modelRouting.sticky = true; const lease = await f.acquire(config); assert.equal(lease.member.id, b.id); assert.equal(lease.decision.selectedBy, 'sticky'); lease.release();
|
||||
assert.equal(f.hub.sticky.has('owned-run'), false, 'disabled affinity does not remember a hidden connection');
|
||||
config.modelRouting.sticky = true; config.modelRouting.affinityScope = 'run';
|
||||
const first = await f.acquire(config); assert.equal(first.member.id, a.id); assert.notEqual(first.decision.selectedBy, 'sticky'); first.release();
|
||||
const continued = await f.acquire(config); assert.equal(continued.member.id, a.id); assert.equal(continued.decision.selectedBy, 'sticky'); continued.release();
|
||||
});
|
||||
|
||||
test('matching upstream negative/retired metadata excludes automatic candidates, stale model/endpoint metadata does not', async t => {
|
||||
|
||||
Reference in New Issue
Block a user