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'; const stopReasons: Record = { 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.git_review_declined = 'Git预览已撤回,文件和检查记录保留'; stopReasons.task_plan_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 }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; 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.goal}

{task.id.slice(0, 8)} · 任务 {!!task.instructions.length &&
追加要求 · {task.instructions.length}{task.instructions.map(instruction =>

{instruction.content}

)}
} :

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

}
{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.model?.verified === false ? '历史模型信息未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model?.model || '未记录'}
接口
{run.model?.verified === false ? '未记录' : run.model?.baseUrl || '本地演示'}
{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}

}

用量以服务返回为准;未报告的请求单独估算。

:

正在读取运行记录

}
} {run && }

工程检查

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

{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.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 PythonRuntimeInfo({ runtime }: { runtime: PythonRuntimeIdentity }) { return
Python {runtime.version || (runtime.status === 'deferred' ? '执行时核对版本' : '尚未找到')} {runtime.logicalExecutable || runtime.executable || '请安装Python或配置项目虚拟环境'}{runtime.message &&

{runtime.message}

}
; }