import { ModelIdentityDetails } from './ModelIdentityDetails'; import { useEffect, useRef, useState } from 'react'; import { Check, ClipboardCheck, FileText, GitBranch, LoaderCircle, Play, RefreshCw, ShieldQuestion } from 'lucide-react'; import type { ArtifactPreview, CheckPlan, Project, PythonRuntimeIdentity, Run, Session } from './types'; import { api } from './api'; import { Modal, Status } from './components'; import { DeliveryPanel } from './DeliveryPanel'; import { RequestContextPanel } from './RequestContextPanel'; import { WorkspacePanel } from './WorkspacePanel'; import { BrowserPanel } from './BrowserPanel'; import { TaskPlanPanel } from './TaskPlanPanel'; import { TaskCheckpointPanel } from './TaskCheckpointPanel'; import { McpJobHistory } from './McpJobHistory'; import './TaskPanel.css'; import { EnvironmentPanel } from './EnvironmentPanel'; import { PreviewPanel } from './PreviewPanel'; import { FileResultsPanel } from './FileResultsPanel'; const stopReasons: Record = { model_identity: '模型返回型号需要核对', no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' }; const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN'); stopReasons.git_review = 'Git预览已保存,等待审查与确认'; stopReasons.change_set_review = '完整文件批次已封存,等待审查与应用'; stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留'; stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续'; stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与交付状态保持'; stopReasons.verification_incomplete = '答复已收到,当前任务的工程检查尚未通过'; stopReasons.delivery_incomplete = '答复已收到,当前文件成果或要求的修改仍需核对'; const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中'; export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate, onOpenPreview }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onOpenPreview?:()=>void; onWorkspaceRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise; onWorkspaceNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise }) { const execution = session.execution, task = execution?.task; const [runId, setRunId] = useState(''); const [historicalRun, setHistoricalRun] = useState(null); const [preview, setPreview] = useState(null); const [previewBusy, setPreviewBusy] = useState(false); const [planning, setPlanning] = useState(false); const [confirmPlan, setConfirmPlan] = useState(null); const [selectedChecks, setSelectedChecks] = useState([]); const [starting, setStarting] = useState(false); const artifactRequest = useRef(0); const actionScope = useRef(0); const id = runId || execution?.run?.id || ''; const run = id === execution?.run?.id ? execution.run : historicalRun; const plans = execution?.plans ?? []; const latestPlan = plans.filter(plan => plan.taskId === task?.id).at(-1); const checkChoices = latestPlan ? [...(latestPlan.project.packageManager === 'npm' ? latestPlan.project.scripts ?? [] : []), ...(latestPlan.project.python?.checks ?? [])] : []; const checksChanged = !!latestPlan && JSON.stringify(selectedChecks.slice().sort()) !== JSON.stringify(latestPlan.checks.map(check => check.name).sort()); const jobs = execution?.checks ?? []; const checkRunning = jobs.some(job => ['queued', 'running'].includes(job.status)); useEffect(() => { setSelectedChecks(latestPlan?.checks.map(check => check.name) ?? []); }, [latestPlan?.id]); useEffect(() => { setRunId(''); setHistoricalRun(null); setPreview(null); setPreviewBusy(false); setConfirmPlan(null); setPlanning(false); setStarting(false); artifactRequest.current++; actionScope.current++; return () => { artifactRequest.current++; actionScope.current++; }; }, [session.id, task?.id]); useEffect(() => { if (!id || id === execution?.run?.id) return; let alive = true; setHistoricalRun(null); api('/sessions/' + session.id + '/runs/' + id).then(value => { if (alive) setHistoricalRun(value); }).catch(error => { if (alive) onError(error); }); return () => { alive = false; }; }, [session.id, id, execution?.run?.id]); async function openArtifact(artifactId: string, offset = 0) { const request = ++artifactRequest.current; setPreviewBusy(true); try { const value = await api('/artifacts/' + artifactId + '?session=' + session.id + '&offset=' + offset + '&limit=16000'); if (artifactRequest.current === request) setPreview(value); } catch (error) { if (artifactRequest.current === request) onError(error); } finally { if (artifactRequest.current === request) setPreviewBusy(false); } } async function planChecks(names?: string[]) { const scope = actionScope.current; setPlanning(true); try { const value = await api('/sessions/' + session.id + '/check-plans', names ? { names } : {}); if (actionScope.current === scope) onSession(value); } catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setPlanning(false); } } async function runChecks() { if (!confirmPlan) return; setStarting(true); const scope = actionScope.current; try { const value = await api('/sessions/' + session.id + '/check-jobs', { planId: confirmPlan.id }); if (actionScope.current === scope) { onSession(value); setConfirmPlan(null); } } catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setStarting(false); } } async function stopCheck(jobId: string) { const scope = actionScope.current; try { const value = await api('/sessions/' + session.id + '/check-jobs/' + jobId + '/stop', {}); if (actionScope.current === scope) onSession(value); } catch (error) { if (actionScope.current === scope) onError(error); } } return

任务目标

{task && }
{task ? <>

{task.contract?.goal || task.goal}

{task.id.slice(0, 8)} · 任务 {task.contract?.checks === 'skip' &&

检查约定:按用户要求不自动测试。

} {task.contract?.inheritedFromTaskId &&

原目标续接自 {task.contract.inheritedFromTaskId.slice(0, 8)},历史记录保留。

} {task.delivery?.status === 'files_applied' &&
文件已应用{task.delivery.paths.map(path =>

{path}

)}{task.delivery.checks === 'not_requested' &&

已按原要求交付文件,未运行测试。

}
} {!!task.instructions.length &&
追加要求 · {task.instructions.length}{task.instructions.map(instruction =>

{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}
{instruction.content}

)}
} :

发送任务后,这里保存目标、每次运行和实际结果。

}
{task && } {task && } {task && } {execution?.progress.requiresVerification.length ?
{execution.progress.requiresVerification.length} 项结果需要核对

这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。

{execution.progress.requiresVerification.map(tool => {tool.tool} · {tool.id.slice(0, 8)})}
: null} {task && !!execution?.mcpJobs?.length && } {task &&

运行记录

{execution?.runs.filter(item => item.taskId === task.id).length} 次
{run ? <>
{run.id.slice(0, 8)}
{run.status === 'needs_review' && task.delivery?.status === 'files_applied' &&

这次运行在文件审查前结束;文件此后已应用,当前交付状态见上方任务目标。

} {run.purpose === 'diagnostic' &&

本次为只读诊断,运行结束仅表示答复完成;原任务状态另行保留。

}
{run.workspaceIdentity && <>
执行目录
{run.workspaceIdentity.root}
{run.workspaceIdentity.branch && <>
独立分支
{run.workspaceIdentity.branch}
}}
开始 / 结束
{time(run.startedAt)}
{time(run.finishedAt)}
模型轮次 / 工具
{run.steps} / {run.toolCalls}
已报告用量
{number(run.usage?.totalTokens)} tokens
输入 {number(run.usage?.inputTokens)} · 输出 {number(run.usage?.outputTokens)}
{!!run.usage?.unknownRequests && <>
未报告用量
{run.usage.unknownRequests} 次请求 · 估算 {number(run.usage.estimatedUnknownTokens)} tokens
}
本次预算
{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮
任务累计
{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens
{run.stopReason &&

{stopReasons[run.stopReason] || run.stopReason}

}

用量按请求尝试累计,包含失败响应已报告的 tokens;未报告的请求单独估算。历史缺失不补造,tokens 不等于费用。

:

正在读取运行记录

}
} {run && } {task && } {task && }

工程检查

{task?.verification.status === 'failed' &&

原工程检查有失败记录;文件应用或答复完成不代表检查通过。

} {task?.contract?.checks === 'skip' &&

原任务无需测试。下方操作只在你明确选择并确认后执行。

}

检查对应当时的工程快照。先识别测试与执行环境,再确认检查;项目变化后重新检查。

{latestPlan &&

{latestPlan.project.name} · {latestPlan.project.languages.join(' / ') || '待识别'}

{latestPlan.project.git.available ? `${latestPlan.project.git.branch || 'detached'} · ${latestPlan.project.git.head?.slice(0, 8) || '尚无提交'}${latestPlan.project.git.dirty ? ' · 有未提交改动' : ' · 工作区干净'}` : '项目尚未启用 Git'}

{latestPlan.environment&&

环境:Node {latestPlan.environment.runtime.node.version} · npm {latestPlan.environment.runtime.npm?.version??'未找到'} · {latestPlan.environment.status==='ready'?'依赖已就绪':'依赖需要核对,请先查看上方工程环境'}{latestPlan.environment.preparation&&' · 引用依赖准备 '+latestPlan.environment.preparation.jobId.slice(0,8)}

} {latestPlan.project.python?.status === 'invalid' &&

{latestPlan.project.python.message}

} {checkChoices.length > 0 &&
选择检查范围 {checkChoices.map(check => )} {checksChanged && <>

按所选范围重新识别,确认后执行新计划。

}
} {latestPlan.checks.length ? <>
    {latestPlan.checks.map(check =>
  • {check.name}{check.command}
  • )}
{latestPlan.checks.find(check => check.python)?.python && check.python)!.python!.runtime} />} :

没有识别到可执行的检查。请配置项目测试或构建。

}
} {jobs.slice().reverse().map(job =>
{job.id.slice(0, 8)}{['queued', 'running'].includes(job.status) && }
{job.currentCheck &&

正在执行 {job.currentCheck.command}

}{job.summary &&

{job.summary}

} {job.results.map(result =>
{result.name}

退出码 {result.exitCode === null ? '未返回' : result.exitCode} · {(result.durationMs / 1000).toFixed(1)} 秒{result.tests && ` · 测试 ${result.tests.passed}/${result.tests.total} 通过`}{!!result.tests?.failed && ` · 失败 ${result.tests.failed}`}{!!result.tests?.skipped && ` · 跳过 ${result.tests.skipped}`}{!!result.collectionErrors && ` · 收集错误 ${result.collectionErrors}`}

{result.python && } {result.compilation &&

语法编译 {result.compilation.compiled}/{result.compilation.total} 个源码文件

} {result.reason &&

{result.reason}

} {result.logArtifactId && } {result.metricsArtifactId && }
)}
)}
{task && } {task && } {!!execution?.artifacts.length &&

结果工件

最近 {execution.artifacts.length} 项
{execution.artifacts.filter(artifact => !artifact.mediaType?.startsWith('image/')).slice().reverse().map(artifact => )}
} {confirmPlan && setConfirmPlan(null)}>
{confirmPlan.checks.map(check =>
{check.command}
{check.script}{check.lifecycle?.length ? '\n\n' + check.lifecycle.map(item => item.name + ': ' + item.script).join('\n') : ''}
{check.python && }
)}

{confirmPlan.project.name}

} {preview && { artifactRequest.current++; setPreview(null); setPreviewBusy(false); }}>
{preview.content}
字符 {number(preview.offset)}–{number(preview.offset + preview.content.length)} / {number(preview.totalCharacters)}
}
; } function ActualModelFields({ run, session }: { run: Run; session: Session }) { const receipts = run.consumption ?? []; const events = session.events.filter(event => event.runId === run.id && event.actualModel && event.connectionId); const observed = receipts.length ? receipts.map(receipt => ({ id: receipt.connectionId, name: receipt.connectionName, model: receipt.model, endpoint: receipt.endpoint, identity: receipt.modelIdentity })) : events.map(event => { const member = run.model.routing?.members?.find(member => member.id === event.connectionId); return { id: event.connectionId, name: member?.name, model: event.actualModel!, endpoint: member?.baseUrl, identity: undefined }; }); const routes = observed.filter((value, index) => observed.findIndex(candidate => candidate.id === value.id && candidate.model === value.model && candidate.endpoint === value.endpoint && JSON.stringify(candidate.identity) === JSON.stringify(value.identity)) === index); return <>
启动选择
{run.model?.verified === false ? '历史配置未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model.routing?.name || run.model.model || '未记录'}
实际调用
{routes.length ? routes.map((route, index) =>
{route.name ? route.name + ' · ' : ''}{route.model}{route.endpoint &&
{route.endpoint}
}
) : run.model.mode === 'demo' ? '未调用模型服务' : '尚无可核对的实际连接记录'}
{!receipts.length && run.model.mode !== 'demo' && <>
启动接口
{run.model.baseUrl || '未记录'}
启动配置不代表实际池成员
} {!!receipts.length && <>
用量凭据
{receipts.length} 次请求尝试 · {receipts.filter(receipt => receipt.usageStatus === 'reported').length} 次已报告
} ; } function PythonRuntimeInfo({ runtime }: { runtime: PythonRuntimeIdentity }) { return
Python {runtime.version || (runtime.status === 'deferred' ? '执行时核对版本' : '尚未找到')} {runtime.logicalExecutable || runtime.executable || '请安装Python或配置项目虚拟环境'}{runtime.message &&

{runtime.message}

}
; }