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 = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' }; const toolReasons: Record = { 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 = { 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([]); const [selected, setSelected] = useState(''); const [historyId, setHistoryId] = useState(''); useEffect(() => { let alive = true; setHistorical([]); setSelected(''); setHistoryId(''); if (runId && runId !== session.execution?.run?.id) { api('/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

请求上下文

{states[plan.status] ?? plan.status}
{plans.length > 1 && } {plan.budget.contextLimit !== null &&
}
请求输入估算
{number(plan.estimatedInputTokens)} tokens
输出 / 安全余量
{plan.budget.outputReservation === null ? '不附加上限' : number(plan.budget.outputReservation) + ' tokens'} / {number(plan.budget.safetyTokens)} tokens
模型上下文窗口
{plan.budget.contextLimit === null ? '由上游处理 · 无本地窗口限制' : number(plan.budget.contextLimit) + ' tokens'}
已报告输入
{plan.actualUsage?.prompt_tokens === undefined ? '服务未返回' : number(plan.actualUsage.prompt_tokens) + ' tokens'}
历史记录
保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录
已报告输出
{plan.actualUsage?.completion_tokens === undefined ? '服务未返回' : number(plan.actualUsage.completion_tokens) + ' tokens'}
{plan.prefixAudit && <>
缓存前缀核对
{plan.prefixAudit.variants.map((variant, index) =>
{variant.model} · {variant.previousPromptBytes === null ? '首次请求或新路线' : '共同前缀 ' + number(variant.commonPrefixBytes) + ' B'}{variant.reason === 'tool_surface_changed' ? ' · 可用工具已变化' : ''}
)}共同前缀用于核对稳定性,不等于上游命中。
} {plan.requestContractAudit && <>
版本与非提示参数
{plan.requestContractAudit.variants.map((variant, index) => )}
} {observation && <>
请求归属
{({ main: '主任务', diagnostic: '独立诊断', worker: '子任务' } as Record)[observation.path.kind] ?? observation.path.kind}
} {userMessage && <>
用户消息实例
{userMessage.id.slice(0, 12)}同样的文字分别记录,不按文本合并。
} {plan.prefixAudit?.variants.some(variant => variant.firstChange && variant.previousPromptBytes !== null) && <>
首次变化位置
{plan.prefixAudit.variants.filter(variant => variant.previousPromptBytes !== null).map((variant, index) =>
{variant.model} · {variant.firstChange ? changeLabel(variant.firstChange.path) : '前缀内容相同'}
)}
} {!!plan.workingSetEntries && <>
当前任务依据
{plan.workingSetEntries} 项代码与执行结果
} {!!plan.projectMemoryEntries && <>
项目记忆
{plan.projectMemoryEntries} 条来源已核对的记录
} {!!plan.skillCatalogEntries && <>
技能目录
{plan.skillCatalogEntries} 项本次目录记录
}
发送内容
{number(plan.requestBytes)} B{plan.requestSha256.slice(0, 16)}
{surface &&
本轮工具 · 可见 {surface.entries.filter(entry => entry.visible).length} / 已登记 {surface.entries.length}

这是本次实际发送的工具范围。资源和权限在执行时重新核对;登记不代表本轮可用。

    {surface.entries.map(entry =>
  • {entry.name}{toolReasons[entry.reason] ?? entry.reason}
    {number(entry.definitionBytes)} B · schema {entry.schemaSha256.slice(0, 12)} · 代次 {entry.generation.slice(0, 8)}
  • )}
}

估算包含系统提示、工具定义和历史。{plan.budget.capacityMode === 'passthrough' ? '本次完整传递历史,不按本地上下文额度裁剪或拒发。' : plan.historyPolicy === 'preserve' ? '本次完整传递历史,容量不足时暂停。' : '任务要求完整保留;整理过的原记录可从本机工件检索。'}实际用量与缓存命中以模型服务为准。

{plan.error &&

{plan.error}

}
{plan.workingSetArtifactId && } {plan.latestToolsArtifactId && } {plan.projectMemoryArtifactId && } {plan.skillCatalogArtifactId && } {!!plan.archivedGroups && }
{historyId && setHistoryId('')} openArtifact={id => { setHistoryId(''); openArtifact(id); }} />}
; } 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(null), [offset, setOffset] = useState(0), [loading, setLoading] = useState(false); useEffect(() => { let alive = true; setLoading(true); api('/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
{loading ?

正在核对历史工件

: history?.groups.map(group =>
{groupTitle(group)}原消息 {group.startMessage + 1}–{group.endMessage + 1}
SHA256 {group.sha256.slice(0, 20)} {!!group.archive.chunks &&

原记录较大,已保存 {group.archive.chunks} 份可核验分片。

} {group.tools?.map(tool =>
{toolNames[tool.name] ?? tool.name}{tool.call_id} {(tool.requires_verification || tool.result.requires_verification || tool.result.status === 'unknown') && 结果需核对} {tool.result.path && {tool.result.path}}{tool.result_artifact_id && }
)}
)}
记录 {history ? Math.min(history.totalGroups, history.offset + 1) + '–' + Math.min(history.totalGroups, history.offset + history.groups.length) + ' / ' + history.totalGroups : '正在读取'}
; }