92 lines
9.0 KiB
TypeScript
92 lines
9.0 KiB
TypeScript
import { useEffect, useState } from 'react';
|
||
import { Archive, BrainCircuit, FileText, LoaderCircle } from 'lucide-react';
|
||
import { api } from './api';
|
||
import { Modal } from './components';
|
||
import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types';
|
||
|
||
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
|
||
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
|
||
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 total = plan.estimatedInputTokens + plan.budget.outputReservation + 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>}
|
||
<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>{number(plan.budget.outputReservation)} / {number(plan.budget.safetyTokens)} tokens</dd>
|
||
<dt>模型上下文窗口</dt><dd>{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>
|
||
{!!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>
|
||
<p className="record-footnote">估算包含系统提示、工具定义和历史。任务要求完整保留;省略的原记录可从本机工件检索。实际用量以模型服务为准。</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>;
|
||
}
|