116 lines
13 KiB
TypeScript
116 lines
13 KiB
TypeScript
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';
|
||
import { ModelRequestDetails } from './ModelRequestDetails';
|
||
import { ModelProviderStateDetails } from './ModelProviderStateDetails';
|
||
|
||
const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN');
|
||
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
|
||
const toolReasons: Record<string, string> = { visible: '本轮可见', not_assembled: '未装配', missing_current_resource: '缺少当前任务资源', disabled: '已停用',
|
||
disabled_by_policy: '当前策略未启用', disabled_by_execution_mode: '当前执行方式未启用', disabled_by_worker_contract: '子任务范围外', disabled_by_task_contract: '当前任务约定不执行', not_assembled_for_worker: '子任务未装配' };
|
||
const changeLabel = (path: string) => path === 'tools' ? '工具定义' : path === 'model' ? '请求型号' : path === 'system' ? '系统规则'
|
||
: path.startsWith('messages[') || path.startsWith('input[') ? '消息段 ' + (Number(path.match(/\[(\d+)\]/)?.[1]) + 1) : path;
|
||
const toolNames: Record<string, string> = { read_file: '读取文件', read_artifact: '读取保存工件', inspect_project: '识别工程', inspect_session: '核对运行记录',
|
||
index_project: '建立符号索引', query_code: '定位代码', propose_patch: '精确补丁提案', propose_file: '文件提案', run_command: '终端命令', run_checks: '工程检查',
|
||
plan_checks: '检查计划', prepare_change_set: '封存变更集', plan_delivery: 'Git交付预览', delivery_report: '交付报告', list_files: '查看文件', search_files: '搜索文件' };
|
||
|
||
export function RequestContextPanel({ session, runId, openArtifact, onError }: {
|
||
session: Session; runId: string; openArtifact: (id: string) => void; onError: (error: unknown) => void;
|
||
}) {
|
||
const [historical, setHistorical] = useState<ContextPlan[]>([]);
|
||
const [selected, setSelected] = useState('');
|
||
const [historyId, setHistoryId] = useState('');
|
||
useEffect(() => {
|
||
let alive = true; setHistorical([]); setSelected(''); setHistoryId('');
|
||
if (runId && runId !== session.execution?.run?.id) {
|
||
api<ContextPlan[]>('/sessions/' + session.id + '/context-plans?run=' + runId).then(value => { if (alive) setHistorical(value); })
|
||
.catch(error => { if (alive) onError(error); });
|
||
}
|
||
return () => { alive = false; };
|
||
}, [session.id, runId, session.execution?.run?.id]);
|
||
const plans = runId === session.execution?.run?.id ? session.execution?.contextPlans?.filter(plan => plan.runId === runId) ?? []
|
||
: historical.filter(plan => plan.runId === runId && plan.sessionId === session.id);
|
||
const plan = plans.find(plan => plan.id === selected) ?? plans.at(-1);
|
||
if (!plan) return null;
|
||
const observation = plan.requestObservation, surface = observation?.toolSurface;
|
||
const userMessage = observation?.userMessageInstances.filter(message => message.origin === 'user').at(-1);
|
||
const total = plan.estimatedInputTokens + (plan.budget.outputReservation ?? 0) + plan.budget.safetyTokens;
|
||
return <section className="task-record-section request-context" aria-label="请求上下文">
|
||
<div className="record-heading"><BrainCircuit size={15} /><h3>请求上下文</h3><span>{states[plan.status] ?? plan.status}</span></div>
|
||
{plans.length > 1 && <label className="run-picker">查看一次模型请求<select aria-label="选择模型请求" value={plan.id} onChange={event => setSelected(event.target.value)}>
|
||
{plans.map((value, index) => <option key={value.id} value={value.id}>第 {value.requestIndex ?? index + 1} 次 · {states[value.status] ?? value.status}</option>)}
|
||
</select></label>}
|
||
{plan.budget.contextLimit !== null && <div className="context-meter" aria-label="估算上下文占用"><i style={{ width: Math.min(100, total / plan.budget.contextLimit * 100) + '%' }} /></div>}
|
||
<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?.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></>}
|
||
{plan.requestContractAudit && <><dt>版本与非提示参数</dt><dd>{plan.requestContractAudit.variants.map((variant, index) => <ModelRequestDetails key={index} request={variant} />)}</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></>}
|
||
{plan.prefixAudit?.variants.some(variant => variant.firstChange && variant.previousPromptBytes !== null) && <><dt>首次变化位置</dt><dd>{plan.prefixAudit.variants.filter(variant => variant.previousPromptBytes !== null).map((variant, index) => <div key={variant.connectionId ?? index}>{variant.model} · {variant.firstChange ? changeLabel(variant.firstChange.path) : '前缀内容相同'}</div>)}</dd></>}
|
||
{!!plan.workingSetEntries && <><dt>当前任务依据</dt><dd>{plan.workingSetEntries} 项代码与执行结果</dd></>}
|
||
{!!plan.projectMemoryEntries && <><dt>项目记忆</dt><dd>{plan.projectMemoryEntries} 条来源已核对的记录</dd></>}
|
||
{!!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>
|
||
<ModelProviderStateDetails audit={plan.nativeStateAudit} />
|
||
<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}>
|
||
<div><code>{entry.name}</code><span>{toolReasons[entry.reason] ?? entry.reason}</span></div>
|
||
<small title={'schema ' + entry.schemaSha256 + ' · generation ' + entry.generation}>{number(entry.definitionBytes)} B · schema {entry.schemaSha256.slice(0, 12)} · 代次 {entry.generation.slice(0, 8)}</small>
|
||
</li>)}</ul>
|
||
</details>}
|
||
<p className="record-footnote">估算包含系统提示、工具定义和历史。{plan.budget.capacityMode === 'passthrough' ? '本次完整传递历史,不按本地上下文额度裁剪或拒发。' : plan.historyPolicy === 'preserve' ? '本次完整传递历史,容量不足时暂停。' : '任务要求完整保留;整理过的原记录可从本机工件检索。'}实际用量与缓存命中以模型服务为准。</p>
|
||
{plan.error && <p className="run-stop">{plan.error}</p>}
|
||
<div className="context-actions"><button type="button" className="text-button" onClick={() => openArtifact(plan.requestArtifactId)}><FileText size={13} />查看发送内容</button>
|
||
<button type="button" className="text-button" onClick={() => openArtifact(plan.artifactId)}><FileText size={13} />查看请求计划</button>
|
||
{plan.workingSetArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.workingSetArtifactId!)}><BrainCircuit size={13} />查看工作依据</button>}
|
||
{plan.latestToolsArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.latestToolsArtifactId!)}><FileText size={13} />查看最近工具反馈</button>}
|
||
{plan.projectMemoryArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.projectMemoryArtifactId!)}><BrainCircuit size={13} />查看本次项目记忆</button>}
|
||
{plan.skillCatalogArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.skillCatalogArtifactId!)}><FileText size={13} />查看本次技能目录</button>}
|
||
{!!plan.archivedGroups && <button type="button" className="text-button" onClick={() => setHistoryId(plan.id)}><Archive size={13} />检索完整历史</button>}</div>
|
||
{historyId && <HistoryModal key={session.id + ':' + historyId} sessionId={session.id} planId={historyId} onError={onError}
|
||
onClose={() => setHistoryId('')} openArtifact={id => { setHistoryId(''); openArtifact(id); }} />}
|
||
</section>;
|
||
}
|
||
|
||
function groupTitle(group: ContextHistoryGroup) {
|
||
if (group.tools?.length) return group.tools.map(tool => toolNames[tool.name] ?? tool.name).join(' · ');
|
||
return group.roles[0] === 'user' ? '用户要求' : '助手记录';
|
||
}
|
||
|
||
function HistoryModal({ sessionId, planId, onClose, openArtifact, onError }: {
|
||
sessionId: string; planId: string; onClose: () => void; openArtifact: (id: string) => void; onError: (error: unknown) => void;
|
||
}) {
|
||
const [history, setHistory] = useState<ContextHistory | null>(null), [offset, setOffset] = useState(0), [loading, setLoading] = useState(false);
|
||
useEffect(() => {
|
||
let alive = true; setLoading(true);
|
||
api<ContextHistory>('/sessions/' + sessionId + '/context-plans/' + planId + '/history?offset=' + offset + '&limit=12')
|
||
.then(value => { if (alive) setHistory(value); }).catch(error => { if (alive) onError(error); }).finally(() => { if (alive) setLoading(false); });
|
||
return () => { alive = false; };
|
||
}, [sessionId, planId, offset]);
|
||
return <Modal title="完整历史记录" description="这些记录已从本次请求中省略,原始参数和实际结果仍保存在本机。读取记录不会执行工具。" wide onClose={onClose}>
|
||
<div className="context-history-list" aria-busy={loading}>{loading ? <p className="record-empty"><LoaderCircle size={15} className="spin" />正在核对历史工件</p>
|
||
: history?.groups.map(group => <article className="context-history-group" key={group.index}>
|
||
<div><strong>{groupTitle(group)}</strong><small>原消息 {group.startMessage + 1}–{group.endMessage + 1}</small></div>
|
||
<code className="context-sha" title={group.sha256}>SHA256 {group.sha256.slice(0, 20)}</code>
|
||
{!!group.archive.chunks && <p>原记录较大,已保存 {group.archive.chunks} 份可核验分片。</p>}
|
||
{group.tools?.map(tool => <div className="context-history-tool" key={tool.call_id}><span>{toolNames[tool.name] ?? tool.name}</span><code>{tool.call_id}</code>
|
||
{(tool.requires_verification || tool.result.requires_verification || tool.result.status === 'unknown') && <span className="context-unknown">结果需核对</span>}
|
||
{tool.result.path && <small>{tool.result.path}</small>}{tool.result_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(tool.result_artifact_id!)}>读取工具结果</button>}
|
||
</div>)}
|
||
<button type="button" className="text-button" onClick={() => openArtifact(group.archive.artifact_id)}><FileText size={13} />读取原记录</button>
|
||
</article>)}</div>
|
||
<div className="artifact-pagination"><span>记录 {history ? Math.min(history.totalGroups, history.offset + 1) + '–' + Math.min(history.totalGroups, history.offset + history.groups.length) + ' / ' + history.totalGroups : '正在读取'}</span>
|
||
<button type="button" className="button secondary" disabled={loading || offset === 0} onClick={() => setOffset(Math.max(0, offset - 12))}>上一页</button>
|
||
<button type="button" className="button secondary" disabled={loading || !history?.truncated} onClick={() => setOffset(offset + 12)}>下一页</button></div>
|
||
</Modal>;
|
||
}
|