feat: add model center and pool routing
This commit is contained in:
+15
@@ -323,3 +323,18 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
|
||||
- 持续SSE应用无法用networkidle作为页面就绪条件,正式smoke使用实际bootstrap、连接文字和计划占位符消失;1280px/390px通过且没有写请求。两次等待错误如实保留,未将验证器竞争条件当作产品故障。
|
||||
- 本轮真实模型请求为0,原Task续接按用户选择另行验收;公开hasKey=true不等于模型调用已通过。后续模型池必须分清“有凭据”“连通”“能力验证”“任务成功”,界面状态来自各自证据。
|
||||
- 证据副本的原CRLF散列不能直接当作Git中LF副本的散列。发行身份同时记录原副本散列及LF保存副本散列,检出/索引都按保存字节核验;原阶段日志无需更改。
|
||||
|
||||
# 1.12开发接续发现(2026-10-30)
|
||||
|
||||
- 开发树中已有未提交的模型注册、池路由、导入器、巡检API和模型中心UI实现;先审查并验证现有改动,不重复覆盖。
|
||||
- 真实模型凭据只驻留Provider内存,公开连接状态只返回hasKey/credentialRevision;SQLite保存的模型尝试账本保存请求SHA256和已脱敏请求工件引用,不保存API Key。宿主重启将仍为running的请求标记unknown,不自动重放。
|
||||
- 模型池通过真实HTTP夹具已覆盖429故障切换、轮询/权重、停用、401凭据阻断、排队取消、租约释放、Run归属与请求工件散列;当前六项模型中心测试已通过。
|
||||
- 首次304项全量运行302通过/2失败。两项失败由测试未注入固定QA解释器而使pytest不可用导致;系统默认命令中Node 16先于Node 24。固定Node `D:\Ai-project\REA逆向\tools\node-v24.22.1-win-x64\node.exe`和隔离Python 3.10.11/pytest 8.4.2后再执行最终回归。
|
||||
- 现有CCSwitch导入器只读SQLite的已确认表列,限制100条、只接受解析后`wire_api=chat`的Codex配置;Responses/Anthropic/未知格式只报告兼容边界。WorkBuddy尚无本地已验证schema,界面必须如实显示未支持,不猜测导入其登录态。
|
||||
|
||||
## 2026-10-30 1.12切片验证结论
|
||||
|
||||
- 模型池首次429断言把“Retry-After=2秒”错误写成“测试结束时仍未过期”;产品实际已记录准确冷却截止时间。断言改为核对`lastFailureAt + retryAfterMs`,并新增用户停止不创建故障冷却的检查。
|
||||
- `ConfigImporter.apply` 保留既有来源自动同步偏好;同步只在来源指纹变化时导入,来源不变也更新`lastCheckedAt`。手动修改后的连接不被自动同步覆盖,并报告冲突;凭据始终只写入Provider内存。
|
||||
- 独立UI验收的可访问标签在原页面使用自定义label结构,模型池/连接操作按实际DOM定位;桌面1440px和手机390px截图均核对无横向溢出。巡检报告明确`modelRequests=0`。
|
||||
- 1.12代码仍未作为不可变发行部署;真实模型、WorkBuddy schema、加密凭据、多模态和移动远程配对属于后续切片,不能从本地夹具通过推断完成。
|
||||
|
||||
+2
-1
@@ -20,7 +20,8 @@
|
||||
"package": "node scripts/package.mjs",
|
||||
"verify:browser": "node scripts/verify-browser.mjs",
|
||||
"verify:browser-ui": "node scripts/verify-browser-ui.mjs",
|
||||
"verify:task-plans": "node scripts/verify-task-plans-ui.mjs"
|
||||
"verify:task-plans": "node scripts/verify-task-plans-ui.mjs",
|
||||
"verify:model-center": "node scripts/verify-model-center-ui.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
|
||||
+14
@@ -366,3 +366,17 @@
|
||||
- 正式Edge1280px/390px只读smoke通过,0页面/请求异常、0写入;截图目视核对,smoke后数据库散列仍一致。SSE阻止networkidle和计划异步返回前断言的两次验证脚本失败独立保留,未改产品逻辑。
|
||||
- 完整结果、最终原TAP、日志散列、部署及当前真实模型待验状态写入docs/task-plans-*与QA-1.11;接下来按独立切片规划专业UI、连接注册/模型池及运行巡检。
|
||||
- 1.12详细方案已建立:先连接注册与专业控制台,再模型池/故障恢复、已验证配置导入和运行巡检;明确凭据状态、Run绑定、冷却/租约/预算/未知结果与不重放工具。多模态、Skills/MCP、记忆/缓存、多worker、桌面/手机及自我迭代均写明依赖与首个验收切片,没有计入1.11。
|
||||
|
||||
## 2026-10-30 1.12实现与全量回归
|
||||
|
||||
- 接续现有开发树的模型中心/API/路由改动;未读取正式服务凭据或数据,也未发起真实模型请求。正式4318仍由不可变1.11服务负责。
|
||||
- 首轮固定Node24的全量回归304项中302项通过、2项因未注入pytest解释器失败;模型中心六项专项(包括重启后临时Key清空)通过。系统PATH先解析Node16,项目已有隔离Python位于 `.qa/python-qa-1.7.0`,已确认pytest 8.4.2可用。
|
||||
- 后续完整复验必须显式固定Node24和 `AGENT_WORKBENCH_TEST_PYTHON`;不得把首次环境失败覆盖为产品通过。
|
||||
|
||||
## 2026-10-30 1.12-A/B/C/D本地切片完成
|
||||
|
||||
- 模型中心实现已完成:连接增改/启停/选择、临时内存凭据、模型与协议状态、模型池轮询/权重/运行内粘连、并发租约、失败冷却、429 Retry-After、401凭据阻断、停止释放和请求账本。模型请求工件仅保存脱敏请求体及SHA256;宿主重启把运行中的请求标为unknown,不自动重放。
|
||||
- 配置导入已完成:只读已验证CCSwitch SQLite表与工作台schema:1 JSON;预览指纹、来源变化拒绝、导入冲突保护、显式启用/关闭自动同步和每分钟本地同步。WorkBuddy当前如实显示未取得固定schema,不读取其登录态。
|
||||
- 本地巡检只读检查Node、SQLite、最近工件和模型配置,不发送模型请求、不执行项目命令;前端专业模型中心覆盖桌面和390px窄屏。
|
||||
- 固定Node `v24.22.1`并设置隔离Python `3.10.11/pytest 8.4.2`后完整回归 **305/305通过**;最终构建通过。模型中心专项7/7通过;独立桌面/390px验收5组通过,0页面错误、0请求失败、0巡检模型请求。证据目录:`.qa/model-center-ui-69ae2c90-cd8d-461f-86ca-d598f56ce15e`。
|
||||
- 首轮304项的2项pytest失败是环境未注入解释器,已原样保留;本轮不覆盖该诊断。正式4318未重启、不读取Key、不发真实模型请求。
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { chromium, expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench } from '../tests/helpers.mjs';
|
||||
|
||||
if (process.argv.includes('--help')) { console.log('node scripts/verify-model-center-ui.mjs — isolated model connections, pool, import preview, local inspection and 390px layout'); process.exit(0); }
|
||||
const evidenceDir = path.resolve('.qa', 'model-center-ui-' + randomUUID()); fs.mkdirSync(evidenceDir, { recursive: true });
|
||||
const disposers = [], t = { after: dispose => disposers.push(dispose) };
|
||||
const f = fixture(t); f.store.close();
|
||||
const importFile = path.join(evidenceDir, 'owned-import.json');
|
||||
fs.writeFileSync(importFile, JSON.stringify({ schema: 1, connections: [{ name: 'Imported Fixture', brand: '自定义', model: 'fixture-imported',
|
||||
baseUrl: 'http://127.0.0.1:9/v1', apiKey: 'ui-owned-import-key' }] }));
|
||||
const host = await launchWorkbench(t, f.data);
|
||||
assert.notEqual(new URL(host.url).port, '4318'); assert.equal(host.bootstrap.config.hasKey, false);
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const pageErrors = [], requestFailures = [], marks = [];
|
||||
page.on('pageerror', error => pageErrors.push(error.message));
|
||||
page.on('requestfailed', request => requestFailures.push(request.url() + ': ' + request.failure()?.errorText));
|
||||
const mark = value => { marks.push(value); console.log('PASS ' + value); };
|
||||
try {
|
||||
await page.goto(host.url); await page.waitForLoadState('networkidle');
|
||||
await page.getByRole('button', { name: '打开模型中心', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: '模型中心', exact: true }); await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '添加连接', exact: true }).click();
|
||||
const editor = dialog.getByRole('form', { name: '编辑模型连接', exact: true });
|
||||
await editor.getByLabel('连接名称', { exact: true }).fill('Fixture Primary');
|
||||
await editor.getByLabel('接口根地址', { exact: true }).fill('http://127.0.0.1:9/v1');
|
||||
await editor.getByLabel('实际模型名称', { exact: true }).fill('fixture-primary');
|
||||
await editor.getByLabel('临时 API Key', { exact: true }).fill('ui-owned-primary-key');
|
||||
await editor.getByRole('button', { name: '保存模型连接', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-connection').filter({ hasText: 'Fixture Primary' })).toContainText('已设置,重启需重新填写');
|
||||
assert.equal(JSON.stringify(await host.api('/model-center')).includes('ui-owned-primary-key'), false);
|
||||
assert.equal((await host.api('/model-center')).connections.find(value => value.name === 'Fixture Primary').hasKey, true);
|
||||
mark('connection form stores only the volatile credential and renders configured status without exposing it');
|
||||
|
||||
await dialog.getByRole('button', { name: '添加连接', exact: true }).click();
|
||||
const second = dialog.getByRole('form', { name: '编辑模型连接', exact: true });
|
||||
await second.getByLabel('连接名称', { exact: true }).fill('Fixture Reserve');
|
||||
await second.getByLabel('接口根地址', { exact: true }).fill('http://127.0.0.1:9/v1');
|
||||
await second.getByLabel('实际模型名称', { exact: true }).fill('fixture-reserve');
|
||||
await second.getByRole('button', { name: '保存模型连接', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '模型池', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '新建模型池', exact: true }).click();
|
||||
const poolForm = dialog.getByRole('form', { name: '编辑模型池', exact: true });
|
||||
await poolForm.getByLabel('模型池名称', { exact: true }).fill('Fixture failover pool');
|
||||
await poolForm.locator('.mc-member-choice').filter({ hasText: 'Fixture Primary' }).locator('input[type=checkbox]').check();
|
||||
await poolForm.locator('.mc-member-choice').filter({ hasText: 'Fixture Reserve' }).locator('input[type=checkbox]').check();
|
||||
await poolForm.getByLabel('Fixture Primary权重', { exact: true }).fill('2');
|
||||
await poolForm.getByRole('button', { name: '保存模型池', exact: true }).click();
|
||||
const poolCard = dialog.locator('.mc-pool').filter({ hasText: 'Fixture failover pool' }); await expect(poolCard).toContainText('2 个成员');
|
||||
await poolCard.getByRole('button', { name: '使用此模型池', exact: true }).click();
|
||||
const center = await host.api('/model-center'); assert.equal(center.selected.type, 'pool');
|
||||
assert.equal(center.pools.find(value => value.id === center.selected.id).members.length, 2);
|
||||
mark('pool editor saves weighted members and binds selection for new Runs');
|
||||
|
||||
await dialog.getByRole('button', { name: '配置导入', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-tabs button[aria-current]')).toContainText('配置导入');
|
||||
await dialog.locator('.mc-content select').selectOption('workbench-json');
|
||||
await dialog.getByLabel('本地文件路径', { exact: true }).fill(importFile);
|
||||
await dialog.getByRole('button', { name: '预览可导入连接', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-editor').filter({ hasText: '本次预览' })).toContainText('Imported Fixture');
|
||||
assert.equal((await page.locator('body').innerText()).includes('ui-owned-import-key'), false);
|
||||
await dialog.getByRole('button', { name: '导入这些连接', exact: true }).click();
|
||||
assert.ok((await host.api('/model-center')).connections.some(value => value.name === 'Imported Fixture'));
|
||||
const sourceCard = dialog.locator('.mc-import-source').filter({ hasText: 'workbench-json' });
|
||||
await sourceCard.getByRole('button', { name: '启用自动同步', exact: true }).click();
|
||||
let view = await host.api('/model-center'); assert.equal(view.imports[0].enabled, true);
|
||||
fs.writeFileSync(importFile, JSON.stringify({ schema: 1, connections: [{ name: 'Imported Fixture', brand: '自定义', model: 'fixture-imported-v2',
|
||||
baseUrl: 'http://127.0.0.1:9/v1', apiKey: 'ui-owned-import-key' }] }));
|
||||
await dialog.getByRole('button', { name: '立即同步已启用来源', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-notice')).toContainText('更新 1 项');
|
||||
view = await host.api('/model-center'); assert.equal(view.connections.find(value => value.name === 'Imported Fixture').model, 'fixture-imported-v2');
|
||||
await sourceCard.getByRole('button', { name: '关闭自动同步', exact: true }).click();
|
||||
assert.equal((await host.api('/model-center')).imports[0].enabled, false);
|
||||
assert.equal(JSON.stringify(view).includes('ui-owned-import-key'), false);
|
||||
mark('schema-bound import preview, opt-in automatic sync, revision update and sync shutdown keep credentials hidden');
|
||||
|
||||
await dialog.getByRole('button', { name: '运行巡检', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '开始本地巡检', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-checks')).toContainText('SQLite quick_check通过');
|
||||
const operations = await host.api('/operations'); assert.equal(operations.modelRequests, 0);
|
||||
await page.screenshot({ path: path.join(evidenceDir, 'desktop-operations.png'), fullPage: false });
|
||||
mark('local inspection shows real database and artifact checks and emits zero model requests');
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390), '390px viewport must not overflow horizontally');
|
||||
await page.screenshot({ path: path.join(evidenceDir, 'mobile-operations.png'), fullPage: false });
|
||||
await dialog.getByRole('button', { name: '模型连接', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-connection').filter({ hasText: 'Fixture Primary' })).toBeVisible();
|
||||
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390), '390px connections must not overflow horizontally');
|
||||
await page.screenshot({ path: path.join(evidenceDir, 'mobile-connections.png'), fullPage: false });
|
||||
mark('390px model-center modal and connection cards remain operable without horizontal page overflow');
|
||||
|
||||
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
|
||||
const report = { url: host.url, viewportWidths: [1440, 390], assertions: marks, pageErrors, requestFailures,
|
||||
modelRequests: operations.modelRequests, screenshots: ['desktop-operations.png', 'mobile-operations.png', 'mobile-connections.png'] };
|
||||
fs.writeFileSync(path.join(evidenceDir, 'result.json'), JSON.stringify(report, null, 2));
|
||||
console.log('EVIDENCE ' + evidenceDir);
|
||||
} finally {
|
||||
await browser.close();
|
||||
for (const dispose of disposers.reverse()) await dispose();
|
||||
}
|
||||
+5
-2
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Activity, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Search, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
|
||||
import { Activity, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
|
||||
import type { Bootstrap, Change, Config, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
|
||||
import { api, downloadBlob, exportSession, setToken } from './api';
|
||||
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard } from './components';
|
||||
@@ -9,6 +9,7 @@ import { CodeIndexPanel } from './CodeIndexPanel';
|
||||
import { ChangesInspector } from './ChangesInspector';
|
||||
import { ResearchPanel } from './ResearchPanel';
|
||||
import { EnginePanel } from './EnginePanel';
|
||||
import { ModelCenter } from './ModelCenter';
|
||||
|
||||
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
||||
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000 };
|
||||
@@ -64,6 +65,7 @@ export default function App() {
|
||||
const [researchOpen, setResearchOpen] = useState(false);
|
||||
const [reaOpen, setReaOpen] = useState(false);
|
||||
const [engineOpen, setEngineOpen] = useState(false);
|
||||
const [modelCenterOpen, setModelCenterOpen] = useState(false);
|
||||
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
||||
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
|
||||
const chatEnd = useRef<HTMLDivElement>(null);
|
||||
@@ -502,7 +504,7 @@ export default function App() {
|
||||
</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>
|
||||
<button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button>
|
||||
<div className="model-launch"><button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : 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>
|
||||
@@ -549,6 +551,7 @@ export default function App() {
|
||||
{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} /></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} onConfig={setConfig} onLegacy={() => { setModelCenterOpen(false); openSettings(); }} /></Modal>}
|
||||
{toast && <div className="toast" role="status"><span>{toast}</span><IconButton label="关闭提示" onClick={() => setToast('')}><X size={14} /></IconButton></div>}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
.modal:has(.model-center){width:min(1260px,calc(100vw - 48px));max-width:none;height:min(900px,calc(100dvh - 48px));display:flex;flex-direction:column;padding:0;overflow:hidden}.modal:has(.model-center)>.modal-header{padding:20px 28px 16px;border-bottom:1px solid #cbd5df;flex-shrink:0}.modal:has(.model-center)>.modal-body{padding:0;display:flex;min-height:0;overflow:hidden;flex:1}
|
||||
.model-center{display:flex;flex-direction:column;width:100%;min-width:0;min-height:0;color:#15283f;background:#f1f4f7;font-size:13px}.mc-overview{padding:25px 28px;display:flex;align-items:center;gap:25px;background:#e7edf2;border-bottom:1px solid #cbd5df;flex-shrink:0}.mc-eyebrow{font-family:Bahnschrift,sans-serif;letter-spacing:.13em;font-size:10px;font-weight:650;color:#526782}.mc-overview h2{font-size:25px;font-weight:650;letter-spacing:-.04em;margin:8px 0;line-height:1.3}.mc-overview p,.mc-section-title p{color:#52647a;font-size:12px;line-height:1.7}.mc-current{margin-left:auto;display:flex;gap:12px;align-items:center;padding:14px 18px;background:#fff;border:1px solid #c2d0dd;border-radius:8px;min-width:220px}.mc-current>span{font-size:11px;color:#62728a}.mc-current strong{display:block;font-size:14px;color:#15283f;margin-top:3px;overflow-wrap:anywhere}.mc-current .mc-count{margin-left:auto;white-space:nowrap}
|
||||
.mc-tabs{display:flex;gap:4px;padding:0 24px;flex-shrink:0;border-bottom:1px solid #cbd5df;background:white;overflow-x:auto}.mc-tabs button{display:flex;align-items:center;gap:8px;white-space:nowrap;min-height:49px;padding:12px 15px;border-bottom:3px solid transparent;color:#53647c;font-weight:600}.mc-tabs button[aria-current]{color:#215b96;border-bottom-color:#2560a3}.mc-tabs button:hover{background:#edf2f7}.mc-tabs .mc-refresh{margin-left:auto;padding:12px}.mc-content{padding:24px 28px 32px;overflow:auto;min-height:0;flex:1;scrollbar-gutter:stable}.mc-section-title{display:flex;gap:20px;align-items:center;justify-content:space-between;margin-bottom:20px}.mc-section-title h3{font-size:17px;margin-bottom:5px}.mc-section-title>.button{flex-shrink:0}.mc-notice{padding:12px 28px;line-height:1.7;border-bottom:1px solid #e0b777;color:#734c1c;background:#fff5df;overflow-wrap:anywhere;flex-shrink:0}
|
||||
.mc-connections{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.mc-connection{background:white;border:1px solid #c7d3de;border-radius:9px;padding:19px;min-width:0;box-shadow:0 2px 5px #15283f06}.mc-card-heading{display:flex;gap:12px;align-items:center;margin-bottom:18px}.mc-card-heading>div{min-width:0;flex:1}.mc-card-heading h4{font-size:15px;overflow-wrap:anywhere}.mc-card-heading>div>span{font-size:11px;color:#62728a;display:block;margin-top:4px}.mc-service-icon{display:grid;place-items:center;flex-shrink:0;border:1px solid #b9c9d8;border-radius:7px;width:41px;height:41px;color:#2560a3;background:#edf3fa}.mc-state{display:inline-flex;padding:4px 7px;border-radius:4px;font-size:11px;font-weight:600;background:#e9eef3;color:#4a5d74;white-space:nowrap;border:1px solid #d1dbe4}.mc-state-completed,.mc-state-passed{color:#216d5f;background:#e6f3ee;border-color:#b9d9cb}.mc-state-configured{color:#255d91;background:#edf4fd;border-color:#bcd0e7}.mc-state-failed,.mc-state-needs_attention{color:#a7353e;background:#fff0f0;border-color:#e8bac0}.mc-state-needs_key,.mc-state-cooling,.mc-state-unknown,.mc-state-attention{color:#8b5c12;background:#fff4d9;border-color:#e6d09d}.mc-connection dl{display:grid;grid-template-columns:86px minmax(0,1fr);gap:10px 7px;margin:0}.mc-connection dt{color:#67788d;font-size:11px}.mc-connection dd{margin:0;overflow-wrap:anywhere;font-size:12px;line-height:1.5;font-family:"Cascadia Code",Consolas,"Microsoft YaHei",monospace}.mc-capabilities{display:flex;flex-wrap:wrap;gap:6px;margin-top:17px}.mc-capabilities span{padding:4px 6px;color:#61738b;border:1px solid #d7e0e9;border-radius:4px;font-size:10px}.mc-connection footer{border-top:1px solid #e0e6ec;padding-top:14px;margin-top:15px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}.mc-icon-action{display:flex;gap:5px;align-items:center;font-size:11px;padding:8px}.mc-probe{width:100%;text-align:left;color:#476180;font-size:11px;padding:7px 0 0}.mc-disabled{background:#f7f9fb}.mc-card-warning{font-size:12px;line-height:1.7;overflow-wrap:anywhere;color:#8b4a39;margin-top:12px}
|
||||
.mc-editor{padding:22px;border:1px solid #b2c6da;border-top:3px solid #2560a3;border-radius:7px;background:white;margin:22px 0 4px}.mc-editor h3{font-size:16px;margin-bottom:18px}.mc-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:17px}.mc-form-grid label{display:flex;flex-direction:column;gap:8px;font-size:12px;color:#4b5f77}.mc-form-grid input,.mc-form-grid select{width:100%;min-width:0;min-height:40px;background:white;border:1px solid #b9c8d6;border-radius:5px;padding:9px 11px}.mc-form-grid .mc-full{grid-column:1/-1}.mc-actions{display:flex;gap:9px;justify-content:flex-end;margin-top:18px;flex-wrap:wrap}.mc-checkbox{display:flex!important;flex-direction:row!important;align-items:center;gap:9px;font-size:12px;line-height:1.7;margin:14px 0;color:#51647c}.mc-checkbox input{width:16px!important;min-height:16px!important;height:16px;flex-shrink:0;accent-color:#2560a3}.mc-help{display:flex;gap:7px;align-items:flex-start;color:#67788d;font-size:11px;line-height:1.8;margin:15px 0;overflow-wrap:anywhere}.mc-empty{padding:38px 20px;background:#fff;border:1px dashed #b5c6d7;border-radius:7px;color:#61738a;font-size:13px;line-height:1.8;margin:18px 0}
|
||||
.mc-pool{display:flex;gap:18px;align-items:flex-start;background:white;border:1px solid #c7d3de;border-radius:8px;padding:21px;margin-bottom:14px}.mc-pool>svg{color:#2560a3;margin-top:2px}.mc-pool>div:first-of-type{flex:1;min-width:0}.mc-pool h4{font-size:15px}.mc-pool p{font-size:12px;color:#64748b;line-height:1.8;margin-top:6px}.mc-pool .mc-actions{margin:0}.mc-members{display:flex;gap:6px;flex-wrap:wrap;margin-top:13px}.mc-members span{font-size:11px;color:#4b607d;padding:4px 8px;background:#eff3f8;border-radius:4px}.mc-editor fieldset{border:1px solid #d0dae5;border-radius:5px;margin:16px 0 0;padding:5px 14px}.mc-editor legend{font-size:12px;color:#566a83;padding:0 6px}.mc-member-choice{display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid #e2e8ef}.mc-member-choice:last-child{border:0}.mc-member-choice>span{flex:1;font-size:13px}.mc-member-choice small{display:block;margin-top:3px;font-size:11px;color:#6c7e94}.mc-member-choice>input[type=number]{width:60px;padding:7px;border:1px solid #c6d2df;border-radius:4px}
|
||||
.mc-attempts article{padding:17px 18px;background:white;border:1px solid #cbd6e2;border-left:3px solid #748eac;margin-bottom:10px;border-radius:4px}.mc-attempts article>div{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.mc-attempts strong{font-size:13px}.mc-attempts time{font-size:11px;color:#637891;margin-left:auto}.mc-attempts p{font-size:12px;color:#556b87;line-height:1.7;margin-top:9px}.mc-attempts code{font-size:10px;color:#7a8ca0;display:block;margin-top:7px;overflow-wrap:anywhere}.mc-checks{display:grid;gap:11px}.mc-checks article{display:flex;align-items:flex-start;gap:14px;border:1px solid #cbd6e2;border-radius:6px;padding:18px;background:white}.mc-checks h4{font-size:14px}.mc-checks p{font-size:12px;color:#5d7088;line-height:1.8;margin-top:5px}.mc-import-source{padding:17px;background:white;border:1px solid #cbd6e2;margin-bottom:10px;display:flex;align-items:center;gap:15px;flex-wrap:wrap;border-radius:6px}.mc-import-source code{flex:1;overflow-wrap:anywhere;font-size:11px;min-width:140px}.mc-import-source>span,.mc-import-source p{font-size:12px;color:#64778e}
|
||||
@media(max-width:940px){.mc-connections{grid-template-columns:1fr}.mc-overview h2{font-size:22px}.mc-pool{flex-wrap:wrap}.mc-pool .mc-actions{width:100%}}
|
||||
@media(max-width:620px){.modal:has(.model-center){width:100vw;height:100dvh;max-height:100dvh;border-radius:0}.modal:has(.model-center)>.modal-header{padding:17px 16px}.mc-overview{padding:17px 16px;display:block}.mc-overview h2{font-size:21px}.mc-current{padding:10px 12px;margin:13px 0 0;min-width:0}.mc-current strong{font-size:13px}.mc-tabs{padding:0 8px}.mc-tabs button{padding:12px 10px;min-height:48px;font-size:12px}.mc-content{padding:18px 15px 28px}.mc-section-title{gap:12px;align-items:flex-start;flex-direction:column}.mc-form-grid{grid-template-columns:1fr}.mc-form-grid .mc-full{grid-column:auto}.mc-editor{padding:18px 14px}.mc-connection{padding:16px 13px}.mc-card-heading{gap:9px}.mc-service-icon{width:34px;height:34px}.mc-card-heading h4{font-size:14px}.mc-connection dl{grid-template-columns:72px minmax(0,1fr)}.mc-notice{padding:12px 16px}.model-center button{min-height:44px}.mc-state{font-size:10px}.mc-attempts time{margin-left:0}.mc-import-source{gap:9px}.mc-member-choice input[type=number]{min-height:44px}.mc-form-grid input,.mc-form-grid select{min-height:44px}}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Activity, Check, CircleHelp, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react';
|
||||
import { api } from './api';
|
||||
import type { Config } from './types';
|
||||
import './ModelCenter.css';
|
||||
|
||||
type Connection = { id: string; name: string; brand: string; protocol: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
|
||||
requiresKey: boolean; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; health: { state: string; reason?: string; cooldownUntil?: number } };
|
||||
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
|
||||
type Attempt = { id: string; connectionId: string; poolId: string | null; model: string; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; runId: string; requestArtifactId?: string; usage?: { prompt_tokens?: number; completion_tokens?: number } };
|
||||
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
|
||||
type Center = { revision: number; selected: { type: string; id: string }; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number };
|
||||
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[] };
|
||||
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', passed: '通过', attention: '待配置' };
|
||||
const initial = { name: '', brand: '自定义', model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 };
|
||||
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
|
||||
export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Config) => void; onLegacy: () => void; busy: boolean }) {
|
||||
const [view, setView] = useState<Center | null>(null);
|
||||
const [tab, setTab] = useState('connections');
|
||||
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number }>(initial);
|
||||
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
|
||||
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
|
||||
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
|
||||
const [operations, setOperations] = useState<Operations | null>(null), [autoInspect, setAutoInspect] = useState(false);
|
||||
const [importPath, setImportPath] = useState(''), [importSource, setImportSource] = useState('ccswitch');
|
||||
const [preview, setPreview] = useState<{ id: string; entries: { id: string; name: string; model: string; baseUrl: string; hasKey: boolean }[]; notices: string[] } | null>(null);
|
||||
const [discovery, setDiscovery] = useState<{ source: string; path: string; available: boolean; supported: boolean; detail?: string }[]>([]);
|
||||
const alive = useRef(true), generation = useRef(0);
|
||||
async function refresh() { const marker = ++generation.current; const result = await api<Center>('/model-center'); if (alive.current && marker === generation.current) setView(result); }
|
||||
async function act(action: () => Promise<void>) {
|
||||
setWorking(true); setNotice('');
|
||||
try { await action(); if (alive.current) await refresh(); }
|
||||
catch (cause) { if (alive.current) setNotice(cause instanceof Error ? cause.message : '操作未完成,请刷新核对。'); }
|
||||
finally { if (alive.current) setWorking(false); }
|
||||
}
|
||||
async function inspect() { const value = await api<Operations>('/operations'); if (alive.current) setOperations(value); }
|
||||
useEffect(() => { alive.current = true; void refresh().catch(error => { if (alive.current) setNotice(error.message); }); return () => { alive.current = false; generation.current++; }; }, []);
|
||||
useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]);
|
||||
const selected = view?.selected;
|
||||
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;
|
||||
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>{selectionName || '原模型连接'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
|
||||
<nav className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['pools', '模型池', Layers3], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['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>
|
||||
{notice && <div className="mc-notice" role="status">{notice}</div>}
|
||||
{busy && <p className="mc-notice">有任务正在执行;连接可停用,其他配置请在任务结束后修改。</p>}
|
||||
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <div className="mc-content">
|
||||
{tab === 'connections' && <>
|
||||
<div className="mc-section-title"><div><h3>模型连接</h3><p>凭据仅在本次宿主内存中使用。已配置与调用通过分别显示。</p></div><button className="button primary" disabled={locked} onClick={() => { setDraft(initial); setKey(''); setEditing(true); }}><Plus size={16} />添加连接</button></div>
|
||||
<div className="mc-connections">{view.connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id}>
|
||||
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · Chat Completions</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>{value.baseUrl}</dd><dt>临时凭据</dt><dd>{value.hasKey ? '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
|
||||
<div className="mc-capabilities"><span>工具:协议声明</span><span>视觉 / 语音:待验证</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 }); if (alive.current) onConfig(result.config); })}>{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(value); setKey(''); setEditing(true); }}>编辑</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-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { await api('/model-center/probe', { id: value.id }); if (alive.current) setNotice('该连接已收到实际响应;请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
|
||||
</article>)}</div>
|
||||
{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, ...(key ? { apiKey: key } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice('连接已保存。'); } }); }}>
|
||||
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
|
||||
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
|
||||
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
|
||||
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
|
||||
<label>实际模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
|
||||
<label>临时 API Key<input type="password" autoComplete="off" value={key} placeholder={draft.id ? '留空保留本次凭据' : '按服务要求填写'} onChange={event => setKey(event.target.value)} /></label>
|
||||
<label>上下文上限<input type="number" min="1000" max="200000" value={draft.contextLimit} onChange={event => setDraft({ ...draft, contextLimit: Number(event.target.value) })} /></label>
|
||||
<label>输出上限<input type="number" min="256" max="16000" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
|
||||
<label>并发请求上限<input type="number" min="1" max="8" value={draft.concurrency} onChange={event => setDraft({ ...draft, concurrency: Number(event.target.value) })} /></label>
|
||||
<label className="mc-checkbox"><input type="checkbox" checked={draft.requiresKey} onChange={event => setDraft({ ...draft, requiresKey: event.target.checked })} />服务需要 API Key</label></div>
|
||||
<p className="mc-help"><CircleHelp size={14} />选择品牌仅用于分类;接口需要提供兼容的 Chat Completions 协议。</p>
|
||||
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked} type="submit">保存模型连接</button></div>
|
||||
</form>}
|
||||
</>}
|
||||
{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 }); if (alive.current) onConfig(result.config); })}>{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>
|
||||
<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.ordinal} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : '用量未知'}</p><code>Run {value.runId}</code>{value.reason && <p className="mc-card-warning">{value.reason}</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>)}
|
||||
<div className="mc-editor"><div className="mc-form-grid"><label>配置格式<select value={importSource} onChange={event => setImportSource(event.target.value)}><option value="ccswitch">CCSwitch SQLite</option><option value="workbench-json">工作台连接 JSON</option></select></label><label>本地文件路径<input value={importPath} onChange={event => { setImportPath(event.target.value); setPreview(null); }} /></label></div><button className="button secondary" disabled={locked || !importPath} onClick={() => void act(async () => { const value = await api<typeof preview>('/model-center/import-preview', { source: importSource, path: importPath }); if (alive.current) setPreview(value); })}>预览可导入连接</button></div>
|
||||
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id }); if (alive.current) { setPreview(null); setNotice('已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
|
||||
</>}
|
||||
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对真实宿主、数据与近期工件,不发送模型请求。</p></div><button className="button primary" disabled={working} onClick={() => void act(inspect)}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div><p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
:root{font-family:"Segoe UI Variable","Segoe UI","Microsoft YaHei",sans-serif;color:#15283f;background:#e7edf2;font-size:14px;--teal:#2560a3;--ink:#15283f;--muted:#5b6d83;--line:#cbd5df;--paper:#fff;--blue:#2560a3}
|
||||
.workbench{background:#e7edf2}.project-sidebar{background:#192d46;color:#dae4ef;border-color:#32465e}.brand{border-color:#35475c;min-height:82px}.brand-mark{background:#2c5d8f;border:1px solid #6583a1;border-radius:7px;font-family:Bahnschrift,sans-serif}.brand strong{color:#fff;font-size:14px}.brand div>span{color:#9dafc5;font-size:11px}.project-sidebar .icon-button,.project-sidebar .field-eyebrow,.project-sidebar .section-heading,.project-sidebar .project-root,.project-sidebar .example-tag{color:#aabed4}.project-sidebar .project-select-row{color:#edf4fb}.project-sidebar select{background:#192d46;color:#e6edf6}.project-sidebar select option{background:#fff;color:#15283f}.project-selector,.file-sidebar,.sidebar-footer{border-color:#35475c}.session-list button{color:#c8d6e6;border-radius:5px}.session-list button:hover,.session-list button.selected{background:#304a67;color:white}.new-session{border:1px solid #5b7490;background:#263e58;color:#e0ebf7;border-radius:5px;min-height:37px}.tree-item{color:#bbcce0}.tree-item:hover,.tree-item.active{background:#304962;color:white}.file-filter{background:#233a54;border:1px solid #48617d}.file-filter input{color:#edf5ff}.file-filter input::placeholder{color:#9eafc5}.sidebar-footer button{color:#bacde1;min-height:38px}.sidebar-footer button:hover{background:#2c4561}.sidebar-footer .connection{color:#9ab2cc;border-top:1px solid #35475c;padding-top:12px}.sidebar-footer .connection small{color:#9bb6d5}.sidebar-footer .connection.connected>span{background:#62b69b}
|
||||
.task-pane{background:#fff;border-color:#c6d1de}.work-header{height:82px;min-height:82px;background:#fff;border-bottom:1px solid #cbd5df;padding-left:26px;padding-right:24px}.work-title h1{font-size:18px;font-weight:650;letter-spacing:-.02em;line-height:1.4}.header-breadcrumb{color:#61748d;font-size:11px}.header-symbol{color:#2560a3;border-color:#bacbdd;background:#eff4fa}.model-button{border:1px solid #bccbdb;border-radius:6px;background:#f5f8fc;min-height:35px;color:#26466a;font-size:12px;font-weight:600}.task-toolbar{background:#f1f4f8;border-bottom:1px solid #ced8e3;min-height:44px;padding-left:26px}.conversation{padding:28px 30px 22px}.message-text{color:#233b55}.tool-row{border-radius:6px;border-color:#c5d2df;background:#f5f8fb}.tool-row summary{min-height:44px}.composer-wrap{background:#f5f7fa;border-top:1px solid #cbd5df;padding:17px 24px 14px}.composer{border:1px solid #afc1d3;border-radius:8px;background:#fff;box-shadow:0 2px 5px #15283f07}.composer:focus-within{border-color:#2560a3;box-shadow:0 0 0 2px #2560a31a}.composer textarea{font-size:14px;line-height:1.8}.button{border-radius:5px;font-weight:600;min-height:34px}.button.primary{background:#2560a3;border:1px solid #20558f;color:white}.button.primary:hover{background:#1e528c}.button.secondary{background:white;color:#365570;border:1px solid #bbcad9}.button.secondary:hover{background:#edf3fa}.inspector{background:#f8fafc;border-color:#cbd5df}.inspector-tabs{background:#edf2f7;border-color:#cbd5df;min-height:49px}.inspector-tabs button{font-size:12px;color:#4e657f}.inspector-tabs button.active{color:#235e98;border-color:#2560a3}.record-heading h3,.task-record-section h3{font-size:14px;font-weight:650;color:#203e60}.task-record-section{border-color:#ccd8e4}.status{font-size:11px;border-radius:4px;font-weight:600}.modal{background:#f8fafc;border:1px solid #bdcbda;border-radius:10px;box-shadow:0 24px 90px #07172e33}.modal-header h2{color:#173653;font-size:19px}.failure-card{border-left:3px solid #bb7a31;border-radius:6px}.approval-card{border-left:3px solid #2560a3;border-radius:6px}.form-field input,.form-field select{border-color:#b8c8d8;background:white;border-radius:5px;min-height:39px}.model-launch{display:flex;gap:8px;align-items:center}.model-launch>.button{font-size:12px;white-space:nowrap}
|
||||
@media(max-width:940px){.conversation{padding:23px 20px}.work-header{padding:0 18px}.task-toolbar{padding-left:18px}.model-launch .model-button{max-width:170px;overflow:hidden;text-overflow:ellipsis}}
|
||||
@media(max-width:620px){.work-header{height:72px;min-height:72px;padding:0 13px}.work-title h1{font-size:15px}.header-breadcrumb{font-size:10px}.model-launch>.button span{display:none}.model-launch>.button{width:40px;height:44px;padding:8px}.model-launch .model-button{max-width:106px;font-size:11px;min-height:36px}.task-toolbar{padding-left:13px;min-height:48px}.conversation{padding:23px 15px}.composer-wrap{padding:12px}.toolbar-actions .icon-button{min-height:40px;min-width:32px}.project-sidebar button{min-height:42px}.composer textarea{font-size:14px}.work-title .header-symbol{display:none}}
|
||||
@@ -2,4 +2,5 @@ import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
import './styles.css';
|
||||
import './control-console.css';
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { parse as parseToml } from 'smol-toml';
|
||||
import { modelEndpoint } from './model-hub.mjs';
|
||||
|
||||
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
export class ConfigImporter {
|
||||
constructor(hub) { this.hub = hub; this.previews = new Map(); }
|
||||
discover() {
|
||||
const root = os.homedir();
|
||||
const sourcePath = path.join(root, '.cc-switch', 'cc-switch.db');
|
||||
return { sources: [{ source: 'ccswitch', path: sourcePath, available: fs.existsSync(sourcePath), supported: true,
|
||||
detail: '仅导入可验证的Chat Completions配置;Responses、Anthropic和客户端登录态分别标记不兼容。' },
|
||||
{ source: 'workbuddy', path: '', available: false, supported: false, detail: '当前尚未取得固定版本的WorkBuddy模型配置契约。可通过连接JSON导入已知API配置;不读取其登录态。' }] };
|
||||
}
|
||||
read(source, filename) {
|
||||
if (!path.isAbsolute(filename)) throw new Error('请选择配置文件的绝对路径。');
|
||||
const stat = fs.lstatSync(filename);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024) throw new Error('配置必须为64MB以内的普通文件。');
|
||||
const rows = [], notices = [];
|
||||
if (source === 'workbench-json') {
|
||||
const value = JSON.parse(fs.readFileSync(filename, 'utf8').replace(/^\uFEFF/, ''));
|
||||
if (value.schema !== 1 || !Array.isArray(value.connections) || value.connections.length > 100) throw new Error('连接JSON需要schema:1与connections数组(最多100项)。');
|
||||
for (const [index, item] of value.connections.entries()) {
|
||||
if (item.protocol && item.protocol !== 'chat-completions') { notices.push('第' + (index + 1) + '项协议暂不支持,已跳过。'); continue; }
|
||||
rows.push({ sourceId: String(item.id ?? index), name: item.name, model: item.model, baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand });
|
||||
}
|
||||
} else if (source === 'ccswitch') {
|
||||
const db = new DatabaseSync(filename, { readOnly: true });
|
||||
try {
|
||||
const columns = db.prepare('PRAGMA table_info(providers)').all().map(value => value.name);
|
||||
if (!['id', 'app_type', 'name', 'settings_config'].every(value => columns.includes(value))) throw new Error('CCSwitch providers表不符合已验证格式。');
|
||||
const providers = db.prepare('SELECT id,app_type,name,settings_config FROM providers ORDER BY app_type,id LIMIT 101').all();
|
||||
if (providers.length > 100) throw new Error('来源超过100个provider,请缩小导入范围。');
|
||||
for (const provider of providers) {
|
||||
let config;
|
||||
try { config = JSON.parse(provider.settings_config); } catch { notices.push(provider.name + '配置不是有效JSON,已跳过。'); continue; }
|
||||
if (provider.app_type === 'codex') {
|
||||
let parsed;
|
||||
try { parsed = typeof config.config === 'string' ? parseToml(config.config) : null; } catch { notices.push(provider.name + '的Codex TOML无法解析。'); continue; }
|
||||
const selected = parsed?.model_providers?.[parsed.model_provider];
|
||||
if (!selected?.base_url || selected.wire_api !== 'chat') { notices.push(provider.name + '使用Responses或未知协议,需对应的独立适配器。'); continue; }
|
||||
rows.push({ sourceId: 'codex:' + provider.id, name: provider.name, baseUrl: selected.base_url, model: parsed.model,
|
||||
apiKey: config.auth?.OPENAI_API_KEY, requiresKey: true, brand: 'CCSwitch' });
|
||||
} else notices.push(provider.name + '(' + provider.app_type + ')不属于已验证的Chat Completions配置,已跳过。');
|
||||
}
|
||||
} finally { db.close(); }
|
||||
} else throw new Error('不支持该来源格式。');
|
||||
const entries = [];
|
||||
for (const row of rows) {
|
||||
try {
|
||||
if (!String(row.model ?? '').trim() || !String(row.name ?? '').trim()) throw new Error('缺少名称或模型');
|
||||
if (row.apiKey !== undefined && typeof row.apiKey !== 'string') throw new Error('凭据不是字符串');
|
||||
entries.push({ ...row, name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: modelEndpoint(row.baseUrl),
|
||||
origin: digest({ source, path: path.resolve(filename), id: row.sourceId }), apiKey: row.apiKey?.trim() ?? '' });
|
||||
} catch { notices.push(String(row.name ?? '某项配置').slice(0, 100) + '缺少有效的接口或模型,已跳过。'); }
|
||||
}
|
||||
return { entries, notices, fingerprint: digest(entries) };
|
||||
}
|
||||
preview(source, filename) {
|
||||
const contents = this.read(source, filename), id = randomUUID();
|
||||
for (const [key, value] of this.previews) if (Date.now() - value.created > 300000) this.previews.delete(key);
|
||||
if (this.previews.size >= 8) throw new Error('预览数量过多,请先完成已有导入。');
|
||||
this.previews.set(id, { source, path: path.resolve(filename), created: Date.now(), ...contents });
|
||||
return { id, entries: contents.entries.map(({ apiKey, sourceId, origin, ...value }, index) => ({ ...value, id: String(index), hasKey: !!apiKey })), notices: contents.notices, expiresInMs: 300000 };
|
||||
}
|
||||
apply(id, autoSync) {
|
||||
const preview = this.previews.get(id);
|
||||
if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。');
|
||||
const current = this.read(preview.source, preview.path);
|
||||
if (current.fingerprint !== preview.fingerprint) { this.previews.delete(id); throw new Error('来源配置已变化,请重新预览再导入。'); }
|
||||
const imported = [], conflicts = [];
|
||||
const sourceId = digest({ source: preview.source, path: preview.path });
|
||||
for (const item of current.entries) {
|
||||
const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin);
|
||||
if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; }
|
||||
const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true,
|
||||
...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) });
|
||||
const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision;
|
||||
imported.push(value.id);
|
||||
}
|
||||
const previousSource = this.hub.state.imports[sourceId];
|
||||
const checkedAt = new Date().toISOString();
|
||||
this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true,
|
||||
lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null,
|
||||
lastResult: { imported: imported.length, conflicts } };
|
||||
this.hub.save(); this.previews.delete(id);
|
||||
return { imported, conflicts, sourceId };
|
||||
}
|
||||
toggle(id, enabled) {
|
||||
const source = this.hub.state.imports[id]; if (!source) throw new Error('导入来源不存在。');
|
||||
source.enabled = enabled === true; this.hub.save(); return { id, enabled: source.enabled };
|
||||
}
|
||||
sync() {
|
||||
const reports = [];
|
||||
for (const [id, source] of Object.entries(this.hub.state.imports)) {
|
||||
if (!source.enabled) continue;
|
||||
try {
|
||||
const read = this.read(source.source, source.path);
|
||||
source.lastCheckedAt = new Date().toISOString();
|
||||
if (read.fingerprint === source.lastFingerprint) { this.hub.save(); continue; }
|
||||
const preview = this.preview(source.source, source.path);
|
||||
reports.push(this.apply(preview.id, true));
|
||||
} catch (cause) { source.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; source.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: source.lastError }); }
|
||||
}
|
||||
return reports;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { ModelRequestError } from '../../server/diagnostics.mjs';
|
||||
|
||||
const legacyId = 'legacy-default';
|
||||
const stamp = () => new Date().toISOString();
|
||||
const error = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const bounded = (value, fallback, min, max) => Number.isFinite(Number(value)) ? Math.max(min, Math.min(max, Math.trunc(Number(value)))) : fallback;
|
||||
const label = (value, maximum = 100) => String(value ?? '').trim().slice(0, maximum);
|
||||
export function modelEndpoint(value) {
|
||||
let url;
|
||||
try { url = new URL(String(value)); } catch { throw error('请输入有效的模型接口根地址。'); }
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.toString().length > 1000) throw error('模型地址只支持不含账号、查询参数的 http/https 地址。');
|
||||
return url.toString().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export class ModelHub {
|
||||
constructor(store, provider) {
|
||||
this.store = store; this.provider = provider;
|
||||
this.state = store.storage.meta('modelRegistry', { schema: 1, revision: 0, selected: { type: 'legacy', id: legacyId }, connections: [], pools: [], imports: {} });
|
||||
this.health = new Map(); this.leases = new Map(); this.cursors = new Map(); this.sticky = new Map(); this.waiting = 0;
|
||||
this.attempts = store.storage.meta('modelAttempts', []);
|
||||
// A process exit leaves a request outcome unknown; never replay it here.
|
||||
let recovered = false;
|
||||
for (const attempt of this.attempts) if (attempt.status === 'running') { attempt.status = 'unknown'; attempt.finishedAt = stamp(); attempt.reason = '宿主重启,请求结果与用量待核对。'; recovered = true; }
|
||||
if (recovered) this.saveAttempts();
|
||||
provider.credentials ??= new Map();
|
||||
}
|
||||
save() { this.state.revision++; this.store.storage.transaction(() => this.store.storage.setMeta('modelRegistry', this.state)); }
|
||||
saveAttempts() { 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' }, ...this.state.connections];
|
||||
}
|
||||
credential(connection) { return connection.id === legacyId ? { key: this.provider.apiKey, revision: 1 } : this.provider.credentials.get(connection.id); }
|
||||
identity(connection) { return connection.id + ':' + connection.revision + ':' + (this.credential(connection)?.revision ?? 0); }
|
||||
status(connection) {
|
||||
const credential = this.credential(connection), health = this.health.get(this.identity(connection));
|
||||
const ready = connection.enabled && (!connection.requiresKey || !!credential?.key);
|
||||
return { ...connection, hasKey: !!credential?.key, credentialRevision: credential?.revision ?? 0, credentialStorage: 'memory',
|
||||
status: !connection.enabled ? 'disabled' : !ready ? 'needs_key' : health?.blocked ? 'needs_attention' : health?.cooldownUntil > Date.now() ? 'cooling' : 'configured',
|
||||
activeRequests: this.leases.get(connection.id) ?? 0, health: health ?? { state: 'unverified' },
|
||||
capabilities: { tools: 'protocol_declared', vision: 'unknown', audio: 'unknown' } };
|
||||
}
|
||||
view() { return { revision: this.state.revision, selected: this.state.selected, connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
|
||||
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: this.attempts.slice(-100).reverse(), waiting: this.waiting,
|
||||
storage: { credentials: 'memory', restart: '临时凭据在宿主退出后需要重新填写。', attemptsRetained: 1000 } }; }
|
||||
connection(id) { const value = this.connections().find(item => item.id === id); if (!value) throw error('模型连接不存在。', 404); return value; }
|
||||
upsert(input) {
|
||||
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
|
||||
const previous = input.id ? this.connection(input.id) : null;
|
||||
if (this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
|
||||
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
|
||||
if (input.protocol && input.protocol !== 'chat-completions') throw error('当前接入仅支持经过验证的 Chat Completions 协议。');
|
||||
const name = label(input.name), model = label(input.model, 200);
|
||||
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
|
||||
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol: 'chat-completions', model,
|
||||
baseUrl: modelEndpoint(input.baseUrl), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
|
||||
contextLimit: bounded(input.contextLimit, 16000, 1000, 200000), maxOutputTokens: bounded(input.maxOutputTokens, 2048, 256, 16000),
|
||||
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
|
||||
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
|
||||
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
|
||||
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];
|
||||
this.save();
|
||||
if (Object.hasOwn(input, 'apiKey')) this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision: (this.provider.credentials.get(connection.id)?.revision ?? 0) + 1 });
|
||||
return this.status(connection);
|
||||
}
|
||||
toggle(id, enabled) {
|
||||
if (id === legacyId) throw error('原连接不能停用,请选择离线演示或其他连接。');
|
||||
const value = this.connection(id); value.enabled = enabled === true; value.revision++; value.updatedAt = stamp(); this.save(); return this.status(value);
|
||||
}
|
||||
pool(input) {
|
||||
const previous = input.id ? this.state.pools.find(value => value.id === input.id) : null;
|
||||
if (input.id && !previous) throw error('模型池不存在。', 404);
|
||||
if (previous && input.revision !== previous.revision) throw error('模型池已修改,请刷新后重试。', 409);
|
||||
if (!previous && this.state.pools.length >= 32) throw error('最多保存32个模型池。');
|
||||
if (!label(input.name) || !Array.isArray(input.members) || !input.members.length || input.members.length > 32) throw error('模型池需要名称和1–32个成员。');
|
||||
const seen = new Set();
|
||||
const members = input.members.map(value => {
|
||||
this.connection(value.connectionId);
|
||||
if (seen.has(value.connectionId)) throw error('同一连接不能重复加入模型池。');
|
||||
seen.add(value.connectionId); return { connectionId: value.connectionId, weight: bounded(value.weight, 1, 1, 10) };
|
||||
});
|
||||
if (!['round-robin', 'weighted'].includes(input.strategy || 'round-robin')) throw error('请选择轮询或权重策略。');
|
||||
const value = { id: previous?.id ?? randomUUID(), name: label(input.name), members, strategy: input.strategy || 'round-robin', sticky: input.sticky !== false,
|
||||
maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 };
|
||||
this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value;
|
||||
}
|
||||
select(input) {
|
||||
if (input.type === 'connection') this.connection(input.id);
|
||||
else if (input.type === 'pool') { if (!this.state.pools.some(item => item.id === input.id)) throw error('模型池不存在。'); }
|
||||
else if (input.type !== 'legacy') throw error('模型选择无效。');
|
||||
this.state.selected = { type: input.type, id: input.type === 'legacy' ? legacyId : input.id }; this.save();
|
||||
if (input.type !== 'legacy') {
|
||||
// Keep the original endpoint/key pair intact. Only a Run's immutable
|
||||
// routing snapshot receives the selected member's endpoint and model.
|
||||
this.store.saveConfig({ mode: 'compatible' });
|
||||
}
|
||||
return this.view();
|
||||
}
|
||||
prepare(config) {
|
||||
if (config.mode === 'demo' || this.state.selected.type === 'legacy') return config;
|
||||
const selection = this.state.selected;
|
||||
const pool = selection.type === 'pool' ? this.state.pools.find(value => value.id === selection.id) : null;
|
||||
if (selection.type === 'pool' && !pool) throw error('选中的模型池不存在。');
|
||||
const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), weight: value.weight,
|
||||
credentialRevision: this.credential(this.connection(value.connectionId))?.revision ?? 0 }));
|
||||
if (!members.some(value => this.status(value).status === 'configured' || this.status(value).status === 'cooling')) throw error('没有可用模型连接,请核对启用状态、临时凭据和故障。');
|
||||
return { ...config, baseUrl: members[0].baseUrl, model: members[0].model,
|
||||
contextLimit: Math.min(config.contextLimit, ...members.map(value => value.contextLimit)), maxOutputTokens: Math.min(config.maxOutputTokens, ...members.map(value => value.maxOutputTokens)),
|
||||
modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision,
|
||||
strategy: pool?.strategy ?? 'round-robin', sticky: pool?.sticky ?? true, maxAttempts: pool?.maxAttempts ?? 1, queueTimeoutMs: pool?.queueTimeoutMs ?? 15000, members } };
|
||||
}
|
||||
available(member) {
|
||||
const current = this.connections().find(value => value.id === member.id);
|
||||
if (!current?.enabled || current.revision !== member.revision || (this.credential(current)?.revision ?? 0) !== member.credentialRevision) return false;
|
||||
const health = this.health.get(this.identity(member));
|
||||
return (!member.requiresKey || !!this.credential(member)?.key) && !health?.blocked && !(health?.cooldownUntil > Date.now());
|
||||
}
|
||||
async acquire(routing, runId, excluded, signal, deadline) {
|
||||
if (this.waiting >= 100) throw error('模型请求队列已满,请稍后继续任务。');
|
||||
this.waiting++;
|
||||
try {
|
||||
while (true) {
|
||||
signal?.throwIfAborted();
|
||||
const healthy = routing.members.filter(value => this.available(value) && !excluded.has(value.id));
|
||||
const ready = healthy.filter(value => (this.leases.get(value.id) ?? 0) < value.concurrency);
|
||||
if (ready.length) {
|
||||
const remembered = routing.sticky && this.sticky.get(runId);
|
||||
let selected = ready.find(value => value.id === remembered);
|
||||
if (!selected) {
|
||||
const weighted = ready.flatMap(value => Array(routing.strategy === 'weighted' ? value.weight : 1).fill(value));
|
||||
const cursor = this.cursors.get(routing.id) ?? 0; selected = weighted[cursor % weighted.length]; this.cursors.set(routing.id, cursor + 1);
|
||||
}
|
||||
this.leases.set(selected.id, (this.leases.get(selected.id) ?? 0) + 1);
|
||||
this.sticky.set(runId, selected.id); if (this.sticky.size > 1000) this.sticky.delete(this.sticky.keys().next().value);
|
||||
let released = false;
|
||||
return { member: selected, release: () => { if (!released) { released = true; this.leases.set(selected.id, Math.max(0, (this.leases.get(selected.id) ?? 0) - 1)); } } };
|
||||
}
|
||||
if (!healthy.length) throw error('模型池暂时没有可用成员;已完成操作保留,请核对凭据、停用状态和冷却时间。');
|
||||
if (Date.now() >= deadline) throw error('等待模型并发槽位超时,任务已保留。');
|
||||
await delay(50, undefined, signal ? { signal } : {});
|
||||
}
|
||||
} finally { this.waiting--; }
|
||||
}
|
||||
async complete(config, body, signal, onProgress, plan, execute) {
|
||||
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
|
||||
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
|
||||
let lastError;
|
||||
for (let count = 1; count <= routing.maxAttempts; count++) {
|
||||
signal?.throwIfAborted();
|
||||
let lease;
|
||||
try { lease = await this.acquire(routing, runId, excluded, signal, deadline); }
|
||||
catch (cause) { throw lastError ?? cause; }
|
||||
const member = lease.member, credential = this.credential(member);
|
||||
const actualBody = { ...body, model: member.model };
|
||||
const bytes = JSON.stringify(actualBody);
|
||||
const attempt = { id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
|
||||
connectionId: member.id, connectionRevision: member.revision, credentialRevision: member.credentialRevision, poolId: routing.type === 'pool' ? routing.id : null,
|
||||
poolRevision: routing.revision, model: member.model, endpoint: member.baseUrl, ordinal: count, status: 'running', startedAt: stamp(),
|
||||
requestSha256: createHash('sha256').update(bytes).digest('hex'), usage: null, usageStatus: 'unknown' };
|
||||
try {
|
||||
if (plan?.sessionId) {
|
||||
const session = this.store.session(plan.sessionId), run = this.store.owned('run', plan.runId, session.id);
|
||||
const artifact = this.store.artifactStore.write(session, run, JSON.parse(this.provider.redact(bytes)), { kind: 'model-attempt-request' });
|
||||
attempt.requestArtifactId = artifact.id;
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
this.store.save(session);
|
||||
}
|
||||
this.attempts.push(attempt); this.saveAttempts();
|
||||
const progress = event => onProgress?.({ ...event, attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, connectionName: member.name, model: member.model, modelAttemptId: attempt.id });
|
||||
const result = await execute({ ...config, baseUrl: member.baseUrl, model: member.model }, credential?.key ?? '', actualBody, progress);
|
||||
attempt.status = 'completed'; attempt.usage = result.usage ?? null; attempt.usageStatus = result.usage ? 'reported' : 'unknown';
|
||||
this.health.set(this.identity(member), { state: 'responded', lastSuccessAt: stamp(), cooldownUntil: 0, failures: 0 });
|
||||
return result;
|
||||
} catch (cause) {
|
||||
const diagnostic = cause.diagnostic;
|
||||
attempt.status = signal?.aborted ? 'interrupted' : 'failed';
|
||||
attempt.reason = this.provider.redact(cause.message).slice(0, 600); attempt.httpStatus = diagnostic?.status ?? diagnostic?.httpStatus ?? null;
|
||||
const health = this.health.get(this.identity(member)) ?? {};
|
||||
if (signal?.aborted) {
|
||||
// A user stop is not evidence that the provider is unhealthy. Keep
|
||||
// the attempt, release its lease, and leave the connection eligible.
|
||||
this.health.set(this.identity(member), { ...health, state: 'interrupted', lastInterruptedAt: stamp() });
|
||||
} else {
|
||||
const blocked = [401, 403].includes(attempt.httpStatus);
|
||||
const failedAt = Date.now();
|
||||
this.health.set(this.identity(member), { state: blocked ? 'needs_attention' : 'failed', blocked, lastFailureAt: new Date(failedAt).toISOString(),
|
||||
failures: (health.failures ?? 0) + 1, cooldownUntil: failedAt + (diagnostic?.retryAfterMs ?? Math.min(60000, 1000 * 2 ** Math.min(health.failures ?? 0, 5))), reason: attempt.reason });
|
||||
}
|
||||
lastError = cause; excluded.add(member.id); this.sticky.delete(runId);
|
||||
signal?.throwIfAborted();
|
||||
if (!diagnostic?.retryable || count === routing.maxAttempts) throw cause;
|
||||
onProgress?.({ phase: 'retrying', attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, modelAttemptId: attempt.id,
|
||||
diagnostic, waitMs: 0, switching: true });
|
||||
} finally { attempt.finishedAt = stamp(); lease.release(); this.saveAttempts(); }
|
||||
}
|
||||
throw lastError ?? new ModelRequestError({ message: '模型池请求未完成。', kind: 'connection' });
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { publicEngineJob } from '../shared/contracts/engines.mjs';
|
||||
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -71,6 +72,48 @@ return async (request, response) => {
|
||||
const method = request.method;
|
||||
const route = url.pathname;
|
||||
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: true, uptimeMs: Date.now() - started });
|
||||
if (route.startsWith('/api/model-center')) {
|
||||
const hub = provider.modelHub(store);
|
||||
const importer = () => hub.importer ??= new ConfigImporter(hub);
|
||||
if (method === 'GET' && route === '/api/model-center') return json(response, hub.view());
|
||||
if (method === 'GET' && route === '/api/model-center/imports') return json(response, importer().discover());
|
||||
if (method === 'POST') {
|
||||
const input = await body(request);
|
||||
if (route === '/api/model-center/toggle') return json(response, hub.toggle(input.id, input.enabled));
|
||||
if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务,再修改或测试模型配置。'), { status: 409 });
|
||||
if (route === '/api/model-center/connections') return json(response, hub.upsert(input), 201);
|
||||
if (route === '/api/model-center/pools') return json(response, hub.pool(input), 201);
|
||||
if (route === '/api/model-center/select') return json(response, { center: hub.select(input), config: { ...store.config, hasKey: provider.hasKey() } });
|
||||
if (route === '/api/model-center/import-preview') return json(response, importer().preview(input.source, String(input.path ?? '')));
|
||||
if (route === '/api/model-center/import-apply') return json(response, importer().apply(input.previewId, input.autoSync));
|
||||
if (route === '/api/model-center/import-toggle') return json(response, importer().toggle(input.id, input.enabled));
|
||||
if (route === '/api/model-center/import-sync') return json(response, { results: importer().sync(), center: hub.view() });
|
||||
if (route === '/api/model-center/probe') {
|
||||
const connection = hub.connection(input.id);
|
||||
if (!hub.available({ ...connection, credentialRevision: hub.credential(connection)?.revision ?? 0 })) throw new Error('该连接不可用,请核对凭据、冷却或停用状态。');
|
||||
const config = { ...store.config, mode: 'compatible', modelRouting: { type: 'connection', id: connection.id, revision: connection.revision,
|
||||
strategy: 'round-robin', sticky: false, maxAttempts: 1, queueTimeoutMs: 1000, members: [{ ...connection, credentialRevision: hub.credential(connection)?.revision ?? 0 }] } };
|
||||
const result = await hub.complete(config, { model: connection.model, stream: false, max_tokens: 16, messages: [{ role: 'user', content: 'Reply OK.' }] }, undefined, undefined, null,
|
||||
async (selected, key, payload) => {
|
||||
const value = await provider.request(selected, '/chat/completions', payload, undefined, key, undefined, { attempts: 1 });
|
||||
if (!value.choices?.[0]?.message) throw new Error('模型响应缺少完整message。');
|
||||
return value;
|
||||
});
|
||||
return json(response, { ok: true, usage: result.usage ?? null, center: hub.view() });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (method === 'GET' && route === '/api/operations') {
|
||||
const checks = [];
|
||||
const inspect = (id, title, action) => { try { checks.push({ id, title, status: 'passed', detail: action() }); } catch (cause) { checks.push({ id, title, status: 'failed', detail: provider.redact(cause.message) }); } };
|
||||
inspect('node', '执行宿主', () => { if (Number(process.versions.node.split('.')[0]) < 24) throw new Error('需要Node.js24或以上。'); return process.version + ' · PID ' + process.pid; });
|
||||
inspect('database', '任务数据库', () => { const rows = store.storage.database.prepare('PRAGMA quick_check').all(); if (rows.some(row => Object.values(row)[0] !== 'ok')) throw new Error('数据库一致性检查未通过。'); return 'SQLite quick_check通过;' + store.sessions.size + '个会话。'; });
|
||||
inspect('artifacts', '最近执行工件', () => { const values = [...store.core.artifact.values()].slice(-50); for (const value of values) store.artifactStore.readBytes(value); return '逐字节核对最近' + values.length + '个工件;更早记录未在本次范围内。'; });
|
||||
const center = provider.modelHub(store).view();
|
||||
checks.push({ id: 'models', title: '模型连接', status: center.connections.some(value => value.status === 'configured' && value.model) ? 'configured' : 'attention', detail: center.connections.filter(value => value.enabled).length + '个启用连接;配置状态与真实模型响应分别记录。' });
|
||||
return json(response, { version: APP_VERSION, checkedAt: new Date().toISOString(), checks, activeTasks: runtime.active.size,
|
||||
queue: center.waiting, modelAttempts: center.attempts.length, modelRequests: 0, scope: '本地只读巡检;不发送模型请求、不执行项目命令。' });
|
||||
}
|
||||
if (method === 'GET' && route === '/api/bootstrap') return json(response, {
|
||||
token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() },
|
||||
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
|
||||
@@ -447,6 +490,7 @@ return async (request, response) => {
|
||||
};
|
||||
provider.validate(config);
|
||||
if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey);
|
||||
if (provider.hub) provider.hub.select({ type: 'legacy' });
|
||||
store.saveConfig(config);
|
||||
return json(response, { ...store.config, hasKey: provider.hasKey() });
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Provider } from './provider.mjs';
|
||||
import { Runtime } from './runtime.mjs';
|
||||
import { createRequestHandler, createSessionPublisher } from './app.mjs';
|
||||
import { APP_VERSION } from './diagnostics.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
|
||||
const appDirectory = process.env.AGENT_WORKBENCH_APP_DIR || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const dataDirectory = process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local', 'share'), 'AgentWorkbench');
|
||||
@@ -23,6 +24,14 @@ const started = Date.now();
|
||||
let actualPort = requestedPort;
|
||||
let closing = false;
|
||||
let exampleProject = null;
|
||||
const modelImportSync = setInterval(() => {
|
||||
try {
|
||||
const hub = provider.modelHub(store);
|
||||
if (!Object.values(hub.state.imports).some(source => source.enabled)) return;
|
||||
(hub.importer ??= new ConfigImporter(hub)).sync();
|
||||
} catch {}
|
||||
}, 60000);
|
||||
modelImportSync.unref();
|
||||
try {
|
||||
const exampleRoot = path.join(appDirectory, 'examples', 'starter-project');
|
||||
if (fs.existsSync(exampleRoot)) exampleProject = store.addProject(exampleRoot);
|
||||
@@ -36,6 +45,7 @@ server.on('request', createRequestHandler({ appDirectory, server, store, provide
|
||||
|
||||
async function shutdown() {
|
||||
if (closing) return; closing = true;
|
||||
clearInterval(modelImportSync);
|
||||
await runtime.stopAll();
|
||||
for (const response of clients) response.end();
|
||||
clients.clear();
|
||||
|
||||
+18
-4
@@ -3,6 +3,7 @@ import { listFiles } from './files.mjs';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { executionEnvironment, ModelRequestError, connectionFailure, httpFailure } from './diagnostics.mjs';
|
||||
import { completionBody, assertPlannedRequest } from '../shared/contracts/model-request.mjs';
|
||||
import { ModelHub } from '../core/models/model-hub.mjs';
|
||||
|
||||
export const engineToolDefinitions = [
|
||||
{ type: 'function', function: { name: 'inspect_engine_checks', description: '读取当前Task已经保存的外部引擎连接核验:真实安装版本、启动完成信号、SDK会话、进程关闭、原报告工件和能力限制。不会启动引擎或发送prompt;完整原记录通过已有read_artifact读取。', parameters: { type: 'object', properties: {}, additionalProperties: false } } },
|
||||
@@ -97,18 +98,24 @@ export class Provider {
|
||||
constructor(options = {}) { this.apiKey = process.env.AGENT_WORKBENCH_API_KEY || ''; this.fetcher = options.fetch; this.retryPolicy = options.retryPolicy; }
|
||||
hasKey() { return !!this.apiKey; }
|
||||
setKey(value) { this.apiKey = String(value ?? '').trim(); }
|
||||
redact(value, key = this.apiKey) { return key ? String(value).replaceAll(key, '[已隐藏]') : String(value); }
|
||||
modelHub(store) { return this.hub ??= new ModelHub(store, this); }
|
||||
prepareConfig(config, store) { return this.modelHub(store).prepare(config); }
|
||||
redact(value, key = this.apiKey) {
|
||||
let text = String(value);
|
||||
for (const secret of [key, this.apiKey, ...[...(this.credentials?.values() ?? [])].map(value => value.key)].filter(Boolean).sort((a, b) => b.length - a.length)) text = text.replaceAll(secret, '[已隐藏]');
|
||||
return text;
|
||||
}
|
||||
validate(config) {
|
||||
const url = new URL(config.baseUrl);
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error('请输入不含账号、查询参数的 http/https 服务地址。');
|
||||
if (config.mode === 'compatible' && !String(config.model).trim()) throw new Error('请先在模型设置中填写模型名称。');
|
||||
return config.baseUrl.replace(/\/+$/, '');
|
||||
}
|
||||
async request(config, route, body, signal, key = this.apiKey, onProgress) {
|
||||
async request(config, route, body, signal, key = this.apiKey, onProgress, options = {}) {
|
||||
const base = this.validate({ ...config, mode: 'demo' });
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (key) headers.Authorization = 'Bearer ' + key;
|
||||
const policy = { attempts: 3, delays: [500, 1500], timeoutMs: signal ? 60000 : 20000, totalTimeoutMs: signal ? 90000 : 20000, ...this.retryPolicy };
|
||||
const policy = { attempts: 3, delays: [500, 1500], timeoutMs: signal ? 60000 : 20000, totalTimeoutMs: signal ? 90000 : 20000, ...this.retryPolicy, ...options };
|
||||
const deadline = Date.now() + policy.totalTimeoutMs;
|
||||
const startedAt = Date.now();
|
||||
let attempts = 0;
|
||||
@@ -173,7 +180,14 @@ export class Provider {
|
||||
assertPlannedRequest(body, requestPlan);
|
||||
if (config.mode === 'demo') return this.demo(messages, project);
|
||||
this.validate(config);
|
||||
const result = await this.request(config, '/chat/completions', body, signal, this.apiKey, onProgress);
|
||||
const execute = async (selected, key, input, progress) => {
|
||||
const value = await this.request(selected, '/chat/completions', input, signal, key, progress, config.modelRouting ? { attempts: 1 } : {});
|
||||
if (!value.choices?.[0]?.message || value.choices[0].finish_reason === 'length') throw new ModelRequestError({ kind: 'protocol', source: 'model_connection',
|
||||
stage: 'model_request', title: '模型响应不完整', message: '模型响应缺少完整message或达到输出上限,未执行工具。', retryable: false, occurredAt: new Date().toISOString() });
|
||||
return value;
|
||||
};
|
||||
const result = config.modelRouting && this.hub ? await this.hub.complete(config, body, signal, onProgress, requestPlan, execute)
|
||||
: await execute(config, this.apiKey, body, onProgress);
|
||||
const received = result.choices?.[0]?.message;
|
||||
if (!received) throw new Error('兼容服务响应中缺少 choices[0].message。');
|
||||
if (result.choices[0].finish_reason === 'length') throw new Error('模型输出达到长度上限,未执行未完整的工具请求。请提高输出上限或缩小任务。');
|
||||
|
||||
@@ -141,7 +141,8 @@ export class Runtime {
|
||||
const project = this.store.project(session.projectId);
|
||||
safePath(project);
|
||||
const controller = new AbortController();
|
||||
const config = structuredClone(this.store.config);
|
||||
const initialConfig = structuredClone(this.store.config);
|
||||
const config = this.provider.prepareConfig ? this.provider.prepareConfig(initialConfig, this.store) : initialConfig;
|
||||
if (config.mode !== 'demo') this.provider.validate(config);
|
||||
const record = this.store.beginRun(session, content, resume, config, { instructionSource });
|
||||
const run = { controller, id: record.id, taskId: record.taskId, project, record, config };
|
||||
@@ -232,7 +233,8 @@ export class Runtime {
|
||||
planned.record.requestAttempts = Math.max(planned.record.requestAttempts, progress.attempt ?? 0);
|
||||
stepRecord.modelAttempts = Math.max(stepRecord.modelAttempts, progress.attempt ?? 0);
|
||||
requestEvent.phase = progress.phase; requestEvent.attempts = progress.attempt;
|
||||
requestEvent.label = progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
|
||||
if (progress.connectionId) { requestEvent.connectionId = progress.connectionId; requestEvent.modelAttemptId = progress.modelAttemptId; requestEvent.actualModel = progress.model; }
|
||||
requestEvent.label = progress.switching ? '正在切换模型池连接' : progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
|
||||
requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。'
|
||||
: progress.phase === 'completed' ? '模型响应已收到;工具请求将在校验后执行。'
|
||||
: progress.diagnostic?.message ?? '正在等待模型响应。';
|
||||
|
||||
@@ -11,6 +11,7 @@ export function modelSnapshot(config) {
|
||||
mode: config.mode, baseUrl: config.baseUrl, model: config.model,
|
||||
contextLimit: config.contextLimit, maxOutputTokens: config.maxOutputTokens,
|
||||
configRevision: config.configRevision ?? 1,
|
||||
...(config.modelRouting ? { routing: structuredClone(config.modelRouting) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
# Agent Workbench:核心代理能力研究与产品计划
|
||||
|
||||
## 当前执行:1.11本地交付完成,接续1.12
|
||||
## 当前执行:1.11本地交付完成,1.12-A/B/C/D进入实现与验收
|
||||
|
||||
最新接续:main已封存1.11交付2bd7d48及报告散列修复0442c48;正式4318为1.11.0/PID19084,15项目/26全部会话(19可见/7归档)。原PID23080在断线期间退出,PID19084沿用原数据。验收期间公开hasKey由false变为true,升级保留原Provider和当前公开配置;本轮0模型请求,真实模型续接按用户选择暂缓。
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
4. [complete] 保留PID19084升级1.11.0;15项目/26会话/2,499记录/4,463事件逐行与导出一致,正式桌面/390px只读页面通过,smoke后原数据散列仍一致。
|
||||
5. [pending] 原真实页面Task续接单独待验;已有连接状态不触发付费验收,保持用户“先本地验收,稍后配置”的决定。
|
||||
6. [complete] 将专业UI、连接注册、模型池、导入与巡检细化为docs/PLAN-1.12.md;区分下一阶段方案与已部署能力。
|
||||
7. [pending] 按1.12-A先实现连接注册/旧配置迁移/运行时凭据引用和模型中心;使用隔离HTTP夹具验证选择/停用/重启,再进入模型池轮询与冷却。
|
||||
7. [complete] 用户授权按计划全量开发;1.12-A/B/C/D切片已实现连接注册、内存凭据引用、模型池调度、CCSwitch/工作台JSON预览导入、可选自动同步、运行巡检入口和模型中心专业界面。固定Node 24与pytest隔离环境下完整源码回归305/305通过;正式4318继续使用不可变1.11,开发验证使用隔离数据。
|
||||
8. [pending] 原真实模型调用、WorkBuddy固定配置契约、Windows本机加密凭据、更多协议/多模态与下一发行包另行验收;当前不得把本地配置或模型池切换当作真实模型任务通过。
|
||||
|
||||
1. [complete] 有界无环依赖、不可变/只追加修订、原目标与工作区绑定及真实工具/变更/检查/页面证据。
|
||||
2. [complete] 模型工具、上下文保留、未完成暂停、Git预览/提交核对及交付报告。
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, compatibleFixture, completion, call, until, launchWorkbench, assertToolPairs } from './helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { ConfigImporter } from '../src/core/models/config-import.mjs';
|
||||
|
||||
const add = (hub, server, name, extra = {}) => hub.upsert({ name, model: name, baseUrl: server.baseUrl, requiresKey: true, apiKey: 'owned-' + name, ...extra });
|
||||
|
||||
test('model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart', t => {
|
||||
const f = fixture(t), provider = new Provider(); provider.setKey('owned-legacy');
|
||||
f.store.saveConfig({ baseUrl: 'http://127.0.0.1:12000/v1', model: 'old' });
|
||||
const hub = provider.modelHub(f.store), connection = add(hub, { baseUrl: 'http://127.0.0.1:13000/v1' }, 'new');
|
||||
hub.select({ type: 'connection', id: connection.id });
|
||||
assert.equal(f.store.config.baseUrl, 'http://127.0.0.1:12000/v1'); assert.equal(provider.apiKey, 'owned-legacy');
|
||||
assert.equal(provider.prepareConfig(f.store.config, f.store).baseUrl, 'http://127.0.0.1:13000/v1');
|
||||
assert.throws(() => hub.upsert({ ...connection, revision: 0 }), /刷新/);
|
||||
assert.equal(JSON.stringify(hub.view()).includes('owned-new'), false);
|
||||
const stored = JSON.stringify(f.store.storage.meta('modelRegistry')); assert.equal(stored.includes('owned-'), false);
|
||||
f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
|
||||
const fresh = new Provider(); fresh.setKey(''); const restored = fresh.modelHub(reopened).view();
|
||||
assert.equal(restored.connections.find(value => value.id === connection.id).status, 'needs_key');
|
||||
assert.equal(restored.selected.id, connection.id);
|
||||
});
|
||||
|
||||
test('config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts', t => {
|
||||
const f = fixture(t), provider = new Provider(), hub = provider.modelHub(f.store), importer = new ConfigImporter(hub);
|
||||
const filename = path.join(f.root, 'connections.json');
|
||||
const write = (model, name = 'Owned import') => fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: [{ name, model,
|
||||
baseUrl: 'http://127.0.0.1:12345/v1', apiKey: 'import-owned-secret' }] }));
|
||||
write('fixture-one');
|
||||
const preview = importer.preview('workbench-json', filename);
|
||||
assert.equal(JSON.stringify(preview).includes('import-owned-secret'), false);
|
||||
write('fixture-changed'); assert.throws(() => importer.apply(preview.id), /来源配置已变化/);
|
||||
write('fixture-one');
|
||||
const accepted = importer.preview('workbench-json', filename), result = importer.apply(accepted.id);
|
||||
assert.equal(result.imported.length, 1);
|
||||
const sourceId = Object.keys(hub.state.imports)[0], initial = hub.connection(result.imported[0]);
|
||||
assert.equal(initial.model, 'fixture-one'); assert.equal(importer.read('workbench-json', filename).entries.length, 1);
|
||||
assert.equal(JSON.stringify(f.store.storage.meta('modelRegistry')).includes('import-owned-secret'), false);
|
||||
write('fixture-two'); assert.deepEqual(importer.sync(), []); assert.equal(hub.connection(initial.id).model, 'fixture-one');
|
||||
importer.toggle(sourceId, true); const synced = importer.sync(); assert.equal(synced[0].imported.length, 1);
|
||||
assert.equal(hub.connection(initial.id).model, 'fixture-two');
|
||||
const current = hub.connection(initial.id); hub.upsert({ ...current, name: 'Manual owner edit' });
|
||||
write('fixture-three'); const conflicted = importer.sync(); assert.deepEqual(conflicted[0].conflicts, ['Manual owner edit']);
|
||||
assert.equal(hub.connection(initial.id).name, 'Manual owner edit'); assert.equal(hub.connection(initial.id).model, 'fixture-two');
|
||||
assert.ok(hub.state.imports[sourceId].lastCheckedAt);
|
||||
importer.toggle(sourceId, false); write('fixture-four'); assert.deepEqual(importer.sync(), []);
|
||||
assert.equal(hub.connection(initial.id).model, 'fixture-two');
|
||||
const workbuddy = importer.discover().sources.find(value => value.source === 'workbuddy');
|
||||
assert.equal(workbuddy.supported, false); assert.equal(workbuddy.available, false);
|
||||
});
|
||||
|
||||
test('real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity', async t => {
|
||||
const f = fixture(t), bad = await compatibleFixture(t, () => ({ status: 429, headers: { 'retry-after': '2' }, body: { error: { message: 'owned rate limit' } } }));
|
||||
const good = await compatibleFixture(t, (_url, body) => body.messages.some(value => value.role === 'tool') ? completion([], 'Done') : completion([call('pool_read', 'list_files', { path: '', depth: 1 })]));
|
||||
const provider = new Provider(), hub = provider.modelHub(f.store), first = add(hub, bad, 'rate-limited'), second = add(hub, good, 'working');
|
||||
const pool = hub.pool({ name: 'Owned pool', members: [{ connectionId: first.id }, { connectionId: second.id }], sticky: true });
|
||||
hub.select({ type: 'pool', id: pool.id });
|
||||
const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'List files and finish.');
|
||||
await until(() => !runtime.isActive(f.session.id), 15000);
|
||||
assert.equal(f.session.status, 'completed'); assert.equal(bad.requests.length, 1); assert.equal(good.requests.length, 2);
|
||||
assert.equal(f.session.events.filter(value => value.tool === 'list_files' && value.phase === 'completed').length, 1);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
const attempts = hub.view().attempts; assert.equal(attempts.length, 3); assert.equal(attempts.filter(value => value.status === 'failed').length, 1);
|
||||
assert.ok(attempts.every(value => value.taskId === f.session.taskId && value.runId === f.session.runId));
|
||||
for (const attempt of attempts) {
|
||||
const artifact = f.store.owned('artifact', attempt.requestArtifactId, f.session.id);
|
||||
const body = JSON.parse(f.store.artifactStore.read(artifact));
|
||||
assert.equal(body.model, attempt.model); assert.equal(artifact.sha256, attempt.requestSha256);
|
||||
}
|
||||
const rateLimit = hub.view().connections.find(value => value.id === first.id).health;
|
||||
assert.equal(Date.parse(rateLimit.lastFailureAt) + 2000, rateLimit.cooldownUntil, 'Retry-After is reflected in the recorded cooldown even if the test finishes after it expires');
|
||||
assert.equal(good.requests[0].headers.authorization, 'Bearer owned-working');
|
||||
assert.equal(bad.requests[0].headers.authorization, 'Bearer owned-rate-limited');
|
||||
});
|
||||
|
||||
test('pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests', async t => {
|
||||
const f = fixture(t), a = await compatibleFixture(t, () => completion()), b = await compatibleFixture(t, () => completion());
|
||||
const provider = new Provider(), hub = provider.modelHub(f.store), first = add(hub, a, 'A'), second = add(hub, b, 'B');
|
||||
const pool = hub.pool({ name: 'Weighted', strategy: 'weighted', members: [{ connectionId: first.id, weight: 2 }, { connectionId: second.id, weight: 1 }] });
|
||||
hub.select({ type: 'pool', id: pool.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
|
||||
for (let index = 0; index < 3; index++) { runtime.start(f.session.id, 'Finish ' + index); await until(() => !runtime.isActive(f.session.id)); }
|
||||
assert.equal(a.requests.length, 2); assert.equal(b.requests.length, 1);
|
||||
hub.toggle(first.id, false);
|
||||
runtime.start(f.session.id, 'Use enabled member'); await until(() => !runtime.isActive(f.session.id));
|
||||
assert.equal(a.requests.length, 2); assert.equal(b.requests.length, 2);
|
||||
hub.toggle(second.id, false); assert.throws(() => runtime.start(f.session.id, 'Nothing available'), /没有可用/);
|
||||
});
|
||||
|
||||
test('401 blocks the credential revision; updating the key restores availability without leaking error echoes', async t => {
|
||||
const f = fixture(t), server = await compatibleFixture(t, () => ({ status: 401, body: { error: { message: 'invalid owned-secret' } } }));
|
||||
const provider = new Provider(), hub = provider.modelHub(f.store), connection = add(hub, server, 'secret', { apiKey: 'owned-secret' });
|
||||
hub.select({ type: 'connection', id: connection.id }); const runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'Try'); await until(() => !runtime.isActive(f.session.id));
|
||||
assert.equal(server.requests.length, 1); assert.equal(hub.view().connections.find(value => value.id === connection.id).status, 'needs_attention');
|
||||
assert.equal(JSON.stringify(f.session).includes('owned-secret'), false); assert.equal(JSON.stringify(hub.view()).includes('owned-secret'), false);
|
||||
const changed = hub.upsert({ ...connection, apiKey: 'replacement' }); assert.equal(changed.status, 'configured');
|
||||
});
|
||||
|
||||
test('queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request', async t => {
|
||||
const f = fixture(t); let release;
|
||||
const server = await compatibleFixture(t, async () => { await new Promise(resolve => { release = resolve; }); return completion(); });
|
||||
const provider = new Provider(), hub = provider.modelHub(f.store), value = add(hub, server, 'queue'); hub.select({ type: 'connection', id: value.id });
|
||||
const config = hub.prepare(f.store.config), first = new AbortController(), second = new AbortController();
|
||||
const payload = { model: value.model, messages: [] };
|
||||
const execute = (selected, key, body) => provider.request(selected, '/chat/completions', body, first.signal, key, undefined, { attempts: 1 });
|
||||
const pending = hub.complete(config, payload, first.signal, null, null, execute);
|
||||
await until(() => !!release);
|
||||
const queued = hub.complete(config, payload, second.signal, null, null, execute);
|
||||
await until(() => hub.waiting === 1); second.abort(); await assert.rejects(queued);
|
||||
hub.toggle(value.id, false); first.abort(); await assert.rejects(pending); release();
|
||||
assert.equal(server.requests.length, 1); assert.equal(hub.leases.get(value.id), 0); assert.equal(hub.waiting, 0);
|
||||
const attempt = hub.view().attempts.at(-1);
|
||||
assert.equal(attempt.status, 'interrupted');
|
||||
const health = hub.health.get(value.id + ':' + attempt.connectionRevision + ':' + attempt.credentialRevision);
|
||||
assert.equal(health.state, 'interrupted'); assert.equal(health.cooldownUntil, undefined);
|
||||
});
|
||||
|
||||
test('compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model', async t => {
|
||||
const f = fixture(t); f.store.close(); const host = await launchWorkbench(t, f.data);
|
||||
const saved = await host.api('/model-center/connections', { name: 'HTTP own profile', model: 'owned-model', baseUrl: 'http://127.0.0.1:12000/v1', apiKey: 'owned-http-key' });
|
||||
assert.equal(saved.hasKey, true); assert.equal(saved.apiKey, undefined);
|
||||
const view = await host.api('/model-center'); assert.ok(view.connections.some(value => value.id === saved.id));
|
||||
const operations = await host.api('/operations'); assert.equal(operations.modelRequests, 0); assert.ok(operations.checks.some(value => value.id === 'database' && value.status === 'passed'));
|
||||
const response = await fetch(host.url + '/api/model-center/connections', { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: 'https://unowned.example', 'X-Workbench-Token': host.bootstrap.token }, body: '{}' });
|
||||
assert.equal(response.status, 403);
|
||||
assert.equal(fs.readFileSync(path.join(f.data, 'workbench.sqlite')).includes(Buffer.from('owned-http-key')), false);
|
||||
});
|
||||
Reference in New Issue
Block a user