feat(agent): Agent 工作台 - 计划插话记忆、统一模型选择器并修复摘要与视频入库

将计划清单、运行中插话和个人记忆接入云端 Agent;全站模型选择器统一为左右二级菜单。画布摘要按预算截断不再整轮拒绝,首页视频未知宽高可入库。README 补充贡献者 morrow。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ddCatandCursor committed 2026-09-17 20:21:25 +08:00
1 parent 73a1d2bdfd
commit d9abe41ceb
80 files changed
+7361 -179

No files matched your search

@@ -42,7 +42,7 @@ export function CanvasAgentImageApprovalSettings({ initial, value, onChange, the
return <fieldset disabled={disabled} className="min-w-0 space-y-3 border-0 p-0" data-canvas-no-zoom data-canvas-wheel-scroll aria-label="图片生成设置">
<div className="space-y-1.5">
<div className="text-xs" style={{ color: theme.node.muted }}>生成模型</div>
<ModelPicker config={config} capability="image" value={model} onChange={changeModel} requirements={requirements} fullWidth showOptionPrices placeholder="选择生成模型" />
<ModelPicker config={config} capability="image" value={model} onChange={changeModel} requirements={requirements} variant="creation" fullWidth showOptionPrices placeholder="选择生成模型" popoverClassName="agent-model-picker-popover" />
</div>
{model ? <ImageSettingsPanel config={{ ...config, model, imageModel: model, size: settings.size, quality: settings.quality, count: "1" }} onConfigChange={changeOption} theme={theme} showTitle={false} showCount={false} showTransparent={false} className="min-w-0 space-y-3" /> : <p className="text-xs" style={{ color: theme.node.muted }}>当前模型不在可选目录中,可重新选择;提交时将重新校验模型与规格。</p>}
<p className="text-xs" style={{ color: theme.node.text }}>本次规格:{settings.size}{settings.quality ? ` · ${settings.quality}` : ""}</p>
@@ -4,7 +4,7 @@ import { Tooltip } from "@/components/ui/base/tooltip";
import { useCallback, useEffect, useMemo, useRef, useState, type ClipboardEvent as ReactClipboardEvent, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
import { motion, useReducedMotion } from "motion/react";
import { ArrowUp, AtSign, CheckCircle2, ChevronDown, CircleAlert, CircleDot, Eye, ImagePlus, LoaderCircle, Pencil, Plus, RotateCcw, Sparkles, Square, X, XCircle } from "lucide-react";
import { ArrowUp, AtSign, CheckCircle2, ChevronDown, ChevronUp, CircleAlert, CircleDot, Eye, HelpCircle, ImagePlus, ListChecks, LoaderCircle, Pencil, Plus, RotateCcw, Sparkles, Square, X, XCircle } from "lucide-react";
import { canvasThemes } from "@/lib/canvas-theme";
import { AIMessageMarkdown } from "@/components/ai/ai-message-markdown";
@@ -24,6 +24,12 @@ type CloudAgentOperationImpact = {
items: string[];
warning?: string;
};
export type CloudAgentPlanItem = { id: string; title: string; status: "pending" | "doing" | "done" };
export type CloudAgentUserQuestion = {
question: string;
options: Array<{ label: string; detail?: string }>;
allowFreeform?: boolean;
};
export type CloudAgentChatMessage = {
id: string;
role: "user" | "assistant" | "system" | "tool" | "error";
@@ -31,9 +37,12 @@ export type CloudAgentChatMessage = {
text: string;
streaming?: boolean;
reasoning?: boolean;
planItems?: CloudAgentPlanItem[];
question?: CloudAgentUserQuestion;
meta?: string;
detail?: unknown;
attachments?: CloudAgentChatAttachment[];
interjection?: "sent" | "undelivered";
};
export type CloudAgentQuickAction = { label: string; prompt: string };
@@ -156,6 +165,16 @@ export function AgentChatMessage({
<div className={`flex items-start gap-3 ${isUser ? "justify-end" : "justify-start"}`}>
{!isUser ? <AgentTimelineMarker theme={theme} tone="agent" /> : null}
<div className={`min-w-0 text-sm leading-6 ${isUser ? "max-w-[82%] rounded-2xl rounded-br-md px-3.5 py-2.5 text-right" : "max-w-[calc(100%-36px)] flex-1 text-left"}`} style={{ color, ...(isUser ? { background: theme.node.agentUserMessage } : {}) }}>
{item.interjection ? (
<span
className="mb-1 inline-flex items-center rounded-full px-1.5 py-[1px] text-[var(--fs-label)] leading-4"
style={item.interjection === "undelivered"
? { background: `${theme.accent.danger}22`, color: theme.accent.danger }
: { background: "rgba(255,255,255,0.16)", opacity: 0.72 }}
>
{item.interjection === "undelivered" ? "插话未送达" : "插话"}
</span>
) : null}
{item.role === "assistant" ? (
<AIMessageMarkdown className="text-left" isStreaming={isStreaming}>
{item.text}
@@ -343,11 +362,89 @@ export function AgentWorkingMessage({ theme, label = WORKING_TEXT }: { theme: (t
);
}
export function AgentPlanBar({ items, theme, minimized, onToggle }: {
items: CloudAgentPlanItem[];
theme: (typeof canvasThemes)[keyof typeof canvasThemes];
minimized: boolean;
onToggle: () => void;
}) {
const doneCount = items.filter((entry) => entry.status === "done").length;
const allDone = doneCount === items.length;
return (
<div className="agent-plan-bar mx-3 mb-2 overflow-hidden rounded-xl" style={{ background: theme.node.fill, border: `1px solid ${theme.node.stroke}`, color: theme.node.text }}>
<button type="button" className="flex w-full items-center gap-2 px-3 py-2 text-left focus-visible:outline focus-visible:outline-2" aria-expanded={!minimized} onClick={onToggle}>
<ListChecks className="size-3.5 shrink-0" style={{ color: allDone ? "#429477" : theme.node.muted }} />
<span className="text-xs font-semibold">本轮待办</span>
<span className="text-[11px] tabular-nums opacity-50">{doneCount}/{items.length}</span>
<span className="min-w-0 flex-1" />
<span className="shrink-0 text-[11px] opacity-50">{minimized ? "展开" : "收起"}</span>
{minimized ? <ChevronDown className="size-3.5 shrink-0 opacity-50" /> : <ChevronUp className="size-3.5 shrink-0 opacity-50" />}
</button>
{minimized ? null : (
<ul className="thin-scrollbar max-h-40 space-y-1 overflow-y-auto px-3 pb-2">
{items.map((entry) => {
const done = entry.status === "done";
const doing = entry.status === "doing";
const Icon = done ? CheckCircle2 : doing ? LoaderCircle : CircleDot;
return (
<li key={entry.id} className="flex min-w-0 items-start gap-1.5 text-xs">
<Icon className={doing ? "mt-[3px] size-3 shrink-0 animate-spin" : "mt-[3px] size-3 shrink-0"} style={{ color: done ? "#429477" : doing ? theme.accent.primary : theme.node.muted }} />
<span className={done ? "min-w-0 break-words line-through opacity-50" : "min-w-0 break-words"}>{entry.title}</span>
</li>
);
})}
</ul>
)}
</div>
);
}
export function AgentQuestionBar({ question, theme, onAnswer, disabled = false }: {
question: CloudAgentUserQuestion;
theme: (typeof canvasThemes)[keyof typeof canvasThemes];
onAnswer: (label: string) => void;
disabled?: boolean;
}) {
return (
<div className="agent-question-bar mx-3 mb-2 overflow-hidden rounded-xl" style={{ background: theme.node.fill, border: `1px solid ${theme.accent.primary}`, color: theme.node.text }}>
<div className="flex items-start gap-2 px-3 pt-2.5">
<HelpCircle className="mt-[1px] size-3.5 shrink-0" style={{ color: theme.accent.primary }} />
<span className="min-w-0 flex-1 text-xs font-semibold leading-5">{question.question}</span>
</div>
<div className="flex flex-wrap gap-2 px-3 pb-2 pt-2">
{question.options.map((option) => (
<button
key={option.label}
type="button"
disabled={disabled}
title={option.detail || option.label}
className="max-w-full rounded-md border px-3 py-1.5 text-left text-xs transition focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50"
style={{ borderColor: theme.node.stroke, background: theme.toolbar.itemHover }}
onMouseDown={(event) => event.stopPropagation()}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
event.stopPropagation();
onAnswer(option.label);
}}
>
<span className="block break-words font-medium">{option.label}</span>
{option.detail ? <span className="mt-0.5 block break-words text-[10px] leading-4 opacity-60">{option.detail}</span> : null}
</button>
))}
</div>
<div className="px-3 pb-2 text-[10px] opacity-50">
{question.allowFreeform === false ? "请从上面选一项。" : "点一项即可,也可以在下方输入框里自己说明。"}
</div>
</div>
);
}
export function AgentChatComposer({
prompt,
attachments = [],
disabled,
sending,
running,
placeholder,
theme,
onPromptChange,
@@ -365,6 +462,7 @@ export function AgentChatComposer({
attachments?: CloudAgentChatAttachment[];
disabled?: boolean;
sending?: boolean;
running?: boolean;
placeholder: string;
theme: (typeof canvasThemes)[keyof typeof canvasThemes];
onPromptChange: (value: string) => void;
@@ -397,7 +495,7 @@ export function AgentChatComposer({
const attachmentReferences = useMemo(() => agentAttachmentReferences(attachments), [attachments]);
const skillReferences = useMemo(() => buildSkillMentionReferences(availableSlashSkills), [availableSlashSkills]);
const composerReferences = useMemo(() => [...references, ...skillReferences, ...attachmentReferences].filter((reference, index, all) => all.findIndex((item) => item.id === reference.id) === index), [attachmentReferences, references, skillReferences]);
const canStop = Boolean(sending && onStop);
const canStop = Boolean(running && onStop);
const canSubmit = !disabled && !sending && Boolean(prompt.trim() || attachments.length);
const reducedMotion = useReducedMotion();
const activeSlashIndex = Math.min(Math.max(slashIndex, 0), Math.max(slashCandidates.length - 1, 0));
@@ -643,32 +741,47 @@ export function AgentChatComposer({
{left}
</div>
<div className="agent-composer-submit flex items-center gap-2">
<span className="agent-composer-send-hint">Enter 换行 · ⌘/Ctrl+Enter 发送</span>
<span className="agent-composer-send-hint">{canStop ? "运行中:发送即插话,下一步生效" : "Enter 换行 · ⌘/Ctrl+Enter 发送"}</span>
{canStop ? <motion.button
type="button"
disabled={stopping}
aria-label="停止本轮"
title="停止当前 Agent 运行"
onClick={() => void onStop?.()}
whileHover={!reducedMotion && !stopping ? { scale: 1.06, y: -1 } : undefined}
whileTap={!reducedMotion && !stopping ? { scale: 0.9, y: 1 } : undefined}
animate={stopping && !reducedMotion ? { scale: [1, 0.94, 1] } : { scale: 1 }}
transition={{ type: "spring", stiffness: 420, damping: 24 }}
className="grid size-9 shrink-0 place-items-center rounded-full p-0 outline-none transition-[background-color,box-shadow,color,transform] duration-200 focus-visible:ring-2 focus-visible:ring-current/35 disabled:cursor-not-allowed"
style={{ background: theme.accent.danger, color: theme.accent.onPrimary, boxShadow: `0 8px 20px ${theme.accent.danger}45` }}
>
{stopping ? <LoaderCircle className="size-4 animate-spin" /> : <Square className="size-3.5" fill="currentColor" />}
</motion.button> : null}
<motion.button
type="button"
disabled={!canSubmit && !canStop}
aria-label={canStop ? "停止本轮" : sending ? "发送中" : "发送"}
title={canStop ? "停止当前 Agent 运行" : "点击发送;⌘/Ctrl+Enter 发送"}
onClick={() => void (canStop ? onStop?.() : onSubmit())}
whileHover={(canSubmit || canStop) && !reducedMotion ? { scale: 1.06, y: -1 } : undefined}
whileTap={(canSubmit || canStop) && !reducedMotion ? { scale: 0.9, y: 1 } : undefined}
disabled={!canSubmit}
aria-label={sending ? "发送中" : canStop ? "插话" : "发送"}
title={canStop ? "插话:Agent 下一次开口时看到它" : "点击发送;⌘/Ctrl+Enter 发送"}
onClick={() => onSubmit()}
whileHover={canSubmit && !reducedMotion ? { scale: 1.06, y: -1 } : undefined}
whileTap={canSubmit && !reducedMotion ? { scale: 0.9, y: 1 } : undefined}
animate={stopping && !reducedMotion ? { scale: [1, 0.94, 1] } : { scale: 1, rotate: 0 }}
transition={sending && !reducedMotion ? { duration: 0.42, ease: "easeOut" } : { type: "spring", stiffness: 420, damping: 24 }}
className="grid size-9 shrink-0 place-items-center rounded-full p-0 outline-none transition-[background-color,box-shadow,color,transform] duration-200 focus-visible:ring-2 focus-visible:ring-current/35 disabled:cursor-not-allowed"
style={{
background: canStop ? theme.accent.danger : canSubmit || sending ? theme.accent.primary : theme.spatial.surface,
color: canStop || canSubmit || sending ? theme.accent.onPrimary : theme.node.muted,
boxShadow: canStop || canSubmit || sending ? `0 8px 20px ${canStop ? theme.accent.danger : theme.accent.primary}45` : "none",
background: canSubmit || sending ? theme.accent.primary : theme.spatial.surface,
color: canSubmit || sending ? theme.accent.onPrimary : theme.node.muted,
boxShadow: canSubmit || sending ? `0 8px 20px ${theme.accent.primary}45` : "none",
}}
>
<motion.span
key={stopping ? "stopping" : canStop ? "stop" : sending ? "sending" : "ready"}
key={stopping ? "stopping" : sending ? "sending" : "ready"}
initial={reducedMotion ? false : { opacity: 0, scale: 0.65, rotate: sending ? -25 : 25 }}
animate={{ opacity: 1, scale: 1, rotate: 0 }}
transition={{ duration: reducedMotion ? 0 : 0.18, ease: "easeOut" }}
className="grid place-items-center"
>
{stopping || (sending && !canStop) ? <LoaderCircle className="size-4 animate-spin" /> : canStop ? <Square className="size-3.5" fill="currentColor" /> : <ArrowUp className="size-4" />}
{sending ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
</motion.span>
</motion.button>
</div>
@@ -4,7 +4,7 @@ import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { ArrowLeft, Bot, Check, ChevronRight, CircleDot, Clock3, Download, History, LoaderCircle, MessageSquarePlus, Settings2, ShieldCheck, Trash2, Sparkles, X } from "lucide-react";
import { saveAs } from "file-saver";
import { buildAgentDebugExport } from "@/lib/canvas/agent-debug-export";
import { markdownPlainText } from "@/lib/markdown-plain-text";
import { agentPlanVisible, latestAgentPlanItems, pendingAgentQuestion } from "@/lib/canvas/cloud-agent-plan";
import { nanoid } from "nanoid";
import { ModelPicker } from "@/components/model-picker";
@@ -14,7 +14,7 @@ import { modelCapabilityConfigFor } from "@/lib/model-capabilities";
import type { CanvasResourceReference } from "@/lib/canvas/canvas-resource-references";
import { canvasThemes, type CanvasTheme } from "@/lib/canvas-theme";
import { agentErrorPresentation, agentSubmissionErrorTitle } from "@/lib/canvas/agent-error-presentation";
import { cancelAgentRun, getAgentCapabilities, getAgentProfile, getAgentRun, createAgentRun, decideAgentApproval, sendAgentMessage, subscribeAgentEvents, updateAgentProfile, type AgentEvent, type AgentPermissionMode, type AgentProfileScope, type AgentProfileView, type AgentReasoningMode, type AgentRun } from "@/services/api/agent";
import { cancelAgentRun, getAgentCapabilities, getAgentProfile, getAgentRun, createAgentRun, decideAgentApproval, sendAgentInterjection, sendAgentMessage, subscribeAgentEvents, updateAgentProfile, type AgentEvent, type AgentPermissionMode, type AgentProfileScope, type AgentProfileView, type AgentReasoningMode, type AgentRun } from "@/services/api/agent";
import { agentApprovalPresentation } from "@/lib/canvas/agent-approval-presentation";
import { agentApprovalMatchesSettings, agentImageApproval } from "@/lib/canvas/agent-media-approval";
import type { AgentMediaSettings } from "@/services/api/agent";
@@ -26,7 +26,7 @@ import { useActiveTheme } from "@/stores/canvas/use-canvas-theme-store";
import { applyAgentCanvasPatches, refreshCanvasAfterAgent, saveRemoteUserDataNow } from "@/services/user-data-sync";
import { createAgentCanvasSync } from "@/services/agent-canvas-sync";
import { buildSkillMentionReferences, resolveSkillMentions } from "@/services/skill-runtime";
import { AgentChatComposer, AgentChatMessage, AgentWorkingMessage, type CloudAgentChatMessage } from "./canvas-cloud-agent-chat-ui";
import { AgentChatComposer, AgentChatMessage, AgentPlanBar, AgentQuestionBar, AgentWorkingMessage, type CloudAgentChatMessage, type CloudAgentPlanItem } from "./canvas-cloud-agent-chat-ui";
import { CanvasAgentSkillLibraryModal } from "./canvas-agent-skill-library-modal";
import { CanvasCloudAgentSettings, agentPermissionLabel, agentPermissionMenuItems, agentPermissionVisual, type AgentContextKey } from "./canvas-cloud-agent-settings";
import { useAgentPanelLayout } from "./use-agent-panel-layout";
@@ -79,6 +79,10 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
const [activeConversationId, setActiveConversationId] = useState(() => nanoid());
const [historyHydrated, setHistoryHydrated] = useState(false);
const [pendingHydrated, setPendingHydrated] = useState(false);
const [planMinimized, setPlanMinimized] = useState(false);
const planItems = useMemo(() => latestAgentPlanItems(messages), [messages]);
const planVisible = agentPlanVisible(planItems);
const pendingQuestion = useMemo(() => pendingAgentQuestion(messages), [messages]);
const panelLayout = useAgentPanelLayout();
const lastSeqRef = useRef(0);
const canvasSyncRef = useRef<ReturnType<typeof createAgentCanvasSync> | null>(null);
@@ -321,7 +325,7 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
lastSeqRef.current = event.seq;
}
setMessages((current) => current.filter((item) => item.id !== `stream-error-${run.id}`));
applyAgentEvent(event, setMessages, setRun, setApproval);
applyAgentEvent(event, setMessages, setRun, setApproval, setPrompt);
canvasSyncRef.current?.receive(event);
},
{
@@ -345,8 +349,33 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
return () => window.removeEventListener("online", reconnect);
}, [run?.id, connectionStatus]);
const submit = async () => {
const value = prompt.trim();
const interject = async (value: string) => {
const activeRun = run;
if (!value || !activeRun?.id || busy || connectionStatus !== "connected" || currentScope.current !== conversationScope || !historyHydrated) return;
const scope = conversationScope;
const messageId = `user-${crypto.randomUUID()}`;
setBusy(true);
try {
await sendAgentInterjection(activeRun.id, { text: value, messageId });
if (currentScope.current !== scope) return;
setPrompt("");
setMessages((current) => appendUniqueMessage(current, { id: messageId, role: "user", text: value, interjection: "sent" }));
} catch (cause) {
if (currentScope.current !== scope) return;
const status = (cause as { status?: number }).status;
setMessages((current) => appendAgentError(current, `interject-error-${activeConversationId}-${messageId}`, cause, "插话没有送达"));
if (status === 409) setPrompt(value);
} finally {
if (currentScope.current === scope) setBusy(false);
}
};
const submit = async (override?: string) => {
const value = (override ?? prompt).trim();
if (running) {
await interject(value);
return;
}
if (!value || busy || running || (run && connectionStatus !== "connected") || submissionRequestRef.current || !historyHydrated || !pendingHydrated || currentScope.current !== conversationScope) return;
const scope = conversationScope;
submissionRequestRef.current = true;
@@ -689,11 +718,21 @@ export function CanvasCloudAgentPanel({ canvasId, domainProjectId, nodeCount, re
onApprove={(settings) => void submitApproval("approve", settings)}
onReject={() => void submitApproval("reject")}
/>
{planVisible ? <AgentPlanBar items={planItems} theme={theme} minimized={planMinimized} onToggle={() => setPlanMinimized((value) => !value)} /> : null}
{pendingQuestion ? (
<AgentQuestionBar
question={pendingQuestion}
theme={theme}
disabled={approvalSubmitting || connectionStatus !== "connected"}
onAnswer={(label) => void submit(label)}
/>
) : null}
<AgentChatComposer
prompt={prompt}
disabled={busy || running || Boolean(run && connectionStatus !== "connected") || !historyHydrated || !pendingHydrated}
sending={busy || running}
placeholder="输入操作指导;用 @ 引用画布节点,用 / 引用 Skills"
disabled={Boolean(run && connectionStatus !== "connected") || !historyHydrated || !pendingHydrated}
sending={busy}
running={running}
placeholder={running ? "运行中可直接插话,会在它下一步生效" : "输入操作指导;用 @ 引用画布节点,用 / 引用 Skills"}
theme={theme}
onPromptChange={setPrompt}
onSubmit={() => void submit()}
@@ -1047,7 +1086,7 @@ function ApprovalCard({ approval, theme, submitting, onFocusNode, onReasonChange
}
function ApprovalPreviewItemView({ item, theme, onFocusNode }: { item: ReturnType<typeof agentApprovalPresentation>["items"][number]; theme: CanvasTheme; onFocusNode?: (nodeId: string) => void }) {
const operationLabel = item.operation === "add_node" ? "新增" : item.operation === "update_node" ? "修改" : item.operation === "connect_nodes" ? "连线" : item.operation === "create_storyboard" ? "创建分镜" : item.operation === "edit_storyboard" ? "修改分镜" : "生成";
const operationLabel = item.operation === "add_node" ? "新增" : item.operation === "update_node" ? "修改" : item.operation === "connect_nodes" ? "连线" : item.operation === "create_storyboard" ? "创建分镜" : item.operation === "edit_storyboard" ? "修改分镜" : item.operation === "plan_step" ? "计划" : "生成";
const renderNode = (title: string | undefined, id: string | undefined, typeLabel: string | undefined, role: "source" | "target" | "node") => {
if (!title) return null;
const content = <><span className="canvas-agent-approval-node-title">{title}</span>{typeLabel ? <span className="canvas-agent-approval-node-type">{typeLabel}</span> : null}</>;
@@ -1093,7 +1132,7 @@ function formatConversationTime(value: string) {
if (date.toDateString() === today.toDateString()) return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit", hour12: false });
return date.toLocaleDateString("zh-CN", { month: "numeric", day: "numeric" });
}
function applyAgentEvent(event: AgentEvent, setMessages: Dispatch<SetStateAction<CloudAgentChatMessage[]>>, setRun: Dispatch<SetStateAction<AgentRun | null>>, setApproval: Dispatch<SetStateAction<ApprovalState | null>>) {
function applyAgentEvent(event: AgentEvent, setMessages: Dispatch<SetStateAction<CloudAgentChatMessage[]>>, setRun: Dispatch<SetStateAction<AgentRun | null>>, setApproval: Dispatch<SetStateAction<ApprovalState | null>>, setPrompt?: Dispatch<SetStateAction<string>>) {
const payload = event.payload || {};
const text = String(payload.text || payload.summary || payload.message || "");
if (event.type === "run_status") {
@@ -1132,6 +1171,51 @@ function applyAgentEvent(event: AgentEvent, setMessages: Dispatch<SetStateAction
.map((item) => item.id === id ? { ...item, reasoning: true } : item));
return;
}
if (event.type === "plan_updated" && Array.isArray(payload.items)) {
const id = `plan-${event.runId}`;
const planItems = payload.items as CloudAgentPlanItem[];
setMessages((current) => {
const index = current.findIndex((entry) => entry.id === id);
const message: CloudAgentChatMessage = { id, role: "tool", text: "", planItems };
if (index < 0) return [...current, message];
const next = [...current];
next[index] = message;
return next;
});
return;
}
if (event.type === "user_interjection") {
if (!text) return;
setMessages((current) => appendUniqueMessage(current, { id: String(payload.messageId || event.eventId), role: "user", text, interjection: "sent" }));
return;
}
if (event.type === "user_interjection_dropped") {
const messageId = String(payload.messageId || event.eventId);
const reason = String(payload.reason || "本轮已结束");
setMessages((current) => {
const marked = current.map((item) => item.id === messageId ? { ...item, interjection: "undelivered" as const } : item);
return appendUniqueMessage(marked, { id: `interjection-dropped-${messageId}`, role: "system", text: `${reason},这条插话没有送到模型。需要的话重新发一次,它会作为新一轮。` });
});
setPrompt?.((current) => (current.trim() ? current : text));
return;
}
if (event.type === "user_question") {
const options = Array.isArray(payload.options)
? (payload.options as Array<{ label?: unknown; detail?: unknown }>)
.map((option) => ({ label: String(option?.label || "").trim(), detail: option?.detail === undefined ? undefined : String(option.detail) }))
.filter((option) => option.label)
: [];
const question = String(payload.question || "").trim();
if (!question || options.length < 2) return;
const id = `question-${event.runId}:${event.seq ?? event.eventId}`;
setMessages((current) => appendUniqueMessage(current, {
id,
role: "assistant",
text: "",
question: { question, options, allowFreeform: payload.allowFreeform !== false },
}));
return;
}
if (event.type === "assistant_message") {
setMessages((current) => upsertTextMessage(current, String(payload.messageId || event.eventId), text, false));
return;
@@ -1,15 +1,16 @@
import { useEffect, useState, type ReactNode } from "react";
import { Button, Checkbox, Input } from "antd";
import { ArrowLeft, Check, ChevronRight, Cpu, Gauge, LockKeyhole, PlugZap, Search, ShieldCheck, Sparkles, Wrench } from "lucide-react";
import { ArrowLeft, BookMarked, Check, ChevronRight, Cpu, Gauge, LockKeyhole, PlugZap, Search, ShieldCheck, Sparkles, Wrench } from "lucide-react";
import { ModelPicker } from "@/components/model-picker";
import type { CanvasTheme } from "@/lib/canvas-theme";
import AgentMemoryPane from "@/pages/settings/agent-memory-pane";
import type { AgentPermissionMode, AgentProfileLayer, AgentProfileScope, AgentProfileView, AgentReasoningMode } from "@/services/api/agent";
import type { Skill } from "@/services/api/skills";
import type { AiConfig } from "@/stores/use-config-store";
export type AgentContextKey = "canvas" | "resources" | "generation_history" | "skills" | "project";
type SettingsSection = "home" | "profile" | "skills" | "mcp" | "context" | "budget";
type SettingsSection = "home" | "profile" | "memories" | "skills" | "mcp" | "context" | "budget";
type AgentSettingsProps = {
theme: CanvasTheme;
@@ -83,6 +84,7 @@ export function CanvasCloudAgentSettings(props: AgentSettingsProps) {
{section === "home" ? <SettingsHome props={props} theme={theme} onOpen={setSection} /> : null}
{section === "profile" ? <ProfileWorkspace props={props} theme={theme} /> : null}
{section === "memories" ? <MemoriesWorkspace /> : null}
{section === "skills" ? <SkillsWorkspace props={props} theme={theme} tab={skillTab} onTabChange={setSkillTab} /> : null}
{section === "mcp" ? <McpWorkspace theme={theme} /> : null}
{section === "context" ? <ContextWorkspace props={props} theme={theme} /> : null}
@@ -126,6 +128,7 @@ function SettingsHome({ props, theme, onOpen }: { props: AgentSettingsProps; the
<div className="space-y-1">
<SettingRow theme={theme} icon={<Cpu className="size-4" />} title="上下文" summary={`${props.nodeCount} 个节点 · ${props.contextScope.length} 个范围`} onClick={() => onOpen("context")} />
<SettingRow theme={theme} icon={<Sparkles className="size-4" />} title="长期偏好" summary={profileSummary(props.profileView)} onClick={() => onOpen("profile")} />
<SettingRow theme={theme} icon={<BookMarked className="size-4" />} title="个人记忆" summary="批准、添加、导出导入;只影响你的会话" onClick={() => onOpen("memories")} />
<SettingRow theme={theme} icon={<Sparkles className="size-4" />} title="Skills · 用户技能库" summary={`${props.installedSkills.length} 个已安装 · 本轮启用 ${props.selectedSkillIds.length} 个`} onClick={() => onOpen("skills")} />
<SettingRow theme={theme} icon={<Wrench className="size-4" />} title="工具与连接" summary="画布、技能参考文件、生成任务" onClick={() => onOpen("mcp")} />
<SettingRow theme={theme} icon={<Gauge className="size-4" />} title="预算" summary={`每轮最多 ${props.maxCredits || "未设置"} 积分 · 固定计价模型`} onClick={() => onOpen("budget")} />
@@ -135,6 +138,14 @@ function SettingsHome({ props, theme, onOpen }: { props: AgentSettingsProps; the
);
}
function MemoriesWorkspace() {
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden p-4">
<AgentMemoryPane compact />
</div>
);
}
function SkillsWorkspace({ props, theme, tab, onTabChange }: { props: AgentSettingsProps; theme: CanvasTheme; tab: "installed" | "market"; onTabChange: (tab: "installed" | "market") => void }) {
const query = props.skillSearch.trim().toLocaleLowerCase();
const source = tab === "installed" ? props.installedSkills.filter((skill) => `${skill.skillName} ${skill.description || ""}`.toLocaleLowerCase().includes(query)) : props.marketSkills;
@@ -302,8 +313,8 @@ function SettingRow({ theme, icon, title, summary, onClick }: { theme: CanvasThe
function TabButton({ active, label, onClick, theme }: { active: boolean; label: string; onClick: () => void; theme: CanvasTheme }) { return <button type="button" aria-pressed={active} className="min-w-0 flex-1 rounded-lg px-2 py-2 text-xs font-medium transition-colors focus-visible:outline focus-visible:outline-2" style={{ background: active ? theme.toolbar.itemHover : "transparent", color: active ? theme.node.text : theme.node.muted }} onClick={onClick}>{label}</button>; }
function SettingLabel({ label, hint }: { label: string; hint?: string }) { return <div className="mb-2 flex items-center justify-between text-xs font-semibold"><span>{label}</span>{hint ? <span className="text-[10px] font-normal opacity-40">{hint}</span> : null}</div>; }
function BudgetInput({ label, hint, value, onChange, theme }: { label: string; hint: string; value: string; onChange: (value: string) => void; theme: CanvasTheme }) { return <label className="block"><span className="flex items-center justify-between text-xs font-medium"><span>{label}</span><span className="text-[10px] opacity-40">{hint}</span></span><Input size="large" value={value} onChange={(event) => onChange(event.target.value.replace(/[^0-9]/g, ""))} inputMode="numeric" className="mt-2 !rounded-lg" style={{ background: theme.node.fill }} /></label>; }
function sectionTitle(section: SettingsSection) { return section === "profile" ? "长期偏好" : section === "skills" ? "Skills" : section === "mcp" ? "MCP 与工具" : section === "context" ? "上下文" : "预算"; }
function sectionSubtitle(section: SettingsSection) { return section === "profile" ? "用户、项目和画布的长期行为偏好" : section === "skills" ? "搜索、安装并选择本轮技能" : section === "mcp" ? "云端工具与连接状态" : section === "context" ? "控制 Agent 能读取的范围" : "控制本轮积分与生成消耗"; }
function sectionTitle(section: SettingsSection) { return section === "profile" ? "长期偏好" : section === "memories" ? "个人记忆" : section === "skills" ? "Skills" : section === "mcp" ? "MCP 与工具" : section === "context" ? "上下文" : "预算"; }
function sectionSubtitle(section: SettingsSection) { return section === "profile" ? "用户、项目和画布的长期行为偏好" : section === "memories" ? "只属于你,批准后才会注入会话" : section === "skills" ? "搜索、安装并选择本轮技能" : section === "mcp" ? "云端工具与连接状态" : section === "context" ? "控制 Agent 能读取的范围" : "控制本轮积分与生成消耗"; }
export function agentPermissionLabel(mode: AgentPermissionMode) { return permissionOptions.find((option) => option.value === mode)?.label || "请求审批"; }
export function agentPermissionVisual(mode: AgentPermissionMode) { const option = permissionOptions.find((item) => item.value === mode) || permissionOptions[0]; return { color: option.color, soft: `${option.color}1f` }; }
@@ -3,28 +3,11 @@
overscroll-behavior: contain;
}
/* Agent 浮窗高于普通画布层,模型菜单必须叠在对话窗之上。 */
/* Agent 浮窗高于普通画布层,模型菜单必须叠在对话窗之上;菜单本身与全站二级选择器同一套。 */
.agent-model-picker-popover {
z-index: calc(var(--z-modal-overlay) + 1000) !important;
}
.agent-model-picker-popover .canvas-model-picker-menu {
width: min(340px, calc(100vw - 24px)) !important;
max-width: min(340px, calc(100vw - 24px)) !important;
}
.agent-model-picker-popover .canvas-model-picker-two-pane {
grid-template-columns: minmax(0, 1fr) !important;
}
.agent-model-picker-popover .canvas-model-picker-brand-rail {
display: none !important;
}
.agent-model-picker-popover .canvas-model-picker-model-pane {
min-width: 0 !important;
}
/* Flex 子页必须允许收缩,长模型名和 Skill 文案不能决定窗口宽度。 */
.canvas-agent-panel > div,
.canvas-agent-settings,
+6 -8
View File
@@ -42,7 +42,7 @@ export function ModelPicker({
onMissingConfig,
showSelectedPrice = true,
showOptionPrices = showSelectedPrice,
variant = "default",
variant = "creation",
requirements,
showConfiguredModelName = false,
}: ModelPickerProps) {
@@ -173,10 +173,8 @@ export function ModelPicker({
ref={menuRef}
data-canvas-no-zoom
className={cn(
"canvas-model-picker-menu max-w-[calc(100vw-24px)]",
creationVariant
? cn("creation-model-picker-menu", activeGroupKey === null ? "is-brand-list" : "is-model-list")
: "w-[var(--panel-width-compact)]",
"canvas-model-picker-menu creation-model-picker-menu max-w-[calc(100vw-24px)]",
activeGroupKey === null ? "is-brand-list" : "is-model-list",
)}
style={
{
@@ -252,7 +250,7 @@ export function ModelPicker({
model={displayModel}
capability={capability}
theme={theme}
creationVariant={creationVariant}
creationVariant
showConfiguredModelName={showConfiguredModelName}
showPrice={showOptionPrices && creditsEnabled}
disabledReason={disabledReason}
@@ -283,8 +281,8 @@ export function ModelPicker({
arrow={false}
content={content}
classNames={{
root: cn("canvas-model-picker-popover", creationVariant && "creation-model-picker-popover", popoverClassName),
container: cn("canvas-composer-popover-surface", creationVariant && "creation-model-picker-surface"),
root: cn("canvas-model-picker-popover", "creation-model-picker-popover", popoverClassName),
container: cn("canvas-composer-popover-surface", "creation-model-picker-surface"),
content: "canvas-composer-popover-content",
}}
>
+4 -2
View File
@@ -66,8 +66,10 @@ export function parseAssetRecord(value: unknown): Asset {
const parsed = {
url: requireString(data, "url"),
storageKey: optionalString(data, "storageKey"),
width: requirePositiveNumber(data, "width"),
height: requirePositiveNumber(data, "height"),
// 上游视频结果经常不带 width/height。0 表示未知,不是伪造尺寸;
// 若按「必须大于 0」拒绝,生成成功并已扣费的视频会在入库时被判失败。
width: requireNonNegativeNumber(data, "width"),
height: requireNonNegativeNumber(data, "height"),
durationMs: optionalNonNegativeNumber(data, "durationMs"),
hasAudio: optionalBoolean(data, "hasAudio"),
bytes: requireNonNegativeNumber(data, "bytes"),
@@ -41,7 +41,7 @@ function fieldLabel(key: string, nodeType: string): string {
}
function operation(value: unknown): AgentApprovalPreviewOperation | null {
return value === "add_node" || value === "update_node" || value === "connect_nodes" || value === "generate_media" || value === "create_storyboard" || value === "edit_storyboard" ? value : null;
return value === "add_node" || value === "update_node" || value === "connect_nodes" || value === "generate_media" || value === "create_storyboard" || value === "edit_storyboard" || value === "plan_step" ? value : null;
}
function normalizeServerPreview(value: unknown): AgentApprovalPresentation | null {
+50
View File
@@ -0,0 +1,50 @@
import type { CloudAgentPlanItem, CloudAgentUserQuestion } from "@/components/canvas/canvas-cloud-agent-chat-ui";
type PlanCarrier = { planItems?: CloudAgentPlanItem[] };
/**
* 从对话消息流里挑出**当前该展示的那份**待办清单。
*
* 一个对话会跨多轮运行,**每轮各有一条** `plan-${runId}` 清单消息,它们都在同一个 messages
* 数组里。这里必须取**最新**的那条:取第一条(`messages.find`)会把清单永远钉在第 1 轮的
* 初始状态 —— 后面怎么推进都不刷新、全部做完也不消失(2026-09-16 实测反馈)。
*/
export function latestAgentPlanItems(messages: readonly PlanCarrier[]): CloudAgentPlanItem[] {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const items = messages[index].planItems;
if (items?.length) return items;
}
return [];
}
/** 全部完成才收起清单;只要还有未开始/进行中,就一直占着输入框上方那一行。 */
export function agentPlanVisible(items: readonly CloudAgentPlanItem[]): boolean {
return items.length > 0 && items.some((entry) => entry.status !== "done");
}
type QuestionCarrier = { role: string; question?: CloudAgentUserQuestion };
/**
* 挑出**当前还没作答**的那道提问。
*
* 取最后一条带 question 的消息;如果它之后已经有用户消息,说明用户答过了,面板收起。
*
* 为什么需要它:运行中输入框是禁用的,模型在正文里提问用户根本答不了
* (生产实测它连问 4 轮、白烧十几步)。`ask_user` 让本轮干净收尾并把问题结构化,
* 这个选择器决定「现在该不该把选项面板亮给用户」。
*/
export function pendingAgentQuestion(messages: readonly QuestionCarrier[]): CloudAgentUserQuestion | undefined {
let index = -1;
for (let cursor = messages.length - 1; cursor >= 0; cursor -= 1) {
if (messages[cursor].question) {
index = cursor;
break;
}
}
if (index < 0) return undefined;
// 之后只要出现过用户发言,就说明这道题已经答过了。
for (let cursor = index + 1; cursor < messages.length; cursor += 1) {
if (messages[cursor].role === "user") return undefined;
}
return messages[index].question;
}
@@ -13,6 +13,7 @@ const AccessSettingsPanel = lazy(() => import("./components/access-settings-pane
const EmailSettingsPanel = lazy(() => import("./components/email-settings-panel"));
const FeatureAvailabilityPanel = lazy(() => import("./components/feature-availability-panel"));
const StorageResourcesPanel = lazy(() => import("./components/storage-resources-panel"));
const AgentLessonsPanel = lazy(() => import("./components/agent-lessons-panel"));
export function AnalyticsPage() {
const { references } = useAdminContext();
@@ -106,3 +107,11 @@ export function StorageResourcesPage() {
</AdminPageFrame>
);
}
export function AgentLessonsPage() {
return (
<AdminPageFrame title="Agent 记忆" description="按用户查看个人记忆;批准仍由用户自己处理" scroll>
<AgentLessonsPanel />
</AdminPageFrame>
);
}
@@ -27,6 +27,7 @@ import {
PlugZap,
RadioTower,
RefreshCw,
Sparkles,
Settings2,
ShieldAlert,
ShieldCheck,
@@ -77,6 +78,7 @@ const adminNavigation: Array<{ label: string; items: AdminNavigationItem[] }> =
label: "运营",
items: [
{ path: "/admin/announcements", label: "系统公告", description: "发布、关闭与历史公告", icon: <BellRing className="size-4" /> },
{ path: "/admin/agent-lessons", label: "Agent 记忆", description: "按用户查看个人记忆", icon: <Sparkles className="size-4" /> },
{ path: "/admin/payments", label: "支付充值", description: "支付渠道、订单与对账", icon: <CreditCard className="size-4" /> },
{ path: "/admin/credit-operations", label: "积分运营", description: "人工调账与异常计费", icon: <Coins className="size-4" /> },
{ path: "/admin/redemption-codes", label: "兑换码", description: "生成与查看兑换码批次", icon: <TicketCheck className="size-4" /> },
@@ -0,0 +1,239 @@
import { App, Button, Input, Select, Space, Tag, Tooltip } from "antd";
import type { ColumnsType } from "antd/es/table";
import { RefreshCw, Trash2 } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { agentLessonCategoryLabel, deleteAdminAgentLesson, listAdminAgentLessons, type AdminAgentLesson } from "@/services/api/admin-agent-lessons";
import { listAdminUsers, type AdminUser } from "@/services/api/auth";
import { AdminDataTable, AdminStatusBadge, AdminTableEmpty } from "./admin-ui";
function authorLabel(record: AdminAgentLesson) {
if (record.authorDisplayName && record.authorUsername) return `${record.authorDisplayName}(${record.authorUsername})`;
return record.authorDisplayName || record.authorUsername || record.authorUserId || "未知用户";
}
export default function AgentLessonsPanel() {
const { message, modal } = App.useApp();
const [items, setItems] = useState<AdminAgentLesson[]>([]);
const [loading, setLoading] = useState(true);
const [status, setStatus] = useState<string>("all");
const [keyword, setKeyword] = useState("");
const [userId, setUserId] = useState<string | undefined>();
const [users, setUsers] = useState<AdminUser[]>([]);
const [userSearch, setUserSearch] = useState("");
const [searchingUsers, setSearchingUsers] = useState(false);
const debouncedKeyword = useDebouncedValue(keyword.trim(), 250);
const debouncedUserSearch = useDebouncedValue(userSearch.trim(), 250);
const seqRef = useRef(0);
const userSearchRef = useRef(0);
const load = useCallback(async () => {
const seq = ++seqRef.current;
setLoading(true);
try {
const data = await listAdminAgentLessons({
status: status === "all" ? undefined : status,
userId,
keyword: debouncedKeyword || undefined,
limit: 100,
});
if (seq !== seqRef.current) return;
setItems(data.lessons || []);
} catch (error) {
if (seq === seqRef.current) message.error(error instanceof Error ? error.message : "读取记忆失败");
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [debouncedKeyword, message, status, userId]);
useEffect(() => {
void load();
}, [load]);
useEffect(() => {
const requestId = ++userSearchRef.current;
setSearchingUsers(true);
void listAdminUsers({ keyword: debouncedUserSearch || undefined, page: 1, pageSize: 50 })
.then((result) => {
if (requestId !== userSearchRef.current) return;
setUsers((current) => {
const selected = current.find((user) => user.id === userId);
if (selected && !result.users.some((user) => user.id === selected.id)) return [selected, ...result.users];
return result.users;
});
})
.catch((error) => {
if (requestId === userSearchRef.current) message.error(error instanceof Error ? error.message : "搜索用户失败");
})
.finally(() => {
if (requestId === userSearchRef.current) setSearchingUsers(false);
});
}, [debouncedUserSearch, message, userId]);
const remove = (record: AdminAgentLesson) => {
modal.confirm({
title: `删除「${record.topic}」`,
content: `这是 ${authorLabel(record)} 的个人记忆。删除后该用户的 Agent 也无法召回。确认删除?`,
okText: "删除",
okButtonProps: { danger: true },
onOk: async () => {
await deleteAdminAgentLesson(record.id);
message.success("已删除");
await load();
},
});
};
const columns: ColumnsType<AdminAgentLesson> = [
{
title: "用户",
key: "author",
width: 168,
render: (_, record) => (
<div className="flex flex-col gap-0.5">
<span className="font-medium">{authorLabel(record)}</span>
{record.authorUserId ? <span className="text-[10px] opacity-60">{record.authorUserId}</span> : null}
</div>
),
},
{
title: "分类",
dataIndex: "category",
width: 92,
render: (value: string) => <Tag>{agentLessonCategoryLabel(value)}</Tag>,
},
{
title: "主题",
dataIndex: "topic",
width: 180,
render: (value: string, record) => (
<div className="flex flex-col gap-0.5">
<span className="font-medium">{value}</span>
{record.source ? <span className="text-[10px] opacity-60">来源:{record.source}</span> : null}
</div>
),
},
{
title: "适用场景 / 做法",
dataIndex: "situation",
render: (_: string, record) => {
const steps = record.steps || [];
return (
<div className="flex flex-col gap-1 text-xs">
<span className="opacity-80">{record.situation}</span>
{record.lesson ? <span>{record.lesson}</span> : null}
{steps.length ? (
<ol className="ml-4 list-decimal space-y-0.5 opacity-80">
{steps.map((step, index) => (
<li key={`${record.id}-${index}`}>
<span className="font-medium">{step.tool}</span>
{" — "}
{step.action}
{step.note ? <span className="opacity-60">({step.note})</span> : null}
</li>
))}
</ol>
) : null}
</div>
);
},
},
{
title: "状态",
dataIndex: "status",
width: 96,
render: (value: string) => <AdminStatusBadge label={value === "approved" ? "已批准" : value === "rejected" ? "已拒绝" : "待审"} tone={value === "approved" ? "success" : value === "rejected" ? "error" : "warning"} />,
},
{
title: (
<Tooltip title="被附进该用户 Agent 上下文的次数">
<span>注入</span>
</Tooltip>
),
dataIndex: "injected",
width: 64,
render: (value: number) => <span className="tabular-nums opacity-80">{value ?? 0}</span>,
},
{
title: (
<Tooltip title="该用户的 Agent 用 recall_lessons 取全文的次数">
<span>查阅</span>
</Tooltip>
),
dataIndex: "hits",
width: 64,
render: (value: number) => <span className="tabular-nums opacity-80">{value ?? 0}</span>,
},
{
title: "操作",
key: "actions",
width: 72,
render: (_, record) => (
<Space size={4}>
<Button size="small" danger icon={<Trash2 className="size-3.5" />} onClick={() => remove(record)} />
</Space>
),
},
];
return (
<div className="flex flex-col gap-3">
<p className="text-xs text-foreground/60">
记忆归用户自己批准和管理。这里只做巡查:可按用户、状态、关键词筛选,必要时删除违规内容。批准入口在用户的「设置 → Agent 记忆」。
</p>
<AdminDataTable
toolbar={
<div className="flex flex-wrap items-center gap-2">
<Select
value={status}
onChange={setStatus}
className="w-[120px]"
options={[
{ label: "全部", value: "all" },
{ label: "待审", value: "pending" },
{ label: "已批准", value: "approved" },
{ label: "已拒绝", value: "rejected" },
]}
/>
<Select
allowClear
showSearch
filterOption={false}
loading={searchingUsers}
placeholder="筛选用户"
className="w-[220px]"
value={userId}
onSearch={setUserSearch}
onChange={(value) => setUserId(value)}
options={users.map((user) => ({
value: user.id,
label: user.displayName ? `${user.displayName}(${user.username})` : user.username,
}))}
/>
<Input.Search
allowClear
placeholder="主题、内容或用户名"
className="w-[220px]"
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
/>
<Button icon={<RefreshCw className="size-4" />} onClick={() => void load()}>
刷新
</Button>
<span className="text-xs opacity-60">共 {items.length} 条</span>
</div>
}
table={{
rowKey: "id",
size: "small",
loading,
columns,
dataSource: items,
pagination: { defaultPageSize: 20, showSizeChanger: true },
}}
empty={<AdminTableEmpty title="没有匹配的记忆" description="换一个用户或关键词再查。用户自己在设置页批准后才会注入该用户的会话。" />}
/>
</div>
);
}
+6 -2
View File
@@ -1434,7 +1434,7 @@ function assetArchiveFacts(asset: LibraryAsset) {
{ label: "分类", value: assetCategoryLabel(asset.category) },
];
if (asset.kind === "image" || asset.kind === "video") {
facts.push({ label: "尺寸", value: `${asset.data.width}x${asset.data.height}` });
facts.push({ label: "尺寸", value: assetSizeLabel(asset.data.width, asset.data.height) });
}
if (asset.kind === "video" || asset.kind === "audio") {
facts.push({ label: "时长", value: formatAssetClock(asset.data.durationMs) || "未知" });
@@ -1454,7 +1454,11 @@ function assetSummary(asset: LibraryAsset) {
if (asset.kind === "text") return asset.data.content;
if (asset.kind === "audio") return `${formatAssetDuration(asset.data.durationMs)} · ${formatBytes(asset.data.bytes)} · ${asset.data.mimeType}`;
if (asset.kind === "model") return `${asset.data.fileName} · ${formatBytes(asset.data.bytes)} · ${asset.data.mimeType}`;
return `${asset.data.width}x${asset.data.height} · ${formatBytes(asset.data.bytes)} · ${asset.data.mimeType}`;
return `${assetSizeLabel(asset.data.width, asset.data.height)} · ${formatBytes(asset.data.bytes)} · ${asset.data.mimeType}`;
}
function assetSizeLabel(width: number, height: number) {
return width > 0 && height > 0 ? `${width}x${height}` : "未知";
}
function StorageTag({ asset }: { asset: LibraryAsset }) {
+2 -2
View File
@@ -623,7 +623,7 @@ export default function ProjectChaptersView({ detail, refreshProject }: ProjectD
</div>
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground/68">文本模型</span>
<ModelPicker config={effectiveConfig} capability="text" value={selectedTextModel} onChange={setSelectedTextModel} fullWidth placeholder="选择用于提取角色、场景与道具的文本模型" showSelectedPrice={false} onMissingConfig={() => navigateToSettings({ continueCreation: true })} />
<ModelPicker config={effectiveConfig} capability="text" value={selectedTextModel} onChange={setSelectedTextModel} variant="creation" fullWidth placeholder="选择用于提取角色、场景与道具的文本模型" showSelectedPrice={false} onMissingConfig={() => navigateToSettings({ continueCreation: true })} />
</label>
</div>
</Modal>
@@ -637,7 +637,7 @@ export default function ProjectChaptersView({ detail, refreshProject }: ProjectD
{storyboardImpact.shotCount ? <Callout tone="warning" title={`本章已有 ${storyboardImpact.shotCount} 个分镜`}>继续后会先生成新分镜;生成成功后,再按确认内容整体替换旧镜头及其关联数据。</Callout> : null}
<label className="block">
<span className="mb-1.5 block text-xs font-medium text-foreground/68">文本模型</span>
<ModelPicker config={effectiveConfig} capability="text" value={selectedTextModel} onChange={setSelectedTextModel} fullWidth placeholder="选择用于生成分镜的文本模型" showSelectedPrice={false} onMissingConfig={() => navigateToSettings({ continueCreation: true })} />
<ModelPicker config={effectiveConfig} capability="text" value={selectedTextModel} onChange={setSelectedTextModel} variant="creation" fullWidth placeholder="选择用于生成分镜的文本模型" showSelectedPrice={false} onMissingConfig={() => navigateToSettings({ continueCreation: true })} />
</label>
<div>
<label className="block">
@@ -0,0 +1,534 @@
import { App, Button, Form, Input, Select, Space } from "antd";
import { Check, Download, Pencil, Plus, Sparkles, Trash2, Upload, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { WorkspaceState } from "@/components/layout/workspace-state";
import { ModelPicker } from "@/components/model-picker";
import { StatusBadge } from "@/components/ui/base/badges";
import { IconButton } from "@/components/ui/base/buttons";
import { SegmentedControl } from "@/components/ui/base/segmented-control";
import { AppModal } from "@/components/ui/product/app-modal";
import { Callout } from "@/components/ui/product/callout";
import {
agentMemoryCategoryLabel,
AGENT_MEMORY_CATEGORIES,
compactAgentMemories,
createAgentMemory,
decideAgentMemory,
deleteAgentMemory,
exportAgentMemories,
getAgentMemorySettings,
importAgentMemories,
listAgentMemories,
updateAgentMemory,
updateAgentMemorySettings,
type AgentMemory,
type AgentMemoryBundle,
type AgentMemoryCompactInterval,
type AgentMemoryCompactView,
type AgentMemoryRequest,
type AgentMemoryStep,
} from "@/services/api/agent-memories";
import { encodeChannelModel, logicalModelIDForConfig, modelOptionName, resolveModelRequestConfig, useEffectiveConfig, type AiConfig } from "@/stores/use-config-store";
const COMPACT_INTERVALS: Array<{ value: AgentMemoryCompactInterval; label: string }> = [
{ value: "off", label: "手动" },
{ value: "daily", label: "每天" },
{ value: "weekly", label: "每周" },
{ value: "monthly", label: "每月" },
];
const STATUS_FILTERS = [
{ value: "all", label: "全部" },
{ value: "pending", label: "待审" },
{ value: "approved", label: "已批" },
{ value: "rejected", label: "已拒" },
] as const;
function memoryStatusTone(status: string) {
if (status === "approved") return "success" as const;
if (status === "rejected") return "error" as const;
if (status === "pending") return "warning" as const;
return "neutral" as const;
}
function memoryStatusLabel(status: string) {
if (status === "approved") return "已批准";
if (status === "rejected") return "已拒绝";
if (status === "pending") return "待审";
return status;
}
function compactModelFields(config: AiConfig, selectedModel: string) {
const model = selectedModel.trim();
if (!model) return {};
const agentConfig = { ...config, model };
const requestConfig = resolveModelRequestConfig(agentConfig, model);
return {
logicalModelId: logicalModelIDForConfig(agentConfig) || undefined,
channelId: requestConfig.channelId || undefined,
channelModelKey: modelOptionName(model) || undefined,
model,
};
}
function restoreCompactModel(settings: AgentMemoryCompactView | null, fallback: string) {
if (settings?.model?.trim()) return settings.model.trim();
if (settings?.channelId && settings?.channelModelKey) return encodeChannelModel(settings.channelId, settings.channelModelKey);
return fallback;
}
function compactStatusLabel(settings: AgentMemoryCompactView | null) {
if (!settings) return "";
if (settings.lastStatus === "queued") return "已排队,等待文本模型压缩";
if (settings.lastStatus === "running") return "正在调用文本模型压缩记忆";
if (settings.lastStatus === "failed") return settings.lastError || "上次压缩失败";
if (settings.lastStatus === "succeeded") {
const summary = settings.summary;
const parts = [
summary?.merged ? `合并 ${summary.merged}` : "",
summary?.rewritten ? `改写 ${summary.rewritten}` : "",
summary?.removed ? `删除 ${summary.removed}` : "",
].filter(Boolean);
const when = settings.lastCompactAt ? new Date(settings.lastCompactAt).toLocaleString() : "";
return [when && `上次 ${when}`, parts.join(" · ") || "模型认为没有需要改动的条目"].filter(Boolean).join(" · ");
}
return "压缩会按你的文本模型计费,把相近记忆合并、把含糊条目改清楚。";
}
type MemoryFormValues = {
topic: string;
category: string;
situation: string;
lesson?: string;
source?: string;
steps?: AgentMemoryStep[];
};
function toRequest(values: MemoryFormValues): AgentMemoryRequest {
const steps = (values.steps || []).filter((step) => step.tool?.trim() && step.action?.trim());
return {
topic: values.topic.trim(),
category: values.category,
situation: values.situation.trim(),
lesson: values.lesson?.trim() || undefined,
source: values.source?.trim() || undefined,
steps: steps.length ? steps : undefined,
};
}
function AgentMemoryCompactCard({ compact = false, onApplied }: { compact?: boolean; onApplied: () => Promise<void> }) {
const { message } = App.useApp();
const config = useEffectiveConfig();
const [settings, setSettings] = useState<AgentMemoryCompactView | null>(null);
const [model, setModel] = useState("");
const [saving, setSaving] = useState(false);
const [compacting, setCompacting] = useState(false);
const seqRef = useRef(0);
const busy = settings?.lastStatus === "queued" || settings?.lastStatus === "running";
const loadSettings = useCallback(async () => {
const seq = ++seqRef.current;
try {
const next = await getAgentMemorySettings();
if (seq !== seqRef.current) return null;
setSettings(next);
setModel((current) => restoreCompactModel(next, current || config.textModel || ""));
return next;
} catch (error) {
if (seq === seqRef.current) message.error(error instanceof Error ? error.message : "读取压缩设置失败");
return null;
}
}, [config.textModel, message]);
useEffect(() => {
void loadSettings();
}, [loadSettings]);
useEffect(() => {
if (!busy) return;
const timer = window.setInterval(() => {
void loadSettings().then((next) => {
if (next?.lastStatus === "succeeded") void onApplied();
});
}, 3000);
return () => window.clearInterval(timer);
}, [busy, loadSettings, onApplied]);
const persist = async (interval: AgentMemoryCompactInterval, selectedModel: string) => {
setSaving(true);
try {
const next = await updateAgentMemorySettings({
compactInterval: interval,
...compactModelFields(config, selectedModel),
});
setSettings(next);
setModel(restoreCompactModel(next, selectedModel));
} catch (error) {
message.error(error instanceof Error ? error.message : "保存压缩设置失败");
} finally {
setSaving(false);
}
};
const runCompact = async () => {
const selected = model.trim();
if (!selected) {
message.warning("请先选择用于压缩的文本模型");
return;
}
setCompacting(true);
try {
const next = await compactAgentMemories(compactModelFields(config, selected));
setSettings(next);
message.success("已提交压缩任务,完成后会刷新记忆列表");
} catch (error) {
message.error(error instanceof Error ? error.message : "提交压缩失败");
} finally {
setCompacting(false);
}
};
const statusText = compactStatusLabel(settings);
const failed = settings?.lastStatus === "failed";
return (
<section className={compact ? "space-y-2.5" : "space-y-3 rounded-2xl bg-surface-secondary/80 px-4 py-3.5"}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className="text-sm font-medium text-foreground">压缩优化</h3>
{compact ? null : <p className="mt-0.5 text-caption leading-5 text-muted-foreground">按文本模型计费,合并相近条目、改写含糊内容。</p>}
</div>
<Button size="small" icon={<Sparkles className="size-3.5" />} loading={compacting || busy} disabled={!model.trim()} onClick={() => void runCompact()}>
{busy ? "压缩中" : "立即压缩"}
</Button>
</div>
<div className="flex min-w-0 flex-col gap-2">
<SegmentedControl
size="sm"
ariaLabel="压缩周期"
value={settings?.compactInterval || "off"}
disabled={saving || busy}
options={COMPACT_INTERVALS}
onChange={(value) => void persist(value, model)}
/>
<div className="min-w-0 overflow-hidden rounded-xl bg-surface-tertiary">
<ModelPicker
config={config}
value={model}
capability="text"
variant="creation"
fullWidth
showSelectedPrice
showOptionPrices
className="!h-9 !min-h-9 !border-0 !bg-transparent !shadow-none"
placeholder="选择压缩用的文本模型"
onChange={(value) => {
setModel(value);
void persist(settings?.compactInterval || "off", value);
}}
/>
</div>
</div>
{failed && settings?.lastError ? (
<Callout tone="warning" title="上次压缩未完成">{settings.lastError}</Callout>
) : statusText ? (
<p className="text-caption leading-5 text-muted-foreground">{statusText}</p>
) : null}
</section>
);
}
export default function AgentMemoryPane({ compact = false }: { compact?: boolean }) {
const { message, modal } = App.useApp();
const [items, setItems] = useState<AgentMemory[]>([]);
const [loading, setLoading] = useState(true);
const [status, setStatus] = useState<string>("all");
const [busyId, setBusyId] = useState<string | null>(null);
const [editorOpen, setEditorOpen] = useState(false);
const [editing, setEditing] = useState<AgentMemory | null>(null);
const [saving, setSaving] = useState(false);
const [form] = Form.useForm<MemoryFormValues>();
const fileRef = useRef<HTMLInputElement>(null);
const seqRef = useRef(0);
const load = useCallback(async () => {
const seq = ++seqRef.current;
setLoading(true);
try {
const data = await listAgentMemories(status === "all" ? undefined : status, 200);
if (seq !== seqRef.current) return;
setItems(data.memories || []);
} catch (error) {
if (seq === seqRef.current) message.error(error instanceof Error ? error.message : "读取记忆失败");
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [message, status]);
useEffect(() => {
void load();
}, [load]);
const openCreate = () => {
setEditing(null);
form.resetFields();
form.setFieldsValue({ category: "other", steps: [] });
setEditorOpen(true);
};
const openEdit = (record: AgentMemory) => {
setEditing(record);
form.setFieldsValue({
topic: record.topic,
category: record.category || "other",
situation: record.situation,
lesson: record.lesson,
source: record.source,
steps: record.steps || [],
});
setEditorOpen(true);
};
const save = async () => {
const values = await form.validateFields();
const request = toRequest(values);
if (!request.lesson && !(request.steps && request.steps.length)) {
message.warning("请填写做法,或至少添加一步路线");
return;
}
setSaving(true);
try {
if (editing) {
await updateAgentMemory(editing.id, request);
message.success("已保存");
} else {
await createAgentMemory(request);
message.success("已添加,立刻对你的 Agent 生效");
}
setEditorOpen(false);
await load();
} catch (error) {
message.error(error instanceof Error ? error.message : "保存失败");
} finally {
setSaving(false);
}
};
const decide = async (record: AgentMemory, decision: "approve" | "reject") => {
setBusyId(record.id);
try {
await decideAgentMemory(record.id, decision);
message.success(decision === "approve" ? "已批准,之后的会话会用到这条记忆" : "已拒绝,不会再注入会话");
await load();
} catch (error) {
message.error(error instanceof Error ? error.message : "处理失败");
} finally {
setBusyId(null);
}
};
const remove = (record: AgentMemory) => {
modal.confirm({
title: `删除记忆「${record.topic}」`,
content: "删除后不会再出现在你的 Agent 上下文里。确认删除?",
okText: "删除",
okButtonProps: { danger: true },
onOk: async () => {
await deleteAgentMemory(record.id);
message.success("已删除");
await load();
},
});
};
const onExport = async () => {
try {
const bundle = await exportAgentMemories();
const blob = new Blob([JSON.stringify(bundle, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `agent-memories-${bundle.exportedAt.slice(0, 10)}.json`;
link.click();
URL.revokeObjectURL(url);
message.success(`已导出 ${bundle.memories.length} 条`);
} catch (error) {
message.error(error instanceof Error ? error.message : "导出失败");
}
};
const onImportFile = async (file: File) => {
try {
const parsed = JSON.parse(await file.text()) as AgentMemoryBundle;
const result = await importAgentMemories(parsed);
message.success(`导入 ${result.imported} 条,合并 ${result.merged} 条,跳过 ${result.skipped} 条`);
await load();
} catch (error) {
message.error(error instanceof Error ? error.message : "导入失败,请确认是本产品导出的 JSON");
}
};
const pendingCount = items.filter((item) => item.status === "pending").length;
const statusFilters = STATUS_FILTERS.map((option) => ({
...option,
label: option.value === "pending" && pendingCount ? `待审 ${pendingCount}` : option.label,
}));
return (
<div className={compact ? "flex min-h-0 flex-1 flex-col gap-3 overflow-hidden" : "flex flex-col gap-5"}>
<div className="flex shrink-0 flex-wrap items-center gap-2">
<SegmentedControl
size="sm"
ariaLabel="记忆状态"
value={status}
options={statusFilters}
onChange={setStatus}
/>
<div className="ml-auto flex items-center gap-1">
<IconButton variant="ghost" size="sm" icon={Download} aria-label="导出记忆" onClick={() => void onExport()} />
<IconButton variant="ghost" size="sm" icon={Upload} aria-label="导入记忆" onClick={() => fileRef.current?.click()} />
<Button type="primary" icon={<Plus className="size-4" />} onClick={openCreate}>
添加记忆
</Button>
</div>
<input
ref={fileRef}
type="file"
accept="application/json,.json"
className="hidden"
onChange={(event) => {
const file = event.target.files?.[0];
event.target.value = "";
if (file) void onImportFile(file);
}}
/>
</div>
{compact ? null : <AgentMemoryCompactCard onApplied={load} />}
<div className={compact ? "thin-scrollbar flex min-h-0 flex-1 flex-col overflow-y-auto" : undefined}>
{loading ? (
<div className="space-y-2" aria-busy="true" aria-live="polite">
{[0, 1, 2].map((index) => (
<div key={index} className="h-[72px] animate-pulse rounded-2xl bg-surface-secondary" />
))}
</div>
) : null}
{!loading && items.length === 0 ? (
<WorkspaceState
compact
icon="empty"
className={compact ? "min-h-0 flex-1 py-8" : "min-h-[220px] py-10"}
title={status === "pending" ? "没有待批准的记忆" : "还没有个人记忆"}
description={status === "pending" ? "Agent 跑通任务后会把可复用做法记到这里,等你点头。" : "手动添加立刻生效,也可以等 Agent 记下后再批准。"}
action={status === "pending" ? undefined : <Button type="primary" icon={<Plus className="size-4" />} onClick={openCreate}>添加记忆</Button>}
/>
) : null}
{!loading && items.length ? (
<div className="space-y-2">
{items.map((record) => (
<article key={record.id} className="group rounded-2xl bg-surface-secondary/80 px-3.5 py-3 transition-[background,transform] duration-[var(--motion-state)] hover:bg-surface-hover motion-reduce:transition-none">
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-sm font-medium text-foreground">{record.topic}</h3>
<StatusBadge size="sm" tone={memoryStatusTone(record.status)} label={memoryStatusLabel(record.status)} />
<span className="text-[11px] text-muted-foreground">{agentMemoryCategoryLabel(record.category)}</span>
</div>
<p className="mt-1 text-caption leading-5 text-muted-foreground">{record.situation}</p>
{record.lesson ? <p className="mt-1 text-caption leading-5 text-foreground/80">{record.lesson}</p> : null}
{record.steps?.length ? (
<ol className="mt-1.5 ml-4 list-decimal space-y-0.5 text-[11px] leading-5 text-muted-foreground">
{record.steps.map((step, index) => (
<li key={`${record.id}-${index}`}>
<span className="font-medium text-foreground/80">{step.tool}</span>
{" — "}
{step.action}
{step.note ? <span className="text-foreground/45">({step.note})</span> : null}
</li>
))}
</ol>
) : null}
</div>
<div className="flex shrink-0 flex-wrap items-center justify-end gap-1">
{record.status === "pending" ? (
<>
<Button size="small" type="primary" icon={<Check className="size-3.5" />} loading={busyId === record.id} onClick={() => void decide(record, "approve")}>
批准
</Button>
<Button size="small" icon={<X className="size-3.5" />} loading={busyId === record.id} onClick={() => void decide(record, "reject")}>
拒绝
</Button>
</>
) : null}
<IconButton variant="ghost" size="sm" icon={Pencil} aria-label={`编辑 ${record.topic}`} onClick={() => openEdit(record)} />
<IconButton variant="danger" size="sm" icon={Trash2} aria-label={`删除 ${record.topic}`} onClick={() => remove(record)} />
</div>
</div>
</article>
))}
</div>
) : null}
</div>
{compact ? (
<div className="shrink-0 border-t border-border/40 pt-3">
<AgentMemoryCompactCard compact onApplied={load} />
</div>
) : null}
<AppModal
open={editorOpen}
title={editing ? "编辑记忆" : "添加记忆"}
okText={editing ? "保存" : "添加"}
confirmLoading={saving}
onOk={() => void save()}
onCancel={() => setEditorOpen(false)}
>
<Form form={form} layout="vertical" className="pt-2">
<Form.Item name="topic" label="主题" rules={[{ required: true, message: "请填写主题" }]}>
<Input maxLength={120} placeholder="例如 canvas.snapshot-hash" />
</Form.Item>
<Form.Item name="category" label="分类" rules={[{ required: true, message: "请选择分类" }]}>
<Select options={AGENT_MEMORY_CATEGORIES.map((entry) => ({ value: entry.key, label: entry.label }))} />
</Form.Item>
<Form.Item name="situation" label="适用场景" rules={[{ required: true, message: "请填写适用场景" }]}>
<Input maxLength={200} placeholder="什么情况下用这条记忆" />
</Form.Item>
<Form.Item name="lesson" label="做法">
<Input.TextArea rows={3} maxLength={400} placeholder="一句话说明该怎么做" />
</Form.Item>
<Form.Item name="source" label="来源(可选)">
<Input maxLength={200} />
</Form.Item>
<Form.List name="steps">
{(fields, { add, remove: removeStep }) => (
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-sm">路线步骤(可选)</span>
<Button size="small" onClick={() => add({ tool: "", action: "", note: "" })}>
加一步
</Button>
</div>
{fields.map((field) => (
<Space key={field.key} className="flex w-full" align="start">
<Form.Item {...field} name={[field.name, "tool"]} className="mb-0 flex-1">
<Input placeholder="工具名" />
</Form.Item>
<Form.Item {...field} name={[field.name, "action"]} className="mb-0 flex-1">
<Input placeholder="做什么" />
</Form.Item>
<Button type="text" danger onClick={() => removeStep(field.name)}>
删
</Button>
</Space>
))}
</div>
)}
</Form.List>
</Form>
</AppModal>
</div>
);
}
+17 -2
View File
@@ -1,6 +1,6 @@
import { App, Button, InputNumber } from "antd";
import { SettingsRow } from "@/components/ui/product/settings-row";
import { ArrowLeft, Boxes, Bug, Cloud, MessageSquareText, RadioTower, SlidersHorizontal, Workflow } from "lucide-react";
import { ArrowLeft, Boxes, Brain, Bug, Cloud, MessageSquareText, RadioTower, SlidersHorizontal, Workflow } from "lucide-react";
import { useEffect, useLayoutEffect, useMemo, useState, type ReactNode } from "react";
import { useNavigate, useSearchParams } from "react-router";
@@ -12,11 +12,12 @@ import { ChannelSettingsPane, channelValidationError, focusInvalidChannelField,
import { ModelDefaultGrid } from "./model-default-grid";
import { PromptPreferencesPane } from "./prompt-preferences-pane";
import DiagnosticsPanel from "./diagnostics-panel";
import AgentMemoryPane from "./agent-memory-pane";
import { RunningHubSettingsPane } from "./runninghub-settings-pane";
import { RUNNINGHUB_PLUGIN_ID } from "@/lib/plugins/builtin/workflows";
import { usePluginStore } from "@/stores/use-plugin-store";
type ConfigSectionKey = "channels" | "models" | "runninghub" | "preferences" | "prompts" | "storage" | "diagnostics";
type ConfigSectionKey = "channels" | "models" | "runninghub" | "preferences" | "prompts" | "agent-memory" | "storage" | "diagnostics";
const configSections: Array<{ key: ConfigSectionKey; label: string; description: string; icon: ReactNode }> = [
{ key: "channels", label: "个人渠道", description: "模型服务与个人工作流", icon: <RadioTower className="size-4" /> },
@@ -24,6 +25,7 @@ const configSections: Array<{ key: ConfigSectionKey; label: string; description:
{ key: "models", label: "模型选择", description: "按领域选择默认模型", icon: <Boxes className="size-4" /> },
{ key: "preferences", label: "生成偏好", description: "画布生成默认值", icon: <SlidersHorizontal className="size-4" /> },
{ key: "prompts", label: "提示词偏好", description: "按任务定制平台模板", icon: <MessageSquareText className="size-4" /> },
{ key: "agent-memory", label: "Agent 记忆", description: "批准、添加、导出导入、压缩", icon: <Brain className="size-4" /> },
{ key: "storage", label: "我的对象存储", description: "管理个人媒体存储", icon: <Cloud className="size-4" /> },
{ key: "diagnostics", label: "问题诊断", description: "导出日志协助排查", icon: <Bug className="size-4" /> },
];
@@ -153,6 +155,19 @@ export default function SettingsPage() {
</SettingsPane>
),
prompts: <SettingsPane fill><PromptPreferencesPane /></SettingsPane>,
"agent-memory": (
<SettingsPane>
<div className="settings-pane-header">
<div className="min-w-0">
<h2>Agent 记忆</h2>
<p>只属于你。Agent 记下的先待批准;手动添加立刻生效。可导入导出,也可用文本模型压缩相近条目。</p>
</div>
</div>
<div className="settings-section">
<AgentMemoryPane />
</div>
</SettingsPane>
),
diagnostics: <SettingsPane><DiagnosticsPanel taskId={searchParams.get("taskId") || undefined} projectId={searchParams.get("projectId") || undefined} /></SettingsPane>,
storage: (
<SettingsPane>
+2
View File
@@ -16,6 +16,7 @@ const CreditOperationsPage = lazy(() => import("@/pages/admin/admin-route-pages"
const AccessSettingsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.AccessSettingsPage })));
const EmailSettingsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.EmailSettingsPage })));
const FeatureAvailabilityPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.FeatureAvailabilityPage })));
const AgentLessonsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.AgentLessonsPage })));
const ChannelsPage = lazy(() => import("@/pages/admin/channels/channels-page"));
const LogicalModelsPage = lazy(() => import("@/pages/admin/logical-models/logical-models-page"));
const AdminPluginsPage = lazy(() => import("@/pages/admin/plugins/plugins-page"));
@@ -195,6 +196,7 @@ export const router = createBrowserRouter([
{ path: "prompt-templates", element: <StoryboardPromptsPage /> },
{ path: "storyboard-prompts", element: <Navigate to="/admin/prompt-templates" replace /> },
{ path: "announcements", element: <AnnouncementsPage /> },
{ path: "agent-lessons", element: <AgentLessonsPage /> },
{ path: "resources", element: <StorageResourcesPage /> },
{ path: "credit-operations", element: <CreditOperationsPage /> },
{ path: "redemption-codes", element: <RedemptionCodesPage /> },
@@ -0,0 +1,25 @@
import { compactApiParams, http } from "./request";
import { agentMemoryCategoryLabel, AGENT_MEMORY_CATEGORIES, type AgentMemory, type AgentMemoryStep } from "./agent-memories";
export type AdminAgentLesson = AgentMemory & {
authorUserId?: string;
authorUsername?: string;
authorDisplayName?: string;
};
export type { AgentMemoryStep };
export function listAdminAgentLessons(params: { status?: string; userId?: string; keyword?: string; limit?: number } = {}) {
const { status, userId, keyword, limit = 100 } = params;
return http.get<{ lessons: AdminAgentLesson[] }>("/admin/agent-lessons", {
params: compactApiParams({ status, userId, keyword, limit }),
timeout: 15_000,
});
}
export function deleteAdminAgentLesson(id: string) {
return http.delete<{ id: string }>(`/admin/agent-lessons/${encodeURIComponent(id)}`, { timeout: 15_000 });
}
export const AGENT_LESSON_CATEGORIES = AGENT_MEMORY_CATEGORIES;
export const agentLessonCategoryLabel = agentMemoryCategoryLabel;
+145
View File
@@ -0,0 +1,145 @@
import { http, compactApiParams } from "./request";
export type AgentMemoryStep = { tool: string; action: string; note?: string };
export type AgentMemoryStatus = "pending" | "approved" | "rejected" | string;
export type AgentMemory = {
id: string;
topic: string;
category?: string;
situation: string;
lesson?: string;
steps?: AgentMemoryStep[];
source?: string;
status: AgentMemoryStatus;
injected: number;
hits: number;
lastVerifiedAt?: string;
createdAt: string;
updatedAt: string;
};
export type AgentMemoryRequest = {
topic: string;
category: string;
situation: string;
lesson?: string;
steps?: AgentMemoryStep[];
source?: string;
};
export type AgentMemoryBundle = {
version: number;
kind: string;
exportedAt: string;
memories: Array<{
topic: string;
category: string;
situation: string;
lesson?: string;
steps?: AgentMemoryStep[];
source?: string;
status?: string;
}>;
};
export type AgentMemoryImportResult = {
imported: number;
merged: number;
skipped: number;
};
export type AgentMemoryCompactInterval = "off" | "daily" | "weekly" | "monthly" | string;
export type AgentMemoryCompactStatus = "idle" | "queued" | "running" | "succeeded" | "failed" | string;
export type AgentMemoryCompactSummary = {
rewritten: number;
merged: number;
removed: number;
skipped: number;
};
export type AgentMemoryCompactView = {
compactInterval: AgentMemoryCompactInterval;
logicalModelId?: string;
channelId?: string;
channelModelKey?: string;
model?: string;
lastCompactAt?: string;
lastStatus: AgentMemoryCompactStatus;
lastError?: string;
taskId?: string;
summary?: AgentMemoryCompactSummary;
};
export type AgentMemoryCompactRequest = {
logicalModelId?: string;
channelId?: string;
channelModelKey?: string;
model?: string;
};
export type AgentMemorySettingRequest = AgentMemoryCompactRequest & {
compactInterval: AgentMemoryCompactInterval;
};
export const AGENT_MEMORY_CATEGORIES = [
{ key: "storyboard", label: "分镜" },
{ key: "video", label: "视频生成" },
{ key: "image", label: "图像生成" },
{ key: "canvas", label: "画布操作" },
{ key: "asset", label: "资产" },
{ key: "model", label: "模型选择" },
{ key: "workflow", label: "流程顺序" },
{ key: "billing", label: "计费" },
{ key: "other", label: "其他" },
] as const;
export function agentMemoryCategoryLabel(key?: string) {
return AGENT_MEMORY_CATEGORIES.find((entry) => entry.key === key)?.label || "其他";
}
export function listAgentMemories(status?: string, limit = 200) {
return http.get<{ memories: AgentMemory[] }>("/agent/memories", {
params: compactApiParams({ status, limit }),
timeout: 15_000,
});
}
export function createAgentMemory(input: AgentMemoryRequest) {
return http.post<AgentMemory>("/agent/memories", input, { timeout: 15_000 });
}
export function updateAgentMemory(id: string, input: AgentMemoryRequest) {
return http.patch<AgentMemory>(`/agent/memories/${encodeURIComponent(id)}`, input, { timeout: 15_000 });
}
export function decideAgentMemory(id: string, decision: "approve" | "reject") {
return http.post<{ id: string; decision: string }>(`/agent/memories/${encodeURIComponent(id)}/decide`, { decision }, { timeout: 15_000 });
}
export function deleteAgentMemory(id: string) {
return http.delete<{ id: string }>(`/agent/memories/${encodeURIComponent(id)}`, { timeout: 15_000 });
}
export function exportAgentMemories() {
return http.get<AgentMemoryBundle>("/agent/memories/export", { timeout: 30_000 });
}
export function importAgentMemories(bundle: AgentMemoryBundle) {
return http.post<AgentMemoryImportResult>("/agent/memories/import", bundle, { timeout: 30_000 });
}
export function getAgentMemorySettings() {
return http.get<AgentMemoryCompactView>("/agent/memories/settings", { timeout: 15_000 });
}
export function updateAgentMemorySettings(input: AgentMemorySettingRequest) {
return http.patch<AgentMemoryCompactView>("/agent/memories/settings", input, { timeout: 15_000 });
}
export function compactAgentMemories(input: AgentMemoryCompactRequest = {}) {
return http.post<AgentMemoryCompactView>("/agent/memories/compact", input, { timeout: 30_000 });
}
+6 -2
View File
@@ -27,7 +27,7 @@ export type AgentProfileView = {
layers: AgentProfileLayer[];
};
export type AgentApprovalPreviewOperation = "add_node" | "update_node" | "connect_nodes" | "generate_media" | "create_storyboard" | "edit_storyboard";
export type AgentApprovalPreviewOperation = "add_node" | "update_node" | "connect_nodes" | "generate_media" | "create_storyboard" | "edit_storyboard" | "plan_step";
export type AgentApprovalPreviewItem = {
operation: AgentApprovalPreviewOperation;
@@ -114,7 +114,7 @@ export type CreateAgentRunInput = {
skillIds?: string[];
permissionMode?: AgentPermissionMode;
contextScope?: string[];
budget?: { maxCredits?: number; maxGenerationTasks?: number; maxVideoSeconds?: number };
budget?: { maxCredits?: number; maxGenerationTasks?: number; maxVideoSeconds?: number; maxSteps?: number };
idempotencyKey: string;
};
@@ -145,6 +145,10 @@ export async function sendAgentMessage(runId: string, input: CreateAgentRunInput
return submitAgentRequest(`/agent/runs/${encodeURIComponent(runId)}/messages`, input);
}
export function sendAgentInterjection(runId: string, input: { text: string; messageId: string }) {
return http.post<{ accepted: boolean; pending: number }>(`/agent/runs/${encodeURIComponent(runId)}/interjections`, input, { timeout: 20_000 });
}
export function getAgentCapabilities() {
return http.get<{ version: number; permissionModes: AgentPermissionMode[]; contextScopes: string[]; skills: boolean; writeTools: boolean; capabilitySetVersion?: string; capabilitySetHash?: string; nodeTypes?: string[] }>("/agent/capabilities", { timeout: 15_000 });
}
+139
View File
@@ -18025,6 +18025,145 @@ html:not(.dark) .creation-home .creation-user-message-copy-wrap { box-shadow: 0
height: 12px;
}
/* 品牌/模型两级菜单是 ModelPicker 默认结构,不能只写在 creation variant 下。 */
.canvas-model-picker-brands {
display: grid;
gap: 4px;
width: 100%;
}
.canvas-model-picker-brand {
display: flex;
width: 100%;
min-height: 48px;
min-width: 0;
align-items: center;
gap: 10px;
border: 1px solid transparent;
border-radius: 10px;
padding: 8px 10px;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
}
.canvas-model-picker-brand:hover,
.canvas-model-picker-brand.is-active {
border-color: var(--workspace-border);
background: var(--workspace-surface-hover);
}
.canvas-model-picker-brand-icon {
display: grid;
width: 32px;
height: 32px;
flex: 0 0 32px;
place-items: center;
border-radius: 9px;
background: var(--workspace-surface-hover);
}
.canvas-model-picker-brand-copy {
display: grid;
min-width: 0;
flex: 1;
gap: 2px;
}
.canvas-model-picker-brand-copy strong {
overflow: hidden;
font-size: 13px;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.canvas-model-picker-brand-copy small {
overflow: hidden;
color: color-mix(in srgb, currentColor 55%, transparent);
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.canvas-model-picker-brand-arrow {
width: 14px;
height: 14px;
flex: 0 0 14px;
color: color-mix(in srgb, currentColor 48%, transparent);
transform: rotate(-90deg);
}
.canvas-model-picker-menu.is-brand-list {
width: min(360px, calc(100vw - 24px)) !important;
}
.canvas-model-picker-menu.is-model-list {
width: min(720px, calc(100vw - 24px)) !important;
}
.canvas-model-picker-two-pane {
display: grid;
width: 100%;
grid-template-columns: 250px minmax(0, 1fr);
gap: 14px;
min-width: 0;
align-items: start;
}
.canvas-model-picker-menu.is-model-list .canvas-model-picker-brand-rail {
display: grid;
align-content: start;
gap: 5px;
border-right: 1px solid var(--workspace-border);
padding-right: 14px;
}
.canvas-model-picker-menu.is-model-list .canvas-model-picker-brand {
width: 100%;
}
.canvas-model-picker-model-pane {
min-width: 0;
}
@media (max-width: 720px) {
.canvas-model-picker-menu:is(.is-brand-list, .is-model-list) {
width: calc(100vw - 24px) !important;
}
.canvas-model-picker-two-pane {
grid-template-columns: minmax(0, 1fr);
}
.canvas-model-picker-menu.is-model-list .canvas-model-picker-brand-rail {
display: none;
}
}
.canvas-model-picker-secondary-head {
display: flex;
min-width: 0;
align-items: center;
gap: 8px;
padding: 0 2px 8px;
}
.canvas-model-picker-back {
display: grid;
width: 28px;
height: 28px;
flex: 0 0 28px;
place-items: center;
border: 1px solid var(--workspace-border);
border-radius: 8px;
background: var(--workspace-surface-hover);
color: inherit;
cursor: pointer;
}
.canvas-model-picker-back svg {
width: 15px;
height: 15px;
}
.canvas-model-picker-secondary-head > span {
display: grid;
min-width: 0;
gap: 2px;
}
.canvas-model-picker-secondary-head strong {
overflow: hidden;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.canvas-model-picker-secondary-head small {
color: color-mix(in srgb, currentColor 52%, transparent);
font-size: 10px;
}
/* 模型下拉:选中项与当前 hover/focus 项展示说明,其他项保持安静。 */
.canvas-model-picker-option {
transition: min-height 180ms cubic-bezier(.16, 1, .3, 1), background-color 160ms ease, transform 160ms cubic-bezier(.16, 1, .3, 1) !important;
+50
View File
@@ -0,0 +1,50 @@
import { expect, test } from "bun:test";
// 自研(2026-09-17):Agent 运行中插话。
//
// 这条功能的核心是**取消一个此前刻意加上的限制**:运行时输入框本来是禁用的
// (旧代码 `disabled={busy || running || …}`),策略提示词也据此写着「运行中用户无法打字」。
// 所以这里的断言要盯住两件事:入口真的打开了,以及旧前提没有残留在代码里。
test("运行中不再锁死输入框,发送走插话而不是新建轮次", async () => {
const panel = await Bun.file(new URL("../src/components/canvas/canvas-cloud-agent-panel.tsx", import.meta.url)).text();
// 运行中走插话分支(不建轮次、不走那套扣费幂等记账)
expect(panel).toContain("await interject(value)");
expect(panel).toContain("sendAgentInterjection(activeRun.id, { text: value, messageId })");
// 乐观落进时间线时带插话标记,与「开新一轮」的消息在界面上区分开
expect(panel).toContain('interjection: "sent"');
// 输入框的禁用条件里不能再有 running —— 只保留「连不上事件流」「历史/待确认未水合」这类真不能发的状态
expect(panel).toContain('disabled={Boolean(run && connectionStatus !== "connected")');
expect(panel).not.toContain("disabled={busy || running ||");
// 停止按钮由 running 驱动,发送按钮由我们自己的请求驱动,两者不再互斥
expect(panel).toContain("sending={busy}");
expect(panel).toContain("running={running}");
// 两个 SSE 事件都要处理:回显(多标签页)与未送达退回
expect(panel).toContain('event.type === "user_interjection"');
expect(panel).toContain('event.type === "user_interjection_dropped"');
// 退回时要让文案能被再次发送
expect(panel).toContain("setPrompt?.((current) => (current.trim() ? current : text))");
});
test("输入框运行中同时给出「发送(插话)」与「停止」", async () => {
const composer = await Bun.file(new URL("../src/components/canvas/canvas-cloud-agent-chat-ui.tsx", import.meta.url)).text();
// 关键改动:canStop 不再等于 sending —— 否则运行中两个动作只能二选一
expect(composer).toContain("const canStop = Boolean(running && onStop);");
expect(composer).toContain("const canSubmit = !disabled && !sending && Boolean(prompt.trim() || attachments.length);");
expect(composer).not.toContain("const canStop = Boolean(sending && onStop);");
expect(composer).toContain('aria-label="停止本轮"');
// 插话/未送达要有可见标记
expect(composer).toContain('interjection?: "sent" | "undelivered";');
expect(composer).toContain('item.interjection === "undelivered" ? "插话未送达" : "插话"');
});
test("插话走独立接口,不碰轮次接口", async () => {
const api = await Bun.file(new URL("../src/services/api/agent.ts", import.meta.url)).text();
expect(api).toContain("export function sendAgentInterjection(");
expect(api).toContain("/interjections");
expect(api).toContain("messageId: string");
});
+32
View File
@@ -57,3 +57,35 @@ describe("parseAssetRecord", () => {
expect(() => parseAssetRecordList([{ ...completeImage, id: "bad", tags: undefined }])).toThrow(/素材 bad/);
});
});
const completeVideo = {
id: "video-1",
kind: "video",
title: "生成视频",
coverUrl: "https://example.com/a.mp4",
tags: ["生成"],
createdAt: "2026-08-29T00:00:00.000Z",
updatedAt: "2026-08-29T00:00:00.000Z",
data: { url: "https://example.com/a.mp4", width: 720, height: 1280, bytes: 1, mimeType: "video/mp4" },
};
describe("parseAssetRecord 视频尺寸", () => {
test("宽高未知(0)放行,视频照常入库", () => {
const parsed = parseAssetRecord({ ...completeVideo, data: { ...completeVideo.data, width: 0, height: 0 } });
expect(parsed.kind).toBe("video");
if (parsed.kind === "video") {
expect(parsed.data.width).toBe(0);
expect(parsed.data.height).toBe(0);
}
});
test("负数与非法值仍然拒", () => {
expect(() => parseAssetRecord({ ...completeVideo, data: { ...completeVideo.data, width: -1 } })).toThrow(/width/);
expect(() => parseAssetRecord({ ...completeVideo, data: { ...completeVideo.data, height: Number.NaN } })).toThrow(/height/);
expect(() => parseAssetRecord({ ...completeVideo, data: { ...completeVideo.data, width: "720" } })).toThrow(/width/);
});
test("图片不受影响:零尺寸仍然拒", () => {
expect(() => parseAssetRecord({ ...completeImage, data: { ...completeImage.data, width: 0, height: 1 } })).toThrow(/width/);
});
});
+82
View File
@@ -0,0 +1,82 @@
import { describe, expect, test } from "bun:test";
import { agentPlanVisible, latestAgentPlanItems, pendingAgentQuestion } from "@/lib/canvas/cloud-agent-plan";
const items = (...statuses: Array<"pending" | "doing" | "done">) => statuses.map((status, index) => ({ id: `${index + 1}`, title: `第 ${index + 1} 项`, status }));
/**
* 回归(2026-09-16):一个对话会跨多轮运行,每轮各有一条 `plan-${runId}` 清单消息,
* 都在同一个 messages 数组里。原来取的是**第一条**,于是清单永远钉在第 1 轮的初始状态 ——
* 后面怎么推进都不刷新、全部做完也不消失(实测反馈:plan 完成了不更新、全完成也不关闭)。
*/
describe("latestAgentPlanItems", () => {
test("跨轮取最新那份,而不是第一条", () => {
const messages = [
{ id: "plan-run-1", planItems: items("pending", "pending") },
{ id: "user-1", text: "..." },
{ id: "plan-run-2", planItems: items("done", "doing") },
];
expect(latestAgentPlanItems(messages).map((entry) => entry.status)).toEqual(["done", "doing"]);
});
test("最新那份全部完成 → 清单收起", () => {
const messages = [
{ id: "plan-run-1", planItems: items("pending") },
{ id: "plan-run-2", planItems: items("done", "done") },
];
const plan = latestAgentPlanItems(messages);
expect(plan.every((entry) => entry.status === "done")).toBe(true);
expect(agentPlanVisible(plan)).toBe(false);
});
test("最新那份还没做完 → 继续显示", () => {
expect(agentPlanVisible(latestAgentPlanItems([{ id: "plan-run-1", planItems: items("done", "doing") }]))).toBe(true);
});
test("没有任何清单(包括带空数组的)→ 空且不显示", () => {
expect(latestAgentPlanItems([])).toEqual([]);
expect(latestAgentPlanItems([{ id: "user-1" }, { id: "plan-run-1", planItems: [] }])).toEqual([]);
expect(agentPlanVisible([])).toBe(false);
});
});
/**
* 回归(2026-09-16):运行中输入框是禁用的,模型在正文里提问用户根本答不了
* (生产实测它连问 4 轮、白烧十几步)。`ask_user` 让本轮收尾并把问题结构化,
* 这个选择器决定「现在该不该把选项面板亮给用户」。
*/
describe("pendingAgentQuestion", () => {
const question = { question: "选哪个模型?", options: [{ label: "H3文生视频" }, { label: "Seedance 2.5" }] };
test("有未作答的提问 → 亮面板", () => {
const messages = [
{ role: "user" },
{ role: "assistant", question },
];
expect(pendingAgentQuestion(messages)?.question).toBe("选哪个模型?");
});
test("提问之后用户已回复 → 收起面板", () => {
const messages = [
{ role: "assistant", question },
{ role: "user" },
];
expect(pendingAgentQuestion(messages)).toBeUndefined();
});
test("多轮提问取最新那道;旧的那道不算数", () => {
const later = { question: "确认开始吗?", options: [{ label: "开始" }, { label: "再改改" }] };
const messages = [
{ role: "assistant", question },
{ role: "user" },
{ role: "assistant", question },
{ role: "assistant", question: later },
];
expect(pendingAgentQuestion(messages)?.question).toBe("确认开始吗?");
});
test("没有提问 → 不亮面板", () => {
expect(pendingAgentQuestion([])).toBeUndefined();
expect(pendingAgentQuestion([{ role: "assistant" }, { role: "user" }])).toBeUndefined();
});
});
+1
View File
@@ -20,6 +20,7 @@ test("welcome contributors parse the README HTML table", () => {
});
expect(people[0]?.signature).toContain("没有任何黑魔法");
expect(people.some((person) => person.name === "爱笑的毛毛虫")).toBe(true);
expect(people.some((person) => person.name === "morrow" && person.email === "3201190041@qq.com" && person.signature === "最难不过坚持")).toBe(true);
expect(people.filter((person) => person.isFounder)).toHaveLength(1);
});