fix(credentials): persist configured keys across host restarts

This commit is contained in:
Agent Workbench Dev
2026-11-12 09:01:34 +08:00
parent 211117e06d
commit 5b51151f59
24 changed files with 531 additions and 66 deletions
+2
View File
@@ -1,5 +1,7 @@
# Agent Workbench项目执行规范
2026-11-12 用户指出重启丢 Key,本轮按授权修复正常配置默认临时的问题:Windows 手填/目录/确认导入默认 DPAPI,旧配置接口原子保存,显式临时/清除不复活旧副本,普通编辑和同源模型保持。见[计划](docs/CREDENTIAL-PERSISTENCE-1.25.14-PLAN.md)和[验收](docs/QA-CREDENTIAL-PERSISTENCE-1.25.14.md)。52相关/最后旧配置3项、最终构建和实际Edge8步/真实新进程恢复鉴权通过;所有首失败及211117e0两项虚拟目录基线失败保留,相关目录守卫已修。当前1.25.14源码限定提交/程序包/实际安装与正式更新收尾中;正式原数据入口仍4318/1.25.13/PID14388,不读取或重存真实Key,不续旧样本/真实请求/Purge,不委派。原M4/Claude403/unknown/历史封存和未验边界保持,既有GitAtlas增量推送授权有效。下方只读协调“不查正式/不写代码”是原时点,不覆盖本轮明确修复授权。
2026-11-12 新协调来源只读登记在[同Goal工件连接记录](docs/integration/MNEMO-GOAL-WORKER-READONLY-2026-11-12.md):Mnemo指定旧AG42aacbd1/b330b966有限连接/显式complete已过,113=19+94、独立69及31隔离HTTP仅按来源回执范围,原9/build/57未重跑,本增量模型0;4321原观察404、未载入,生产者/完整指纹/派发接收/父交付/语义未验。AD与M4三工程分别登记,旧AG异常/Purge未验和Claude现有两403/unknown及541/41封存不改签。本消息不请求新执行或源线程回复;本次不读Key、不查正式服务、不重跑/重派或新增Claude/Purge,仅本地登记来源,后续开发阶段再按既有授权增量推送。
2026-11-12 本轮提交推送完成:修后Claude驱动97f132d3/验收5ca65a45已普通增量推送并与远端/fetch逐SHA一致,见[回执](docs/gitatlas-claude-proxy-correction-push.json);完成回执与接续最后另提交核最终HEAD。原M4收尾c8c36c27也已推送,两根541/41封存保持;当前Claude上游403客户端分组权限仍未通过,不追加本轮两请求。下一M8新原版Purge独立冻结,历史异常/unknown/真实预留/Mnemo语义/手机/长期边界保持。
+6
View File
@@ -1,5 +1,11 @@
# Agent Workbench 更新记录
## 1.25.14
- 修复正常配置的模型 Key 在重启后丢失:手动填写、上游目录选择和确认导入默认使用 Windows 本机加密保存,重启自动恢复;可明确选择仅本次使用。
- 普通编辑连接保留已保存的凭据,不要求重复填 Key;保存失败保留输入,清除或替换为临时 Key 后不恢复旧副本,自动同步保持来源已选的保存方式。
- 模型中心直接显示本机保存、重启恢复与加载失败状态;目录新增型号共用源连接的保存凭据,旧配置接口的连接与 Key 共同提交。
## 1.25.13
- 新增可选 Mnemo 单项目记忆桥:连接项目绑定、核对完整来源、确认共享、召回及逐请求来源回执;来源变化或桥服务异常时省略远端记忆,继续原任务。
@@ -0,0 +1,18 @@
# 1.25.14 凭据重启恢复修复
2026-11-12,来源 `211117e0` / 正式安装版 1.25.13。用户反馈正常填写的 API Key 在重启后丢失。当前七条连接公开 `hasKey=false`;109 项目、139 全部会话、9290 记录、24211 事件、420 请求,原数据目录的 SQLite `quick_check=ok`。
根因:已有 Windows CurrentUser DPAPI 和自动恢复,但连接表单、目录选择及确认导入默认只保存宿主内存,持久保存必须额外勾选。仅改变提示不能修复此使用路径。
本轮范围:
- Windows 上新填和确认导入的 Key 默认加密保存,显式 `persistKey=false` / `persistCredentials=false` 保留临时方式;自动同步保持来源已选的保存方式。
- 密文和连接配置共同提交;加密或数据库失败不显示成功、不留下部分连接或新内存凭据。普通编辑不重复要求 Key,不重新解密保存已有凭据。
- 显式清除或替换为临时 Key 不允许下次启动恢复旧副本。源连接及目录新增型号共用同一保存来源。
- 修复三个入口的默认选择、字段名称、无新 Key 的编辑及准确成功状态。旧配置接口的新 Key 也按相同策略原子保存。
- 先保留当前源码的复现失败,再执行针对性回归、构建、网页/桌面与 390px 核对,使用合成 Key 运行安装包的真实 Windows DPAPI、退出/新进程恢复和本机兼容服务鉴权。
- 按阶段审查并限定提交;发行 1.25.14 源码、程序及安装器,隔离验证后更新正式服务,按既有 GitAtlas 授权增量推送。
不读取、复制或重存用户真实 Key,不向聊天或日志输出凭据。已经退出且没有加密副本的旧内存 Key 无法恢复,修复后需要由用户在模型中心填写一次。使用原正式数据目录,历史原文、失败、unknown、重复读取及 Purge 未验证结论保持;本轮不请求真实供应商、续旧任务或推进新的 Purge 实验。
关联升级回归发现已有虚拟数据目录案例在读取宿主索引前未采用物理根目录。`211117e0` 独立导出基线复现原两项失败。此次复用同一无符号链接校验/物理根目录解析,先按物理根读取索引,原 Store 的采用仍在可回退阶段中完成,不重开已有 SQLite、不改变原行或 Provider;保留首失败和基线记录。首次 UI 验收的配置格式选择器过于严格,四个已过步骤及失败原件保留,修正验收选择器后另根复验。
+28
View File
@@ -0,0 +1,28 @@
# 1.25.14 模型凭据重启恢复验收
2026-11-12。用户反馈正常填写的 Key 在重启后全部丢失。本轮以 `211117e0` / 已安装 1.25.13 为来源,修复默认保存流程;发行与正式更新正在本轮收尾。
## 修复结果
Windows 上手动填写、上游目录选择及确认导入默认用 CurrentUser DPAPI 加密保存,在新宿主中自动加载。显式 `persistKey=false` / `persistCredentials=false` 才保留临时方式。连接和密文共同提交,加密或数据库失败时恢复原配置、原 Key 和原密文,表单输入保留。
普通名称、并发及原生参数编辑不重复要求 Key、不重加密旧块。显式清除或改用临时 Key 时删除旧保存副本,防止重启恢复旧值。目录新增型号共用源连接;自动同步保持来源原保存选择,旧来源不自动变更。旧配置接口也原子保存新 Key。地址、型号或鉴权变化仍保留原保存块和具体不匹配状态,界面提示更新本机保存。
已经退出且没有保存副本的旧 Key 无法恢复;安装修复后由用户在模型中心补填一次。助手和验收脚本均未读取、复制或重存真实 Key。
## 源码与进程证据
- 修改前新增三项复现全部失败,原日志 `01-before-default-tests.log` 保留。
- 首关联轮 35/36,凭据从共用转为独立时的版本回归已修,独立复验 1/1。随后 48/52 中两项旧临时默认断言改为显式临时或验证新的默认恢复;另两项虚拟数据目录失败在独立 `211117e0` 来源上同样复现。
- 复用原无符号链接校验与物理根解析后,52/52 相关检查通过,覆盖默认加密、真实 DPAPI、独立 Provider 恢复、临时选择、清除、导入同步、事务回退、目录、HTTP 配置和热升级。随后补旧配置的正确显示名,定向 HTTP/旧配置/加密失败 3/3 和最终构建通过。
- 初次网页验收四步骤已过,配置格式选择器的严格文本匹配失败原件保留;修正验收选择器后另根完成 8 步。
- 实际 Edge:手动保存、留空编辑、临时选择、上游两型号共源、导入、退出及新进程恢复、恢复后鉴权、390px 保存失败保留输入通过,三图已实际查看。截图位置之后调整为直接展示目标凭据字段,最终程序包继续复验。
- 四个加密保存来源重启后恢复为五条可用连接,临时连接没有恢复;密文 SHA 不变、公开数据和 SQLite 检查未包含合成 Key 明文。两宿主均正常退出。只向本机合成接收器发送 1 次模型请求,真实供应商请求 0。
证据根:`.qa/credential-persistence-1.25.14-2026-11-12/`。源码网页成功根 `09-source-ui/`;全部首失败、基线失败及后续日志保留。源码、程序/安装器、实际安装副本和正式服务在以下阶段分别登记,源码包不含用户项目数据。
## 收尾待完成
限定源码提交后生成独立源码 ZIP、不可变程序与 Setup,核对清单及编译字节,使用真实程序包完成网页和隐藏原生桌面重启验收,再更新原正式数据目录的服务、核对原行和工件并增量推送。
本轮不续旧任务、不发起真实供应商请求、不重跑历史样本。原模型交付、网络异常、unknown、重复读取、Claude 403 和 Purge 未验证结论保持。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.25.13",
"version": "1.25.14",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.25.13",
"version": "1.25.14",
"dependencies": {
"@babel/parser": "7.29.11",
"@peculiar/x509": "3.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.25.13",
"version": "1.25.14",
"private": true,
"type": "module",
"description": "Orven — an AI development workspace. From an idea to a running result.",
+1 -1
View File
@@ -62,7 +62,7 @@ try {
await dialog().getByRole('button', { name: '手动填写(兼容)', exact: true }).click(); const form = dialog().getByRole('form', { name: '编辑模型连接', exact: true });
await form.getByLabel('连接名称', { exact: true }).fill('本机 Messages 验收'); await form.getByLabel('接口协议', { exact: true }).selectOption('anthropic-messages');
await form.getByLabel('接口根地址', { exact: true }).fill(baseUrl); await form.getByLabel('请求模型名称', { exact: true }).fill('claude-owned-ui');
await form.getByLabel('临时 API Key', { exact: true }).fill('owned-ui-key'); await form.getByLabel('Messages 鉴权', { exact: true }).selectOption('bearer');
await form.getByLabel('API Key', { exact: true }).fill('owned-ui-key'); await form.getByLabel('Messages 鉴权', { exact: true }).selectOption('bearer');
await form.getByLabel('型号核对', { exact: true }).selectOption('require-match'); await form.getByLabel('流式能力', { exact: true }).selectOption('supported'); await form.getByLabel('使用流式输出', { exact: true }).check();
await expect(form.getByLabel('请求地址预览', { exact: true })).toContainText(baseUrl + '/v1/messages'); await shot('desktop-editor');
await page.setViewportSize({ width: 390, height: 844 }); await form.scrollIntoViewIfNeeded(); await shot('narrow-editor');
+225
View File
@@ -0,0 +1,225 @@
// New synthetic credentials only. Never discovers the production host or a user Key.
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, compatibleFixture, until } from '../tests/helpers.mjs';
const args = process.argv.slice(2);
if (args.includes('--help')) {
console.log('node scripts/verify-credential-persistence.mjs --output NEW_DIRECTORY [--app-root DIRECTORY] [--desktop] — synthetic Windows DPAPI, three actual UI entry paths, process restart and local authentication.');
process.exit(0);
}
const options = {};
while (args.length) {
const flag = args.shift();
if (flag === '--desktop') { options.desktop = true; continue; }
if (!['--output', '--app-root'].includes(flag) || !args.length || options[flag]) throw new Error('Use --help.');
options[flag] = args.shift();
}
assert.equal(process.platform, 'win32');
assert.ok(options['--output']);
const workspace = process.cwd(), appRoot = path.resolve(options['--app-root'] ?? workspace), output = path.resolve(options['--output']);
assert.ok(output.startsWith(path.join(workspace, '.qa') + path.sep));
fs.mkdirSync(output, { recursive: false });
const nodePath = fs.existsSync(path.join(appRoot, 'runtime/node.exe')) ? path.join(appRoot, 'runtime/node.exe') : process.execPath;
const disposers = [], t = { after: dispose => disposers.push(dispose) };
const f = fixture(t, { modernDefaults: true }); f.store.close();
const keys = Object.fromEntries(['manual', 'temporary', 'catalog', 'import', 'legacy'].map(name => [name, 'owned-restart-' + name + '-' + randomUUID()]));
const marks = [], screenshots = [], starts = [], exits = [];
const sha = value => createHash('sha256').update(value).digest('hex');
const mark = step => { marks.push({ step, passed: true }); console.log(JSON.stringify({ step, passed: true })); };
const write = (name, value) => fs.writeFileSync(path.join(output, name), JSON.stringify(value, null, 2));
let browser, electron, report;
const mock = await compatibleFixture(t, (url, input, requests) => {
const auth = requests.at(-1).headers.authorization;
if (!Object.values(keys).some(key => auth === 'Bearer ' + key)) return { status: 401, body: { error: { message: 'Synthetic receiver did not accept the restored credential.' } } };
if (url === '/v1/models') return { data: ['owned-catalog-one', 'owned-catalog-two'].map(id => ({ id, capabilities: { text: true, tools: true } })) };
assert.equal(url, '/v1/chat/completions'); assert.ok(input);
return { model: input.model, choices: [{ message: { role: 'assistant', content: 'Owned restart authentication verified.' }, finish_reason: 'stop' }], usage: { prompt_tokens: 12, completion_tokens: 8, total_tokens: 20 } };
});
assert.equal(new URL(mock.baseUrl).hostname, '127.0.0.1');
async function start(label) {
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: appRoot, AGENT_WORKBENCH_DATA_DIR: f.data, AGENT_WORKBENCH_PORT: '0' };
delete env.AGENT_WORKBENCH_API_KEY;
const child = spawn(nodePath, [path.join(appRoot, 'dist-server/server.mjs')], { cwd: appRoot, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '', stderr = '', url = '';
child.stdout.on('data', bytes => {
stdout += bytes.toString('utf8'); fs.writeFileSync(path.join(output, label + '-stdout.log'), stdout);
for (const line of stdout.split('\n')) { try { const value = JSON.parse(line); if (value.ready) url = value.url; } catch {} }
});
child.stderr.on('data', bytes => { stderr += bytes.toString('utf8'); fs.writeFileSync(path.join(output, label + '-stderr.log'), stderr); });
disposers.push(async () => { if (child.exitCode === null && child.signalCode === null) child.kill(); });
await until(() => url || child.exitCode !== null, 60000);
assert.ok(url, 'Owned host did not start; inspect its retained logs.'); assert.notEqual(new URL(url).port, '4318');
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
assert.equal(bootstrap.version, '1.25.14');
const api = async (route, input) => {
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST', headers: {
'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' },
...(input === undefined ? {} : { body: JSON.stringify(input) }), signal: AbortSignal.timeout(30000) });
const value = await response.json(); if (!response.ok) throw Object.assign(new Error(value.error), { status: response.status }); return value;
};
const status = await api('/host/status');
assert.equal(status.identity.pid, child.pid); assert.equal(path.resolve(status.identity.dataRoot), path.resolve(f.data));
starts.push({ label, pid: child.pid, url, identity: status.identity });
const close = async () => {
if (child.exitCode !== null || child.signalCode !== null) return;
await api('/shutdown', {}); await until(() => child.exitCode !== null || child.signalCode !== null, 10000);
exits.push({ label, pid: child.pid, exitCode: child.exitCode, signalCode: child.signalCode });
assert.equal(child.exitCode, 0); assert.equal(child.signalCode, null);
};
disposers.push(close);
return { url, api, bootstrap, child, close };
}
async function openModels(page) {
await page.getByRole('button', { name: '选择与管理模型', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '模型中心', exact: true }); await expect(dialog).toBeVisible(); return dialog;
}
async function picture(page, name) {
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
assert.equal(await page.evaluate(() => document.body.scrollWidth <= window.innerWidth), true);
const filename = name + '.png'; await page.screenshot({ path: path.join(output, filename) });
screenshots.push({ filename, sha256: sha(fs.readFileSync(path.join(output, filename))), viewport: page.viewportSize() });
}
async function manual(dialog, name, key, temporary = false) {
await dialog.getByRole('button', { name: '手动填写(兼容)', exact: true }).click();
const editor = dialog.getByRole('form', { name: '编辑模型连接', exact: true });
await expect(editor.getByRole('checkbox', { name: '加密保存到本机,重启后自动恢复', exact: true })).toBeChecked();
await editor.getByLabel('连接名称', { exact: true }).fill(name);
await editor.getByLabel('接口根地址', { exact: true }).fill(mock.baseUrl);
await editor.getByLabel('请求模型名称', { exact: true }).fill(name);
await editor.getByLabel('API Key', { exact: true }).fill(key);
if (temporary) await editor.getByRole('checkbox', { name: '加密保存到本机,重启后自动恢复', exact: true }).uncheck();
await editor.getByRole('button', { name: '保存模型连接', exact: true }).click();
const card = dialog.locator('.mc-connection').filter({ hasText: name });
await expect(card).toContainText(temporary ? '仅本次使用' : '重启自动恢复'); return card;
}
function vaultSnapshot() {
const database = new DatabaseSync(path.join(f.data, 'workbench.sqlite'), { readOnly: true });
try {
const row = database.prepare("SELECT value FROM metadata WHERE key = 'modelCredentials'").get();
const state = JSON.parse(row.value);
return { sha256: sha(row.value), entries: Object.keys(state.entries), plaintextAbsent: Object.values(keys).every(key => !row.value.includes(key)) };
} finally { database.close(); }
}
try {
const first = await start('before-restart');
browser = await chromium.launch({ channel: 'msedge', headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const errors = []; page.on('pageerror', error => errors.push(error.message));
await page.goto(first.url); await page.waitForLoadState('networkidle');
const dialog = await openModels(page);
const card = await manual(dialog, 'owned-manual', keys.manual); mark('manual form defaults to encrypted restart recovery');
await card.getByRole('button', { name: '编辑', exact: true }).click();
const editor = dialog.getByRole('form', { name: '编辑模型连接', exact: true });
await expect(editor.getByLabel('API Key', { exact: true })).toHaveValue('');
await expect(editor.getByRole('button', { name: '保存模型连接', exact: true })).toBeEnabled();
await editor.getByLabel('连接名称', { exact: true }).fill('owned-manual-edited');
await editor.getByRole('button', { name: '保存模型连接', exact: true }).click();
await expect(dialog.locator('.mc-connection').filter({ hasText: 'owned-manual-edited' })).toContainText('重启自动恢复');
mark('editing without a new key preserves the saved credential and permits submission');
await manual(dialog, 'owned-temporary', keys.temporary, true); mark('explicit temporary choice is reflected accurately');
await dialog.getByRole('button', { name: '从上游添加模型', exact: true }).click();
const catalog = dialog.getByRole('region', { name: '上游模型目录', exact: true });
await catalog.getByLabel('上游名称', { exact: true }).fill('owned-catalog');
await catalog.getByLabel('目录接口根地址', { exact: true }).fill(mock.baseUrl);
await catalog.getByLabel('目录 API Key', { exact: true }).fill(keys.catalog);
await expect(catalog.getByRole('checkbox', { name: '保存 Key 到本机,重启后自动恢复', exact: true })).toBeChecked();
await catalog.getByRole('button', { name: '获取上游模型', exact: true }).click();
for (const id of ['owned-catalog-one', 'owned-catalog-two']) await catalog.getByLabel('选择模型 ' + id, { exact: true }).check();
await catalog.getByLabel('模型使用方式', { exact: true }).selectOption('auto');
await catalog.getByRole('button', { name: '保存所选 2 个模型', exact: true }).click();
await expect(dialog.locator('.mc-connection').filter({ hasText: 'owned-catalog-two' })).toContainText('重启自动恢复');
await dialog.locator('.mc-connection').filter({ hasText: 'owned-catalog-two' }).scrollIntoViewIfNeeded();
await picture(page, 'web-desktop-saved'); mark('actual upstream selection creates two models sharing one saved key');
const importFile = path.join(output, 'synthetic-import.private.json');
fs.writeFileSync(importFile, JSON.stringify({ schema: 1, connections: [{ name: 'owned-import', model: 'owned-import', baseUrl: mock.baseUrl, apiKey: keys.import }] }));
await dialog.getByRole('button', { name: '配置导入', exact: true }).click();
await dialog.getByLabel('配置格式').selectOption('workbench-json');
await dialog.getByLabel('本地文件路径', { exact: true }).fill(importFile);
await dialog.getByRole('button', { name: '预览可导入连接', exact: true }).click();
await expect(dialog.getByRole('checkbox', { name: '本机加密保存导入的 Key,重启后自动恢复', exact: true })).toBeChecked();
await dialog.getByRole('button', { name: '导入这些连接', exact: true }).click();
await expect(dialog.getByRole('status')).toContainText('重启后自动恢复'); mark('confirmed import defaults to encrypted persistence');
await first.api('/config', { ...first.bootstrap.config, mode: 'compatible', model: 'owned-legacy', baseUrl: mock.baseUrl, apiKey: keys.legacy });
const center = await first.api('/model-center');
assert.equal(center.attemptCount, 0); assert.equal(center.connections.filter(value => value.hasKey).length, 6);
const saved = vaultSnapshot(); assert.equal(saved.entries.length, 4); assert.equal(saved.plaintextAbsent, true);
write('before-restart.json', { saved, connections: center.connections.map(({ id, name, hasKey, savedCredential, credentialSource }) => ({ id, name, hasKey, savedCredential, credentialSource })) });
assert.equal(Object.values(keys).some(key => JSON.stringify(center).includes(key)), false);
await page.goto('about:blank'); await first.close();
const second = await start('after-restart'); assert.notEqual(second.child.pid, first.child.pid);
const restored = await second.api('/model-center');
assert.equal(restored.attemptCount, 0); assert.equal(restored.connections.filter(value => value.hasKey).length, 5);
assert.equal(restored.connections.find(value => value.name === 'owned-temporary').hasKey, false);
assert.equal(restored.connections.filter(value => value.name !== 'owned-temporary').every(value => value.hasKey), true);
assert.equal(vaultSnapshot().sha256, saved.sha256);
mark('new process restores saved manual, catalog, import and legacy credentials, while temporary key remains absent');
const manualConnection = restored.connections.find(value => value.name === 'owned-manual-edited');
assert.equal((await second.api('/model-center/probe', { id: manualConnection.id, scope: 'text' })).ok, true);
assert.equal(mock.requests.filter(value => value.url === '/v1/chat/completions').length, 1);
assert.equal(mock.requests.at(-1).headers.authorization, 'Bearer ' + keys.manual);
mark('restored key authenticates one synthetic local model request without re-entry');
await page.goto(second.url); await page.waitForLoadState('networkidle');
const freshDialog = await openModels(page);
await expect(freshDialog.locator('.mc-connection').filter({ hasText: 'owned-manual-edited' })).toContainText('重启自动恢复');
await page.setViewportSize({ width: 390, height: 844 });
await freshDialog.locator('.mc-connection').filter({ hasText: 'owned-manual-edited' }).scrollIntoViewIfNeeded();
await picture(page, 'web-mobile-restored');
await freshDialog.getByRole('button', { name: '手动填写(兼容)', exact: true }).click();
const invalid = freshDialog.getByRole('form', { name: '编辑模型连接', exact: true });
await invalid.getByLabel('连接名称', { exact: true }).fill('owned-invalid');
await invalid.getByLabel('请求模型名称', { exact: true }).fill('owned-invalid');
await invalid.getByLabel('接口根地址', { exact: true }).fill('ftp://127.0.0.1/invalid');
await invalid.getByLabel('API Key', { exact: true }).fill(keys.manual);
await invalid.getByRole('button', { name: '保存模型连接', exact: true }).click();
await expect(freshDialog.getByRole('status')).toContainText('模型地址只支持');
await expect(invalid.getByLabel('API Key', { exact: true })).toHaveValue(keys.manual);
await invalid.getByLabel('API Key', { exact: true }).scrollIntoViewIfNeeded();
await picture(page, 'web-mobile-save-error'); mark('mobile save failure preserves masked key input and gives an actionable error');
assert.deepEqual(errors, []);
assert.equal(Object.values(keys).some(key => JSON.stringify(restored).includes(key)), false);
if (options.desktop) {
const executable = path.join(appRoot, 'desktop/AgentWorkbench.exe'); assert.ok(fs.existsSync(executable));
const cleanEnv = { ...process.env }; delete cleanEnv.AGENT_WORKBENCH_API_KEY;
electron = await _electron.launch({ executablePath: executable, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--hidden-window', '--app-root', appRoot, '--data-root', f.data, '--node', nodePath, '--port', new URL(second.url).port], cwd: appRoot, env: cleanEnv, timeout: 60000 });
const desktop = await electron.firstWindow(); await desktop.waitForLoadState('networkidle');
const nativeDialog = await openModels(desktop);
await expect(nativeDialog.locator('.mc-connection').filter({ hasText: 'owned-manual-edited' })).toContainText('重启自动恢复');
const visible = await electron.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().some(window => window.isVisible())); assert.equal(visible, false);
await desktop.setViewportSize({ width: 1440, height: 1000 });
await nativeDialog.locator('.mc-connection').filter({ hasText: 'owned-manual-edited' }).scrollIntoViewIfNeeded();
await picture(desktop, 'electron-desktop-restored');
await desktop.setViewportSize({ width: 390, height: 844 });
await nativeDialog.locator('.mc-connection').filter({ hasText: 'owned-manual-edited' }).scrollIntoViewIfNeeded();
await picture(desktop, 'electron-mobile-restored');
await electron.close(); electron = null;
assert.equal((await second.api('/host/status')).identity.pid, second.child.pid); mark('actual packaged desktop shows restored credentials at both widths and closing it preserves the host');
}
const final = await second.api('/model-center');
assert.equal(final.attemptCount, 1);
report = { status: 'passed', version: '1.25.14', appRoot, starts, exits, assertions: marks, screenshots,
savedCiphertextUnchangedAcrossRestart: true, plaintextAbsent: saved.plaintextAbsent, restoredSavedConnections: 5,
syntheticModelRequests: 1, realProviderRequests: 0, localCatalogRequests: mock.requests.filter(value => value.url === '/v1/models').length,
temporaryCredentialRestored: false, pageErrors: errors };
} catch (error) {
write('failure.json', { status: 'failed', message: error.message, stack: error.stack, starts, exits, assertions: marks, screenshots });
throw error;
} finally {
await electron?.close(); await browser?.close();
for (const dispose of disposers.reverse()) await dispose();
}
if (report) write('result.json', { ...report, exits, ownedHostsExited: exits.length === starts.length });
+2 -2
View File
@@ -110,9 +110,9 @@ try:
editor.get_by_label('连接名称', exact=True).fill('Owned Saved Primary')
editor.get_by_label('接口根地址', exact=True).fill(endpoint)
editor.get_by_label('实际模型名称', exact=True).fill('owned-primary')
editor.get_by_label('本机加密保存本次填写的 API Key', exact=True).check()
editor.get_by_label('加密保存到本机,重启后自动恢复', exact=True).check()
expect(editor.get_by_role('button', name='保存模型连接', exact=True)).to_be_disabled()
editor.get_by_label('临时 API Key', exact=True).fill(keys[0])
editor.get_by_label('API Key', exact=True).fill(keys[0])
editor.get_by_role('button', name='保存模型连接', exact=True).click()
expect(dialog.locator('.mc-connection').filter(has_text='Owned Saved Primary')).to_contain_text('可从本机加密保存加载')
assert keys[0] not in page.content()
+3 -3
View File
@@ -31,12 +31,12 @@ try {
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.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('已设置,重启需重新填写');
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');
mark('connection form encrypts new credentials by default and renders restart recovery without exposing them');
await dialog.getByRole('button', { name: '手动填写(兼容)', exact: true }).click();
const second = dialog.getByRole('form', { name: '编辑模型连接', exact: true });
+6 -6
View File
@@ -11,11 +11,11 @@ import type { RequestContract } from '../shared/contracts/model-request-contract
type Source = { id: string; revision: number; name: string; protocol: string; baseUrl: string; brand: string; enabled: boolean; credentialSource?: { connectionId: string } };
const initial = { name: '', brand: '自定义', protocol: 'chat-completions', baseUrl: 'https://api.openai.com/v1', messagesAuth: undefined as string | undefined, requestContract: undefined as RequestContract | undefined, requiresKey: true };
const capabilityNames: Record<string, string> = { text: '文本', tools: '工具调用', streaming: '流式输出', vision: '图像输入', audio: '语音' };
export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }: {
sources: Source[]; sourceId?: string; busy: boolean; onSaved: () => Promise<void>; onClose: () => void;
export function ModelCatalog({ sources, sourceId = '', credentialPersistenceSupported = true, busy, onSaved, onClose }: {
sources: Source[]; sourceId?: string; credentialPersistenceSupported?: boolean; busy: boolean; onSaved: () => Promise<void>; onClose: () => void;
}) {
const [source, setSource] = useState(sourceId), [draft, setDraft] = useState(initial);
const [key, setKey] = useState(''), [persistKey, setPersistKey] = useState(false);
const [key, setKey] = useState(''), [persistKey, setPersistKey] = useState(credentialPersistenceSupported);
const [requestValid, setRequestValid] = useState(true);
const [preview, setPreview] = useState<CatalogPreview | null>(null), [chosen, setChosen] = useState<string[]>([]), [query, setQuery] = useState('');
const [routing, setRouting] = useState('keep'), [defaultModel, setDefaultModel] = useState('');
@@ -50,7 +50,7 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
if (!preview) return; setSaving(true); setError(''); setDiagnostic(null);
try {
const result = await api<{ added: string[]; existing: string[] }>('/model-center/catalog/apply', {
previewId: preview.id, models: chosen, routing, defaultModel, persistKey: !source && persistKey,
previewId: preview.id, models: chosen, routing, defaultModel, ...(!source && key.trim() ? { persistKey } : {}),
...(declare ? { declarations: { text: 'supported', tools: 'supported' } } : {}),
});
if (live.current) {
@@ -68,7 +68,7 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
return <section className="mc-editor mc-catalog" aria-label="上游模型目录" ref={region}>
<div className="mc-section-title"><div><h3>从上游选择模型</h3><p>获取目录,勾选要用的型号,再决定手动指定或自动适配。</p></div><button className="button secondary" disabled={saving} onClick={onClose}>关闭目录</button></div>
<div className="mc-form-grid">
<label className="mc-full">上游连接<select aria-label="目录上游连接" value={source} disabled={locked || working} onChange={event => { invalidate(); setSource(event.target.value); setKey(''); setPersistKey(false); }}>
<label className="mc-full">上游连接<select aria-label="目录上游连接" value={source} disabled={locked || working} onChange={event => { invalidate(); setSource(event.target.value); setKey(''); setPersistKey(credentialPersistenceSupported); }}>
<option value="">添加新的上游</option>{sources.filter(value => value.enabled && !value.credentialSource).map(value => <option key={value.id} value={value.id}>{value.name} · {value.baseUrl}</option>)}
</select></label>
{!source ? <>
@@ -83,7 +83,7 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
<label className="mc-full">接口根地址<input aria-label="目录接口根地址" type="url" value={draft.baseUrl} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, baseUrl: event.target.value }); }} /></label>
<label>API Key<input aria-label="目录 API Key" type="password" autoComplete="new-password" value={key} disabled={locked || working} onChange={event => { invalidate(); setKey(event.target.value); }} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={!draft.requiresKey} disabled={locked || working} onChange={event => { invalidate(); setDraft({ ...draft, requiresKey: !event.target.checked }); }} />此上游不需要 Key</label>
<label className="mc-checkbox mc-full"><input type="checkbox" checked={persistKey} disabled={locked || working || !key} onChange={event => setPersistKey(event.target.checked)} />保存模型时,将本次新填写的 Key 在本机加密保存</label>
<label className="mc-checkbox mc-full"><input type="checkbox" checked={persistKey} disabled={locked || working || !key || !credentialPersistenceSupported} onChange={event => setPersistKey(event.target.checked)} />保存 Key 到本机,重启后自动恢复</label>
</> : <p className="mc-help mc-full">使用该连接当前的凭据获取目录;新增型号引用同一凭据来源。</p>}
</div>
<div className="mc-row-actions"><button className="button primary" disabled={locked || working || !!source && !current || !source && (!requestValid || !draft.name.trim() || !draft.baseUrl || draft.requiresKey && !key)} onClick={() => void fetchModels()}>{working ? '正在获取模型…' : preview ? '重新获取模型目录' : '获取上游模型'}</button>
+43 -14
View File
@@ -37,12 +37,24 @@ type Pool = { id?: string; name: string; members: { connectionId: string; weight
const affinityLabels: Record<AffinityScope, string> = { none: '每次请求重新选择', run: '当前运行保持连接', task: '当前任务保持连接', session: '当前会话保持连接' };
const poolAffinity = (pool: Pool): AffinityScope => pool.sticky === false ? 'none' : pool.affinityScope ?? 'run';
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: ModelAttempt[]; waiting: number };
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: ModelAttempt[]; waiting: number;
storage?: { credentialPersistenceSupported: boolean; defaultPersistKey: boolean } };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
artifacts?: { offset: number; checked: number; total: number; remaining: number; olderOffset: number | null; newerOffset: number | null; results: { id: string; passed: boolean; error?: string }[] } };
type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string };
type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string };
const savedStates: Record<string, string> = { reference: '共用上游凭据', not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
const savedStates: Record<string, string> = { reference: '共用上游凭据', not_saved: '未保存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用', invalid_record: '保存记录损坏' };
function credentialLabel(value: Connection, connections: Connection[]) {
const owner = value.credentialSource ? connections.find(connection => connection.id === value.credentialSource?.connectionId) : value;
const saved = owner?.savedCredential?.status;
const source = value.credentialSource ? '共用 ' + (owner?.name ?? '上游源连接') + ',' : '';
if (value.hasKey) return source + (saved === 'saved' ? '已设置,本机加密保存,重启自动恢复'
: saved === 'disabled' ? '已设置,自动恢复已关闭' : '已设置,仅本次使用');
if (saved === 'disabled') return '本机保存已停用,请启用自动恢复';
if (saved && !['not_saved', 'reference', 'saved'].includes(saved)) return '本机保存未能加载:' + (savedStates[saved] ?? saved);
if (value.credentialSource) return source + '请在源连接填写或启用凭据';
return value.requiresKey ? '尚未填写' : '此服务可不填';
}
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', rejected: '能力不匹配', passed: '通过', attention: '待配置' };
const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, ...DEFAULT_MODEL_CAPACITY, concurrency: 1 };
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
@@ -56,7 +68,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [catalogSource, setCatalogSource] = useState<string | null>(null);
const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false);
const [persistKey, setPersistKey] = useState(true), [persistImports, setPersistImports] = useState(true);
const [credentialView, setCredentialView] = useState<CredentialView | null>(null), [credentialKey, setCredentialKey] = useState(''), [credentialTarget, setCredentialTarget] = useState('');
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
@@ -73,9 +85,24 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
async function refresh() {
const marker = ++generation.current;
const [result, selection] = await Promise.all([api<Center>('/model-center'), api<{ config: Config; modelSelection: ModelSelection }>('/model-center/selection')]);
if (alive.current && marker === generation.current) { setView(result); setRuntimeConfig(selection.config); onConfig(selection.config, selection.modelSelection); }
if (alive.current && marker === generation.current) {
setView(result); setRuntimeConfig(selection.config); onConfig(selection.config, selection.modelSelection);
if (result.storage?.credentialPersistenceSupported === false) { setPersistKey(false); setPersistImports(false); }
}
}
function addConnection() { setTab('connections'); setDraft(initial); setKey(''); setPersistKey(view?.storage?.defaultPersistKey ?? true); setCatalogSource(null); setNativeTarget(null); setEditing(true); }
async function saveConnection() {
const enteredKey = !!key.trim();
const result = await api<Connection>('/model-center/connections', { ...draft,
modelIdentityAliases: draft.modelIdentityAliasesText.split(',').map(value => value.trim()).filter(Boolean),
...(enteredKey ? { apiKey: key, persistKey } : {}) });
if (alive.current) {
setKey(''); setEditing(false);
setNotice(enteredKey ? result.savedCredential?.status === 'saved' ? '连接与 Key 已加密保存,重启后自动恢复。' : '连接已保存,Key 仅本次使用。'
: result.savedCredential?.status === 'source_changed' ? '连接设置已保存;地址、型号或鉴权已变化,请填写 Key 以更新本机保存。'
: '连接设置已保存,原凭据保持。');
}
}
function addConnection() { setTab('connections'); setDraft(initial); setKey(''); setPersistKey(false); setCatalogSource(null); setNativeTarget(null); setEditing(true); }
async function selectRoute(value: string) {
await act(async () => {
const [type, id] = value.split(':'); await api('/model-center/select', { type, id });
@@ -108,6 +135,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
const connections = view?.connections.filter(value => value.id !== 'legacy-default' || value.model.trim()) ?? [];
const selectionName = selected?.type === 'pool' ? view?.pools.find(value => value.id === selected.id)?.name : view?.connections.find(value => value.id === selected?.id)?.name;
const locked = working || busy;
const credentialPersistenceSupported = view?.storage?.credentialPersistenceSupported !== false;
const passthrough = !runtimeConfig || runtimeConfig.executionMode === 'unrestricted' || runtimeConfig.capacityMode === 'passthrough';
return <section className="model-center" aria-label="模型控制台" aria-busy={working}>
<div className="mc-overview"><div><span className="mc-eyebrow">ORVEN / MODELS</span><h2>选择模型,继续开发。</h2><p>接入你信任的模型,为项目选择合适的能力。</p></div><div className="mc-current"><Route size={18} /><span>新任务默认<strong>{runtimeConfig?.mode === 'demo' ? '尚未选择' : selectionName || '正在读取'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
@@ -135,24 +163,24 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
})} />}
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>从上游获取目录并选择多个型号,可手动使用或加入自动适配模型池。</p></div><div className="mc-row-actions"><button className="button primary" disabled={locked} onClick={() => { setCatalogSource(''); setEditing(false); setNativeTarget(null); }}><Plus size={16} />从上游添加模型</button><button className="button secondary" disabled={locked} onClick={addConnection}>手动填写(兼容)</button></div></div>
{catalogSource !== null && <ModelCatalog key={catalogSource} sources={connections} sourceId={catalogSource} busy={locked} onSaved={refresh} onClose={() => setCatalogSource(null)} />}
{catalogSource !== null && <ModelCatalog key={catalogSource} sources={connections} sourceId={catalogSource} credentialPersistenceSupported={credentialPersistenceSupported} busy={locked} onSaved={refresh} onClose={() => setCatalogSource(null)} />}
{!connections.length && catalogSource === null && !editing && <div className="mc-empty"><strong>还没有模型连接</strong><p>从上游获取可用型号,选择后即可开始开发。</p></div>}
<div className="mc-connections">{connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id} data-connection-id={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议输出参数</dt><dd>{protocolOutput(value)}</dd><dt>鉴权</dt><dd>{value.requestContract?.auth === 'none' ? '未自动添加' : value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · {requestVersionLabel(value)}</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议输出参数</dt><dd>{protocolOutput(value)}</dd><dt>鉴权</dt><dd>{value.requestContract?.auth === 'none' ? '未自动添加' : value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · {requestVersionLabel(value)}</dd></>}<dt>凭据</dt><dd>{credentialLabel(value, connections)}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
{value.upstreamModel && <p className="mc-help">型号来自上游目录,能力按目录声明与显式设置保存;可在“推理与能力”查看已接入范围。</p>}
{!!value.modelSpecification?.conflicts.length && <p className="mc-help">有 {value.modelSpecification.conflicts.length} 项规格声明差异,可在“推理与能力”的“模型规格与来源”查看。原目录与显式设置分别保留。</p>}
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); setCatalogSource(null); setNativeTarget(null); }}>编辑</button>
<button className="button secondary" disabled={locked} onClick={() => { setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(view?.storage?.defaultPersistKey ?? true); setEditing(true); setCatalogSource(null); setNativeTarget(null); }}>编辑</button>
<button className="button secondary" disabled={locked || !value.enabled} onClick={() => { setCatalogSource(value.credentialSource?.connectionId ?? value.id); setEditing(false); setNativeTarget(null); }}>获取同源模型</button>
<button className="button secondary" onClick={() => { setNetworkTarget(value.id); setTab('network'); }}>连接诊断</button>
<button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option><option value="vision">合成图像识别</option></select></label>
<button className="button secondary" disabled={locked} onClick={() => { setNativeTarget(value); setEditing(false); }}>推理与能力</button><button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{nativeTarget && <NativeParameters executionMode={runtimeConfig?.executionMode} key={nativeTarget.id + ":" + nativeTarget.revision} connection={nativeTarget} busy={locked} onCancel={() => setNativeTarget(null)} onSave={async input => { await act(async () => { const result = await api<{ config: Config }>("/model-center/native-parameters", input); if (alive.current) { onConfig(result.config); setNativeTarget(null); setNotice("原生参数已保存;新任务按所选协议发送,旧请求保持原记录。"); } }); }} />}{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, modelIdentityAliases: draft.modelIdentityAliasesText.split(',').map(v=>v.trim()).filter(Boolean), ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
{nativeTarget && <NativeParameters executionMode={runtimeConfig?.executionMode} key={nativeTarget.id + ":" + nativeTarget.revision} connection={nativeTarget} busy={locked} onCancel={() => setNativeTarget(null)} onSave={async input => { await act(async () => { const result = await api<{ config: Config }>("/model-center/native-parameters", input); if (alive.current) { onConfig(result.config); setNativeTarget(null); setNotice("原生参数已保存;新任务按所选协议发送,旧请求保持原记录。"); } }); }} />}{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(saveConnection); }}>
<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 => { const brand = event.target.value; setDraft({ ...draft, brand,
@@ -171,7 +199,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
<p className="mc-help mc-full">{runtimeConfig?.executionMode === 'unrestricted' ? '当前完全开放执行:记录型号差异后继续;所选核对策略仍会保存。' : '严格核对时,型号不一致或无法核对会暂停并保留原响应。'}</p>
<label className="mc-full">允许的返回型号(可选,逗号分隔)<input value={draft.modelIdentityAliasesText} onChange={event => setDraft({ ...draft, modelIdentityAliasesText: event.target.value })} /></label>
<label className="mc-full">型号映射依据<input required={draft.modelIdentityAliasesText.trim().length > 0} value={draft.modelIdentityAliasSource} placeholder="填写供应商映射说明或可核对的出处" onChange={event => setDraft({ ...draft, modelIdentityAliasSource: 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>API Key<input type="password" autoComplete="new-password" value={key} placeholder={draft.id ? '留空保持已有 Key' : '填写供应商提供的 Key'} onChange={event => setKey(event.target.value)} /></label>
{passthrough ? <div className="mc-full" aria-label="连接容量策略"><strong>默认透传 · 不设本地上限</strong><dl className="mc-capacity-facts"><div><dt>模型最大上下文</dt><dd aria-label="模型最大上下文">{upstreamCapacity(draft, 'contextLimit')}</dd></div><div><dt>模型最大输出</dt><dd aria-label="模型最大输出">{upstreamCapacity(draft, 'maxOutputTokens')}</dd></div></dl><p className="mc-help">容量来自当前型号的上游目录或官方规格,仅供查看;未公开时本地无限制。完整发送上下文;Messages 按协议带 max_tokens,其它协议默认不附加输出上限,上游错误原文保留。</p></div> : <>
<label>上下文上限<input type="number" required step="1" min="1000" value={draft.contextLimit} onChange={event => setDraft({ ...draft, contextLimit: Number(event.target.value) })} /></label>
<label>输出上限<input type="number" required step="1" min="256" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
@@ -179,16 +207,17 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
</>}
<label>{runtimeConfig?.executionMode === 'unrestricted' ? '并发请求数(0 为不限)' : '并发请求上限'}<input type="number" min={runtimeConfig?.executionMode === 'unrestricted' ? 0 : 1} max={runtimeConfig?.executionMode === 'unrestricted' ? undefined : 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>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} onChange={event => setPersistKey(event.target.checked)} />本机加密保存本次填写的 API Key</label>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} disabled={locked || !credentialPersistenceSupported} onChange={event => setPersistKey(event.target.checked)} />加密保存到本机,重启后自动恢复</label>
<p className="mc-help">{credentialPersistenceSupported ? '默认保存本次填写的 Key;取消勾选后仅本次使用。留空保持已有凭据。' : '当前宿主不支持本机加密保存,Key 仅本次使用。'}</p>
<p className="mc-help"><CircleHelp size={14} />品牌仅用于分类,请选择服务实际提供的协议。能力检测会发起一次模型请求,可能产生费用;使用合成输入,不发送项目文件。文本检测不能证明工具或视觉能力。配置变化后需重新检测并核对凭据保存状态。</p>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked || persistKey && !key.trim()} type="submit">保存模型连接</button></div>
<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 === 'network' && <ModelNetworkDiagnostics connections={connections} initialId={networkTarget || (selected?.type !== 'pool' ? selected?.id : undefined)} disabled={locked} />}
{tab === 'credentials' && <section aria-label="本机加密凭据">
<div className="mc-section-title"><div><h3>本机加密凭据</h3><p>使用当前Windows用户加密。保存后的 Key 不会回显或包含在导出中。</p></div></div>
{!credentialView ? <p className="mc-empty">正在核对本机保存状态…</p> : <>
<p className="mc-help">只保存这次填写或确认导入的凭据。临时连接在宿主退出后需要重新填写。</p>
<p className="mc-help">连接默认加密保存,重启后自动恢复。可在这里更换 Key 或管理自动恢复;仅本次使用的 Key 不保存副本。</p>
{credentialView.unavailable && <p className="mc-card-warning">原保存登记格式不可用;原数据保留,请核对后修复。</p>}
{!connections.length && <p className="mc-empty">请先添加模型连接,再管理凭据。</p>}
{!!connections.length && <form className="mc-editor" aria-label="保存加密凭据" onSubmit={event => { event.preventDefault(); void act(async () => {
@@ -226,7 +255,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
{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>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} onChange={event => setPersistImports(event.target.checked)} />本机加密保存本次确认导入的凭据</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(persistImports ? '连接与本次确认导入的加密凭据已共同保存。' : '已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</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>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} disabled={locked || !credentialPersistenceSupported} onChange={event => setPersistImports(event.target.checked)} />本机加密保存导入的 Key,重启后自动恢复</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(preview.entries.some(value => value.hasKey) ? persistImports ? '连接与 Key 已加密保存,重启后自动恢复。' : '连接已导入,Key 仅本次使用。' : '连接已导入。'); } })}>导入这些连接</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>{operations.artifacts && <div className="mc-operations-pages" aria-label="历史工件巡检分页"><p className="mc-help">本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项</p><div className="mc-row-actions"><button className="button" disabled={working || operations.artifacts.olderOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.olderOffset!))}>检查更早工件</button><button className="button" disabled={working || operations.artifacts.newerOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.newerOffset!))}>检查较新工件</button></div>{operations.artifacts.results.filter(value => !value.passed).map(value => <p className="mc-help error" key={value.id}>工件 {value.id}:{value.error}</p>)}</div>}<p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
</>}
+6 -4
View File
@@ -83,7 +83,7 @@ export class ConfigImporter {
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, persistCredentials = false) {
apply(id, autoSync, persistCredentials) {
const preview = this.previews.get(id);
if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。');
const current = this.read(preview.source, preview.path);
@@ -91,18 +91,20 @@ export class ConfigImporter {
const result = this.hub.editRegistry(() => {
const imported = [], conflicts = [];
const sourceId = digest({ source: preview.source, path: preview.path });
const previousSource = this.hub.state.imports[sourceId];
const persist = this.hub.shouldPersistKey(persistCredentials ?? previousSource?.persistCredentials);
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,
persistKey: persistCredentials === true && !!item.apiKey,
persistKey: persist,
...(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,
persistCredentials: persist,
lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null,
lastResult: { imported: imported.length, conflicts } };
this.hub.save();
@@ -124,7 +126,7 @@ export class ConfigImporter {
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));
reports.push(this.apply(preview.id, true, source.persistCredentials ?? false));
} catch (cause) { const current = this.hub.state.imports[id]; current.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; current.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: current.lastError }); }
}
return reports;
+1 -1
View File
@@ -32,7 +32,7 @@ export class CredentialVault {
if (connection.credentialSource) return { status: 'reference', storage: 'source-reference', sourceId: connection.credentialSource.connectionId,
message: '共用上游源连接的凭据与加载状态,请在源连接管理;没有复制或额外保存 Key。' };
if (this.blocked) return { status: 'unavailable', storage: 'windows-user-dpapi', message: '本机保存登记格式损坏或来自新版本,未覆盖原记录。' };
if (!Object.hasOwn(this.state.entries, connection.id)) return { status: 'not_saved', storage: 'memory', message: '当前凭据只在宿主内存中。' };
if (!Object.hasOwn(this.state.entries, connection.id)) return { status: 'not_saved', storage: 'memory', message: '尚无本机加密副本;仅本次使用的凭据不会在重启后恢复。' };
const value = this.state.entries[connection.id];
if (!value || typeof value !== 'object' || Array.isArray(value) || value.schema !== 1 || value.connectionId !== connection.id
|| !Number.isSafeInteger(value.connectionRevision) || value.connectionRevision < 1 || !Number.isSafeInteger(value.credentialRevision) || value.credentialRevision < 1
+2 -1
View File
@@ -122,6 +122,7 @@ export class ModelCatalog {
if (!unrestricted(this.hub.store) && (input.routing === 'auto' && input.models.length > 32)) throw fail('单个自动模型池最多32个成员;可减少本次选择或分别建立模型池。');
if (input.persistKey === true && !value.explicitKey) throw fail('本机加密保存需要本次新填写的 Key;已有凭据沿用原保存状态。');
const hub = this.hub;
hub.shouldPersistKey(input.persistKey);
const result = hub.editRegistry(() => {
let owner = value.binding ? hub.credentialOwner(hub.connection(value.binding.id)) : null;
if (value.binding && !owner) throw fail('原凭据来源已变化,请核对源连接。', 409);
@@ -147,7 +148,7 @@ export class ModelCatalog {
capabilityDeclarationSources: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state !== 'unknown' ? 'upstream_catalog' : declarations[key] !== 'unknown' ? 'user' : 'protocol'])),
contextLimit: reference.fields.contextLimit?.value ?? model.maxInputTokens ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit,
maxOutputTokens: reference.fields.maxOutputTokens?.value ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens,
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey === true } : {}) });
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey } : {}) });
const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog';
if (!owner) owner = connection;
else connection.credentialSource = { connectionId: owner.id, scope: credentialScope(owner) };
+36 -10
View File
@@ -140,6 +140,36 @@ export class ModelHub {
return !owner ? undefined : owner.id === legacyId ? { key: this.provider.apiKey, revision: this.provider.legacyCredentialRevision ?? 1 } : this.provider.credentials.get(owner.id);
}
vault() { return this.credentialVault ??= new CredentialVault(this.store, this.provider); }
shouldPersistKey(value) {
if (value !== undefined && typeof value !== 'boolean') throw error('凭据保存选项必须为开启或关闭。');
return value ?? process.platform === 'win32';
}
writeCredential(connection, apiKey, persistKey, previousRevision = 0) {
if (typeof apiKey !== 'string' || apiKey.length > 16000) throw error('模型凭据格式无效。');
const key = apiKey.trim(), persist = this.shouldPersistKey(persistKey);
const vault = key && persist ? this.vault() : this.credentialVault;
const revision = Math.max(previousRevision, this.credential(connection)?.revision ?? 0, this.provider.credentials.get(connection.id)?.revision ?? 0,
vault?.state.entries[connection.id]?.credentialRevision ?? 0) + 1;
const record = key && persist ? vault.prepare(connection, key, revision) : null;
if (connection.id === legacyId) { this.provider.setKey(key); this.provider.legacyCredentialRevision = revision; }
else this.provider.credentials.set(connection.id, { key, revision });
if (record || vault?.state.entries[connection.id]) vault.stage(connection.id, record);
}
configureLegacy(config, input) {
this.shouldPersistKey(input.persistKey);
const previous = this.connection(legacyId);
const connection = { ...previous, name: this.state.legacyConnection?.name || config.model || '未配置模型', baseUrl: config.baseUrl, model: config.model,
contextLimit: config.contextLimit, maxOutputTokens: config.maxOutputTokens, revision: (this.store.config.configRevision ?? 0) + 1 };
const hasKey = Object.hasOwn(input, 'apiKey');
connection.credentialBindingRevision = !hasKey && credentialProfile(previous) === credentialProfile(connection)
? previous.credentialBindingRevision ?? previous.revision : connection.revision;
return this.editRegistry(() => {
this.state.selected = { type: 'legacy', id: legacyId };
if (this.state.legacyConnection || hasKey || this.credentialVault?.state.entries[legacyId]) this.state.legacyConnection = connection;
if (hasKey) this.writeCredential(connection, input.apiKey, input.persistKey);
this.save();
}, config);
}
manageCredential(input) {
const connection = this.connection(input.id);
if (connection.credentialSource) throw error('该模型共用上游凭据,请在源连接管理凭据。');
@@ -181,7 +211,9 @@ export class ModelHub {
}
view() { const page = this.ledger.page({ limit: 100 }); return { revision: this.state.revision, selected: this.state.selected, waitSettings: modelWaitSettings(this.store.config), connections: this.connections().map(value => this.status(value)), pools: this.state.pools,
imports: Object.entries(this.state.imports).map(([id, value]) => ({ id, ...value })), attempts: page.items, attemptCount: page.retainedTotal, attemptsHasMore: page.hasMore, waiting: this.waiting,
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', restart: '临时凭据在宿主退出后需要重新填写;已明确本机加密保存的连接按用户与原配置加载。', attemptsRetained: null,
storage: { credentials: this.credentialVault ? 'memory-or-windows-user-dpapi' : 'memory', credentialPersistenceSupported: process.platform === 'win32', defaultPersistKey: process.platform === 'win32',
restart: process.platform === 'win32' ? '新填凭据默认本机加密保存并在重启后恢复;只有明确选择仅本次使用的凭据需要重新填写。'
: '当前宿主不支持本机加密保存,凭据仅在本次宿主内存中。', attemptsRetained: null,
attemptStorage: 'incremental-sqlite', attemptPreview: 100, originalMetadataPreserved: true } }; }
selectionView() {
const selected = this.state.selected;
@@ -239,6 +271,7 @@ export class ModelHub {
} finally { this.probing = false; }
}
upsert(input) {
this.shouldPersistKey(input.persistKey);
const previous = input.id ? this.connection(input.id) : null;
if (!unrestricted(this.store) && this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
@@ -289,15 +322,8 @@ export class ModelHub {
if (legacy) this.state.legacyConnection = connection;
else this.state.connections = [...this.state.connections.filter(item => item.id !== connection.id), connection];
this.save();
if (Object.hasOwn(input, 'apiKey')) {
const revision = Math.max(this.credential(previous ?? connection)?.revision ?? 0, this.provider.credentials.get(connection.id)?.revision ?? 0) + 1;
if (legacy) { this.provider.setKey(input.apiKey); this.provider.legacyCredentialRevision = revision; }
else this.provider.credentials.set(connection.id, { key: input.apiKey.trim(), revision });
}
if (input.persistKey === true) {
const vault = this.vault(), record = vault.prepare(connection, input.apiKey, this.credential(connection)?.revision ?? 1);
vault.stage(connection.id, record);
}
if (Object.hasOwn(input, 'apiKey')) this.writeCredential(connection, input.apiKey, input.persistKey, this.credential(previous ?? connection)?.revision ?? 0);
else if (input.persistKey === true) throw error('加密保存需要本次填写 API Key。');
return this.status(connection);
}
setNativeParameters(input) {
+1 -3
View File
@@ -935,9 +935,7 @@ return async (request, response) => {
};
provider.validate(config);
if (Object.hasOwn(input, 'apiKey') && (typeof input.apiKey !== 'string' || input.apiKey.length > 16000)) throw new Error('模型凭据格式无效。');
if (provider.hub) provider.hub.select({ type: 'legacy' }, config);
else store.saveConfig(config);
if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey);
provider.modelHub(store).configureLegacy(config, input);
return json(response, { ...store.config, hasKey: provider.hasKey() });
}
if (method === 'POST' && route === '/api/config/models') {
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.25.13';
export const APP_VERSION = '1.25.14';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+6 -5
View File
@@ -2,7 +2,7 @@ import path from 'node:path';
import fs from 'node:fs';
import { Provider } from './provider.mjs';
import { Runtime } from './runtime.mjs';
import { Store, atomicJson, readJson } from './store.mjs';
import { Store, atomicJson, readJson, physicalDataDirectory } from './store.mjs';
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
import { ModelHub } from '../core/models/model-hub.mjs';
import { ModelCatalog } from '../core/models/model-catalog.mjs';
@@ -42,7 +42,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const root = fs.realpathSync.native(path.resolve(appDirectory));
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
const oldHandlers = server.listeners('request');
const serviceInfoFile = ownedChild(store.directory, 'service-info.json', { missing: true });
const dataDirectory = physicalDataDirectory(store.directory);
const serviceInfoFile = ownedChild(dataDirectory, 'service-info.json', { missing: true });
const originalServiceInfo = fs.existsSync(serviceInfoFile) ? fs.readFileSync(serviceInfoFile) : null;
let publishedServiceInfo = null;
const oldCompanion = server.workbenchCompanion;
@@ -69,7 +70,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const handler = createRequestHandler({ appDirectory: root, server, store, provider, runtime, token, clients, started,
exampleProject, shutdown, getPort: () => server.address().port });
const restoreOriginal = () => {
const readServiceInfo = () => fs.existsSync(serviceInfoFile) ? fs.readFileSync(ownedChild(store.directory, 'service-info.json')) : null;
const readServiceInfo = () => fs.existsSync(serviceInfoFile) ? fs.readFileSync(ownedChild(dataDirectory, 'service-info.json')) : null;
const expectedServiceInfo = publishedServiceInfo ?? originalServiceInfo;
const currentServiceInfo = readServiceInfo();
if (expectedServiceInfo ? !currentServiceInfo?.equals(expectedServiceInfo) : currentServiceInfo !== null) throw new Error('The host index changed outside this adoption; preserve its current bytes before rollback.');
@@ -85,7 +86,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (store.storage && store.storage !== oldStoreProperties.storage) {
const filename = store.storage.filename;
store.close();
if (path.resolve(filename) !== path.join(path.resolve(oldStoreProperties.directory), 'workbench.sqlite')) throw new Error('Upgrade rollback database path is invalid.');
if (path.resolve(filename) !== path.join(dataDirectory, 'workbench.sqlite')) throw new Error('Upgrade rollback database path is invalid.');
for (const suffix of ['', '-wal', '-shm']) if (fs.existsSync(filename + suffix)) fs.renameSync(filename + suffix, filename + '.rolledback-' + Date.now() + suffix);
}
for (const key of Object.keys(store)) if (!Object.hasOwn(oldStoreProperties, key)) delete store[key];
@@ -111,7 +112,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const latest = readServiceInfo();
if (!latest?.equals(publishedServiceInfo)) throw new Error('The published host index changed while restoring the original handler.');
if (originalServiceInfo) {
const temporary = ownedChild(store.directory, 'service-info.rollback-' + randomUUID() + '.json', { missing: true });
const temporary = ownedChild(dataDirectory, 'service-info.rollback-' + randomUUID() + '.json', { missing: true });
fs.writeFileSync(temporary, originalServiceInfo, { flag: 'wx', mode: 0o600 });
try { fs.renameSync(temporary, serviceInfoFile); } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
} else fs.unlinkSync(serviceInfoFile);
+11 -7
View File
@@ -23,6 +23,16 @@ import { COLLABORATION_ACTIVE, COLLABORATION_CLOSED } from '../shared/contracts/
export const now = () => new Date().toISOString();
export function physicalDataDirectory(directory) {
const resolved = path.resolve(directory), parsed = path.parse(resolved);
let current = parsed.root;
for (const component of resolved.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
current = path.join(current, component);
if (fs.lstatSync(current).isSymbolicLink()) throw new Error('任务数据目录不接受符号链接或目录联接。');
}
return fs.realpathSync.native(resolved);
}
export function atomicJson(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = file + '.' + randomUUID() + '.tmp';
@@ -102,13 +112,7 @@ export class Store extends EventEmitter {
// A retained pre-desktop Store may still name an MSIX-virtualized LocalAppData
// directory. Bind new path-scoped services to that same physical directory,
// including when SQLite is already open; do not reopen or move its data.
const resolved = path.resolve(this.directory), parsed = path.parse(resolved);
let current = parsed.root;
for (const component of resolved.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
current = path.join(current, component);
if (fs.lstatSync(current).isSymbolicLink()) throw new Error('任务数据目录不接受符号链接或目录联接。');
}
this.directory = fs.realpathSync.native(resolved);
this.directory = physicalDataDirectory(this.directory);
if (this.storage?.database) {
const missing = CORE_KINDS.filter(kind => !this.core?.[kind]);
if (missing.length) {
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture, compatibleFixture } from './helpers.mjs';
import { Store } from '../src/server/store.mjs';
import { Provider } from '../src/server/provider.mjs';
import { ConfigImporter } from '../src/core/models/config-import.mjs';
const windows = { skip: process.platform !== 'win32' };
const create = store => { const provider = new Provider(); provider.setKey(''); return { provider, hub: provider.modelHub(store) }; };
const reopen = f => {
f.store.close();
const store = new Store(f.data); f.onCleanup(() => store.close());
return { store, ...create(store) };
};
const connection = (name, extra = {}) => ({ name, model: name, baseUrl: 'http://127.0.0.1:12001/v1', ...extra });
test('normal key entry survives a fresh provider by default without plaintext in public views or SQLite files', windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store);
const key = 'OWNED_DEFAULT_CREDENTIAL_SENTINEL_0a3b29ef1d7d';
const saved = hub.upsert(connection('default-manual', { apiKey: key }));
assert.equal(saved.savedCredential?.status, 'saved');
assert.equal(JSON.stringify(hub.view()).includes(key), false);
for (const filename of fs.readdirSync(f.data)) {
const file = path.join(f.data, filename);
if (fs.statSync(file).isFile()) for (const needle of [Buffer.from(key), Buffer.from(key, 'utf16le'), Buffer.from(Buffer.from(key).toString('base64'))])
assert.equal(fs.readFileSync(file).includes(needle), false, filename);
}
const fresh = reopen(f), restored = fresh.hub.connection(saved.id);
assert.equal(fresh.hub.status(restored).hasKey, true);
assert.equal(fresh.hub.credential(restored).key, key);
assert.equal(fresh.hub.credential(restored).revision, saved.credentialRevision);
});
test('new upstream model selection saves one default credential and restores every referenced model', windows, async t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store);
const server = await compatibleFixture(t, () => ({ data: [{ id: 'owned-one' }, { id: 'owned-two' }] }));
const preview = await hub.modelCatalog().fetch({ draft: { name: 'owned-upstream', protocol: 'chat-completions', baseUrl: server.baseUrl }, apiKey: 'owned-catalog-default' });
const result = hub.modelCatalog().apply({ previewId: preview.id, models: ['owned-one', 'owned-two'], routing: 'auto' });
assert.equal(Object.keys(f.store.storage.meta('modelCredentials', { entries: {} }).entries).length, 1);
const fresh = reopen(f), models = result.added.map(id => fresh.hub.connection(id));
assert.equal(models.every(model => fresh.hub.status(model).hasKey), true);
assert.equal(fresh.hub.credential(models[0]), fresh.hub.credential(models[1]));
assert.equal(fresh.hub.state.selected.type, 'pool');
assert.equal(JSON.stringify(fresh.hub.view()).includes('owned-catalog-default'), false);
});
test('confirmed configuration import persists keys by default and retains that policy for automatic sync', windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store), importer = new ConfigImporter(hub);
const filename = path.join(f.root, 'owned-default-import.json');
const write = key => fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: [connection('owned-import', { apiKey: key })] }));
write('owned-import-first');
const preview = importer.preview('workbench-json', filename), accepted = importer.apply(preview.id, true);
const id = accepted.imported[0];
assert.equal(hub.status(hub.connection(id)).savedCredential?.status, 'saved');
assert.equal(hub.state.imports[accepted.sourceId].persistCredentials, true);
write('owned-import-next');
assert.equal(importer.sync()[0].imported.length, 1);
const fresh = reopen(f);
assert.equal(fresh.hub.status(fresh.hub.connection(id)).hasKey, true);
assert.equal(fresh.hub.credential(fresh.hub.connection(id)).key, 'owned-import-next');
});
test('editing a saved connection without a new key preserves its encrypted block and restart recovery', windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store);
const saved = hub.upsert(connection('owned-edit', { apiKey: 'owned-edit-key' }));
const block = structuredClone(hub.vault().state.entries[saved.id]);
hub.upsert({ ...saved, name: 'renamed connection', concurrency: 3 });
assert.deepEqual(hub.vault().state.entries[saved.id], block);
const fresh = reopen(f);
assert.equal(fresh.hub.status(fresh.hub.connection(saved.id)).hasKey, true);
assert.equal(fresh.hub.connection(saved.id).name, 'renamed connection');
});
for (const replacement of [{ apiKey: 'owned-temporary-replacement', persistKey: false }, { apiKey: '' }]) {
test(`${replacement.apiKey ? 'choosing temporary use' : 'clearing a key'} removes the old saved copy instead of restoring it later`, windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store);
const saved = hub.upsert(connection('owned-replacement', { apiKey: 'owned-original-saved' }));
const changed = hub.upsert({ ...saved, ...replacement });
assert.equal(changed.hasKey, !!replacement.apiKey);
assert.equal(hub.vault().state.entries[saved.id], undefined);
const fresh = reopen(f);
assert.equal(fresh.hub.status(fresh.hub.connection(saved.id)).hasKey, false);
});
}
test('temporary import remains temporary during automatic sync, including sources created by older versions', windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store), importer = new ConfigImporter(hub);
const filename = path.join(f.root, 'owned-temporary-import.json');
const write = key => fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: [connection('owned-temporary-import', { apiKey: key })] }));
write('owned-temporary-first');
const accepted = importer.apply(importer.preview('workbench-json', filename).id, true, false);
delete hub.state.imports[accepted.sourceId].persistCredentials; hub.save();
write('owned-temporary-next');
assert.equal(importer.sync()[0].imported.length, 1);
assert.equal(hub.state.imports[accepted.sourceId].persistCredentials, false);
const fresh = reopen(f);
assert.equal(fresh.hub.status(fresh.hub.connection(accepted.imported[0])).hasKey, false);
});
test('legacy configuration and its default encrypted key commit together and survive non-credential edits', windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub } = create(f.store);
const config = { ...f.store.config, mode: 'compatible', baseUrl: 'http://127.0.0.1:12001/v1', model: 'owned-legacy' };
hub.configureLegacy(config, { apiKey: 'owned-legacy-default' });
assert.equal(hub.vault().status(hub.connection('legacy-default')).status, 'saved');
hub.configureLegacy({ ...f.store.config, maxSteps: 30 }, {});
const fresh = reopen(f);
assert.equal(fresh.provider.hasKey(), true);
assert.equal(fresh.provider.apiKey, 'owned-legacy-default');
assert.equal(fresh.store.config.maxSteps, 30);
});
test('default encryption failure rejects a configuration change and keeps both database and resident credentials intact', windows, t => {
const f = fixture(t, { modernDefaults: true }), { hub, provider } = create(f.store);
hub.configureLegacy({ ...f.store.config, mode: 'compatible', baseUrl: 'http://127.0.0.1:12001/v1', model: 'owned-before' }, { apiKey: 'owned-before' });
const config = structuredClone(f.store.config), registry = structuredClone(hub.state), vaultState = structuredClone(hub.vault().state);
const snapshot = () => f.store.storage.database.prepare('SELECT * FROM metadata ORDER BY rowid').all();
const rows = snapshot();
hub.vault().protect = () => { throw new Error('owned default encryption failure'); };
assert.throws(() => hub.configureLegacy({ ...config, model: 'owned-after' }, { apiKey: 'owned-after' }), /owned default encryption failure/);
assert.deepEqual(f.store.config, config); assert.deepEqual(hub.state, registry); assert.deepEqual(hub.vault().state, vaultState);
assert.equal(provider.apiKey, 'owned-before'); assert.deepEqual(snapshot(), rows);
});
+2 -2
View File
@@ -45,9 +45,9 @@ test('actual Windows CurrentUser DPAPI roundtrips owned UTF-8 and rejects damage
encrypted[encrypted.length - 1] ^= 255; assert.throws(() => unprotectCredential(encrypted, entropy), /无法处理/);
});
test('only explicitly supplied keys persist; new provider restores original revisions and public views contain no key', t => {
test('explicit temporary keys stay in memory; saved keys restore original revisions without exposure in public views', t => {
const f = fixture(t), { provider, hub } = create(f); provider.setKey('owned-unsaved-legacy');
const volatile = add(hub, 'volatile'), saved = add(hub, 'saved', { persistKey: true });
const volatile = add(hub, 'volatile', { persistKey: false }), saved = add(hub, 'saved', { persistKey: true });
const ledger = f.store.storage.meta('modelCredentials'); assert.deepEqual(Object.keys(ledger.entries), [saved.id]);
assert.equal(hub.credential(saved).revision, ledger.entries[saved.id].credentialRevision);
assert.equal(JSON.stringify(ledger).includes('owned-vault-'), false); assert.equal(JSON.stringify(hub.vault().view(hub)).includes('owned-vault-'), false);
+2 -1
View File
@@ -207,7 +207,8 @@ test('compiled HTTP directory flow persists selection and references, gates chan
await host.close(); const store = new Store(f.data); f.onCleanup(() => store.close());
const provider = new Provider(); provider.setKey(''); const hub = provider.modelHub(store);
assert.equal(hub.state.selected.type, 'pool'); assert.equal(hub.connection(result.added[1]).credentialSource.connectionId, source.id);
assert.equal(hub.status(hub.connection(result.added[1])).status, 'needs_key', 'volatile credentials are not silently persisted');
assert.equal(hub.status(hub.connection(result.added[1])).status, 'configured', 'normal catalog entry restores its default encrypted credential');
assert.equal(hub.vault().status(hub.connection(source.id)).status, 'saved');
assert.equal(JSON.stringify(hub.view()).includes('owned-http-key'), false);
});
+2 -2
View File
@@ -13,7 +13,7 @@ const add = (hub, server, name, extra = {}) => hub.upsert({ name, model: name, b
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');
const hub = provider.modelHub(f.store), connection = add(hub, { baseUrl: 'http://127.0.0.1:13000/v1' }, 'new', { persistKey: false });
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');
@@ -36,7 +36,7 @@ test('config import previews exact revisions, keeps secrets volatile, syncs only
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);
const accepted = importer.preview('workbench-json', filename), result = importer.apply(accepted.id, undefined, false);
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);