Auto-fix of 602 string literals across 74 files (half-width punctuation next to Chinese, parenthesised Chinese, quotes); biome reflow; e2/e6 assertions follow the new full-width summaries. check:copy now runs with --strict in ci. Co-Authored-By: Claude Opus 5.5 <[email protected]>
328 lines
12 KiB
TypeScript
328 lines
12 KiB
TypeScript
import { useQueryClient } from "@tanstack/react-query";
|
|
import { EventType } from "@umt/contracts";
|
|
import { FlaskConical, RefreshCw, Sparkles, WifiOff } from "lucide-react";
|
|
import { useId, useRef, useState } from "react";
|
|
import { toast } from "sonner";
|
|
import {
|
|
type AgentSessionOptions,
|
|
agentKeys,
|
|
agentMockEnabled,
|
|
isProposeFirst,
|
|
isRunActive,
|
|
useAbortAgentRun,
|
|
useAgentRun,
|
|
useAppendAgentMessage,
|
|
useRunApprovals,
|
|
useRunInvocationAudit,
|
|
} from "~/api/agent.ts";
|
|
import { MessageScroller } from "~/components/agentui/message-scroller.tsx";
|
|
import { PromptInput } from "~/components/agentui/prompt-input.tsx";
|
|
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 { Label } from "~/components/ui/label.tsx";
|
|
import { Switch } from "~/components/ui/switch.tsx";
|
|
import { errorMessage } from "~/lib/api.ts";
|
|
import { useSse, useSseStatus } from "~/lib/sse.ts";
|
|
import { cn, formatDateTime } from "~/lib/utils.ts";
|
|
import {
|
|
AgentConversation,
|
|
ApprovalItem,
|
|
BudgetBar,
|
|
FinalReport,
|
|
RunAnnouncer,
|
|
RunStatusBadge,
|
|
runPlanIds,
|
|
} from "./agent-conversation.tsx";
|
|
import { RunPlan } from "./agent-interaction.tsx";
|
|
import { SubagentTree } from "./agent-subagent-tree.tsx";
|
|
import { useAgentStream } from "./use-agent-stream.ts";
|
|
|
|
const TRIGGER_LABEL = { user: "用户发起", event: "事件触发", schedule: "定时", subagent: "子会话" } as const;
|
|
|
|
/** "先看方案再执行"开关(会话选项,默认关:自动化优先,按步骤直接执行,需授权的动作在步骤处审批) */
|
|
export function ProposeFirstToggle({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
|
|
const id = useId();
|
|
return (
|
|
<div className="flex items-center gap-2 px-1">
|
|
<Switch id={id} checked={checked} onCheckedChange={onChange} />
|
|
<Label htmlFor={id} className="cursor-pointer text-sm font-normal text-muted-foreground">
|
|
先看方案再执行
|
|
</Label>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** 新目标输入:"先看方案再执行"开关 + 自增高输入框(Enter 发送,Shift+Enter 换行) */
|
|
export function GoalComposer({
|
|
onSubmit,
|
|
pending,
|
|
prefix,
|
|
defaultGoal = "",
|
|
compact = false,
|
|
suggestions,
|
|
}: {
|
|
onSubmit: (goal: string, opts: AgentSessionOptions) => void;
|
|
pending: boolean;
|
|
/** 上下文前缀(只读展示,提交时拼在目标前) */
|
|
prefix?: string;
|
|
defaultGoal?: string;
|
|
compact?: boolean;
|
|
/** 快捷目标:点一下填入输入框(不直接提交),光标停在末尾 */
|
|
suggestions?: string[];
|
|
}) {
|
|
const [goal, setGoal] = useState(defaultGoal);
|
|
const [proposeFirst, setProposeFirst] = useState(false);
|
|
const box = useRef<HTMLDivElement>(null);
|
|
const fill = (text: string) => {
|
|
setGoal(text);
|
|
requestAnimationFrame(() => {
|
|
const ta = box.current?.querySelector("textarea");
|
|
if (!ta) return;
|
|
ta.focus();
|
|
ta.setSelectionRange(text.length, text.length);
|
|
});
|
|
};
|
|
return (
|
|
<div ref={box} className="space-y-1.5">
|
|
<PromptInput
|
|
value={goal}
|
|
onValueChange={setGoal}
|
|
onSubmit={(g) => onSubmit(g, { proposeFirst })}
|
|
pending={pending}
|
|
minRows={compact ? 2 : 3}
|
|
maxRows={10}
|
|
maxLength={4000}
|
|
aria-label="目标"
|
|
placeholder="例如:把 沙丘:第二部 的 4K 收进来"
|
|
submitLabel={pending ? "提交中" : "开始"}
|
|
header={
|
|
prefix ? (
|
|
<p
|
|
className="mx-1 mb-1 truncate rounded-lg border border-border/70 px-2.5 py-1 font-mono text-meta text-muted-foreground"
|
|
title={prefix}
|
|
>
|
|
{prefix}
|
|
</p>
|
|
) : null
|
|
}
|
|
toolbar={<ProposeFirstToggle checked={proposeFirst} onChange={setProposeFirst} />}
|
|
/>
|
|
<p className="px-1 text-meta text-muted-foreground" aria-live="polite">
|
|
{proposeFirst
|
|
? "Agent 先调查并给出方案,你选定后才执行。"
|
|
: "Agent 列出步骤后直接执行,需要审批的动作会停在对应步骤等你批准。"}{" "}
|
|
Enter 发送,Shift+Enter 换行。
|
|
</p>
|
|
{suggestions?.length ? (
|
|
<div className="pt-2">
|
|
<p className="mb-1.5 flex items-center gap-1.5 px-1 text-meta text-muted-foreground">
|
|
<Sparkles aria-hidden className="size-3.5" />
|
|
常用目标
|
|
</p>
|
|
<ul aria-label="快捷目标" className="flex flex-col gap-1.5">
|
|
{suggestions.map((s) => (
|
|
<li key={s}>
|
|
<button
|
|
type="button"
|
|
onClick={() => fill(s)}
|
|
className="w-full cursor-pointer rounded-xl border border-border/70 px-3 py-2 text-left text-caption text-foreground/90 outline-none transition-colors duration-micro hover:bg-foreground/[0.04] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
|
>
|
|
{s.endsWith(" ") || s.endsWith(":") ? `${s}…` : s}
|
|
</button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** 一次运行:头部状态 + 预算条 + 步骤清单 + 流式对话(方案选择 / 审批卡在对应步骤处)+ 最终汇报 + 输入框 */
|
|
export function AgentRunPanel({
|
|
runId,
|
|
compact = false,
|
|
className,
|
|
}: {
|
|
runId: string;
|
|
compact?: boolean;
|
|
className?: string;
|
|
}) {
|
|
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("");
|
|
const [confirmStop, setConfirmStop] = useState(false);
|
|
const sseStatus = useSseStatus();
|
|
const qc = useQueryClient();
|
|
const toolCount = live.items.filter((i) => i.kind === "tool" && i.call.status !== "running").length;
|
|
const audit = useRunInvocationAudit(runId, toolCount > 0, toolCount);
|
|
const approvals = useRunApprovals(runPlanIds(live.items, run.data?.report ?? null));
|
|
// 会话内审批卡已在对应步骤处显示,这里只补本次运行计划上的其它审批
|
|
const inline = new Set(live.items.flatMap((i) => (i.kind === "approval" ? [i.view.approvalId] : [])));
|
|
// run 状态变化(queued → running → 终态)经 SSE 推送:到达即刷新快照,不等 3 秒轮询
|
|
// 子会话:本会话收到子会话提示(agent.tool_call / agent.spawn)或任一子会话 / 父会话状态变化时刷新会话树
|
|
const related = new Set([
|
|
runId,
|
|
...(run.data?.children ?? []).map((c) => c.id),
|
|
...(run.data?.parent ? [run.data.parent.id] : []),
|
|
]);
|
|
useSse(
|
|
[EventType.agentRunStatus, EventType.agentToolCall],
|
|
(e) => {
|
|
const p = e.payload as { runId?: string; capabilityId?: string } | null;
|
|
if (!p?.runId) return;
|
|
const hit =
|
|
e.type === EventType.agentRunStatus
|
|
? related.has(p.runId)
|
|
: p.runId === runId && p.capabilityId === "agent.spawn";
|
|
if (hit) void qc.invalidateQueries({ queryKey: agentKeys.run(runId) });
|
|
},
|
|
!agentMockEnabled(),
|
|
);
|
|
|
|
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;
|
|
const streaming = active && !live.finished;
|
|
const proposeFirst = isProposeFirst(r);
|
|
const shownStatus =
|
|
// 事件流已结束但快照还没刷到终态时按运行中显示;waiting(等待下载/入库核验)照实显示
|
|
(live.finished && (r.status === "queued" || r.status === "running")) ||
|
|
(r.status === "queued" && live.events.length > 0)
|
|
? "running"
|
|
: r.status;
|
|
|
|
const send = (text: string) =>
|
|
append.mutate(
|
|
{ id: r.id, text },
|
|
{
|
|
onSuccess: () => {
|
|
setMsg("");
|
|
void run.refetch();
|
|
},
|
|
onError: (err) => toast.error(errorMessage(err)),
|
|
},
|
|
);
|
|
|
|
return (
|
|
<div className={cn("flex min-h-0 flex-col gap-3", className)}>
|
|
<RunAnnouncer status={shownStatus} finished={live.finished} />
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<RunStatusBadge status={shownStatus} />
|
|
{proposeFirst ? <StatusBadge>先看方案再执行</StatusBadge> : null}
|
|
<span className="min-w-0 text-meta text-muted-foreground">
|
|
{TRIGGER_LABEL[r.trigger]} · {formatDateTime(r.createdAt)}
|
|
{r.model ? ` · ${r.provider ?? ""}/${r.model}` : ""}
|
|
</span>
|
|
{agentMockEnabled() ? (
|
|
<StatusBadge tone="warning">
|
|
<FlaskConical className="size-3" />
|
|
mock 数据
|
|
</StatusBadge>
|
|
) : null}
|
|
</div>
|
|
|
|
<div className={cn("rounded-xl border border-border/70 p-3", compact && "p-2.5")}>
|
|
<BudgetBar run={r} live={live} />
|
|
</div>
|
|
|
|
<SubagentTree snapshot={run.data} />
|
|
|
|
<RunPlan plan={live.plan} active={streaming || r.status === "waiting"} compact={compact} />
|
|
|
|
{streaming && sseStatus === "reconnecting" ? (
|
|
<div
|
|
role="status"
|
|
className="flex items-center gap-2 rounded-xl border border-warning/40 bg-warning/10 px-3 py-2 text-caption text-warning"
|
|
>
|
|
<WifiOff aria-hidden className="size-4 shrink-0" />
|
|
<span className="min-w-0 flex-1">实时连接中断,正在重连。期间每 2.5 秒轮询一次。</span>
|
|
</div>
|
|
) : null}
|
|
{live.error ? (
|
|
<div
|
|
role="alert"
|
|
className="flex flex-wrap items-center gap-2 rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-caption text-destructive"
|
|
>
|
|
<span className="min-w-0 flex-1 break-words">事件读取失败:{live.error}</span>
|
|
<Button size="xs" variant="outline" onClick={live.retry}>
|
|
<RefreshCw />
|
|
重试
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
|
|
<MessageScroller
|
|
className={cn("min-h-64 flex-1", compact && "min-h-48")}
|
|
viewportClassName="pr-1"
|
|
busy={streaming}
|
|
label="Agent 会话记录"
|
|
>
|
|
<AgentConversation
|
|
run={r}
|
|
live={live}
|
|
audit={audit.data}
|
|
userMessages={messages.map((m) => ({ at: m.createdAt, text: m.text, pending: m.status === "pending" }))}
|
|
after={
|
|
<>
|
|
{approvals.items
|
|
.filter((a) => !inline.has(a.id))
|
|
.map((a) => (
|
|
<ApprovalItem key={a.id} approval={a} />
|
|
))}
|
|
{finished ? <FinalReport run={r} report={report} live={live} /> : null}
|
|
</>
|
|
}
|
|
/>
|
|
</MessageScroller>
|
|
|
|
<div className="space-y-1.5">
|
|
<PromptInput
|
|
value={msg}
|
|
onValueChange={setMsg}
|
|
onSubmit={send}
|
|
pending={append.isPending}
|
|
loading={streaming}
|
|
onStop={() => setConfirmStop(true)}
|
|
stopLabel={abort.isPending ? "停止中…" : "停止"}
|
|
minRows={1}
|
|
maxRows={6}
|
|
maxLength={8000}
|
|
aria-label="追加消息"
|
|
placeholder={streaming ? "补充或纠正(运行中也可追加)" : "追加消息"}
|
|
/>
|
|
<p className="px-1 text-meta text-muted-foreground">
|
|
{r.status === "waiting" && (r.summary === "等待选择方案" || r.summary === "等待审批")
|
|
? `${r.summary}:在上面的卡片里处理,会话随即继续。`
|
|
: "追加的消息在本轮结束后读取。"}{" "}
|
|
Enter 发送,Shift+Enter 换行{streaming ? ",停止 = 结束本次运行" : ""}。
|
|
</p>
|
|
</div>
|
|
|
|
<ConfirmDialog
|
|
open={confirmStop}
|
|
onOpenChange={setConfirmStop}
|
|
title="停止这次运行?"
|
|
description="后续步骤不再执行,已完成的外部动作(如已提交的下载)不会撤销。"
|
|
confirmLabel="停止运行"
|
|
destructive
|
|
onConfirm={() =>
|
|
abort.mutateAsync(r.id).then(
|
|
() => toast.success("已请求停止"),
|
|
(e) => {
|
|
toast.error(errorMessage(e));
|
|
throw e;
|
|
},
|
|
)
|
|
}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|