fix(models): preserve cache usage categories and receipt sources

This commit is contained in:
Agent Workbench Dev
2026-11-07 11:20:02 +08:00
parent ea2559df7d
commit cb60fb1149
13 changed files with 502 additions and 10 deletions
+4 -2
View File
@@ -3,6 +3,8 @@ import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw,
import { api, downloadArtifact } from './api';
import type { Config, ModelSelection, ModelSnapshot, RuntimeFailure } from './types';
import './ModelCenter.css';
import { ModelUsageDetails } from './ModelUsageDetails';
import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { ModelRoutingDetails, type RoutingDecision } from './ModelRoutingDetails';
import type { ModelIdentity } from '../shared/contracts/model-identity.mjs';
@@ -25,7 +27,7 @@ const upstreamCapacity = (value: { model: string; upstreamModel?: CatalogModel }
type Connection = { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel;
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type Attempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type Attempt = { routingDecision?: RoutingDecision; modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: TokenUsage | null };
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: Attempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
@@ -205,7 +207,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
<fieldset><legend>模型池成员与权重</legend>{connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
</>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.requestArtifactId!, "model-request-" + value.id + ".json"); })}>下载实际请求</button>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><ModelUsageDetails usage={value.usage} /><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}<ModelRoutingDetails decision={value.routingDecision} /><ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.requestArtifactId!, "model-request-" + value.id + ".json"); })}>下载实际请求</button>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
+14
View File
@@ -0,0 +1,14 @@
.model-usage-details { margin-top: 10px; color: var(--muted, #657773); font-size: 12px; line-height: 1.6; }
.model-usage-details > summary { width: fit-content; cursor: pointer; color: var(--ink, #2c4844); font-weight: 600; }
.model-usage-details dl { margin: 8px 0; }
.model-usage-details dl > div { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 8px; padding: 3px 0; }
.model-usage-details dt, .model-usage-details dd { margin: 0; overflow-wrap: anywhere; }
.model-usage-details dd { text-align: right; font-variant-numeric: tabular-nums; }
.model-usage-details dt small { display: block; font-size: 11px; font-weight: 400; }
.model-usage-details > p, .model-usage-sources > p { margin: 6px 0; }
.model-usage-details .model-usage-warning { color: var(--warning-ink, #a05c36); }
.model-usage-sources { margin-top: 7px; }
.model-usage-sources > summary { cursor: pointer; }
.model-usage-sources dl > div { grid-template-columns: 75px minmax(0, 1fr); }
.model-usage-sources dd { text-align: left; }
.model-usage-sources code { font-size: 11px; white-space: normal; overflow-wrap: anywhere; }
+30
View File
@@ -0,0 +1,30 @@
import { tokenAccountingView, type TokenMetric, type TokenUsage } from '../shared/contracts/model-usage.mjs';
import './ModelUsageDetails.css';
const count = (metric: TokenMetric) => metric.status === 'invalid' ? '上游数值无效' : metric.tokens === null ? '上游未报告' : metric.tokens.toLocaleString('zh-CN') + ' tokens';
const protocols: Record<string, string> = { 'anthropic-messages': 'Messages', responses: 'Responses', 'chat-completions': 'Chat' };
const labels = { cacheRead: '缓存读取', cacheWrite: '缓存写入', uncached: '未缓存输入', reasoning: '推理输出' } as const;
const sourceLabels = { input: '全部输入', output: '全部输出', total: '合计', ...labels } as const;
const checkLabel = (value: string) => value === 'consistent' ? '一致' : value === 'inconsistent' ? '不一致' : '尚未完整报告';
const lifetimeNames: Record<string, string> = { ephemeral_5m_input_tokens: '5 分钟写入', ephemeral_1h_input_tokens: '1 小时写入', ttl_30m_tokens: '30 分钟写入', ttl_12h_tokens: '12 小时写入' };
export function ModelUsageDetails({ usage, expanded = false }: { usage: TokenUsage | null | undefined; expanded?: boolean }) {
const view = tokenAccountingView(usage);
if (!view) return null;
return <details className="model-usage-details" open={expanded || undefined}>
<summary>缓存与用量明细</summary>
<dl>{(Object.keys(labels) as (keyof typeof labels)[]).map(key => <div key={key}>
<dt>{key === 'uncached' && view.scheme === 'read-and-miss' ? '未命中缓存输入' : labels[key]}{view.metrics[key].status === 'derived' && <small>按上游用量计算</small>}</dt>
<dd>{count(view.metrics[key])}</dd>
</div>)}{view.lifetimes.map(value => <div key={value.name}><dt>{lifetimeNames[value.name] ?? value.name}</dt><dd>{count(value)}</dd></div>)}</dl>
{view.issues.length > 0 && <p className="model-usage-warning" role="status">上游用量字段存在不一致或无效值,原值已保留,请查看来源与原响应。</p>}
<p>缓存写入不等于命中;推理已包含在输出中。这些 token 统计不代表实际账单。</p>
<details className="model-usage-sources"><summary>用量来源与核对</summary>
<p>{protocols[view.protocol] ?? view.protocol} · {view.projection === 'original-usage' ? '原始上游 usage' : '旧归一记录'}<br />输入分类合计{checkLabel(view.checks.inputPartition)} · 输入输出合计{checkLabel(view.checks.total)}{view.lifetimes.length > 0 && <> · 写入时长分类{checkLabel(view.checks.cacheWriteLifetimes)}</>}</p>
<dl>{(Object.keys(sourceLabels) as (keyof typeof sourceLabels)[]).map(key => <div key={key}><dt>{sourceLabels[key]}</dt><dd><code>{view.metrics[key].sources.join(';')}</code></dd></div>)}
{view.lifetimes.map(value => <div key={value.name}><dt>{lifetimeNames[value.name] ?? value.name}</dt><dd><code>{value.sources.join(';')}</code></dd></div>)}
</dl>
{view.issues.length > 0 && <code>{view.issues.join(' · ')}</code>}
</details>
</details>;
}
+3 -1
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { Archive, BrainCircuit, FileText, LoaderCircle } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import { ModelUsageDetails } from './ModelUsageDetails';
import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types';
const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN');
@@ -44,7 +45,7 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
<dl className="record-fields"><dt>请求输入估算</dt><dd>{number(plan.estimatedInputTokens)} tokens</dd><dt>输出 / 安全余量</dt><dd>{plan.budget.outputReservation === null ? '不附加上限' : number(plan.budget.outputReservation) + ' tokens'} / {number(plan.budget.safetyTokens)} tokens</dd>
<dt>模型上下文窗口</dt><dd>{plan.budget.contextLimit === null ? '由上游处理 · 无本地窗口限制' : number(plan.budget.contextLimit) + ' tokens'}</dd><dt>已报告输入</dt><dd>{plan.actualUsage?.prompt_tokens === undefined ? '服务未返回' : number(plan.actualUsage.prompt_tokens) + ' tokens'}</dd>
<dt>历史记录</dt><dd>保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录</dd>
<dt>上游缓存命中</dt><dd>{plan.actualUsage?.prompt_tokens_details?.cached_tokens === undefined ? '上游未报告' : number(plan.actualUsage.prompt_tokens_details.cached_tokens) + ' tokens'}</dd>
<dt>已报告输出</dt><dd>{plan.actualUsage?.completion_tokens === undefined ? '服务未返回' : number(plan.actualUsage.completion_tokens) + ' tokens'}</dd>
{plan.prefixAudit && <><dt>缓存前缀核对</dt><dd>{plan.prefixAudit.variants.map((variant, index) => <div key={variant.connectionId ?? index}>{variant.model} · {variant.previousPromptBytes === null ? '首次请求或新路线' : '共同前缀 ' + number(variant.commonPrefixBytes) + ' B'}{variant.reason === 'tool_surface_changed' ? ' · 可用工具已变化' : ''}</div>)}<small>共同前缀用于核对稳定性,不等于上游命中。</small></dd></>}
{observation && <><dt>请求归属</dt><dd>{({ main: '主任务', diagnostic: '独立诊断', worker: '子任务' } as Record<string, string>)[observation.path.kind] ?? observation.path.kind}</dd></>}
{userMessage && <><dt>用户消息实例</dt><dd><code title={userMessage.id}>{userMessage.id.slice(0, 12)}</code><small>同样的文字分别记录,不按文本合并。</small></dd></>}
@@ -54,6 +55,7 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
{!!plan.skillCatalogEntries && <><dt>技能目录</dt><dd>{plan.skillCatalogEntries} 项本次目录记录</dd></>}
<dt>发送内容</dt><dd>{number(plan.requestBytes)} B<code className="context-sha" title={plan.requestSha256}>{plan.requestSha256.slice(0, 16)}</code></dd>
</dl>
<ModelUsageDetails key={'usage-' + plan.id} usage={plan.actualUsage} expanded />
{surface && <details className="context-tool-surface" key={plan.id}><summary>本轮工具 · 可见 {surface.entries.filter(entry => entry.visible).length} / 已登记 {surface.entries.length}</summary>
<p className="record-footnote">这是本次实际发送的工具范围。资源和权限在执行时重新核对;登记不代表本轮可用。</p>
<ul aria-label="本轮工具可见性">{surface.entries.map(entry => <li key={entry.name}>
+3 -1
View File
@@ -1,3 +1,5 @@
import type { TokenUsage } from '../shared/contracts/model-usage.mjs';
export interface Config {
approvalMode?: 'ask' | 'auto' | 'full';
mode: 'demo' | 'compatible'; baseUrl: string; model: string;
@@ -193,7 +195,7 @@ export interface ContextPlan {
latestToolsArtifactId?: string | null; latestToolsSha256?: string | null; latestToolsEntries?: number;
projectMemoryArtifactId?: string | null; projectMemorySha256?: string | null; projectMemoryEntries?: number;
skillCatalogArtifactId?: string | null; skillCatalogSha256?: string | null; skillCatalogEntries?: number;
actualUsage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number; prompt_tokens_details?: { cached_tokens?: number; cache_creation_tokens?: number } } | null; requestAttempts: number; error?: string;
actualUsage: TokenUsage | null; requestAttempts: number; error?: string;
historyPolicy?: 'preserve' | 'compact'; contextLayout?: string;
prefixAudit?: { schemaVersion: number; previousPlanId: string | null; variants: { connectionId: string | null; model: string; commonPrefixBytes: number; previousPromptBytes: number | null; reason: string; toolNames: string[]; toolsSha256: string;
firstChange?: { path: string; kind: string; sha256: string | null; previousSha256: string | null } | null;