Files
UHD_Media_Tool/apps/web/app/components/agent/agent-run-panel.tsx
T
rootandClaude Opus 5.5 7103bc8f7c feat(web): W3-3 site workbench, sources/feeds/snapshots, downloads with business timeline, organization records and agent sessions
- sites + /sites/:siteId: organized view with snapshot-first release list, inventory overlay,
  candidate reasons, volatile-field recheck, stale marking that keeps existing data, live search,
  unified download entry; origin view placeholder (M2)
- sources: feed CRUD/enable/fetch/reset, cursor/health/gap hints; per-site snapshot history
- tasks: download tasks with pause/resume (threshold pause cannot be bypassed), plans,
  cache volume thresholds and cleanup, business timeline (observation → plan → download →
  organization → agent/engine)
- organize: record list/detail with file-level results, manual organize with dryRun preview
- agent: session list/page and layout drawer with context prefix; streaming events,
  tool cards, rejection alerts, compaction, budget meters, model text vs server report;
  mock switch (?mock=1) until W2-D endpoints land

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-27 20:52:32 +08:00

213 lines
6.9 KiB
TypeScript

import { Send, Square } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import {
type AgentMode,
agentMockEnabled,
isRunActive,
useAbortAgentRun,
useAgentRun,
useAppendAgentMessage,
} from "~/api/agent.ts";
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
import { ErrorState, LoadingState } from "~/components/console/empty-state.tsx";
import { StatusBadge } from "~/components/console/status-badge.tsx";
import { Button } from "~/components/ui/button.tsx";
import { Textarea } from "~/components/ui/textarea.tsx";
import { errorMessage } from "~/lib/api.ts";
import { cn, formatDateTime } from "~/lib/utils.ts";
import { AgentConversation, BudgetBar, FinalReport, RunStatusBadge } from "./agent-conversation.tsx";
import { useAgentStream } from "./use-agent-stream.ts";
const TRIGGER_LABEL = { user: "用户发起", event: "事件触发", schedule: "定时", subagent: "子代理" } as const;
/** 目标输入:execute / plan_only 分段切换 + 文本框 */
export function GoalComposer({
onSubmit,
pending,
prefix,
defaultGoal = "",
compact = false,
}: {
onSubmit: (goal: string, mode: AgentMode) => void;
pending: boolean;
/** 上下文前缀(只读展示) */
prefix?: string;
defaultGoal?: string;
compact?: boolean;
}) {
const [goal, setGoal] = useState(defaultGoal);
const [mode, setMode] = useState<AgentMode>("execute");
const submit = () => {
const g = goal.trim();
if (!g) {
toast.error("先写下目标");
return;
}
onSubmit(g, mode);
};
return (
<form
className="space-y-2"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
{prefix ? (
<p
className="truncate rounded-lg border border-border/70 px-2.5 py-1 font-mono text-meta text-muted-foreground"
title={prefix}
>
{prefix}
</p>
) : null}
<Textarea
value={goal}
onChange={(e) => setGoal(e.target.value)}
placeholder="例如:把 沙丘:第二部 的 4K 收进来"
rows={compact ? 3 : 3}
maxLength={4000}
aria-label="目标"
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
submit();
}
}}
/>
<div className="flex flex-wrap items-center justify-between gap-2">
<fieldset aria-label="运行模式" className="flex items-center gap-1">
{(
[
["execute", "授权内执行"],
["plan_only", "只要方案"],
] as const
).map(([v, label]) => (
<button
key={v}
type="button"
aria-pressed={mode === v}
onClick={() => setMode(v)}
className={cn(
"h-8 cursor-pointer rounded-full border border-transparent px-3 text-sm text-muted-foreground transition-colors duration-micro hover:text-foreground",
mode === v && "pill-selected text-foreground",
)}
>
{label}
</button>
))}
</fieldset>
<Button type="submit" size="sm" disabled={pending}>
<Send />
{pending ? "提交中…" : "开始"}
</Button>
</div>
<p className="text-meta text-muted-foreground">
{mode === "plan_only"
? "只调查、出方案,不执行任何写操作。"
: "在已授权范围内执行;未授权的动作会被服务端拒绝并在对话里标出。"}
</p>
</form>
);
}
/** 一次运行:头部状态 + 预算条 + 流式对话 + 最终汇报 + 追加消息 */
export function AgentRunPanel({ runId, compact = false }: { runId: string; compact?: boolean }) {
const run = useAgentRun(runId);
const active = isRunActive(run.data?.run.status);
const live = useAgentStream(runId, active || !run.data);
const abort = useAbortAgentRun();
const append = useAppendAgentMessage();
const [msg, setMsg] = useState("");
if (run.isPending) return <LoadingState rows={4} />;
if (run.error || !run.data) return <ErrorState plain error={run.error} onRetry={() => void run.refetch()} />;
const { run: r, report, messages } = run.data;
const finished = !isRunActive(r.status) || live.finished;
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<RunStatusBadge status={live.finished && isRunActive(r.status) ? "running" : r.status} />
<span className="text-meta text-muted-foreground">
{TRIGGER_LABEL[r.trigger]} · {formatDateTime(r.createdAt)}
{r.model ? ` · ${r.provider ?? ""}/${r.model}` : ""}
</span>
{agentMockEnabled() ? <StatusBadge tone="warning">mock 数据</StatusBadge> : null}
{active ? (
<ConfirmDialog
trigger={
<Button variant="destructive" size="sm" className="ml-auto" disabled={abort.isPending}>
<Square />
中止
</Button>
}
title="中止这次运行?"
description="停止后续步骤;已经完成的外部动作(如已提交的下载)不会被撤销。"
confirmLabel="中止"
destructive
onConfirm={() =>
abort.mutateAsync(r.id).then(
() => toast.success("已请求中止"),
(e) => toast.error(errorMessage(e)),
)
}
/>
) : null}
</div>
<div className={cn("rounded-xl border border-border/70 p-3", compact && "p-2.5")}>
<BudgetBar run={r} live={live} />
</div>
<AgentConversation
run={r}
live={live}
userMessages={messages.map((m) => ({ at: m.createdAt, text: m.text, pending: m.status === "pending" }))}
compact={compact}
/>
{finished ? <FinalReport run={r} report={report} live={live} /> : null}
<form
className="flex items-end gap-2"
onSubmit={(e) => {
e.preventDefault();
const text = msg.trim();
if (!text) return;
append.mutate(
{ id: r.id, text },
{
onSuccess: () => {
setMsg("");
void run.refetch();
},
onError: (err) => toast.error(errorMessage(err)),
},
);
}}
>
<Textarea
value={msg}
onChange={(e) => setMsg(e.target.value)}
rows={1}
maxLength={8000}
placeholder={active ? "补充或纠正(运行中也可追加)" : "追加消息,继续这次会话"}
aria-label="追加消息"
className="min-h-9 flex-1"
/>
<Button
type="submit"
size="icon"
variant="outline"
disabled={append.isPending || !msg.trim()}
aria-label="发送"
>
<Send />
</Button>
</form>
</div>
);
}