feat(canvas): 云端 Agent - 缩减画布目录上下文并展示实时用量

This commit is contained in:
ddcat666 committed 2026-09-24 23:54:59 +08:00
1 parent b7cd0291b8
commit 5528dbc3e4
12 files changed
+877 -76

No files matched your search

@@ -1,5 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { Button, Dropdown, Input } from "antd";
import { Button, Dropdown, Input, Popover } from "antd";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { ArrowLeft, Check, ChevronRight, CircleDot, Clock3, Download, History, LoaderCircle, MessageSquarePlus, MoveDiagonal2, RotateCcw, Settings2, ShieldCheck, Trash2, Sparkles, X } from "lucide-react";
import { saveAs } from "file-saver";
@@ -7,6 +7,7 @@ import { buildAgentDebugExport } from "@/lib/canvas/agent-debug-export";
import { markdownPlainText } from "@/lib/markdown-plain-text";
import { agentToolRetry, mergeAgentToolRetry } from "@/lib/canvas/agent-tool-retry";
import { agentPlanVisible, latestAgentPlanItems, pendingAgentQuestion } from "@/lib/canvas/cloud-agent-plan";
import { emptyAgentContextUsage, presentAgentContextUsage, reduceAgentContextUsage, type AgentContextPhase, type AgentContextUsage, type AgentContextUsageView } from "@/lib/canvas/agent-context-usage";
import { nanoid } from "nanoid";
import { ModelPicker } from "@/components/model-picker";
@@ -55,6 +56,7 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
const reducedMotion = useReducedMotion();
const [view, setView] = useState<AgentPanelView>("chat");
const [run, setRun] = useState<AgentRun | null>(null);
const [contextUsage, setContextUsage] = useState<AgentContextUsage>(() => emptyAgentContextUsage(""));
const [connectionStatus, setConnectionStatus] = useState<"connecting" | "connected" | "reconnecting" | "disconnected">("connecting");
const [connectionEpoch, setConnectionEpoch] = useState(0);
const [messages, setMessages] = useState<CloudAgentChatMessage[]>([]);
@@ -462,6 +464,7 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
lastSeqRef.current = event.seq;
}
setMessages((current) => current.filter((item) => item.id !== `stream-error-${run.id}`));
setContextUsage((current) => reduceAgentContextUsage(current, event));
applyAgentEvent(event, setMessages, setRun, setApproval, setPrompt);
canvasSyncRef.current?.receive(event);
},
@@ -570,7 +573,10 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
setMessages(nextMessages);
const result = submission.parentRunId ? await sendAgentMessage(submission.parentRunId, request) : await createAgentRun(request);
accepted = true;
if (currentScope.current === scope) setRun(result.run);
if (currentScope.current === scope) {
setContextUsage(emptyAgentContextUsage(result.run.id));
setRun(result.run);
}
await clearCloudAgentPendingSubmission(canvasId, activeConversationId);
if (currentScope.current === scope) pendingSubmission.current = null;
} catch (cause) {
@@ -898,6 +904,7 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
references={[...references, ...buildSkillMentionReferences(installedSkills)]}
slashSkills={installedSkills}
includeAssetLibrary={false}
submitAccessory={<AgentContextRing view={presentAgentContextUsage(contextUsage)} />}
left={
<ComposerControls
reasoningMode={reasoningSupported ? reasoningMode : "off"}
@@ -971,7 +978,7 @@ function AgentLauncher({ theme, statusColor, approvalPending, reducedMotion, onO
whileTap={reducedMotion || dragging ? undefined : { scale: 0.96 }}
transition={{ duration: reducedMotion ? 0 : 0.18 }}
>
{live ? <Live2DAvatar url={live2DModelURL(appearance.live2dResourceId, appearance.live2dEntry)} width={width} height={height} reducedMotion={reducedMotion} fallback={<FluidOrb size={62} color="#7164f6" />} /> : <FluidOrb size={62} color="#7164f6" />}
{live ? <Live2DAvatar url={live2DModelURL(appearance.live2dResourceId, appearance.live2dEntry)} width={width} height={height} reducedMotion={reducedMotion} fallback={<FluidOrb size={60} color="#7164f6" />} /> : <FluidOrb size={60} color="#7164f6" />}
{appearance.launcherLabel ? <span className="canvas-agent-launcher-label">{appearance.launcherLabel}</span> : null}
<span className={cn("canvas-agent-launcher-status", approvalPending && "is-pending")} style={{ "--canvas-agent-status-color": statusColor } as CSSProperties} />
{approvalPending ? <span className="canvas-agent-launcher-badge">待审批</span> : null}
@@ -1005,6 +1012,165 @@ function AgentHeader({ theme, hasMessages, statusLabel, statusColor, nodeCount,
);
}
const CONTEXT_PHASE_LABEL: Record<AgentContextPhase, string> = {
idle: "尚未测量",
unknown: "窗口未知",
ok: "上下文充足",
watch: "接近压缩",
compress: "即将压缩",
compacting: "正在压缩",
stale: "压缩后待刷新",
};
function formatContextCount(tokens: number | undefined) {
if (tokens === undefined) return "—";
if (tokens >= 1_000_000) return `${Math.round(tokens / 100_000) / 10}M`;
if (tokens >= 1_000) return `${Math.round(tokens / 100) / 10}K`;
return Math.round(tokens).toLocaleString("zh-CN");
}
function formatContextBytes(bytes: number | undefined) {
if (bytes === undefined) return "—";
if (bytes >= 1_000_000) return `${Math.round(bytes / 100_000) / 10} MB`;
if (bytes >= 1_000) return `${Math.round(bytes / 100) / 10} KB`;
return `${Math.round(bytes).toLocaleString("zh-CN")} 字节`;
}
function AgentContextRing({ view }: { view: AgentContextUsageView }) {
const reducedMotion = useReducedMotion();
const [open, setOpen] = useState(false);
const radius = 15;
const circumference = 2 * Math.PI * radius;
const marker = view.compactRatio && view.compactRatio > 0 && view.compactRatio < 1 ? view.compactRatio : undefined;
const percent = view.ratio === undefined ? view.label : `${Math.round(view.ratio * 100)}%`;
const meterLabel = view.ratio === undefined ? "—" : percent;
const used = formatContextCount(view.inputTokens);
const budget = formatContextCount(view.usableTokens);
const remaining = formatContextCount(view.remainingTokens);
const protocolBytes = formatContextBytes(view.protocolBytes);
const usedRatio = view.ratio === undefined ? 0 : Math.max(0, Math.min(1, view.ratio));
const phaseLabel = CONTEXT_PHASE_LABEL[view.phase];
const sourceLabel = view.tokenSource === "provider" ? "模型实测校准" : view.estimate ? "本地估算" : "未测量";
const usageHeading = view.ratio !== undefined
? `上下文已用 ${percent}`
: view.phase === "idle"
? "上下文用量"
: view.phase === "unknown"
? "上下文窗口未知"
: `上下文${view.label}`;
return (
<Popover
open={open}
onOpenChange={setOpen}
trigger="click"
placement="bottomRight"
arrow={false}
overlayClassName="agent-context-popover"
getPopupContainer={(trigger) => trigger.closest<HTMLElement>(".canvas-agent-panel") ?? document.body}
content={(
<div className="agent-context-panel" data-phase={view.phase}>
<span className="agent-context-eyebrow">下一次请求</span>
<div className="agent-context-panel-head">
<strong>{usageHeading}</strong>
{view.phase !== "ok" ? <span className={`agent-context-phase is-${view.phase}`}>{phaseLabel}</span> : null}
</div>
<div className="agent-context-summary">
{view.remainingTokens !== undefined && view.usableTokens !== undefined ? (
<>
<strong>{used}</strong>
<span>/ {budget} Token</span>
<em>剩余 {remaining}</em>
</>
) : (
<>
<strong>{used}</strong>
<span>Token</span>
</>
)}
</div>
<div className="agent-context-progress-head">
<span>输入预算占用</span>
<strong>{percent}</strong>
</div>
<div
className="agent-context-progress"
role="progressbar"
aria-label={`上下文已用 ${percent}`}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={view.ratio === undefined ? undefined : Math.round(view.ratio * 100)}
>
<span style={{ width: `${usedRatio * 100}%` }} />
{marker ? <i style={{ left: `${marker * 100}%` }} aria-hidden="true" /> : null}
</div>
<p className="agent-context-detail">{view.detail}</p>
{view.breakdown.length || view.protocolBytes !== undefined || view.remainingTokens !== undefined ? (
<ul className="agent-context-breakdown">
{view.breakdown.map((item) => (
<li key={item.key}>
<span className="agent-context-breakdown-dot" aria-hidden="true" />
<span className="agent-context-breakdown-label">{item.label}</span>
<span className="agent-context-breakdown-value">{formatContextCount(item.tokens)}</span>
</li>
))}
{view.protocolBytes !== undefined ? (
<li className="is-secondary">
<span className="agent-context-breakdown-dot" aria-hidden="true" />
<span className="agent-context-breakdown-label">协议外壳</span>
<span className="agent-context-breakdown-value">{protocolBytes}</span>
</li>
) : null}
{view.remainingTokens !== undefined ? (
<li className="is-muted">
<span className="agent-context-breakdown-dot" aria-hidden="true" />
<span className="agent-context-breakdown-label">未使用</span>
<span className="agent-context-breakdown-value">{remaining}</span>
</li>
) : null}
</ul>
) : null}
<div className="agent-context-panel-foot">
<span>{sourceLabel}{view.estimate ? " · 不是计费 Token" : " · 预计下次请求"}</span>
{view.compactAtTokens ? <span>压缩线 {formatContextCount(view.compactAtTokens)}</span> : null}
</div>
{view.lastCompaction ? <p className="agent-context-note">本轮已完成一次上下文压缩,下一次读数会刷新。</p> : null}
</div>
)}
>
<button
type="button"
className={`agent-context-ring is-${view.phase}`}
aria-label={`${usageHeading},${phaseLabel}。点击查看明细`}
aria-expanded={open}
title="查看上下文用量"
onPointerDown={(event) => event.stopPropagation()}
>
<span className="agent-context-ring-visual" aria-hidden="true">
<svg viewBox="0 0 40 40">
<circle className="agent-context-ring-track" cx="20" cy="20" r={radius} />
<circle
className="agent-context-ring-value"
cx="20"
cy="20"
r={radius}
strokeDasharray={`${circumference} ${circumference}`}
strokeDashoffset={circumference * (1 - view.ring)}
style={{ transition: reducedMotion ? "none" : undefined }}
/>
{marker ? <circle className="agent-context-ring-marker" cx="20" cy={20 - radius} r="1.35" transform={`rotate(${marker * 360} 20 20)`} /> : null}
</svg>
</span>
<span className="agent-context-meter-copy">
<strong>{meterLabel}</strong>
<small>上下文</small>
</span>
</button>
</Popover>
);
}
function AgentHistory({ conversations, activeConversationId, theme, onBack, onNew, onOpen, onDelete }: { conversations: CloudAgentConversation[]; activeConversationId: string; theme: CanvasTheme; onBack: () => void; onNew: () => void; onOpen: (conversation: CloudAgentConversation) => void; onDelete: (id: string) => void }) {
return (
<div className="canvas-agent-history-root flex min-h-0 min-w-0 flex-1 flex-col">
@@ -1153,14 +1319,15 @@ function ComposerControls({
const permissionVisual = agentPermissionVisual(permissionMode);
const PermissionIcon = permissionVisual.icon;
return (
<div className="flex min-w-0 flex-wrap items-center gap-0.5">
<div className="agent-composer-selection flex min-w-0 flex-1 flex-nowrap items-center gap-0.5">
<ModelPicker
config={config}
value={selectedModel}
capability="text"
onChange={onModelChange}
variant="creation"
className="!h-8 !min-w-0 !w-52 !max-w-full !border-0 !bg-transparent !px-1.5 !shadow-none"
fullWidth
className="agent-composer-model-trigger !h-8 !min-w-0 !w-full !max-w-full !border-0 !bg-transparent !px-1.5 !shadow-none"
popoverClassName="agent-model-picker-popover"
showSelectedPrice={false}
showOptionPrices