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
+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) {