fix(models): unify connection editing and remove demo entry points

This commit is contained in:
Agent Workbench Dev
2026-11-06 10:07:59 +08:00
parent cee6e03247
commit ebd605f9ee
13 changed files with 293 additions and 92 deletions
+2
View File
@@ -1,5 +1,7 @@
# Agent Workbench项目执行规范
1.25.7源码已统一模型连接:删除独立旧设置窗口和用户可选的离线演示,空占位不显示;既有连接按实际型号或保存名使用同一编辑/参数/启停契约,保留内部ID/凭据/当前模型池,历史原证据不改。构建、相关72/72、最终网页与实际Electron各5组通过;不可变发行/正式升级尚待,当前正式仍1.25.6/PID71628。见docs/QA-UNIFIED-MODELS-1.25.7.md;不委派/推送/触真实Key或续跑原项目,真实模型/网络/重复读取/缓存/预留/Purge未知保留。
1.25.6已正式交付:程序2a6554cd/候选20261106013126073,保留PID71628及原instance/Provider,85项目105会话全部原行/导出/工件/公开模型中心exact,9229关闭、空闲/窗口0。默认透传下逐型号只读展示上游最大上下文/输出,缺失时本地无限制;当前DeepSeek未存目录容量,不借手填旧值。源码发布独立于项目数据,原有证据不重打包;源码工具3494ae7a修正Git换行导出身份,1063项ZIP核对及711输入重建22/22通过,最终程序网页/Electron各4组、正式两端通过;首同名连接定位失败已保留并修正验证器。来源/阶段验证与历史失败见docs/QA-SOURCE-CAPACITY-1.25.6.md、docs/source-capacity-1.25.6-release-identity.json;不委派/推送,不触Key或续跑原项目,真实模型/网络/重复读取/缓存/预留/Purge未知保持。下文旧版说明按历史时点理解。
用户已澄清旧“等待审查/继续原任务”两张图来自1.25.4,不能代作1.25.5失败。1.25.5新图确实仍显示连接容量16000/2048;透传wire已不使用这些值,本轮1.25.6仅修正连接列表/编辑器/原连接的实际策略显示,并拆开源码发布与程序发布。源码导出不读服务/用户数据,不把正式数据对账当打包前置;npm run package:source为已提交Git源码,package/app默认只程序,历史证据需显式--with-evidence,原件不动。构建第二轮/相关25及网页11已过,Electron/独立包/实际升级仍待,不称已部署。见docs/QA-SOURCE-CAPACITY-1.25.6.md及docs/PACKAGING.md;下文1.25.5交付状态保持历史时点。
+6
View File
@@ -1,5 +1,11 @@
# Agent Workbench 更新记录
## 1.25.7
- 移除模型中心、主对话与侧栏的离线演示入口,以及独立的旧连接设置窗口;未配置时直接选择或获取上游模型,不再执行演示脚本。
- 既有有效连接按实际型号或保存的名称显示,使用统一编辑、推理与能力、停用及选模流程;保留所属连接身份和凭据。编辑连接不再强制切换当前模型池。
- 保留逐型号上游最大容量与默认无限制透传;空占位连接不再出现在列表、模型目录、模型池或凭据选择中。历史演示记录及真实失败仍保留原证据。
## 1.25.6
- 默认透传时,模型连接列表、编辑器与原连接设置统一显示“由上游决定”,不再把旧 16000/2048 等非活动容量声明显示成请求上限。逐型号只读显示上游目录声明的最大上下文/最大输出,缺失时显示本地无限制,由上游决定。
+28
View File
@@ -0,0 +1,28 @@
# 1.25.7:统一模型入口,移除旧连接与演示界面
状态:源码与相关72/72回归、最终实际网页/Electron各5组验证完成,准备冻结不可变程序。正式服务仍为1.25.6,不把源码修改当作已经部署。
用户截图指出,模型中心卡片的“原模型连接 → 编辑”会关闭模型中心,转到另一套早期“原连接与演示设置”。它含有离线演示切换、旧品牌预设、重复模型列表和独立预算表单,视觉与配置流程均与当前模型中心不一致。
本次集中修正:
- 删除旧设置窗口、表单状态、获取/检测处理器和跳转回调,所有有效连接使用模型中心已有编辑器。
- 移除默认模型选择、主对话、侧栏和欢迎页的演示入口。未配置模型时发送会打开模型中心,保留任务输入,不执行演示工具或发送请求。
- 不再显示未配置过的占位连接;已有配置按实际型号显示,可保存连接名称。普通连接、既有连接共用保存/过期校验/停用/推理参数契约;保存不切换当前模型池,凭据留空仍保留。
- 既有连接内部ID与凭据所属关系保持,修改时原子保存元数据及配置;协议可使用相同的Chat、Responses、Messages适配。旧Run及请求账本不回写,历史演示仍如实标识未调用模型。测试夹具使用的内部固定脚本不向普通用户提供选择入口。
- 上游容量只读展示、完整透传、操作权限与Git回滚沿用1.25.6;并发0显示“不限”。源码发布继续独立于项目数据。
验证与原始记录:
- 首构建与最终构建通过,日志`.qa/model-unification-build.txt`及`model-unification-build-final.txt`。
- 新增3个关键回归通过:既有连接编辑/重新打开持久保存且不切换模型池;Responses原生推理/身份参数实际发送且保留原凭据、无输出上限;配置提交失败完整回滚元数据、配置和凭据。
- 新增用例首轮1/3、第二轮2/3,均为验收夹具错误:受限夹具被断言为允许0并发、错误配置档ID,以及Responses的字符串status误当HTTP状态。原日志分别为`.qa/model-unification-tests-first-failure.txt`和`model-unification-tests-second-failure.txt`,修正后3/3,不改写原记录。
- 首实际网页5组与真实Electron5组通过,均覆盖1440/390、无模型空状态、输入保留、统一窗口、保存及刷新、过期错误恢复、保留选中的模型池与启停。原结果在`.qa/model-unification/web-7d3b3688-263d-48f0-a3ed-77ed9e5d0288/`及`electron-9f39b4af-3435-4c90-bde9-b78058b0512e/`。追加凭据空状态/并发文案/版本后以最终发行验证为准。
回顾:原有连接能兼容旧配置,并不意味着应该继续保留两套面向用户的设置。仅改标题会留下不同的编辑与保存语义;本次同时统一了实际行为,并将只用于历史与夹具的脚本从用户入口移开。
最终实现验证:构建通过;连接、目录、路由、原生参数、凭据保存、容量与等待相关72/72通过(`.qa/model-unification-regression.txt`)。最终网页5组及真实Electron5组通过,目录分别为`.qa/model-unification/web-a0a30be5-7ad4-4d79-bd58-87d2e3666ae4/`及`electron-6b75059c-b1df-4afc-aa01-43bee5025814/`;每端6张原图,1440/390,同窗口、过期错误恢复和刷新保存均实际操作。
发行与源码专项18/18通过(`.qa/model-unification-release-tests.txt`),包括版本/安装完整性、操作连续性、并行复制、源码归档及Git换行后的实际ZIP身份。源码与程序来源将在冻结后另行记录。
本轮真实供应商请求0;不读取、复制、解密、转存或重存真实Key,不续跑用户项目或旧实验,不推送、不委派。历史真实模型交付、网络异常、普遍重复读取、缓存收益、真实预留边界、Purge AB/BA未验证事项完整保留。没有重跑全产品全量测试,原976轮958/18不因此改签。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.25.6",
"version": "1.25.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.25.6",
"version": "1.25.7",
"dependencies": {
"@babel/parser": "7.29.11",
"@peculiar/x509": "3.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.25.6",
"version": "1.25.7",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
+9 -4
View File
@@ -44,13 +44,18 @@ try {
const center = await (await fetch(url + '/api/model-center', { headers: { 'X-Workbench-Token': boot.token, Connection: 'close' } })).json();
const connection = center.connections.find(value => value.id === center.selected.id && value.id !== 'legacy-default' && value.enabled)
?? center.connections.find(value => value.id !== 'legacy-default' && value.enabled);
if (connection) {
const existing = center.connections.find(value => value.id === 'legacy-default' && value.model.trim());
const targets = [...new Map([connection, existing].filter(Boolean).map(value => [value.id, value])).values()];
await expect(dialog.locator('option[value="demo"]')).toHaveCount(0);
for (const connection of targets) {
const cards = dialog.locator('.mc-connections > .mc-connection');
await expect(cards).toHaveCount(center.connections.length);
const card = cards.nth(center.connections.findIndex(value => value.id === connection.id));
await expect(cards).toHaveCount(center.connections.filter(value => value.id !== 'legacy-default' || value.model.trim()).length);
const card = dialog.locator('.mc-connections > [data-connection-id="' + connection.id + '"]');
await expect(card.getByRole('heading', { name: connection.name, exact: true })).toBeVisible();
await card.getByRole('button', { name: '编辑', exact: true }).click();
const editor = dialog.getByRole('form', { name: '编辑模型连接', exact: true });
await expect(page.getByRole('dialog')).toHaveCount(1);
await expect(editor.getByLabel('连接名称', { exact: true })).toHaveValue(connection.name);
await expect(editor.getByLabel('上下文上限', { exact: true })).toHaveCount(0);
await expect(editor.getByLabel('输出上限', { exact: true })).toHaveCount(0);
const upstream = connection.upstreamModel?.id === connection.model ? connection.upstreamModel : {};
@@ -58,7 +63,7 @@ try {
await expect(editor.getByLabel(label, { exact: true })).toHaveText(upstream[field] ? Number(upstream[field]).toLocaleString() + ' tokens' : '本地无限制 · 由上游决定');
}
await editor.getByLabel('连接容量策略', { exact: true }).scrollIntoViewIfNeeded();
const capacityFile = path.join(root, 'model-capacity-390.png'); await page.screenshot({ path: capacityFile, fullPage: true }); screenshots.push(capacityFile);
const capacityFile = path.join(root, 'model-capacity-' + connection.id + '-390.png'); await page.screenshot({ path: capacityFile, fullPage: true }); screenshots.push(capacityFile);
await editor.getByRole('button', { name: '取消', exact: true }).click();
}
await dialog.getByRole('button', { name: '关闭窗口', exact: true }).click();
+119
View File
@@ -0,0 +1,119 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, launchWorkbench, until } from '../tests/helpers.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';
if (process.argv.includes('--help')) { console.log('node scripts/verify-unified-model-ui.mjs [--desktop] — isolated empty/select/edit/save/stale/pool checks, no real credentials or model requests. AGENT_WORKBENCH_QA_APP_ROOT selects a built app.'); process.exit(0); }
assert.ok(process.argv.slice(2).every(value => value === '--desktop'));
const desktop = process.argv.includes('--desktop'), appRoot = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT || '.');
const directory = path.resolve('.qa/model-unification', (desktop ? 'electron-' : 'web-') + randomUUID());
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t, { modernDefaults: true });
f.store.close();
const marks = [], screenshots = [], errors = [], launches = [];
let host, controller, browser, app, page, window, result;
const dialog = () => page.getByRole('dialog', { name: '模型中心', exact: true });
const editor = () => dialog().getByRole('form', { name: '编辑模型连接', exact: true });
const card = () => dialog().locator('[data-connection-id="legacy-default"]');
const mark = message => { marks.push(message); console.log('PASS ' + message); };
async function open() { await page.getByRole('button', { name: '打开模型中心', exact: true }).click(); await expect(dialog()).toBeVisible(); }
async function shot(name) { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, fullPage: true }); screenshots.push(file); }
async function resize(width) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height: 1080 }); await until(() => page.evaluate(w => innerWidth === w, width)); }
else await page.setViewportSize({ width, height: 1080 });
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'page horizontal overflow');
}
try {
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 = { api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }), bootstrap: await controller.api('/bootstrap') };
const executablePath = desktopExecutableIdentity(appRoot).path;
app = await _electron.launch({ executablePath, args: [...(executablePath.toLowerCase().endsWith('agentworkbench.exe') ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]),
'--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port)], env: projectEnvironment({ AGENT_WORKBENCH_QA: '1', AGENT_WORKBENCH_NODE: process.execPath }) });
page = await app.firstWindow(); window = await app.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(); await page.goto(host.url);
}
page.on('pageerror', error => errors.push(error.message));
page.on('request', request => { if (/\/sessions\/[^/]+\/messages$/.test(request.url())) launches.push(request.url()); });
await page.waitForLoadState('networkidle'); await resize(1440);
const goal = 'Keep my task text while I select a model.';
await page.getByLabel('任务内容', { exact: true }).fill(goal);
await page.getByRole('button', { name: '发送任务', exact: true }).click();
await expect(dialog()).toBeVisible(); await expect(dialog().locator('.mc-connections > .mc-connection')).toHaveCount(0);
await expect(dialog()).toContainText('还没有模型连接');
await expect(dialog().getByLabel('新任务默认模型', { exact: true })).toHaveValue('');
await expect(dialog().locator('option[value="demo"]')).toHaveCount(0);
assert.equal(launches.length, 0); assert.doesNotMatch(await page.locator('body').innerText(), /离线演示|原模型连接|原连接与演示设置/);
await shot('empty-1440');
await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click(); await expect(page.getByLabel('任务内容', { exact: true })).toHaveValue(goal);
mark('unconfigured install has no demo or placeholder connection; send opens model selection without executing or losing the task');
await host.api('/config', { ...host.bootstrap.config, mode: 'compatible', model: 'owned-existing-model', baseUrl: 'http://127.0.0.1:9/v1', apiKey: 'owned-ui-credential' });
await page.reload(); await page.waitForLoadState('networkidle'); await open();
await expect(card().getByRole('heading', { name: 'owned-existing-model', exact: true })).toBeVisible();
await card().getByRole('button', { name: '编辑', exact: true }).click();
await expect(editor()).toBeVisible(); await expect(page.getByRole('dialog')).toHaveCount(1);
await expect(editor().getByLabel('请求模型名称', { exact: true })).toHaveValue('owned-existing-model');
await expect(editor().getByLabel('上下文上限', { exact: true })).toHaveCount(0); await expect(editor().getByLabel('输出上限', { exact: true })).toHaveCount(0);
await editor().getByLabel('连接名称', { exact: true }).fill('Owned upstream');
await editor().getByLabel('并发请求数(0 为不限)', { exact: true }).fill('0');
await shot('unified-editor-1440');
await editor().getByRole('button', { name: '保存模型连接', exact: true }).click(); await expect(editor()).toHaveCount(0);
let center = await host.api('/model-center');
assert.equal(center.connections.find(value => value.id === 'legacy-default').name, 'Owned upstream');
assert.equal(center.connections.find(value => value.id === 'legacy-default').hasKey, true);
assert.equal(center.selected.id, 'legacy-default');
assert.equal(JSON.stringify(center).includes('owned-ui-credential'), false);
mark('existing connection opens the shared editor in the same modal, saves zero concurrency and retains credential and identity');
await card().getByRole('button', { name: '编辑', exact: true }).click();
await editor().getByLabel('连接名称', { exact: true }).fill('Keep my unsaved edit');
const current = center.connections.find(value => value.id === 'legacy-default');
await host.api('/model-center/connections', { ...current, name: 'Externally updated' });
await editor().getByRole('button', { name: '保存模型连接', exact: true }).click();
await expect(dialog().getByRole('status')).toContainText('模型连接已修改');
await expect(editor().getByLabel('连接名称', { exact: true })).toHaveValue('Keep my unsaved edit');
await editor().getByRole('button', { name: '取消', exact: true }).click();
await dialog().getByRole('button', { name: '刷新模型中心', exact: true }).click();
await expect(card()).toContainText('Externally updated');
mark('stale save shows its actual error and preserves the unsaved draft; cancel and refresh recover the current connection');
const other = await host.api('/model-center/connections', { name: 'Owned pool member', model: 'owned-other', baseUrl: 'http://127.0.0.1:9/v1', requiresKey: false });
const pool = await host.api('/model-center/pools', { name: 'Owned selected pool', members: [{ connectionId: other.id }] });
await host.api('/model-center/select', { type: 'pool', id: pool.id });
await dialog().getByRole('button', { name: '刷新模型中心', exact: true }).click();
await expect(dialog().getByLabel('新任务默认模型', { exact: true })).toHaveValue('pool:' + pool.id);
await card().getByRole('button', { name: '编辑', exact: true }).click(); await editor().getByLabel('连接名称', { exact: true }).fill('Owned final name');
await editor().getByRole('button', { name: '保存模型连接', exact: true }).click(); await expect(editor()).toHaveCount(0);
assert.equal((await host.api('/model-center')).selected.id, pool.id);
await card().getByRole('button', { name: '停用Owned final name', exact: true }).click(); await expect(card()).toContainText('已停用');
await card().getByRole('button', { name: '启用Owned final name', exact: true }).click(); await expect(card()).toContainText('已配置');
assert.equal((await host.api('/model-center')).selected.id, pool.id);
mark('edit and enable/disable behave like every other connection and keep the selected model pool');
await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click(); await page.reload(); await page.waitForLoadState('networkidle'); await open();
await expect(card()).toContainText('Owned final name'); await expect(dialog().getByLabel('新任务默认模型', { exact: true })).toHaveValue('pool:' + pool.id);
for (const width of [1440, 390]) {
await resize(width); await shot('connections-' + width);
await card().getByRole('button', { name: '编辑', exact: true }).click(); await expect(editor()).toBeVisible();
await editor().getByLabel('连接名称', { exact: true }).scrollIntoViewIfNeeded();
assert.equal(await page.getByRole('dialog').count(), 1); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
assert.doesNotMatch(await page.locator('body').innerText(), /离线演示|原模型连接|原连接与演示设置/);
await shot('editor-' + width); await editor().getByRole('button', { name: '取消', exact: true }).click();
}
mark('saved selection and connection survive reload; 1440px and 390px keep one consistent modal and no horizontal overflow');
assert.deepEqual(errors, []); assert.equal(launches.length, 0); center = await host.api('/model-center'); assert.equal(center.attempts.length, 0);
result = { success: true, desktop, appRoot, marks, screenshots, errors, realModelRequests: 0, totalModelRequests: 0, userProjectsExecuted: 0 };
} catch (error) { if (page) await shot('failure').catch(() => {}); result = { success: false, desktop, error: error.stack, marks, screenshots, errors }; }
finally { await app?.close(); await browser?.close(); await controller?.stop(); for (const dispose of disposers.reverse()) await dispose(); fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); }
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
+9 -46
View File
@@ -29,7 +29,7 @@ import { PermissionModeControl } from './PermissionModeControl';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
const activeMcpStates = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 128000, maxSteps: 0, maxOutputTokens: 16384, executionMode: 'unrestricted', approvalMode: 'ask', capacityMode: 'passthrough', historyPolicy: 'preserve', hasKey: false, maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0, modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0 };
const defaultConfig: Config = { mode: 'compatible', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 128000, maxSteps: 0, maxOutputTokens: 16384, executionMode: 'unrestricted', approvalMode: 'ask', capacityMode: 'passthrough', historyPolicy: 'preserve', hasKey: false, maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0, modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0 };
export default function App() {
const [token, setAccess] = useState('');
@@ -38,7 +38,6 @@ export default function App() {
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
const [resuming, setResuming] = useState(false);
const [modelCheck, setModelCheck] = useState<{ kind: 'success' | 'error'; message: string } | null>(null);
const [projects, setProjects] = useState<Project[]>([]);
const [briefs, setBriefs] = useState<SessionBrief[]>([]);
const [projectId, setProjectId] = useState('');
@@ -46,7 +45,7 @@ export default function App() {
const [session, setSession] = useState<Session | null>(null);
const [config, setConfig] = useState<Config>(defaultConfig);
const [permissionSaving, setPermissionSaving] = useState(false);
const [modelSelection, setModelSelection] = useState<ModelSelection>({ type: "legacy", id: "legacy-default", name: "原模型连接" });
const [modelSelection, setModelSelection] = useState<ModelSelection>({ type: "legacy", id: "legacy-default", name: "选择模型" });
const [exampleId, setExampleId] = useState<string | null>(null);
const [files, setFiles] = useState<FileEntry[]>([]);
const [filter, setFilter] = useState('');
@@ -77,12 +76,6 @@ export default function App() {
const [viewportWidth,setViewportWidth]=useState(()=>window.innerWidth);
const [mobile, setMobile] = useState(() => window.innerWidth <= 620);
const [connected, setConnected] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [settings, setSettings] = useState<Config>(defaultConfig);
const [keyValue, setKeyValue] = useState('');
const [clearKey, setClearKey] = useState(false);
const [models, setModels] = useState<string[]>([]);
const [settingsBusy, setSettingsBusy] = useState(false);
const [projectOpen, setProjectOpen] = useState(false);
const [projectInput, setProjectInput] = useState('');
const [directoryPickerOpen, setDirectoryPickerOpen] = useState(false);
@@ -267,7 +260,7 @@ export default function App() {
async function submit() {
if (!composer.trim() || sending || isRunning || (sessionId && !session)) return;
if (restrictedWorker || session?.execution?.collaborations?.some(value => !['completed', 'discarded', 'resolved_external'].includes(value.status))) { setWorkersOpen(true); return; }
if (config.mode === 'compatible' && modelSelection.type === 'legacy' && !config.model) { setModelCenterOpen(true); notify('请先填写模型名称。'); return; }
if (config.mode === 'demo' || modelSelection.type === 'legacy' && !config.model) { setModelCenterOpen(true); notify('请先选择模型,或从上游添加连接。'); return; }
setSending(true);
const content = composer.trim();
try {
@@ -369,24 +362,6 @@ export default function App() {
notify('操作权限已保存,后续启动继续使用。');
} catch (error) { failure(error); } finally { setPermissionSaving(false); }
}
function openSettings() { setSettings(config); setKeyValue(''); setClearKey(false); setModels([]); setModelCheck(null); setSettingsOpen(true); }
async function saveSettings() {
setSettingsBusy(true);
try {
const payload = { ...settings, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) };
const saved = await api<Config>('/config', payload); setConfig(saved); setModelSelection({ type: "legacy", id: "legacy-default", name: "原模型连接" }); setSettingsOpen(false);
notify(saved.mode === 'demo' ? '已切换到离线演示。' : '模型连接已保存。API Key 仅在本次服务内存中使用。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
async function readModels() {
setSettingsBusy(true);
try {
const result = await api<{ models: string[] }>('/config/models', { baseUrl: settings.baseUrl, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) });
setModels(result.models);
if (!settings.model && result.models[0]) setSettings(previous => ({ ...previous, model: result.models[0] }));
notify('读到 ' + result.models.length + ' 个模型。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
async function openDiagnostics() {
const targetId = sessionId;
setDiagnosticsOpen(true); setDiagnosticsBusy(true);
@@ -407,15 +382,6 @@ export default function App() {
try { acceptSession(await api<Session>('/sessions/' + session.id + '/continue-reviewed', {})); }
catch (error) { failure(error); } finally { setResuming(false); }
}
async function testModel() {
setSettingsBusy(true); setModelCheck(null);
try {
const result = await api<{ ok: boolean; durationMs: number }>('/config/test', { baseUrl: settings.baseUrl, model: settings.model,
...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) });
setModelCheck({ kind: 'success', message: '模型响应验证通过,用时 ' + (result.durationMs / 1000).toFixed(1) + ' 秒。' });
} catch (error) { setModelCheck({ kind: 'error', message: error instanceof Error ? error.message : String(error) }); }
finally { setSettingsBusy(false); }
}
function failureForMessage(message: { id: string; content: string; createdAt: string }): RuntimeFailure | null {
if (session?.failure?.messageId === message.id) return session.failure;
const recorded = session?.events.filter(event => event.kind === 'error' && event.output === message.content && event.diagnostic).at(-1);
@@ -446,7 +412,7 @@ export default function App() {
let alive = true;
api<Bootstrap>('/bootstrap').then(result => {
if (!alive) return;
setToken(result.token); setAccess(result.token); setVersion(result.version); setProjects(result.projects); setBriefs(result.sessions); setConfig(result.config); if (result.modelSelection) setModelSelection(result.modelSelection); setSettings(result.config); setExampleId(result.exampleProjectId);
setToken(result.token); setAccess(result.token); setVersion(result.version); setProjects(result.projects); setBriefs(result.sessions); setConfig(result.config); if (result.modelSelection) setModelSelection(result.modelSelection); setExampleId(result.exampleProjectId);
const savedCursor = Number(sessionStorage.getItem('awb-event-cursor:' + location.origin));
eventCursor.current = Number.isSafeInteger(savedCursor) && savedCursor >= 0 && savedCursor <= (result.eventCursor ?? 0) ? savedCursor : result.eventCursor ?? 0;
for (const brief of result.sessions) revisions.current.set(brief.id, brief.revision);
@@ -599,11 +565,11 @@ export default function App() {
if (file.kind === 'directory') setCollapsed(previous => { const next = new Set(previous); if (next.has(file.path)) next.delete(file.path); else next.add(file.path); return next; }); else loadFile(file.path);
}}>{file.kind === 'directory' ? <><span className="tree-chevron">{collapsed.has(file.path) ? <ChevronRight size={11} /> : <ChevronDown size={11} />}</span><Folder size={14} /></> : <><span className="tree-chevron" /><File size={13} /></>}<span>{filter ? file.path : file.name}</span></button>)}{filter && !visibleFiles.length && <p className="sidebar-hint">没有匹配的文件。</p>}</div>
</div>
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => setMemoryOpen(true)} disabled={!selectedProject || restrictedWorker}><Brain size={16} />项目记忆<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button className="model-sidebar-entry" onClick={() => setModelCenterOpen(true)} aria-label="选择与管理模型"><ModelServer size={16} /><span>模型与连接<small>{config.mode === 'demo' ? '离线演示' : modelSelection.type === 'legacy' ? config.model || '尚未配置' : modelSelection.name}</small></span><ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<button className="version-entry" aria-label="版本与更新" onClick={() => setInstallationOpen(true)}>v{version}</button></div></div>
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => setMemoryOpen(true)} disabled={!selectedProject || restrictedWorker}><Brain size={16} />项目记忆<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button className="model-sidebar-entry" onClick={() => setModelCenterOpen(true)} aria-label="选择与管理模型"><ModelServer size={16} /><span>模型与连接<small>{config.mode === 'demo' ? '尚未选择模型' : modelSelection.name || config.model || '选择模型'}</small></span><ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<button className="version-entry" aria-label="版本与更新" onClick={() => setInstallationOpen(true)}>v{version}</button></div></div>
</aside>
<main className="task-pane">
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
<div className="model-launch"><button className="button secondary" onClick={() => setCompanionOpen(true)} aria-label="手机连接"><Link2 size={16} /><span>手机连接</span></button>{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} aria-label="切换当前模型" title="选择模型、模型池或添加连接" onClick={() => setModelCenterOpen(true)}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : modelSelection.type !== 'legacy' ? modelSelection.name : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
<div className="model-launch"><button className="button secondary" onClick={() => setCompanionOpen(true)} aria-label="手机连接"><Link2 size={16} /><span>手机连接</span></button>{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className="model-button" aria-label="切换当前模型" title="选择模型、模型池或添加连接" onClick={() => setModelCenterOpen(true)}><span className="model-light" />{config.mode === 'demo' ? '选择模型' : modelSelection.name || config.model || '选择模型'}<ChevronDown size={13} /></button></div>
</header>
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
@@ -620,7 +586,7 @@ export default function App() {
{!isRunning && pending.length === 0 && ['failed', 'paused'].includes(session.status) && <button className="text-button" disabled={resuming} onClick={() => resumeSession()}><RotateCw size={13} />{session.status === 'failed' && session.failure?.source === 'model_connection' ? '重试模型请求' : '继续任务'}</button>}</>}
</div></div>
<section ref={conversationRef} className="conversation" aria-label="任务对话">
{!session?.messages.length && !session?.events.length ? <div className="welcome"><span className="welcome-label"><span />从项目到结果</span><h2>读懂项目。<br />把每一步做好。</h2><p>给出一个任务,读取依据、工具执行和文件改动会在这里连成完整过程。</p><div className="starter-prompts">{['了解这个项目,并提出一项改进', '查找关键实现,解释调用关系', '检查项目,并准备可审查的修改'].map((prompt, index) => <button key={prompt} onClick={() => { setComposer(prompt); composerRef.current?.focus(); }}><span>{index === 0 ? <FolderOpen size={17} /> : index === 1 ? <Link2 size={17} /> : <FileCode2 size={17} />}</span>{prompt}<ArrowRight size={14} /></button>)}</div><div className="welcome-note"><ShieldCheck size={16} /><span>{config.executionMode === 'unrestricted' ? '文件改动直接应用,可查看差异和回滚。命令按所选权限执行。' : '当前使用自定义额度;命令按所选权限执行。'}</span></div>{config.mode === 'demo' && <div className="demo-note"><span>演示</span>固定脚本会调用真实本地工具,不进行模型推理。</div>}</div> : <div className="conversation-entries">
{!session?.messages.length && !session?.events.length ? <div className="welcome"><span className="welcome-label"><span />从项目到结果</span><h2>读懂项目。<br />把每一步做好。</h2><p>给出一个任务,读取依据、工具执行和文件改动会在这里连成完整过程。</p><div className="starter-prompts">{['了解这个项目,并提出一项改进', '查找关键实现,解释调用关系', '检查项目,并准备可审查的修改'].map((prompt, index) => <button key={prompt} onClick={() => { setComposer(prompt); composerRef.current?.focus(); }}><span>{index === 0 ? <FolderOpen size={17} /> : index === 1 ? <Link2 size={17} /> : <FileCode2 size={17} />}</span>{prompt}<ArrowRight size={14} /></button>)}</div><div className="welcome-note"><ShieldCheck size={16} /><span>{config.executionMode === 'unrestricted' ? '文件改动直接应用,可查看差异和回滚。命令按所选权限执行。' : '当前使用自定义额度;命令按所选权限执行。'}</span></div></div> : <div className="conversation-entries">
{session?.recoveryNotice && <div className="recovery-note"><ShieldCheck size={16} /><div><strong>已恢复会话记录</strong><p>{session.recoveryNotice}</p></div></div>}
{entries.map(entry => 'message' in entry && entry.message ? <div key={entry.id} className={'message message-' + entry.message.role}><span className="message-avatar">{entry.message.role === 'user' ? '你' : entry.message.role === 'assistant' ? 'AW' : '·'}</span><div className="message-body"><div className="message-label">{entry.message.role === 'user' ? '你的任务' : entry.message.role === 'assistant' ? session?.executionMode === 'demo' ? '演示执行器' : '编程助手' : '工作台'}<time>{new Date(entry.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</time></div><div className="message-text">{entry.message.role === 'system' && failureForMessage(entry.message)
? <FailureCard failure={failureForMessage(entry.message)!} onDiagnose={() => openDiagnostics()} onRetry={session?.status === 'failed' && session?.failure?.messageId === entry.message.id ? () => resumeSession() : undefined} busy={resuming || isRunning} />
@@ -636,7 +602,7 @@ export default function App() {
{canContinueReview && <button type="button" aria-label="继续原任务" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续原任务</strong><small>改动已应用,保留原目标、范围和检查约定继续处理。</small></span><ArrowRight size={17} /></button>}
<div ref={chatEnd} />
</section>
<footer className="composer-wrap"><div className="composer-permissions"><PermissionModeControl value={config.approvalMode ?? 'ask'} disabled={permissionSaving || !ready} onChange={mode => void savePermission(mode)} /><small>{permissionSaving ? '正在保存…' : '选择自动保存 · 可随时切换'}</small></div><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><AttachmentComposer session={session} selectedIds={imageSelection.sessionId===session?.id?imageSelection.ids:[]} onSelection={(id,ids)=>setImageSelection({sessionId:id,ids})} onEnsureSession={newSession} onSession={acceptSession} onError={failure} disabled={isRunning||sending||creatingSession||!ready||restrictedWorker} routeName={modelSelection.type==='legacy'?'原模型连接':modelSelection.name} onModels={()=>setModelCenterOpen(true)}/><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={config.executionMode === 'unrestricted' ? undefined : 20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : modelSelection.type !== 'legacy' ? modelSelection.name : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
<footer className="composer-wrap"><div className="composer-permissions"><PermissionModeControl value={config.approvalMode ?? 'ask'} disabled={permissionSaving || !ready} onChange={mode => void savePermission(mode)} /><small>{permissionSaving ? '正在保存…' : '选择自动保存 · 可随时切换'}</small></div><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><AttachmentComposer session={session} selectedIds={imageSelection.sessionId===session?.id?imageSelection.ids:[]} onSelection={(id,ids)=>setImageSelection({sessionId:id,ids})} onEnsureSession={newSession} onSession={acceptSession} onError={failure} disabled={isRunning||sending||creatingSession||!ready||restrictedWorker} routeName={config.mode === 'demo' ? '尚未选择模型' : modelSelection.name || config.model} onModels={()=>setModelCenterOpen(true)}/><textarea ref={composerRef} aria-label="任务内容" placeholder="描述项目任务,或询问工作台的执行状态与报错…" value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={config.executionMode === 'unrestricted' ? undefined : 20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '选择模型开始开发' : modelSelection.name || config.model}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
</main>
{((mobile && sidebarOpen) || (narrow && wide)) && <button type="button" className="panel-scrim" aria-label="关闭侧边面板" onClick={() => { setSidebarOpen(false); setWide(false); }} />}
<aside className="inspector">
@@ -657,14 +623,11 @@ export default function App() {
{projectOpen && <Modal title="打开项目" description="选择这台电脑上的项目文件夹,或输入完整路径。" onClose={() => { if (!projectBusy) { setProjectOpen(false); setDirectoryPickerOpen(false); setProjectError(''); } }}><form onSubmit={event => { event.preventDefault(); if (!directoryPickerOpen) void openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} disabled={projectBusy} onChange={event => { setProjectInput(event.target.value); setProjectError(''); }} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label>{projectError && <p className="local-files-error" role="alert">{projectError}</p>}{directoryPickerOpen && <ProjectDirectoryPicker initialPath={projectInput.trim()} onChoose={value => { setProjectInput(value); setProjectError(''); setDirectoryPickerOpen(false); }} onCancel={() => setDirectoryPickerOpen(false)} />}<div className="modal-actions"><button type="button" className="button secondary" disabled={pickingProject || projectBusy} onClick={() => desktop ? void pickDesktopProject() : setDirectoryPickerOpen(value => !value)}><FolderOpen size={15} />选择文件夹</button>{exampleId && <button type="button" className="button secondary" disabled={projectBusy} onClick={() => { chooseProject(exampleId); setProjectOpen(false); setDirectoryPickerOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim() || projectBusy || directoryPickerOpen}>{projectBusy ? <LoaderCircle className="spin" size={15} /> : <FolderOpen size={15} />}{projectBusy ? '正在打开…' : '打开项目'}</button></div></form></Modal>}
{companionOpen && <Modal title="手机连接" description="指定项目和权限,连接到同一个Windows执行宿主。" onClose={() => setCompanionOpen(false)} wide><CompanionPanel projects={projects} selectedProjectId={selectedProject?.id ?? ''} /></Modal>}
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
{settingsOpen && <Modal title="原连接与演示设置" description="此处只编辑原连接。添加、切换模型请使用模型中心;运行预算也可单独保存。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
{settings.executionMode === 'unrestricted' || settings.capacityMode === 'passthrough' ? <p className="mc-help" aria-label="原连接容量说明">默认透传 · 上下文与输出由上游决定,不设本地上限。需要主动设置额度时,可在模型中心的运行预算中切换。</p> : <details className="budget-settings"><summary>上下文与任务预算<ChevronDown size={13} /></summary><div className="budget-fields"><label>容量策略<select aria-label="原连接容量策略" value={settings.capacityMode ?? 'manual'} onChange={event => setSettings(previous => ({ ...previous, capacityMode: event.target.value as Config['capacityMode'], historyPolicy: 'preserve' }))}><option value="passthrough">默认透传 · 不设本地上限</option><option value="model">按模型连接容量</option><option value="manual">手动限制上下文与输出</option></select></label><label>上下文预算<input type="number" min={1000} value={settings.contextLimit} onChange={event => setSettings(previous => ({ ...previous, contextLimit: Number(event.target.value) }))} /></label><label>最大工具轮次<input type="number" min={0} value={settings.maxSteps} onChange={event => setSettings(previous => ({ ...previous, maxSteps: Number(event.target.value) }))} /></label><label>输出上限<input type="number" min={256} value={settings.maxOutputTokens} onChange={event => setSettings(previous => ({ ...previous, maxOutputTokens: Number(event.target.value) }))} /></label><label>运行时间(分钟)<input aria-label="运行时间预算" type="number" min={0} value={settings.maxRunDurationMs / 60000} onChange={event => setSettings(previous => ({ ...previous, maxRunDurationMs: Number(event.target.value) * 60000 }))} /></label><label>单次运行 tokens<input aria-label="单次运行token预算" type="number" min={0} value={settings.maxRunTokens} onChange={event => setSettings(previous => ({ ...previous, maxRunTokens: Number(event.target.value) }))} /></label><label>任务累计 tokens<input aria-label="任务累计token预算" type="number" min={0} value={settings.maxTaskTokens} onChange={event => setSettings(previous => ({ ...previous, maxTaskTokens: Number(event.target.value) }))} /></label></div><p>默认透传不附加输出额度、不按本地上下文预算裁剪或拒发;上游限制与错误如实保留。累计 tokens 填 0 表示不限。手动开启限制仅影响后续运行。</p></details>}{anyRunning && <p className="form-warning">有任务在执行,请先停止任务再改变连接。</p>}<div className="modal-actions"><button type="button" className="button secondary" onClick={() => setSettingsOpen(false)}>取消</button><button type="submit" className="button primary" disabled={settingsBusy || anyRunning}><Check size={15} />保存并切换原连接</button></div></form></Modal>}
{diagnosticsOpen && <Modal title="运行诊断" description="查看工作台的模型连接、终端环境、最近错误和文件实际状态。" wide onClose={() => setDiagnosticsOpen(false)}><DiagnosticsPanel value={diagnostics} busy={diagnosticsBusy} onRefresh={() => openDiagnostics()} /></Modal>}
{reaOpen && session && selectedProject && <Modal title="REA 工件研究" description="原分析与同一项目、任务和运行绑定。" wide onClose={() => setReaOpen(false)}><ResearchPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} /></Modal>}
{engineOpen && session && selectedProject && <Modal title="本地代理引擎" description="本地安装、受控工程运行与原记录。" wide onClose={() => setEngineOpen(false)}><EnginePanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onNavigate={async (projectId, sessionId) => { setEngineOpen(false); await navigateWorkspace(projectId, sessionId); }} /></Modal>}
{researchOpen && <Modal title="机制研究与独立设计" description="从分发客户端的静态证据提炼产品机制。运行时与远端服务的未知部分在报告中说明。" wide onClose={() => setResearchOpen(false)}><div className="research-layout"><nav>{researchDocs.map(document => <button className={report?.title === document.title ? 'selected' : ''} key={document.id} onClick={() => loadReport(document.id)}><BookOpenText size={15} /><span><strong>{document.title}</strong><small>{document.description}</small></span></button>)}</nav><article className="research-document">{report && <ResearchContent content={report.content} />}</article></div></Modal>}
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} runModel={session?.execution?.run?.model} onConfig={(value, selection) => { setConfig(value); if (selection) setModelSelection(selection); }} onLegacy={() => { setModelCenterOpen(false); openSettings(); }} /></Modal>}
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} runModel={session?.execution?.run?.model} onConfig={(value, selection) => { setConfig(value); if (selection) setModelSelection(selection); }} /></Modal>}
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与决策绑定源码指纹,变化后自动要求重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel key={selectedProject.id + ':' + (session?.id ?? '')} project={selectedProject} session={session?.projectId === selectedProject.id ? session : null} /></Modal>}
{skillsOpen && selectedProject && <Modal title="项目技能" description="管理当前项目的技能来源、版本与启用状态。" wide onClose={() => setSkillsOpen(false)}><SkillCenter key={selectedProject.id} projectId={selectedProject.id} busy={isRunning} /></Modal>}
{mcpOpen && selectedProject && <Modal title="项目 MCP 工具" description="实际探测本地 stdio 服务,选择可以请求的工具,并核对每次运行原记录。" wide onClose={() => setMcpOpen(false)}><McpPanel key={selectedProject.id + ':' + (session?.id ?? '')} projectId={selectedProject.id} session={session?.projectId === selectedProject.id ? session : null} busy={isRunning} onSession={acceptSession} onError={session ? failureFor(session) : failure} /></Modal>}
+27 -25
View File
@@ -37,7 +37,7 @@ const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', m
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 };
export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig: (value: Config, selection?: ModelSelection) => void; onLegacy: () => void; busy: boolean; runModel?: ModelSnapshot }) {
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);
const [tab, setTab] = useState('connections');
@@ -63,12 +63,11 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
const [result, selection] = await Promise.all([api<Center>('/model-center'), api<{ config: Config; modelSelection: ModelSelection }>('/model-center/selection')]);
if (alive.current && marker === generation.current) { setView(result); setRuntimeConfig(selection.config); onConfig(selection.config, selection.modelSelection); }
}
function addConnection() { setTab('connections'); setDraft(initial); setKey(''); setPersistKey(false); setEditing(true); }
function addConnection() { setTab('connections'); setDraft(initial); setKey(''); setPersistKey(false); setCatalogSource(null); setNativeTarget(null); setEditing(true); }
async function selectRoute(value: string) {
await act(async () => {
if (value === 'demo') await api('/model-center/mode', { mode: 'demo' });
else { const [type, id] = value.split(':'); await api('/model-center/select', { type, id }); }
if (alive.current) setNotice(value === 'demo' ? '已切换到离线演示;已保存连接仍保留。' : '默认模型已更新;后续运行使用此选择,旧运行保留原记录。');
const [type, id] = value.split(':'); await api('/model-center/select', { type, id });
if (alive.current) setNotice('默认模型已更新;后续运行使用此选择,旧运行保留原记录。');
});
}
async function act(action: () => Promise<void>) {
@@ -93,11 +92,12 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
return () => { cancelAnimationFrame(frame); window.removeEventListener('resize', ensureVisible); };
}, [tab]);
const selected = view?.selected;
const connections = view?.connections.filter(value => value.id !== 'legacy-default' || value.model.trim()) ?? [];
const selectionName = selected?.type === 'pool' ? view?.pools.find(value => value.id === selected.id)?.name : view?.connections.find(value => value.id === selected?.id)?.name;
const locked = working || busy;
const passthrough = !runtimeConfig || runtimeConfig.executionMode === 'unrestricted' || runtimeConfig.capacityMode === 'passthrough';
return <section className="model-center" aria-label="模型控制台" aria-busy={working}>
<div className="mc-overview"><div><span className="mc-eyebrow">MODEL CONTROL</span><h2>选择模型,继续开发。</h2><p>连接、模型池和实际请求使用同一个入口。</p></div><div className="mc-current"><Route size={18} /><span>新任务默认<strong>{runtimeConfig?.mode === 'demo' ? '离线演示' : selectionName || '正在读取'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
<div className="mc-overview"><div><span className="mc-eyebrow">MODEL CONTROL</span><h2>选择模型,继续开发。</h2><p>连接、模型池和实际请求使用同一个入口。</p></div><div className="mc-current"><Route size={18} /><span>新任务默认<strong>{runtimeConfig?.mode === 'demo' ? '尚未选择' : selectionName || '正在读取'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
<nav ref={tabsRef} className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['network', '连接诊断', Activity], ['pools', '模型池', Layers3], ['budgets', '运行预算', Settings2], ['waits', '等待时限', Settings2], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['credentials', '凭据保存', KeyRound], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
const Symbol = Icon as typeof Server; return <button key={id as string} type="button" aria-current={tab === id ? 'page' : undefined} onClick={() => { setTab(id as string); setNotice(''); }}><Symbol size={16} />{title as string}</button>;
})}<button className="mc-refresh" type="button" disabled={working} onClick={() => void act(refresh)} aria-label="刷新模型中心"><RefreshCw size={16} /></button></nav>
@@ -106,12 +106,12 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <div className="mc-content">
<section className="mc-route-control" aria-label="默认模型选择">
<div className="mc-route-heading"><div><h3>新任务默认模型</h3><p>选择已保存的连接,或使用模型池调度。切换本身不请求模型。</p></div><button className="button secondary" disabled={locked} onClick={addConnection}><Plus size={15} />添加模型</button></div>
<label className="mc-route-select">当前选择<select aria-label="新任务默认模型" disabled={locked || !runtimeConfig} value={runtimeConfig?.mode === 'demo' ? 'demo' : selected?.type + ':' + selected?.id} onChange={event => void selectRoute(event.target.value)}>
<option value="demo">离线演示 · 固定脚本</option>
<optgroup label="模型连接">{view.connections.map(connection => <option key={connection.id} value={(connection.id === 'legacy-default' ? 'legacy' : 'connection') + ':' + connection.id} disabled={!connection.enabled || connection.requiresKey && !connection.hasKey}>{connection.name} · {connection.model || '尚未填写型号'}{connection.status !== 'configured' ? ' · ' + states[connection.status] : ''}</option>)}</optgroup>
<label className="mc-route-select">当前选择<select aria-label="新任务默认模型" disabled={locked || !runtimeConfig} value={runtimeConfig?.mode === 'demo' || !connections.some(value => value.id === selected?.id) && selected?.type !== 'pool' ? '' : selected?.type + ':' + selected?.id} onChange={event => void selectRoute(event.target.value)}>
<option value="" disabled>选择模型或添加连接</option>
<optgroup label="模型连接">{connections.map(connection => <option key={connection.id} value={(connection.id === 'legacy-default' ? 'legacy' : 'connection') + ':' + connection.id} disabled={!connection.enabled || connection.requiresKey && !connection.hasKey}>{connection.name} · {connection.model || '尚未填写型号'}{connection.status !== 'configured' ? ' · ' + states[connection.status] : ''}</option>)}</optgroup>
{!!view.pools.length && <optgroup label="模型池">{view.pools.map(pool => <option key={pool.id} value={'pool:' + pool.id}>{pool.name} · {pool.members.length} 个连接</option>)}</optgroup>}
</select></label>
<div className="mc-route-detail">{runtimeConfig?.mode === 'demo' ? '离线演示使用固定脚本,不调用大模型。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = view.connections.find(c => c.id === selected?.id); return connection ? `${protocolLabel(connection.protocol)} · ${previewUrl(connection)} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}</div>
<div className="mc-route-detail">{runtimeConfig?.mode === 'demo' ? '请从上游获取模型,或选择已配置的连接开始开发。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = connections.find(c => c.id === selected?.id); return connection ? `${protocolLabel(connection.protocol)} · ${previewUrl(connection)} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}</div>
{runModel && <div className="mc-run-model"><strong>当前会话最近运行</strong><span>{runModel.mode === 'demo' ? '离线演示' : runModel.routing?.members?.length ? runModel.routing.members.map(member => member.name + ' · ' + member.model).join(';') : runModel.model}</span><small>这是该次运行封存的请求配置;实际返回型号请看请求账本。更改默认选择不会改写旧记录。</small></div>}
</section>
{tab === 'budgets' && runtimeConfig && <ModelBudgetSettings key={JSON.stringify(runtimeConfig)} value={runtimeConfig} disabled={locked} onSave={input => void act(async () => { await api('/model-center/runtime-budgets', input); if (alive.current) setNotice('运行预算已保存,当前模型选择保持。'); })} />}
@@ -121,18 +121,19 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
})} />}
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>从上游获取目录并选择多个型号,可手动使用或加入自动适配模型池。</p></div><div className="mc-row-actions"><button className="button primary" disabled={locked} onClick={() => { setCatalogSource(''); setEditing(false); setNativeTarget(null); }}><Plus size={16} />从上游添加模型</button><button className="button secondary" disabled={locked} onClick={addConnection}>手动填写(兼容)</button></div></div>
{catalogSource !== null && <ModelCatalog key={catalogSource} sources={view.connections} sourceId={catalogSource} busy={locked} onSaved={refresh} onClose={() => setCatalogSource(null)} />}
<div className="mc-connections">{view.connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id}>
{catalogSource !== null && <ModelCatalog key={catalogSource} sources={connections} sourceId={catalogSource} busy={locked} onSaved={refresh} onClose={() => setCatalogSource(null)} />}
{!connections.length && catalogSource === null && !editing && <div className="mc-empty"><strong>还没有模型连接</strong><p>从上游获取可用型号,选择后即可开始开发。</p></div>}
<div className="mc-connections">{connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id} data-connection-id={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (view.connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
{value.upstreamModel && <p className="mc-help">型号来自上游目录,能力按目录声明与显式设置保存;可在“推理与能力”查看已接入范围。</p>}
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); setCatalogSource(null); setNativeTarget(null); }}>编辑</button>
<button className="button secondary" disabled={locked || !value.enabled} onClick={() => { setCatalogSource(value.credentialSource?.connectionId ?? value.id); setEditing(false); setNativeTarget(null); }}>获取同源模型</button>
<button className="button secondary" onClick={() => { setNetworkTarget(value.id); setTab('network'); }}>连接诊断</button>
{value.id !== 'legacy-default' && <button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>}
<button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option><option value="vision">合成图像识别</option></select></label>
<button className="button secondary" disabled={locked} onClick={() => { setNativeTarget(value); setEditing(false); }}>推理与能力</button><button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
@@ -165,24 +166,25 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked || persistKey && !key.trim()} type="submit">保存模型连接</button></div>
</form>}
</>}
{tab === 'network' && <ModelNetworkDiagnostics connections={view.connections} initialId={networkTarget || (selected?.type !== 'pool' ? selected?.id : undefined)} disabled={locked} />}
{tab === 'network' && <ModelNetworkDiagnostics connections={connections} initialId={networkTarget || (selected?.type !== 'pool' ? selected?.id : undefined)} disabled={locked} />}
{tab === 'credentials' && <section aria-label="本机加密凭据">
<div className="mc-section-title"><div><h3>本机加密凭据</h3><p>使用当前Windows用户加密。保存后的 Key 不会回显或包含在导出中。</p></div></div>
{!credentialView ? <p className="mc-empty">正在核对本机保存状态…</p> : <>
<p className="mc-help">只保存这次填写或确认导入的凭据。临时连接在宿主退出后需要重新填写。</p>
{credentialView.unavailable && <p className="mc-card-warning">原保存登记格式不可用;原数据保留,请核对后修复。</p>}
<form className="mc-editor" aria-label="保存加密凭据" onSubmit={event => { event.preventDefault(); void act(async () => {
const target = view.connections.find(value => value.id === (credentialTarget || view.connections[0]?.id));
{!connections.length && <p className="mc-empty">请先添加模型连接,再管理凭据。</p>}
{!!connections.length && <form className="mc-editor" aria-label="保存加密凭据" onSubmit={event => { event.preventDefault(); void act(async () => {
const target = connections.find(value => value.id === (credentialTarget || connections[0]?.id));
if (!target) return;
const result = await api<{ config: Config }>('/model-center/credentials', { id: target.id, revision: target.revision, action: 'save', apiKey: credentialKey });
if (alive.current) { setCredentialKey(''); setNotice('本机加密凭据已保存;宿主重启后按原连接身份加载。'); onConfig(result.config); }
}); }}>
<div className="mc-form-grid"><label>选择保存连接<select aria-label="选择保存连接" value={credentialTarget || view.connections[0]?.id || ''} onChange={event => { setCredentialTarget(event.target.value); setCredentialKey(''); }}>{view.connections.filter(value => !value.credentialSource).map(value => <option key={value.id} value={value.id}>{value.name} · {value.model || '未填写模型'}</option>)}</select></label>
<div className="mc-form-grid"><label>选择保存连接<select aria-label="选择保存连接" value={credentialTarget || connections[0]?.id || ''} onChange={event => { setCredentialTarget(event.target.value); setCredentialKey(''); }}>{connections.filter(value => !value.credentialSource).map(value => <option key={value.id} value={value.id}>{value.name} · {value.model || '未填写模型'}</option>)}</select></label>
<label>重新填写 API Key<input type="password" autoComplete="off" value={credentialKey} onChange={event => setCredentialKey(event.target.value)} /></label></div>
<p className="mc-help">只保存这次新填的凭据。不同用户、目录或连接配置无法加载原保存块。</p>
<div className="mc-actions"><button type="submit" className="button primary" disabled={locked || !credentialView.supported || credentialView.unavailable || !credentialKey.trim()}>加密保存凭据</button></div>
</form>
<div className="mc-connections">{credentialView.connections.map(value => <article className="mc-connection" key={value.id}>
</form>}
<div className="mc-connections">{credentialView.connections.filter(value => connections.some(connection => connection.id === value.id)).map(value => <article className="mc-connection" key={value.id}>
<div className="mc-card-heading"><KeyRound size={20} /><div><h4>{value.name}</h4><span>{savedStates[value.status] || value.status}</span></div></div>
<p className="mc-help">{value.message}</p>{value.savedAt && <p className="mc-help">保存于 {new Date(value.savedAt).toLocaleString()}</p>}
<div className="mc-actions">{value.status !== 'not_saved' && value.status !== 'reference' && <>
@@ -196,12 +198,12 @@ export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig:
</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}>{view.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>)}
{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>
<fieldset><legend>模型池成员与权重</legend>{view.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>
<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>}
</>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{view.connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{<ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />}{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={working} onClick={() => void act(async () => { await 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 + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{<ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />}{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={working} onClick={() => void act(async () => { await 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 + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
+1 -1
View File
@@ -7,7 +7,7 @@ export function ModelWaitSettings({ value, disabled, onSave }: { value: WaitSett
const [idleSeconds, setIdleSeconds] = useState(value.modelStreamIdleTimeoutMs / 1000);
return <form className="mc-editor" aria-label="模型等待时限" onSubmit={event => { event.preventDefault(); onSave({ modelResponseTimeoutMs: responseSeconds * 1000, modelStreamIdleTimeoutMs: idleSeconds * 1000 }); }}>
<h3>模型等待时间</h3>
<p>适用于原模型连接及模型池内的每次请求;从下一次运行生效。保存只调整等待时限,保留当前模型池和连接。</p>
<p>适用于所有模型连接及模型池内的每次请求;从下一次运行生效。保存只调整等待时限,保留当前模型池和连接。</p>
<div className="mc-form-grid">
<label>单次模型响应上限(秒)<input aria-label="单次模型响应上限(秒)" type="number" min={0} step={1} required value={responseSeconds} disabled={disabled} onChange={event => setResponseSeconds(Number(event.target.value))} /><small>默认 0=不限,包含服务排队与生成;可自行填写等待秒数。</small></label>
<label>流式无数据上限(秒)<input aria-label="流式无数据上限(秒)" type="number" min={0} step={1} required value={idleSeconds} disabled={disabled} onChange={event => setIdleSeconds(Number(event.target.value))} /><small>默认 0=不限。可设置开始流式响应后连续没有新数据的等待秒数。</small></label>
+20 -12
View File
@@ -87,9 +87,10 @@ export class ModelHub {
}
saveAttempts() { if (!unrestricted(this.store)) this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); }
connections() {
return [{ id: legacyId, name: '原模型连接', brand: '兼容服务', protocol: 'chat-completions', baseUrl: this.store.config.baseUrl,
model: this.store.config.model, enabled: true, requiresKey: false, revision: this.store.config.configRevision ?? 1,
contextLimit: this.store.config.contextLimit, maxOutputTokens: this.store.config.maxOutputTokens, concurrency: 1, source: 'legacy',
const saved = this.state.legacyConnection;
return [{ ...saved, id: legacyId, name: saved?.name || this.store.config.model || '未配置模型', brand: saved?.brand || '自定义', protocol: saved?.protocol || 'chat-completions', baseUrl: this.store.config.baseUrl,
model: this.store.config.model, enabled: saved?.enabled !== false, requiresKey: saved?.requiresKey === true, revision: this.store.config.configRevision ?? 1,
contextLimit: this.store.config.contextLimit, maxOutputTokens: this.store.config.maxOutputTokens, concurrency: saved?.concurrency ?? 1, source: 'legacy',
...(this.store.config.parameterProfile ? { parameterProfile: this.store.config.parameterProfile } : {}),
...(this.store.config.nativeParameters ? { nativeParameters: this.store.config.nativeParameters, outputTokenField: this.store.config.outputTokenField } : {}) }, ...this.state.connections];
}
@@ -149,7 +150,7 @@ export class ModelHub {
const selected = this.state.selected;
const name = selected.type === 'pool' ? this.state.pools.find(value => value.id === selected.id)?.name
: this.connections().find(value => value.id === selected.id)?.name;
return { ...selected, name: name ?? '原模型连接' };
return { ...selected, name: name ?? '选择模型' };
}
networkDiagnostics() { return this.networkChecks ??= new NetworkDiagnostics(this); }
modelCatalog() { return this.catalog ??= new ModelCatalog(this); }
@@ -201,8 +202,6 @@ export class ModelHub {
} finally { this.probing = false; }
}
upsert(input) {
if (!this.editingRegistry) return this.editRegistry(() => this.upsert(input));
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
const previous = input.id ? this.connection(input.id) : null;
if (!unrestricted(this.store) && this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
@@ -232,10 +231,19 @@ export class ModelHub {
if (Object.hasOwn(input, 'apiKey')) {
if (typeof input.apiKey !== 'string' || input.apiKey.length > 16000) throw error('模型凭据格式无效。');
}
this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
const legacy = connection.id === legacyId;
if (!this.editingRegistry) return this.editRegistry(() => this.upsert(input), legacy ? {
baseUrl: connection.baseUrl, model: connection.model, contextLimit: connection.contextLimit, maxOutputTokens: connection.maxOutputTokens,
...(native ?? {}),
} : null);
if (legacy) this.state.legacyConnection = connection;
else this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
this.save();
if (Object.hasOwn(input, 'apiKey')) this.provider.credentials.set(connection.id, { key: input.apiKey.trim(),
revision: Math.max(this.credential(previous ?? connection)?.revision ?? 0, this.provider.credentials.get(connection.id)?.revision ?? 0) + 1 });
if (Object.hasOwn(input, 'apiKey')) {
const revision = Math.max(this.credential(previous ?? connection)?.revision ?? 0, this.provider.credentials.get(connection.id)?.revision ?? 0) + 1;
if (legacy) { this.provider.setKey(input.apiKey); this.provider.legacyCredentialRevision = revision; }
else this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision });
}
if (input.persistKey === true) {
const vault = this.vault(), record = vault.prepare(connection, input.apiKey, this.credential(connection)?.revision ?? 1);
vault.stage(connection.id, record);
@@ -246,12 +254,12 @@ export class ModelHub {
const connection = this.connection(input.id);
if (connection.revision !== input.revision) throw error('连接已变化,请刷新后核对原生参数。', 409);
const settings = nativeParameterSettings(connection.protocol, input.nativeParameters, input.outputTokenField, input.parameterProfile ?? connection.parameterProfile, this.store.config);
if (connection.id === legacyId) this.save(settings);
if (connection.id === legacyId && !this.state.legacyConnection) this.save(settings);
else this.upsert({ ...connection, ...settings });
return { center: this.view(), config: { ...this.store.config, hasKey: this.provider.hasKey() } };
}
toggle(id, enabled) {
if (id === legacyId) throw error('原连接不能停用,请选择离线演示或其他连接。');
if (id === legacyId) return this.upsert({ ...this.connection(id), enabled: enabled === true });
const value = this.connection(id); value.enabled = enabled === true; value.revision++; value.updatedAt = stamp(); this.save(); return this.status(value);
}
pool(input) {
@@ -282,7 +290,7 @@ export class ModelHub {
return this.view();
}
prepare(config, selection = this.state.selected) {
if (config.mode === 'demo' || selection.type === 'legacy') return config;
if (config.mode === 'demo' || selection.type === 'legacy' && !this.state.legacyConnection) return config;
if (this.catalog?.active.size) throw error('正在获取上游模型目录,请等待完成或取消。', 409);
const pool = selection.type === 'pool' ? this.state.pools.find(value => value.id === selection.id) : null;
if (selection.type === 'pool' && !pool) throw error('选中的模型池不存在。');
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.25.6';
export const APP_VERSION = '1.25.7';
export function executionEnvironment() {
const windows = process.platform === 'win32';
@@ -0,0 +1,68 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fixture, compatibleFixture } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
test('existing connection uses the common editor contract without switching the selected pool or replacing its credential', t => {
const f = fixture(t, { modernDefaults: true }), provider = new Provider(); provider.setKey('owned-existing-key');
f.store.saveConfig({ mode: 'compatible', baseUrl: 'http://127.0.0.1:12340/v1', model: 'existing-model' });
const hub = provider.modelHub(f.store), original = hub.connection('legacy-default');
assert.equal(original.name, 'existing-model');
const second = hub.upsert({ name: 'Other', model: 'other', baseUrl: 'http://127.0.0.1:12341/v1', requiresKey: false });
const pool = hub.pool({ name: 'Current pool', members: [{ connectionId: second.id }] });
hub.select({ type: 'pool', id: pool.id });
const before = structuredClone(hub.state.selected), revision = hub.connection(original.id).revision;
const saved = hub.upsert({ ...hub.connection(original.id), name: 'My upstream', model: 'updated-model', requiresKey: true, concurrency: 0 });
assert.equal(saved.id, original.id); assert.equal(saved.revision, revision + 1);
assert.equal(saved.name, 'My upstream'); assert.equal(saved.hasKey, true);
assert.equal(provider.apiKey, 'owned-existing-key'); assert.equal(provider.legacyCredentialRevision, undefined);
assert.deepEqual(hub.state.selected, before); assert.equal(f.store.config.model, 'updated-model');
assert.equal(hub.connections().filter(value => value.id === original.id).length, 1);
assert.throws(() => hub.upsert({ ...original, name: 'Stale edit' }), { status: 409 });
assert.equal(JSON.stringify(hub.view()).includes('owned-existing-key'), false);
assert.equal(JSON.stringify(f.store.storage.meta('modelRegistry')).includes('owned-existing-key'), false);
f.store.close();
const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
const restored = new Provider().modelHub(reopened);
assert.equal(restored.connection(original.id).name, 'My upstream');
assert.equal(restored.connection(original.id).concurrency, 0);
assert.deepEqual(restored.state.selected, before);
});
test('existing connection saves protocol, reasoning and identity settings and sends them using its unchanged credential', async t => {
const f = fixture(t, { modernDefaults: true }), provider = new Provider(); provider.setKey('owned-retained-key');
const server = await compatibleFixture(t, () => ({ body: { id: 'owned-response', model: 'owned-response-model', status: 'completed',
output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'Complete.' }] }],
usage: { input_tokens: 12, output_tokens: 3, total_tokens: 15 } } }));
f.store.saveConfig({ mode: 'compatible', baseUrl: server.baseUrl, model: 'owned-response-model' });
const hub = provider.modelHub(f.store), saved = hub.upsert({ ...hub.connection('legacy-default'), name: 'Responses service',
protocol: 'responses', requiresKey: true, nativeParameters: { reasoning: { effort: 'high' } }, parameterProfile: 'openai', modelIdentityPolicy: 'require-match' });
assert.equal(hub.selectionView().name, 'Responses service');
const config = provider.prepareConfig(f.store.config, f.store);
assert.equal(config.protocol, 'responses'); assert.equal(config.modelRouting.members[0].modelIdentityPolicy, 'require-match');
const result = await provider.complete(config, [{ role: 'user', content: 'Reply.' }], f.project, undefined, undefined, null, []);
assert.equal(result.message.content, 'Complete.'); assert.equal(server.requests.length, 1);
assert.equal(server.requests[0].url, '/v1/responses');
assert.equal(server.requests[0].headers.authorization, 'Bearer owned-retained-key');
assert.deepEqual(server.requests[0].input.reasoning, { effort: 'high' });
assert.equal(Object.hasOwn(server.requests[0].input, 'max_output_tokens'), false);
assert.equal(hub.toggle(saved.id, false).enabled, false);
assert.throws(() => provider.prepareConfig(f.store.config, f.store), /没有可用模型连接/);
assert.equal(hub.toggle(saved.id, true).enabled, true);
assert.equal(provider.apiKey, 'owned-retained-key');
});
test('failed common-editor save atomically restores existing metadata, configuration and credential', t => {
const f = fixture(t), provider = new Provider(); provider.setKey('owned-before-failure');
f.store.saveConfig({ mode: 'compatible', baseUrl: 'http://127.0.0.1:12340/v1', model: 'before' });
const hub = provider.modelHub(f.store), before = structuredClone({ config: f.store.config, state: hub.state });
const persist = f.store.storage.setMeta.bind(f.store.storage);
f.store.storage.setMeta = (key, value) => { if (key === 'config') throw new Error('owned config commit failure'); return persist(key, value); };
try { assert.throws(() => hub.upsert({ ...hub.connection('legacy-default'), name: 'After', model: 'after', apiKey: 'owned-after-failure' }), /owned config commit failure/); }
finally { f.store.storage.setMeta = persist; }
assert.deepEqual(f.store.config, before.config); assert.deepEqual(hub.state, before.state);
assert.equal(provider.apiKey, 'owned-before-failure'); assert.equal(provider.legacyCredentialRevision, undefined);
assert.equal(f.store.storage.meta('config').model, 'before');
assert.equal(f.store.storage.meta('modelRegistry', null), null);
});