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")}
+5
View File
@@ -1,4 +1,9 @@
export { useLocalSettings, useThreadSettings } from "./hooks";
export {
getKnowledgeRagEnabled,
setKnowledgeRagEnabled,
useKnowledgeRagEnabled,
} from "./knowledge-rag";
export {
getLastAgentId,
isThreadRagModeLocked,
@@ -0,0 +1,48 @@
import { useCallback, useSyncExternalStore } from "react";
/**
* Session-wide switch for knowledge-base RAG injection, toggled from the
* workspace sidebar. Deliberately kept in memory only (NOT localStorage):
* the product decision is "turn it on for this session and every chat sent
* while it is on defaults to enabled" — a page reload resets it to off.
*/
let knowledgeRagEnabled = false;
const listeners = new Set<() => void>();
function emitChange() {
for (const listener of listeners) {
listener();
}
}
export function subscribeKnowledgeRag(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getKnowledgeRagEnabled(): boolean {
return knowledgeRagEnabled;
}
export function setKnowledgeRagEnabled(value: boolean) {
if (knowledgeRagEnabled === value) {
return;
}
knowledgeRagEnabled = value;
emitChange();
}
export function useKnowledgeRagEnabled(): [boolean, (value: boolean) => void] {
const enabled = useSyncExternalStore(
subscribeKnowledgeRag,
getKnowledgeRagEnabled,
() => false,
);
const setEnabled = useCallback((value: boolean) => {
setKnowledgeRagEnabled(value);
}, []);
return [enabled, setEnabled];
}
+11 -4
View File
@@ -71,6 +71,9 @@ export interface LocalSettings {
| "subagent_enabled"
| "model_name"
| "reasoning_effort"
// Session-only sidebar switch (core/settings/knowledge-rag.ts) — must not
// round-trip through localStorage.
| "knowledge_rag_enabled"
> & {
model_name?: string | undefined;
mode: "flash" | "thinking" | "pro" | "ultra" | undefined;
@@ -79,12 +82,16 @@ export interface LocalSettings {
}
function mergeLocalSettings(settings?: Partial<LocalSettings>): LocalSettings {
const context = {
...DEFAULT_LOCAL_SETTINGS.context,
...settings?.context,
};
// Drop the value persisted by the retired per-thread header toggle; the
// knowledge-RAG switch now lives in the sidebar and is session-only.
delete (context as Record<string, unknown>).knowledge_rag_enabled;
return {
...DEFAULT_LOCAL_SETTINGS,
context: {
...DEFAULT_LOCAL_SETTINGS.context,
...settings?.context,
},
context,
notification: {
...DEFAULT_LOCAL_SETTINGS.notification,
...settings?.notification,
+1
View File
@@ -1,2 +1,3 @@
export * from "./api";
export * from "./type";
export * from "./utils";
+22
View File
@@ -0,0 +1,22 @@
import type { Skill } from "./type";
/**
* 智能体技能白名单的候选池过滤。
*
* 编辑智能体时,普通用户只能从「内置技能 + 自己的技能 + 已发布到广场的
* 技能」里挑选,其他用户未发布的自定义技能不可选;管理员仍可使用全部
* 已启用技能。
*/
export function isAgentSkillCandidate(
skill: Skill,
currentUserId: string | null,
isAdmin = false,
): boolean {
if (!skill.enabled) return false;
if (isAdmin) return true;
if ((skill.state ?? "active") !== "active") return false;
const builtin = skill.builtin ?? !skill.owner_user_id;
const ownedByMe =
!!skill.owner_user_id && skill.owner_user_id === currentUserId;
return builtin || ownedByMe || !!skill.published;
}
+10 -2
View File
@@ -16,6 +16,7 @@ import { ExportTrigger } from "@/components/workspace/export-trigger";
import { InputBox } from "@/components/workspace/input-box";
import { MessageList } from "@/components/workspace/messages";
import { ThreadContext } from "@/components/workspace/messages/context";
import { QuestionNavigator } from "@/components/workspace/question-navigator";
import { ThreadTitle } from "@/components/workspace/thread-title";
import { TodoList } from "@/components/workspace/todo-list";
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
@@ -182,8 +183,9 @@ export default function AgentChatPage() {
<div className="flex size-full min-h-0 overflow-hidden">
<div className="min-h-0 min-w-0 flex-1">
<ChatBox threadId={threadId}>
{/* Main conversation column */}
<main className="flex size-full min-h-0 min-w-0 flex-col">
{/* Main conversation column. `relative` hosts the floating
question navigator overlay. */}
<main className="relative flex size-full min-h-0 min-w-0 flex-col">
{/* Header in normal flow, fixed height. */}
<header className="bg-card/90 border-border/70 flex h-12 shrink-0 items-center gap-2 border-b px-4 backdrop-blur-md">
<div className="flex shrink-0 items-center gap-1.5 rounded-md border px-2 py-1">
@@ -271,6 +273,12 @@ export default function AgentChatPage() {
/* Conversation: messages scroll, input
docked at the bottom of the main column only. */
<div className="flex min-h-0 flex-1 flex-col">
{/* Question index pinned to this conversation column; the
bottom inset keeps it clear of the docked input box. */}
<QuestionNavigator
messages={thread.messages}
className="top-14 right-0 bottom-40 left-0"
/>
<MessageList
className="min-h-0 flex-1"
threadId={threadId}
+28 -3
View File
@@ -16,7 +16,6 @@ import {
} from "@/components/workspace/chats";
import { ExportTrigger } from "@/components/workspace/export-trigger";
import { KnowledgeSaveTrigger } from "@/components/workspace/knowledge-save-trigger";
import { KnowledgeRagToggle } from "@/components/workspace/knowledge-rag-toggle";
import { InputBox } from "@/components/workspace/input-box";
import {
MessageList,
@@ -24,6 +23,7 @@ import {
MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM,
} from "@/components/workspace/messages";
import { ThreadContext } from "@/components/workspace/messages/context";
import { QuestionNavigator } from "@/components/workspace/question-navigator";
import { ThreadTitle } from "@/components/workspace/thread-title";
import { TodoList } from "@/components/workspace/todo-list";
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
@@ -35,6 +35,7 @@ import { useNotification } from "@/core/notification/hooks";
import {
getLastAgentId,
saveLastAgentId,
useKnowledgeRagEnabled,
useThreadSettings,
} from "@/core/settings";
import { useThreadStream } from "@/core/threads/hooks";
@@ -90,6 +91,18 @@ export default function ChatPage() {
const { threadId, setThreadId, isNewThread, setIsNewThread, isMock } =
useThreadChat();
const [settings, setSettings] = useThreadSettings(threadId);
// Sidebar session toggle: while on, every message in every chat carries
// knowledge_rag_enabled so the backend injects knowledge-base recall.
// In-memory only — explicitly overrides any value persisted by the old
// per-thread header toggle so stale localStorage can't re-enable it.
const [knowledgeRagEnabled] = useKnowledgeRagEnabled();
const streamContext = useMemo(
() => ({
...settings.context,
knowledge_rag_enabled: knowledgeRagEnabled,
}),
[settings.context, knowledgeRagEnabled],
);
const [mounted, setMounted] = useState(false);
const { tokenUsageEnabled } = useModels();
const { data: promptPrefixSettings } = usePromptPrefixSettings();
@@ -136,7 +149,7 @@ export default function ChatPage() {
const [thread, sendMessage, isUploading] = useThreadStream({
threadId: isNewThread ? undefined : threadId,
context: settings.context,
context: streamContext,
isMock,
onStart: (createdThreadId) => {
setThreadId(createdThreadId);
@@ -410,7 +423,6 @@ export default function ChatPage() {
enabled={tokenUsageEnabled}
messages={thread.messages}
/>
<KnowledgeRagToggle threadId={threadId} />
<ExportTrigger threadId={threadId} />
<KnowledgeSaveTrigger threadId={threadId} />
<ArtifactTrigger />
@@ -521,6 +533,19 @@ export default function ChatPage() {
</div>
</div>
</main>
{/*
ChatGPT-style question index. Anchored to the chat column (this
relative wrapper), not the browser edge; insets keep it below the
overlay header (h-12) and above the docked input box, and it is
pointer-events-none outside its own cards so it never blocks the
header buttons or input.
*/}
{!isLandingState && (
<QuestionNavigator
messages={thread.messages}
className="top-16 right-0 bottom-48 left-0"
/>
)}
</div>
</ChatBox>
</ThreadContext.Provider>
+14 -3
View File
@@ -47,9 +47,10 @@ import {
createAgent,
updateAgent,
} from "@/core/agents/api";
import { getStoredAuth } from "@/core/auth";
import { useI18n } from "@/core/i18n/hooks";
import { useModels } from "@/core/models/hooks";
import type { Skill } from "@/core/skills";
import { isAgentSkillCandidate, type Skill } from "@/core/skills";
import { useSkills } from "@/core/skills/hooks";
import { useThreadStream } from "@/core/threads/hooks";
import { uuid } from "@/core/utils/uuid";
@@ -94,9 +95,19 @@ export default function NewAgentPage() {
const { skills, isLoading: isSkillsLoading } = useSkills();
const { models, isLoading: isModelsLoading } = useModels();
// 可配置的技能限定为「内置 + 自己的 + 已发布到广场的」,
// 其他用户未发布的自定义技能不可选。
const storedAuth = useMemo(() => getStoredAuth(), []);
const enabledSkills = useMemo(
() => skills.filter((skill) => skill.enabled),
[skills],
() =>
skills.filter((skill) =>
isAgentSkillCandidate(
skill,
storedAuth?.user_id ?? null,
storedAuth?.system_role === "admin",
),
),
[skills, storedAuth],
);
const filteredSkills = useMemo(() => {
+1 -1
View File
@@ -281,7 +281,7 @@ Two on-demand/automatic refresh paths layer on top:
**Per-user UI preferences** (`deerflow/persistence/user_preferences/`, wired as `app.state.user_preferences_store`; migration `20260603_03`, also auto-created by `create_all`): one JSON-blob row per user so new toggles need no schema change. Router `/api/user-preferences` (`GET`/`PUT`, account-scoped). Current key: `hide_admin_prompt_prefix` — when true the chat input hides the admin-configured prompt-prefix switch and never applies the prefix (the user uses only their own prompts; enforced in `ChatPage` for both `shouldApplyPrefix` and `promptPrefixProp`). Toggled from the "管理常用提示词" dialog. Tests: `tests/test_user_preferences.py`.
**HTML skills (tools the render step uses).** Two offline skills under `skills/public/` shape the generated HTML and are toggled in the skills settings page (enabled by default): `html-page-builder` (a self-contained inline-CSS design system — colors/cards/tables/KPI/responsive) and `html-charts` (inline-SVG charts that render in the no-`allow-scripts` preview iframe; optional local ECharts documented in its `assets/README.md`). A skill opts into HTML injection via `metadata.kind: html_page` in its SKILL.md frontmatter; `_collect_html_skill_instructions()` reads the bodies of **enabled** such skills and `build_generation_prompt(skill_instructions=…)` injects them, so the (raw-model) render step honors the user's skill selection. The data-gathering step and the render/repair/style passes all use the task's selected `model_name` (no silent fallback to the default model — and there is **no hardcoded GLM-5**; an unset selection falls back to config `models[0]`). To stop auxiliary LLM calls from leaking onto the default model, **`TitleMiddleware` is skipped when `is_scheduled_run` is set** (`_build_middlewares` in `lead_agent/agent.py`) — scheduled/HTML runs use throwaway threads whose titles are never shown, and `config.title.model_name` is usually unset (→ would call `models[0]`, not the chosen model). The completeness gate (`validate_html`) also requires a non-empty `<title>` and forbids external stylesheets, on top of the doctype/html/head/body + non-empty-body + no-script checks.
**HTML skills (tools the render step uses).** Two offline skills under `skills/public/` shape the generated HTML and are toggled in the skills settings page (enabled by default): `html-page-builder` (a self-contained inline-CSS design system — colors/cards/tables/KPI/responsive), `html-charts` (inline-SVG charts that render in the no-`allow-scripts` preview iframe; optional local ECharts documented in its `assets/README.md`), and `html-multipage` (multi-"page" navigation **inside the single generated HTML file**: each page is a `<section class="page" id="page-…">` toggled by anchor links + CSS `:target` — no JS, so it survives `sanitize_html`, and `constrain_same_page_anchor_links` keeps `#page-…` hrefs untouched; the frontend's `html-preview-frame.tsx` renders via a `blob:` URL precisely so in-page anchors work; cross-file `*.html` links remain forbidden/stripped). A skill opts into HTML injection via `metadata.kind: html_page` in its SKILL.md frontmatter; `_collect_html_skill_instructions()` reads the bodies of **enabled** such skills and `build_generation_prompt(skill_instructions=…)` injects them, so the (raw-model) render step honors the user's skill selection. The data-gathering step and the render/repair/style passes all use the task's selected `model_name` (no silent fallback to the default model — and there is **no hardcoded GLM-5**; an unset selection falls back to config `models[0]`). To stop auxiliary LLM calls from leaking onto the default model, **`TitleMiddleware` is skipped when `is_scheduled_run` is set** (`_build_middlewares` in `lead_agent/agent.py`) — scheduled/HTML runs use throwaway threads whose titles are never shown, and `config.title.model_name` is usually unset (→ would call `models[0]`, not the chosen model). The completeness gate (`validate_html`) also requires a non-empty `<title>` and forbids external stylesheets, on top of the doctype/html/head/body + non-empty-body + no-script checks.
### Knowledge Base (`packages/harness/deerflow/knowledge/`)
@@ -8,6 +8,7 @@
"workspace-search": { "enabled": true },
"policy-knowledge": { "enabled": false },
"html-page-builder": { "enabled": true },
"html-charts": { "enabled": true }
"html-charts": { "enabled": true },
"html-multipage": { "enabled": true }
}
}