feat: 提问导航悬浮索引 + 知识库召回会话级开关 + 智能体技能白名单收紧

- 新增 QuestionNavigator:聊天/智能体页右侧悬浮提问索引,点击滚动定位到对应消息(message-list 为 human 消息生成锚点 id)
- 知识库召回开关从单会话头部按钮迁移到侧边栏,改为会话级内存开关(刷新重置,不再写 localStorage),开启时所有对话默认携带 knowledge_rag_enabled
- 智能体可配置技能收紧为「内置 + 自己的 + 已发布到广场的」(新增 core/skills/utils.ts 的 isAgentSkillCandidate,NewAgentPage 与 agent-detail-panel 共用)
- 智能体详情面板在 artifact 预览展开/新文件生成时自动收起让位
- 启用 html-multipage 技能并更新后端 CLAUDE.md 文档

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
吉鑫升andClaude Fable 5 committed 2026-06-12 16:10:00 +08:00
1 parent 81f2a48c6d
commit d9d5780ea7
16 files changed
+598 -49

No files matched your search

@@ -19,7 +19,7 @@ import {
XIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState, type ReactNode } from "react";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
@@ -42,6 +42,7 @@ import {
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor";
import { useArtifactsOptional } from "@/components/workspace/artifacts";
import { EnabledSkillList } from "@/components/workspace/agents/enabled-skill-list";
import { SkillPickerSheet } from "@/components/workspace/agents/skill-picker-sheet";
import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog";
@@ -57,6 +58,7 @@ import {
type UpdateAgentRequest,
} from "@/core/agents";
import { getStoredAuth } from "@/core/auth";
import { isAgentSkillCandidate } from "@/core/skills";
import { useSkills } from "@/core/skills/hooks";
import { usePublishSquares } from "@/core/system-settings/hooks";
import { desensitize } from "@/lib/desensitize";
@@ -176,18 +178,22 @@ export function AgentDetailPanel({
const setFeatured = useSetAgentFeatured();
const { data: publishSquares } = usePublishSquares();
const { skills, isLoading: isSkillsLoading } = useSkills();
// Same pool the edit dialog offers: only globally enabled skills are
// whitelist candidates.
const enabledPool = useMemo(
() => skills.filter((skill) => skill.enabled),
[skills],
);
// Permission model mirrors agent-card: admins manage the full catalog,
// owners manage their own agents, everyone else is read-only.
const storedAuth = useMemo(() => getStoredAuth(), []);
const currentUserId = storedAuth?.user_id ?? null;
const isAdmin = storedAuth?.system_role === "admin";
// 可配置的技能限定为「内置 + 自己的 + 已发布到广场的」,
// 其他用户未发布的自定义技能不可选(管理员例外)。
const enabledPool = useMemo(
() =>
skills.filter((skill) =>
isAgentSkillCandidate(skill, currentUserId, isAdmin),
),
[skills, currentUserId, isAdmin],
);
const isOwned =
!!agent &&
!agent.builtin &&
@@ -199,6 +205,25 @@ export function AgentDetailPanel({
const isSaving = updateAgent.isPending || setFeatured.isPending;
// 对话生成文件(md/txt 等 artifact)并在右侧展开预览时,自动收起智能体
// 信息面板给预览让位;新文件落地时同样收起。编辑中不打断用户,用户随时
// 可手动重新展开。
const artifactsCtx = useArtifactsOptional();
const artifactCount = artifactsCtx?.artifacts.length ?? 0;
const artifactPanelVisible = !!artifactsCtx?.open && artifactCount > 0;
const prevArtifactPanelVisible = useRef(false);
const prevArtifactCount = useRef(0);
useEffect(() => {
const opened = artifactPanelVisible && !prevArtifactPanelVisible.current;
const grew =
artifactPanelVisible && artifactCount > prevArtifactCount.current;
prevArtifactPanelVisible.current = artifactPanelVisible;
prevArtifactCount.current = artifactCount;
if ((opened || grew) && !editing) {
setCollapsed(true);
}
}, [artifactPanelVisible, artifactCount, editing]);
const displayName = desensitize(agent?.name ?? agentName);
const questions = useMemo(
() => normalizeAgentQuestions(agent?.common_questions),
@@ -2,43 +2,52 @@
import { Database } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useThreadSettings } from "@/core/settings";
import {
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { useKnowledgeRagEnabled } from "@/core/settings";
import { cn } from "@/lib/utils";
import { Tooltip } from "./tooltip";
/**
* Per-conversation toggle for knowledge-base RAG injection (phase 2).
* Sidebar toggle for knowledge-base RAG injection (phase 2).
*
* Writes ``context.knowledge_rag_enabled`` into the thread settings, which the
* run forwards as ``runtime.context`` so ``KnowledgeRagMiddleware`` injects
* recalled knowledge before each model call for this conversation only.
* Session-wide and in-memory only: while enabled, every conversation sends
* ``context.knowledge_rag_enabled`` as ``runtime.context`` so
* ``KnowledgeRagMiddleware`` injects recalled knowledge before each model
* call. A page reload resets the switch to off.
*/
export function KnowledgeRagToggle({ threadId }: { threadId: string }) {
const [settings, setSettings] = useThreadSettings(threadId);
const enabled = settings.context.knowledge_rag_enabled === true;
const toggle = () => {
setSettings("context", {
...settings.context,
knowledge_rag_enabled: !enabled,
});
};
export function KnowledgeRagToggle({ className }: { className?: string }) {
const [enabled, setEnabled] = useKnowledgeRagEnabled();
return (
<Tooltip content={enabled ? "知识库召回:已开启" : "知识库召回:已关闭"}>
<Button
variant="ghost"
onClick={toggle}
className={cn(
"text-muted-foreground hover:text-foreground",
enabled && "text-primary hover:text-primary",
)}
<SidebarMenuItem>
<Tooltip
content={
enabled
? "知识库召回:已开启(本次会话内所有对话默认开启)"
: "知识库召回:已关闭"
}
>
<Database />
知识库
</Button>
</Tooltip>
<SidebarMenuButton
isActive={enabled}
onClick={() => setEnabled(!enabled)}
className={className}
>
<Database />
<span>知识库召回</span>
<span
className={cn(
"ml-auto text-xs",
enabled ? "text-primary" : "text-muted-foreground/70",
)}
>
{enabled ? "已开启" : "已关闭"}
</span>
</SidebarMenuButton>
</Tooltip>
</SidebarMenuItem>
);
}
@@ -129,6 +129,7 @@ function useArtifactResolver(threadId: string): (path: string) => string {
export function MessageListItem({
className,
fitRowToContent = false,
anchorId,
message,
isLoading,
threadId,
@@ -140,6 +141,11 @@ export function MessageListItem({
}: {
className?: string;
fitRowToContent?: boolean;
/**
* Stable DOM id so the question navigator can scrollIntoView to this
* message. `scroll-mt` keeps the target clear of the overlay header.
*/
anchorId?: string;
message: Message;
isLoading?: boolean;
threadId: string;
@@ -156,10 +162,12 @@ export function MessageListItem({
'';
return (
<AIElementMessage
id={anchorId}
className={cn(
'group/conversation-message relative',
fitRowToContent ? 'max-w-full w-fit' : 'w-full',
isHuman && fitRowToContent && 'ml-auto',
anchorId && 'scroll-mt-20',
className,
)}
from={isHuman ? 'user' : 'assistant'}
@@ -35,6 +35,7 @@ import { cn } from "@/lib/utils";
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
import { ArtifactFileList } from "../artifacts/artifact-file-list";
import { getQuestionAnchorId } from "../question-navigator";
import { StreamingIndicator } from "../streaming-indicator";
import { ReferenceBatchesContext, ThreadContext } from "./context";
@@ -297,6 +298,11 @@ export function MessageList({
<MessageListItem
key={`${group.id}/${msg.id}`}
fitRowToContent={fitMessageRowsToContent}
anchorId={
msg.type === "human"
? getQuestionAnchorId(msg, messages.indexOf(msg))
: undefined
}
message={msg}
isLoading={thread.isLoading}
threadId={threadId}
@@ -0,0 +1,371 @@
"use client";
import type { Message } from "@langchain/langgraph-sdk";
import { ChevronsRightIcon, ListIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import {
extractContentFromMessage,
stripArtifactTag,
stripUploadedFilesTag,
} from "@/core/messages/utils";
import { cn } from "@/lib/utils";
import { Tooltip } from "./tooltip";
/** Width of the expanded floating panel, in px. */
const PANEL_WIDTH = 300;
/** Minimum side gutter (beyond the panel itself) required to float the panel. */
const PANEL_GUTTER_MARGIN = 24;
/** Max characters kept in a question summary card. */
const SUMMARY_MAX_LENGTH = 80;
/** Questions needed before the navigator shows up at all. */
const MIN_QUESTIONS = 2;
const COLLAPSE_STORAGE_KEY = "deerflow.question-navigator.collapsed";
/**
* Stable DOM anchor id for a message. Prefers the server-side message id and
* falls back to the render index so messages without ids still get a target
* (requirement: `message-${index}` style fallback).
*/
export function getQuestionAnchorId(
message: Pick<Message, "id">,
index: number,
): string {
return `message-${message.id ?? index}`;
}
/**
* Turn the raw markdown of a user question into a short plain-text summary:
* strips upload/artifact/page-context envelopes and common Markdown syntax,
* collapses whitespace, and truncates with an ellipsis.
*/
function summarizeQuestion(raw: string): string {
let text = stripArtifactTag(stripUploadedFilesTag(raw));
text = text
.replace(/<page_context>[\s\S]*?<\/page_context>/gi, " ")
.replace(/```[\s\S]*?(```|$)/g, " ")
.replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/`([^`]*)`/g, "$1")
.replace(/^#{1,6}\s+/gm, "")
.replace(/^\s*>\s?/gm, "")
.replace(/^\s*[-*+]\s+/gm, "")
.replace(/^\s*\d+\.\s+/gm, "")
.replace(/(\*\*|__|~~)/g, "")
.replace(/\s+/g, " ")
.trim();
if (text.length > SUMMARY_MAX_LENGTH) {
return `${text.slice(0, SUMMARY_MAX_LENGTH)}…`;
}
return text;
}
type QuestionItem = {
anchorId: string;
summary: string;
};
/** Walk up from a message anchor to the element that actually scrolls. */
function findScrollParent(el: HTMLElement | null): HTMLElement | null {
let node = el?.parentElement ?? null;
while (node) {
const overflowY = window.getComputedStyle(node).overflowY;
if (
(overflowY === "auto" || overflowY === "scroll") &&
node.scrollHeight > node.clientHeight
) {
return node;
}
node = node.parentElement;
}
return null;
}
function readCollapsedPreference(): boolean {
if (typeof window === "undefined") return false;
try {
return window.localStorage.getItem(COLLAPSE_STORAGE_KEY) === "1";
} catch {
return false;
}
}
/**
* ChatGPT-style question index floating at the right edge of the conversation
* column. Reads questions straight from the live `messages` array (no global
* state copy), so it stays in sync with streaming, history switches and new
* turns for free.
*
* Layout contract: render inside a `relative` ancestor that spans the chat
* content area, and pass the inset via `className` (e.g. `top-16 bottom-48
* left-0 right-0`). The component measures its own width: when the side gutter
* next to the centered message column is wide enough it floats an expandable
* panel there; on narrower viewports it degrades to a small pill button that
* opens a right-side drawer, so it never covers the chat body or input box.
*/
export function QuestionNavigator({
messages,
className,
contentMaxWidth = 1024,
}: {
messages: Message[];
className?: string;
/** Max width (px) of the centered message column, used to size the gutter. */
contentMaxWidth?: number;
}) {
const rootRef = useRef<HTMLDivElement | null>(null);
const [panelFits, setPanelFits] = useState(false);
const [collapsed, setCollapsed] = useState(readCollapsedPreference);
const [sheetOpen, setSheetOpen] = useState(false);
const [activeId, setActiveId] = useState<string | null>(null);
const questions = useMemo(() => {
const items: QuestionItem[] = [];
messages.forEach((message, index) => {
if (message.type !== "human") return;
const summary = summarizeQuestion(extractContentFromMessage(message));
if (!summary) return;
items.push({ anchorId: getQuestionAnchorId(message, index), summary });
});
return items;
}, [messages]);
const visible = questions.length >= MIN_QUESTIONS;
// Decide between floating panel and drawer mode from the actual gutter width
// next to the centered message column — not from the browser viewport — so
// opening the artifact preview or the sidebar reflows the mode correctly.
useEffect(() => {
if (!visible) return;
const root = rootRef.current;
if (!root) return;
const update = () => {
const gutter = (root.clientWidth - contentMaxWidth) / 2;
setPanelFits(gutter >= PANEL_WIDTH + PANEL_GUTTER_MARGIN);
};
update();
const observer = new ResizeObserver(update);
observer.observe(root);
return () => observer.disconnect();
}, [visible, contentMaxWidth]);
// Highlight the question nearest the top of the chat viewport. A plain
// rAF-throttled scroll listener over a handful of anchors is cheaper and
// more predictable here than juggling IntersectionObserver thresholds.
useEffect(() => {
if (!visible) {
setActiveId(null);
return;
}
const firstAnchor = document.getElementById(questions[0]!.anchorId);
const scroller = findScrollParent(firstAnchor);
if (!scroller) return;
let raf = 0;
const update = () => {
raf = 0;
const viewportTop = scroller.getBoundingClientRect().top;
let current = questions[0]!.anchorId;
for (const question of questions) {
const el = document.getElementById(question.anchorId);
if (!el) continue;
if (el.getBoundingClientRect().top - viewportTop <= 140) {
current = question.anchorId;
} else {
break;
}
}
setActiveId(current);
};
const onScroll = () => {
if (!raf) raf = requestAnimationFrame(update);
};
update();
scroller.addEventListener("scroll", onScroll, { passive: true });
return () => {
scroller.removeEventListener("scroll", onScroll);
if (raf) cancelAnimationFrame(raf);
};
}, [visible, questions]);
const scrollToQuestion = useCallback((anchorId: string) => {
document
.getElementById(anchorId)
?.scrollIntoView({ behavior: "smooth", block: "start" });
setActiveId(anchorId);
}, []);
const toggleCollapsed = useCallback(() => {
setCollapsed((prev) => {
const next = !prev;
try {
window.localStorage.setItem(COLLAPSE_STORAGE_KEY, next ? "1" : "0");
} catch {
// localStorage unavailable (private mode) — keep in-memory state only.
}
return next;
});
}, []);
if (!visible) return null;
const pillButton = (label: string, onClick: () => void) => (
<Tooltip content={label}>
<Button
type="button"
variant="outline"
size="sm"
className="bg-background/80 pointer-events-auto h-8 gap-1.5 rounded-full px-3 shadow-md backdrop-blur-md"
onClick={onClick}
>
<ListIcon className="size-3.5" />
<span className="text-xs">问题列表</span>
<span className="text-muted-foreground text-xs tabular-nums">
{questions.length}
</span>
</Button>
</Tooltip>
);
return (
<div
ref={rootRef}
className={cn("pointer-events-none absolute z-20", className)}
>
<div className="absolute inset-y-0 right-3 flex items-start justify-end">
{panelFits ? (
collapsed ? (
pillButton("展开问题导航", toggleCollapsed)
) : (
<div
className="border-border/60 bg-background/85 pointer-events-auto flex max-h-full flex-col overflow-hidden rounded-xl border shadow-lg backdrop-blur-md"
style={{ width: PANEL_WIDTH }}
>
<div className="border-border/50 flex shrink-0 items-center gap-2 border-b px-3 py-2">
<Tooltip content="收起问题导航">
<Button
type="button"
size="icon-sm"
variant="ghost"
className="size-6"
onClick={toggleCollapsed}
>
<ChevronsRightIcon className="size-3.5" />
</Button>
</Tooltip>
<span className="text-xs font-medium">本轮问题</span>
<span className="text-muted-foreground ml-auto text-xs tabular-nums">
{questions.length}
</span>
</div>
<QuestionCardList
questions={questions}
activeId={activeId}
onSelect={scrollToQuestion}
className="min-h-0 flex-1"
/>
</div>
)
) : (
<>
{pillButton("打开问题导航", () => setSheetOpen(true))}
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
<SheetContent
side="right"
className="flex w-[320px] flex-col gap-0 p-0 sm:max-w-[320px]"
>
<SheetHeader className="border-border/50 border-b px-4 py-3">
<SheetTitle className="text-sm">
本轮问题({questions.length})
</SheetTitle>
</SheetHeader>
<QuestionCardList
questions={questions}
activeId={activeId}
onSelect={(anchorId) => {
setSheetOpen(false);
scrollToQuestion(anchorId);
}}
className="min-h-0 flex-1"
/>
</SheetContent>
</Sheet>
</>
)}
</div>
</div>
);
}
function QuestionCardList({
questions,
activeId,
onSelect,
className,
}: {
questions: QuestionItem[];
activeId: string | null;
onSelect: (anchorId: string) => void;
className?: string;
}) {
const itemRefs = useRef(new Map<string, HTMLButtonElement>());
// Keep the active card visible as the chat scrolls. `block: "nearest"` only
// nudges this inner list — the card is already inside the on-screen panel,
// so no outer container moves.
useEffect(() => {
if (!activeId) return;
itemRefs.current.get(activeId)?.scrollIntoView({ block: "nearest" });
}, [activeId]);
return (
<nav
aria-label="问题导航"
className={cn("flex flex-col gap-2 overflow-y-auto p-2", className)}
>
{questions.map((question, index) => {
const isActive = question.anchorId === activeId;
return (
<button
key={question.anchorId}
ref={(el) => {
if (el) itemRefs.current.set(question.anchorId, el);
else itemRefs.current.delete(question.anchorId);
}}
type="button"
title={question.summary}
onClick={() => onSelect(question.anchorId)}
className={cn(
"w-full cursor-pointer rounded-lg border px-3 py-2 text-left text-[13px] leading-5 shadow-xs transition-colors",
isActive
? "border-primary/40 border-l-primary bg-primary/10 text-foreground border-l-2 font-medium"
: "border-border/50 bg-background/60 text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
>
<span className="flex items-start gap-1.5">
<span
className={cn(
"shrink-0 text-[11px] leading-5 tabular-nums",
isActive ? "text-primary" : "text-muted-foreground/60",
)}
>
{index + 1}.
</span>
<span className="line-clamp-2 break-words">
{question.summary}
</span>
</span>
</button>
);
})}
</nav>
);
}
@@ -16,6 +16,7 @@ import { useI18n } from "@/core/i18n/hooks";
// import { BotIcon, BrainIcon, ListChecks, MessageSquarePlus, MessagesSquare, SparklesIcon, UsersIcon } from "lucide-react";
import { BookOpen, BotIcon, BrainIcon, ListChecks, MessageSquarePlus, MessagesSquare, PenLine, SparklesIcon, Users } from "lucide-react";
import { KnowledgeRagToggle } from "./knowledge-rag-toggle";
import { SidebarCollapseButton } from "./workspace-header";
import { WorkspaceNavStudio } from "./workspace-nav-studio";
import { cn } from "@/lib/utils";
@@ -161,6 +162,7 @@ export function WorkspaceNavChatList({
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<KnowledgeRagToggle className={NAV_ITEM_CLASS} />
<SidebarMenuItem>
<SidebarMenuButton
isActive={pathname.startsWith("/page/workspace/knowledge")}