This commit is contained in:
fengxiangdebaozi committed 2026-06-12 18:34:14 +08:00
commit c6b17d5946
90 files changed
+3612 -1452

No files matched your search

@@ -26,13 +26,24 @@ import {
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { getStoredAuth } from "@/core/auth";
import { queryClient } from "@/components/query-client-provider";
import Empty from "./empty";
import { NetworkActor } from "./network-actor";
// ── 适配层 ─────────────────────────────────────────────────
function authenticatedFetch(url: string, init?: RequestInit) {
const token = getStoredAuth()?.access_token;
// 本组件只对接「我的笔记/空间」后端,用不到本系统(DeerFlow)token。
// notebook token 由 fetchStudioToken(getTokenByEmail) 获取,缓存在 react-query
// 的 ["studio","token",email] 下(见 core/studio/hooks)。
function getNotebookToken(): string | undefined {
const email = getStoredAuth()?.email ?? "";
return queryClient.getQueryData<string>(["studio", "token", email]);
}
// 上传到笔记后端时传 useNotebookToken=true 注入我的笔记 token;
// 其余请求不注入本系统 token,调用方自行在 init.headers 里带 Authorization。
export function authenticatedFetch(url: string, init?: RequestInit, useNotebookToken = false): Promise<Response> {
const token = useNotebookToken ? getNotebookToken() : undefined;
return fetch(url, {
...init,
headers: {
@@ -334,7 +345,7 @@ const DocumentUploadPopupContent: FC<{
if (!files.length) return;
setUploading(true);
try {
const token = getStoredAuth()?.access_token ?? "";
const token = getNotebookToken() ?? "";
const formData = new FormData();
formData.append("search_space_id", searchSpaceId);
for (const file of files) {
@@ -389,7 +400,7 @@ const DocumentUploadPopupContent: FC<{
search_space_id: Number(searchSpaceId),
source_list: dataList,
}),
});
}, true);
if (response.ok) {
const data = await response.json() as { imported_count?: number };
toast.success(`成功导入 ${data.imported_count || dataList.length} 个来源`);
@@ -10,17 +10,8 @@ import { Loader2, Plus, Search, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { getStoredAuth } from "@/core/auth";
import { authenticatedFetch } from "@/components/assistant-ui/document-upload-popup";
function authenticatedFetch(url: string, init?: RequestInit) {
const token = getStoredAuth()?.access_token;
return fetch(url, {
...init,
headers: {
...(init?.headers ?? {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
}
interface NetworkActorProps {
inputValue: string;
@@ -195,7 +186,7 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
const [actorCount, setActorCount] = useState<number>(0);
const [directionType, setDirectionType] = useState<string>('TW');
const directionValue = useRef<string>('TW');
const consumerUrl = 'http://ch1.b.uat.4.cn/consumer';
const consumerUrl = import.meta.env.VITE_AIPI_CONSUMER_URL || 'https://ch1.b.uat.4.cn/consumer';
const backendUrl = typeof window !== 'undefined'
? (import.meta.env.VITE_BACKEND_BASE_URL || 'http://localhost:8001')
: 'http://localhost:8001';
@@ -395,7 +386,7 @@ export function NetworkActor({ inputValue, searchSpaceId, onSuccess }: NetworkAc
search_space_id: Number(searchSpaceId),
source_list: dataList,
}),
});
}, true);
if (response.ok) {
const data = await response.json();
toast.success(`成功导入 ${data.imported_count || dataList.length} 个来源`);
@@ -5,7 +5,7 @@ import {
QueryClientProvider as TanStackQueryClientProvider,
} from "@tanstack/react-query";
const queryClient = new QueryClient();
export const queryClient = new QueryClient();
export function QueryClientProvider({
children,
@@ -0,0 +1,186 @@
import {
ChevronLeft,
ChevronRight,
FileText,
Hash,
Loader2,
Search,
Sparkles,
} from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useKnowledgeNotes } from "@/core/knowledge/hooks";
import type { KnowledgeNote } from "@/core/knowledge/types";
import { SOURCE_TYPE_LABELS, formatDateTime } from "./wikiUtils";
/** What was clicked: a tag (exact filter) or an entity (relation-graph match). */
export type RelatedNotesFilter =
| { kind: "tag"; value: string }
| { kind: "entity"; value: string };
const PAGE_SIZE = 20;
function useDebounced<T>(value: T, delay = 300): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = window.setTimeout(() => setDebounced(value), delay);
return () => window.clearTimeout(id);
}, [value, delay]);
return debounced;
}
/**
* Click a tag / entity chip → list every other note that shares it.
* Server-side keyword search + pagination so huge graphs stay usable:
* tags use the backend's exact `tag` filter, entities the exact `entity`
* filter (note→entity relations), both combinable with `keyword`.
*/
export function RelatedNotesDialog({
filter,
currentNoteId,
onOpenChange,
onSelect,
}: {
filter: RelatedNotesFilter | null;
currentNoteId?: string;
onOpenChange: (open: boolean) => void;
onSelect: (noteId: string) => void;
}) {
const [search, setSearch] = useState("");
const debouncedSearch = useDebounced(search.trim());
const [page, setPage] = useState(0);
// New chip or new search term → back to the first page.
useEffect(() => {
setPage(0);
}, [filter?.kind, filter?.value, debouncedSearch]);
// Reset the search box whenever a different chip is opened.
useEffect(() => {
setSearch("");
}, [filter?.kind, filter?.value]);
const params = {
...(filter?.kind === "tag" ? { tag: filter.value } : {}),
...(filter?.kind === "entity" ? { entity: filter.value } : {}),
keyword: debouncedSearch || undefined,
limit: filter ? PAGE_SIZE : 0,
offset: page * PAGE_SIZE,
};
const { data, isLoading, isFetching } = useKnowledgeNotes(params);
const items = (data?.items ?? []).filter(
(n: KnowledgeNote) => n.id !== currentNoteId,
);
const total = data?.total ?? 0;
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE));
return (
<Dialog open={!!filter} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{filter?.kind === "entity" ? (
<Sparkles className="size-4 text-violet-500" />
) : (
<Hash className="size-4 text-rose-500" />
)}
<span className="truncate">{filter?.value}</span>
</DialogTitle>
<DialogDescription>
{filter?.kind === "entity"
? "提到该实体的关联知识"
: "使用该标签的关联知识"}
{total > 0 ? ` · 共 ${total} 条` : ""}
</DialogDescription>
</DialogHeader>
<div className="relative">
<Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="在关联知识中搜索标题/内容..."
className="h-9 pl-8"
/>
</div>
<ScrollArea className="max-h-[50vh]">
{isLoading || (isFetching && items.length === 0) ? (
<div className="text-muted-foreground flex items-center gap-2 p-4 text-sm">
<Loader2 className="size-4 animate-spin" /> 加载中...
</div>
) : items.length === 0 ? (
<div className="text-muted-foreground rounded-md border border-dashed p-6 text-center text-sm">
{debouncedSearch ? "没有匹配的关联知识。" : "暂无其他关联知识。"}
</div>
) : (
<ul className="flex flex-col gap-1 pr-2">
{items.map((note) => (
<li key={note.id}>
<button
type="button"
onClick={() => onSelect(note.id)}
className="flex w-full flex-col gap-0.5 rounded-md border border-transparent px-3 py-2 text-left transition-colors hover:border-slate-200 hover:bg-slate-50 dark:hover:border-slate-700 dark:hover:bg-slate-800/60"
>
<span className="flex items-center gap-2 text-sm font-medium text-slate-800 dark:text-slate-100">
<FileText className="size-3.5 shrink-0 text-slate-400" />
<span className="truncate">{note.title}</span>
</span>
{note.summary ? (
<span className="line-clamp-2 pl-[1.375rem] text-xs text-slate-500 dark:text-slate-400">
{note.summary}
</span>
) : null}
<span className="text-muted-foreground pl-[1.375rem] text-[11px]">
{SOURCE_TYPE_LABELS[note.source_type] ?? note.source_type}
{note.updated_at
? ` · ${formatDateTime(note.updated_at).slice(0, 10)}`
: ""}
</span>
</button>
</li>
))}
</ul>
)}
</ScrollArea>
{pageCount > 1 ? (
<div className="flex items-center justify-between border-t pt-3">
<span className="text-muted-foreground text-xs">
第 {page + 1} / {pageCount} 页
</span>
<div className="flex items-center gap-2">
<Button
size="sm"
variant="outline"
disabled={page === 0 || isFetching}
onClick={() => setPage((p) => Math.max(0, p - 1))}
>
<ChevronLeft className="size-4" /> 上一页
</Button>
<Button
size="sm"
variant="outline"
disabled={page >= pageCount - 1 || isFetching}
onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
>
下一页 <ChevronRight className="size-4" />
</Button>
</div>
</div>
) : null}
</DialogContent>
</Dialog>
);
}
@@ -25,6 +25,10 @@ import { DocumentToolbar } from "./DocumentToolbar";
import { FloatingToc } from "./FloatingToc";
import { MarkdownViewer } from "./MarkdownViewer";
import { RelatedDocs } from "./RelatedDocs";
import {
RelatedNotesDialog,
type RelatedNotesFilter,
} from "./RelatedNotesDialog";
import {
SOURCE_TYPE_LABELS,
STATUS_LABELS,
@@ -91,6 +95,10 @@ export function WikiContent({
const [draftContent, setDraftContent] = useState(note.content_md);
const [draftStatus, setDraftStatus] = useState<string>(note.status);
const [activeHeadingId, setActiveHeadingId] = useState<string | null>(null);
// Tag / entity chip clicked → show notes that share it.
const [relatedFilter, setRelatedFilter] = useState<RelatedNotesFilter | null>(
null,
);
// Pull the backend-injected `## Related` wikilinks out of the body so they
// render as a structured module; editing still works on the full source.
@@ -270,12 +278,15 @@ export function WikiContent({
<MetaTag>创建:{formatDateTime(note.created_at).slice(0, 10)}</MetaTag>
) : null}
{note.tags.map((tag) => (
<span
<button
key={tag}
className="inline-flex h-6 items-center rounded-md bg-rose-50 px-2 text-xs font-medium text-rose-500 dark:bg-rose-500/10 dark:text-rose-300"
type="button"
title={`查看「${tag}」的关联知识`}
onClick={() => setRelatedFilter({ kind: "tag", value: tag })}
className="inline-flex h-6 cursor-pointer items-center rounded-md bg-rose-50 px-2 text-xs font-medium text-rose-500 transition-colors hover:bg-rose-100 hover:text-rose-600 dark:bg-rose-500/10 dark:text-rose-300 dark:hover:bg-rose-500/20"
>
#{tag}
</span>
</button>
))}
</div>
@@ -287,11 +298,15 @@ export function WikiContent({
{note.entities.map((ent) => {
const meta = entityMeta(ent.entity_type);
return (
<span
<button
key={`${ent.name}-${ent.entity_type ?? ""}`}
title={meta.label}
type="button"
title={`查看与「${ent.name}」(${meta.label})相关的知识`}
onClick={() =>
setRelatedFilter({ kind: "entity", value: ent.name })
}
className={cn(
"inline-flex items-center gap-1.5 rounded-full border py-1 pl-2 pr-1 text-xs font-medium",
"inline-flex cursor-pointer items-center gap-1.5 rounded-full border py-1 pl-2 pr-1 text-xs font-medium transition-opacity hover:opacity-80",
meta.className,
)}
>
@@ -300,7 +315,7 @@ export function WikiContent({
<span className="rounded-full bg-current/15 px-1.5 py-0.5 text-[10px] leading-none opacity-90">
{meta.label}
</span>
</span>
</button>
);
})}
</div>
@@ -373,6 +388,18 @@ export function WikiContent({
</div>
</div>
</div>
<RelatedNotesDialog
filter={relatedFilter}
currentNoteId={note.id}
onOpenChange={(open) => {
if (!open) setRelatedFilter(null);
}}
onSelect={(id) => {
setRelatedFilter(null);
navigate(`/page/workspace/knowledge/${id}`);
}}
/>
</div>
);
}
@@ -1,5 +1,4 @@
import {
BookOpen,
Copy,
Menu,
Network,
@@ -41,7 +40,7 @@ function HeaderButton({
);
}
/** Light 56px wiki header: logo + product name on the left, action entries on the right. */
/** Light 56px wiki header: plain page title on the left, action entries on the right. */
export function WikiHeader({
onToggleSidebar,
onImportFile,
@@ -68,14 +67,8 @@ export function WikiHeader({
>
<Menu className="size-5" />
</button>
<div className="flex size-9 items-center justify-center rounded-[9px] bg-red-600 text-white">
<BookOpen className="size-5" />
</div>
<div className="leading-none">
<div className="text-base font-extrabold tracking-tight text-slate-900 dark:text-slate-100">
问答梳理
</div>
<div className="mt-1 text-xs text-emerald-500">LLM Wiki · 问答梳理中心</div>
<div className="text-base font-semibold tracking-tight text-slate-900 dark:text-slate-100">
问答梳理
</div>
</div>
@@ -3,6 +3,7 @@
import {
BotIcon,
CopyIcon,
EyeOffIcon,
GlobeIcon,
LockIcon,
MessageSquareIcon,
@@ -529,7 +530,7 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
来自他人
</Badge>
)}
{isOwned && agent.published && !agent.is_private && (
{(isOwned || isAdmin) && !isBuiltin && agent.published && !agent.is_private && (
<Badge
variant="outline"
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
@@ -539,6 +540,16 @@ export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCar
已发布
</Badge>
)}
{(isOwned || isAdmin) && !isBuiltin && !agent.published && !agent.is_private && (
<Badge
variant="outline"
className="border-zinc-400/40 text-zinc-500 dark:text-zinc-400 text-xs"
title="该智能体尚未发布,仅所有者可见"
>
<EyeOffIcon className="size-3" />
未发布
</Badge>
)}
{agent.is_private && (
<Badge
variant="outline"
@@ -15,11 +15,12 @@ import {
SparklesIcon,
SquarePenIcon,
Trash2Icon,
UploadCloudIcon,
UserRoundIcon,
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 +43,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,33 +59,12 @@ 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";
import { cn } from "@/lib/utils";
/**
* Turn the admin-authored SOUL.md markdown into a clean, readable profile blurb
* for the narrow panel. The view mode is a profile card, not a document view —
* so we strip markdown syntax (headings, emphasis, inline code, list bullets,
* blockquotes) rather than rendering it, keeping the line structure intact.
*/
function cleanProfileText(raw: string): string {
return raw
.split("\n")
.map((line) =>
line
.replace(/^\s{0,3}#{1,6}\s*/, "")
.replace(/^\s{0,3}>\s?/, "")
.replace(/^(\s*)[-*+]\s+/, "$1• ")
.replace(/(\*\*|__)(.*?)\1/g, "$2")
.replace(/(\*|_)(.*?)\1/g, "$2")
.replace(/`([^`]+)`/g, "$1"),
)
.join("\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
/** Local edit-mode draft — committed in one `updateAgent` call on 保存. */
interface AgentDraft {
@@ -94,6 +75,7 @@ interface AgentDraft {
skills: string[];
published: boolean;
featured: boolean;
templateName: string;
}
function draftFromAgent(agent: Agent): AgentDraft {
@@ -105,6 +87,7 @@ function draftFromAgent(agent: Agent): AgentDraft {
skills: agent.skills ?? [],
published: agent.published,
featured: agent.featured_order != null,
templateName: agent.template_name ?? "",
};
}
@@ -176,18 +159,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,14 +186,30 @@ 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),
[agent?.common_questions],
);
const soulPreview = agent?.soul?.trim()
? cleanProfileText(desensitize(agent.soul))
: undefined;
function beginEdit() {
if (!agent || !canEdit) return;
@@ -280,6 +283,8 @@ export function AgentDetailPanel({
if (draft.description !== (agent.description ?? ""))
request.description = draft.description;
if (draft.soul !== (agent.soul ?? "")) request.soul = draft.soul;
if (draft.templateName.trim() !== (agent.template_name ?? ""))
request.template_name = draft.templateName.trim();
if (nextPublished !== agent.published) request.published = nextPublished;
if (JSON.stringify(draft.skills) !== JSON.stringify(agent.skills ?? []))
request.skills = draft.skills;
@@ -422,14 +427,7 @@ export function AgentDetailPanel({
</div>
) : (
<div className="flex items-center gap-1">
<Button
size="sm"
variant="outline"
className="hidden"
onClick={beginEdit}
aria-hidden="true"
tabIndex={-1}
>
<Button size="sm" variant="outline" onClick={beginEdit}>
<SquarePenIcon className="size-3.5" />
编辑
</Button>
@@ -528,9 +526,31 @@ export function AgentDetailPanel({
)}
</div>
{/* 入库模板名 — view mode shows a hint row when configured. */}
{!editing && agent.template_name?.trim() && (
<div className="text-muted-foreground mt-2 flex items-center gap-1 text-xs">
<UploadCloudIcon className="size-3 shrink-0" />
入库模板:{desensitize(agent.template_name)}
</div>
)}
{/* Publish / featured toggles — only meaningful in edit mode. */}
{editing && draft && (
<div className="mt-3 space-y-2">
<div className="bg-background/60 space-y-1 rounded-lg border px-3 py-2">
<p className="text-sm font-medium">入库模板名</p>
<Input
value={draft.templateName}
onChange={(e) =>
setDraft({ ...draft, templateName: e.currentTarget.value })
}
placeholder="例如:临时策略库(留空表示不支持入库)"
className="h-8 text-sm"
/>
<p className="text-muted-foreground text-xs">
配置后,对话生成的 Markdown 文件可一键发布到知识入库接口。
</p>
</div>
<div className="bg-background/60 flex items-center justify-between rounded-lg border px-3 py-2">
<div>
<p className="text-sm font-medium">公开发布</p>
@@ -564,41 +584,31 @@ export function AgentDetailPanel({
)}
</section>
{/* ── SOUL / 人设 ────────────────────────────────────────────────── */}
{(editing || soulPreview) && (
<Section
icon={<SparklesIcon className="size-3.5" />}
title="人设(SOUL)"
>
{editing && draft ? (
<Textarea
value={draft.soul}
onChange={(e) =>
setDraft({ ...draft, soul: e.currentTarget.value })
}
placeholder="输入 SOUL.md 内容"
className="max-h-[45vh] min-h-48 resize-y font-mono text-xs"
/>
) : (
// Viewport-relative cap: the SOUL preview expands with the screen
// (taller than the old fixed 240px box) but never swallows the
// whole panel — long content still scrolls inside.
<p className="text-muted-foreground max-h-[40vh] overflow-y-auto whitespace-pre-wrap text-sm leading-relaxed">
{soulPreview}
</p>
)}
</Section>
)}
{/* ── 常用问题 ───────────────────────────────────────────────────── */}
{(editing || questions.length > 0) && (
{(editing || questions.length > 0 || canEdit) && (
<Section
icon={<MessageCircleQuestionIcon className="size-3.5" />}
title="常用问题"
extra={
<span className="text-muted-foreground text-xs tabular-nums">
{(editing && draft ? draft.questions : questions).length} 个
</span>
<div className="flex items-center gap-1">
<span className="text-muted-foreground text-xs tabular-nums">
{(editing && draft ? draft.questions : questions).length} 个
</span>
{!editing && canEdit && (
<Tooltip content="管理常用问题(新增 / 删除 / 排序)">
<Button
type="button"
size="icon-sm"
variant="ghost"
onClick={beginEdit}
aria-label="管理常用问题"
>
<SquarePenIcon className="size-3.5" />
</Button>
</Tooltip>
)}
</div>
}
>
{editing && draft ? (
@@ -607,6 +617,15 @@ export function AgentDetailPanel({
onChange={(next) => setDraft({ ...draft, questions: next })}
disabled={isSaving}
/>
) : questions.length === 0 ? (
<button
type="button"
onClick={beginEdit}
className="text-muted-foreground hover:text-foreground hover:border-border w-full rounded-lg border border-dashed px-3 py-4 text-center text-xs transition-colors"
>
<PlusIcon className="mr-1 inline size-3.5 align-[-2px]" />
添加常用问题
</button>
) : (
<div className="flex flex-col gap-2">
{questions.map((question, index) => {
@@ -1,6 +1,6 @@
"use client";
import { ArrowDownUpIcon, BotIcon, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
import { ArrowDownUpIcon, BotIcon, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
@@ -190,16 +190,21 @@ export function AgentGallery() {
list: Agent[];
total: number;
isLoading: boolean;
isFetching: boolean;
tab: string;
emptyDescription: string;
showNewButton?: boolean;
}) => {
const { list, total, isLoading, tab, emptyDescription, showNewButton } = opts;
const { list, total, isLoading, isFetching, tab, emptyDescription, showNewButton } =
opts;
// keepPreviousData keeps the old page visible while a new page loads, so
// only show the spinner on the very first load (no rows yet).
if (isLoading && list.length === 0) {
// this full-height spinner only covers the very first load (no rows yet),
// or a filter change while the previous result was already empty (where
// isLoading stays false but there is nothing to keep on screen).
if ((isLoading || isFetching) && list.length === 0) {
return (
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
<div className="text-muted-foreground flex h-40 items-center justify-center gap-2 text-sm">
<Loader2 className="size-4 animate-spin" />
{t.common.loading}
</div>
);
@@ -208,8 +213,29 @@ export function AgentGallery() {
return renderEmpty(emptyDescription, showNewButton);
}
return (
<div className="flex flex-col gap-4">
{renderGrid(list)}
<div className="relative flex flex-col gap-4">
{/* While a server-side search/tag/page query is in flight the stale
keepPreviousData rows stay mounted — dim them and float a spinner
on top so a slow backend query never looks like the filter was
ignored, and block clicks on results that are about to change. */}
<div
className={
isFetching
? "pointer-events-none opacity-40 transition-opacity duration-200"
: "transition-opacity duration-200"
}
aria-busy={isFetching}
>
{renderGrid(list)}
</div>
{isFetching && (
<div className="absolute inset-0 z-10 flex items-start justify-center pt-24">
<div className="bg-background/90 text-muted-foreground flex items-center gap-2 rounded-full border px-4 py-2 text-sm shadow-sm">
<Loader2 className="size-4 animate-spin" />
正在查询…
</div>
</div>
)}
<Pagination
page={pages[tab] ?? 1}
pageSize={PAGE_SIZE}
@@ -315,6 +341,7 @@ export function AgentGallery() {
list: privateAgents,
total: privateTotal,
isLoading: isPrivateLoading,
isFetching: isPrivateFetching,
tab: "private",
emptyDescription: "私密广场暂时还没有智能体。",
});
@@ -444,6 +471,7 @@ export function AgentGallery() {
list: mainAgents,
total: mainTotal,
isLoading: mainLoading,
isFetching: mainFetching,
tab: sq.id,
emptyDescription: `「${sq.name}」广场暂时还没有智能体。`,
})}
@@ -455,6 +483,7 @@ export function AgentGallery() {
list: mainAgents,
total: mainTotal,
isLoading: mainLoading,
isFetching: mainFetching,
tab: "mine",
emptyDescription: t.agents.emptyDescription,
showNewButton: true,
@@ -0,0 +1,78 @@
"use client";
import { ArrowRightIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { useState } from "react";
import type { AgentQuestion } from "@/core/agents";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
/** Chips shown before the rest folds behind the 更多问题 toggle. */
const VISIBLE_COUNT = 4;
/**
* 常用问题 prompt chips on the agent chat landing screen — light-gray
* borderless pills stacked left-aligned between the welcome hero and the
* input box. Clicking a chip sends the question's full prompt through the
* page's existing submit flow. Lists longer than {@link VISIBLE_COUNT} fold
* behind a 更多问题 toggle; an empty list renders nothing.
*/
export function AgentQuestionChips({
questions,
onAsk,
disabled,
className,
}: {
questions: AgentQuestion[];
onAsk: (prompt: string) => void;
disabled?: boolean;
className?: string;
}) {
const [expanded, setExpanded] = useState(false);
if (questions.length === 0) return null;
const visible = expanded ? questions : questions.slice(0, VISIBLE_COUNT);
const foldedCount = questions.length - VISIBLE_COUNT;
return (
<div className={cn("flex flex-col items-start gap-2 px-1", className)}>
{visible.map((question, index) => (
<button
key={index}
type="button"
disabled={disabled}
onClick={() => onAsk(question.prompt)}
title={desensitize(question.prompt)}
className={cn(
"group bg-muted text-foreground/90 flex max-w-full items-center gap-2 rounded-full px-4 py-2.5 text-left text-sm leading-5 transition",
"hover:bg-accent active:scale-[0.98]",
"disabled:cursor-not-allowed disabled:opacity-50",
)}
>
<span className="min-w-0 truncate">{desensitize(question.title)}</span>
<ArrowRightIcon className="text-muted-foreground size-3.5 shrink-0 transition-transform group-hover:translate-x-0.5" />
</button>
))}
{foldedCount > 0 && (
<button
type="button"
onClick={() => setExpanded((v) => !v)}
className="text-muted-foreground hover:text-foreground flex items-center gap-1 rounded-full px-4 py-1.5 text-xs transition-colors"
>
{expanded ? (
<>
收起
<ChevronUpIcon className="size-3.5" />
</>
) : (
<>
更多问题({foldedCount})
<ChevronDownIcon className="size-3.5" />
</>
)}
</button>
)}
</div>
);
}
@@ -12,10 +12,20 @@ import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import type { AgentQuestion } from "@/core/agents";
/** Soft cap on the chip label length — beyond this the landing chip truncates. */
const TITLE_SOFT_LIMIT = 80;
/** The text a question row would actually persist as (panel save falls back
* title↔prompt), used for duplicate detection. */
function effectivePrompt(q: AgentQuestion): string {
return (q.prompt.trim() || q.title.trim()).toLowerCase();
}
/**
* Editable list of an agent's 常用问题 (recommended questions). Each row has a
* short `title` (the chip label) and the full `prompt` sent on click. Supports
* add / remove / inline edit / reorder (move up & down). Pure controlled
* add / remove / inline edit / reorder (move up & down), with non-blocking
* hints for over-long titles and duplicate questions. Pure controlled
* component — persistence stays with the caller (edit dialog or detail panel).
*/
export function AgentQuestionEditor({
@@ -52,7 +62,13 @@ export function AgentQuestionEditor({
尚未配置常用问题,点击下方按钮添加。
</p>
)}
{value.map((item, index) => (
{value.map((item, index) => {
const titleLength = item.title.trim().length;
const prompt = effectivePrompt(item);
const duplicateOf = prompt
? value.findIndex((other, i) => i < index && effectivePrompt(other) === prompt)
: -1;
return (
<div key={index} className="bg-background/60 space-y-1.5 rounded-lg border p-2.5">
<div className="flex items-center gap-1.5">
<Input
@@ -103,8 +119,19 @@ export function AgentQuestionEditor({
onChange={(e) => update(index, { prompt: e.currentTarget.value })}
className="min-h-16 resize-none text-sm"
/>
{titleLength > TITLE_SOFT_LIMIT && (
<p className="text-destructive text-xs">
标题建议不超过 {TITLE_SOFT_LIMIT} 字(当前 {titleLength} 字),过长会在聊天区被截断。
</p>
)}
{duplicateOf >= 0 && (
<p className="text-xs text-amber-600 dark:text-amber-400">
与第 {duplicateOf + 1} 条问题内容重复。
</p>
)}
</div>
))}
);
})}
<Button
type="button"
variant="outline"
@@ -4,15 +4,16 @@ import {
ArrowDownIcon,
Code2Icon,
CopyIcon,
DownloadIcon,
EyeIcon,
FileType2Icon,
LoaderIcon,
PackageIcon,
SaveIcon,
SquareArrowOutUpRightIcon,
XIcon,
} from "lucide-react";
DownloadIcon,
EyeIcon,
FileType2Icon,
LoaderIcon,
PackageIcon,
SaveIcon,
UploadCloudIcon,
XIcon,
} from "lucide-react";
import { useParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react";
import { toast } from "sonner";
@@ -35,11 +36,12 @@ import {
} from "@/components/ui/select";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { CodeEditor } from "@/components/workspace/code-editor";
import { apiFetch } from "@/core/api";
import {
downloadArtifactFile,
openArtifactInNewTab,
} from "@/core/artifacts/download";
import { publishArtifactToKnowledge } from "@/core/agents/api";
import { useAgent } from "@/core/agents/hooks";
import { apiFetch } from "@/core/api";
import {
downloadArtifactFile,
} from "@/core/artifacts/download";
import {
useArtifactContent,
useUpdateArtifactContent,
@@ -86,6 +88,13 @@ function extractTextFromChildren(children: ReactNode): string {
return "";
}
/** 取 md 标题用于入库:优先文中第一个标题行,否则退回文件名(去扩展名)。 */
function extractMarkdownTitle(content: string, filepath: string): string {
const heading = /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/m.exec(content);
if (heading?.[1]) return heading[1].trim();
return getFileName(filepath).replace(/\.(md|markdown)$/i, "");
}
function findScrollableArtifactElement(root: HTMLElement | null) {
if (!root) {
return null;
@@ -439,6 +448,50 @@ export function ArtifactFileDetail({
updateArtifact,
]);
// 发布入库:仅当当前路由是智能体会话(agents/:agent_id/chats/…)且该智能体
// 配置了入库模板名(template_name)时,md 产物右上角才出现发布按钮。
const { agent_id: routeAgentId } = useParams<{ agent_id?: string }>();
const { agent: routeAgent } = useAgent(routeAgentId ?? null);
const ingestTemplateName = routeAgent?.template_name?.trim() ?? "";
const canPublishToKnowledge =
!!routeAgentId &&
!!ingestTemplateName &&
language === "markdown" &&
!isSkillFile &&
!isMock;
const [isPublishingToKnowledge, setIsPublishingToKnowledge] = useState(false);
const handlePublishToKnowledge = useCallback(async () => {
if (!routeAgentId || isPublishingToKnowledge) {
return;
}
const source = (displayContent ?? "").trim();
if (!source) {
toast.error("Markdown 内容为空,无法发布入库");
return;
}
setIsPublishingToKnowledge(true);
try {
const result = await publishArtifactToKnowledge({
agent_id: routeAgentId,
title: extractMarkdownTitle(source, filepath),
content: source,
});
if (result.success) {
toast.success(`已发布入库:${result.node_name}`);
} else {
const last = result.attempts[result.attempts.length - 1];
toast.error(
`发布入库失败:${last?.error ?? last?.response_text ?? "接口返回失败"}`,
);
}
} catch (error) {
console.error("Failed to publish artifact to knowledge base:", error);
toast.error(error instanceof Error ? error.message : "发布入库失败");
} finally {
setIsPublishingToKnowledge(false);
}
}, [displayContent, filepath, isPublishingToKnowledge, routeAgentId]);
const [isExportingWord, setIsExportingWord] = useState(false);
const handleDownloadAsWord = useCallback(async () => {
const source = (displayContent ?? "").trim();
@@ -459,32 +512,7 @@ export function ArtifactFileDetail({
}
}, [displayContent, filepath]);
const handleOpenWriteFileInNewTab = useCallback(() => {
const source = displayContent ?? "";
if (!source.trim()) {
toast.error("文件内容为空,暂时无法打开");
return;
}
if (language === "mermaid") {
void openMermaidSvgInNewTab(source).catch((error) => {
console.error("Failed to open mermaid artifact:", error);
toast.error(error instanceof Error ? error.message : "Failed to open artifact");
});
return;
}
const blobType =
language === "html"
? "text/html;charset=utf-8"
: language === "markdown"
? "text/markdown;charset=utf-8"
: "text/plain;charset=utf-8";
const blob = new Blob([source], { type: blobType });
const url = URL.createObjectURL(blob);
window.open(url, "_blank", "noopener,noreferrer");
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
}, [displayContent, language]);
const handleDownloadWriteFile = useCallback(() => {
const handleDownloadWriteFile = useCallback(() => {
const source = displayContent ?? "";
if (!source.trim()) {
toast.error("文件内容为空,暂时无法下载");
@@ -516,7 +544,7 @@ export function ArtifactFileDetail({
return (
<Artifact className={cn(className)}>
<ArtifactHeader className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3 px-4 py-3">
<ArtifactHeader className="flex flex-wrap items-center gap-3 px-4 py-3">
<div className="flex min-w-0 items-center gap-2">
<div className="bg-muted/65 inline-flex min-w-0 items-center rounded-full border border-black/6 p-1 shadow-sm dark:border-white/8">
<span className="bg-background text-muted-foreground inline-flex h-7 shrink-0 items-center rounded-full border border-black/6 px-2.5 text-[10px] font-semibold tracking-[0.16em] dark:border-white/8">
@@ -546,7 +574,7 @@ export function ArtifactFileDetail({
</ArtifactTitle>
</div>
</div>
<div className="flex items-center justify-center">
<div className="flex w-full items-center justify-center md:w-auto md:flex-1">
{isSupportPreview && (
<div className="flex items-center gap-2">
<ToggleGroup
@@ -589,8 +617,17 @@ export function ArtifactFileDetail({
</div>
)}
</div>
<div className="flex items-center justify-end gap-2">
<ArtifactActions className="bg-muted/45 rounded-full border border-black/6 p-1 dark:border-white/8">
<div className="flex w-full items-center justify-end gap-2 md:ml-auto md:w-auto">
<ArtifactActions className="bg-muted/45 max-w-full flex-wrap justify-end rounded-3xl border border-black/6 p-1 dark:border-white/8">
{canPublishToKnowledge && (
<ArtifactAction
icon={isPublishingToKnowledge ? LoaderIcon : UploadCloudIcon}
label="发布入库"
tooltip={`发布到知识库(模板:${ingestTemplateName})`}
disabled={isPublishingToKnowledge || !displayContent}
onClick={() => void handlePublishToKnowledge()}
/>
)}
{canEditArtifact && (
<ArtifactAction
icon={updateArtifact.isPending ? LoaderIcon : SaveIcon}
@@ -614,45 +651,6 @@ export function ArtifactFileDetail({
/>
</Tooltip>
)}
<ArtifactAction
icon={SquareArrowOutUpRightIcon}
label={t.common.openInNewWindow}
tooltip={t.common.openInNewWindow}
onClick={async () => {
if (useWriteFileStreaming) {
handleOpenWriteFileInNewTab();
return;
}
if (language === "mermaid") {
try {
await openMermaidSvgInNewTab(displayContent ?? "");
} catch (error) {
console.error(error);
toast.error(
error instanceof Error
? error.message
: "Failed to open artifact",
);
}
return;
}
try {
await openArtifactInNewTab({
filepath,
threadId,
isMock,
publicShareCode,
});
} catch (error) {
console.error(error);
toast.error(
error instanceof Error
? error.message
: "Failed to open artifact",
);
}
}}
/>
{isCodeFile && (
<ArtifactAction
icon={CopyIcon}
@@ -1,44 +1,10 @@
"use client";
import { Database } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useThreadSettings } from "@/core/settings";
import { cn } from "@/lib/utils";
import { Tooltip } from "./tooltip";
/**
* Per-conversation 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.
*/
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,
});
};
return (
<Tooltip content={enabled ? "知识库召回:已开启" : "知识库召回:已关闭"}>
<Button
variant="ghost"
onClick={toggle}
className={cn(
"text-muted-foreground hover:text-foreground",
enabled && "text-primary hover:text-primary",
)}
>
<Database />
知识库
</Button>
</Tooltip>
);
export function KnowledgeRagToggle({
className: _className,
}: {
className?: string;
}) {
void _className;
return null;
}
@@ -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>
);
}
@@ -10,12 +10,14 @@ import {
ChevronRightIcon,
ClockIcon,
CopyIcon,
EyeOffIcon,
FileArchive,
GlobeIcon,
InfoIcon,
Loader2,
LockIcon,
PinIcon,
PlusIcon,
RefreshCwIcon,
SparklesIcon,
TagsIcon,
@@ -436,6 +438,18 @@ function SkillSettingsList({ onClose }: { onClose?: () => void }) {
<Upload className="size-4" />
{t.settings.skills.installSkill}
</Button>
<Button
size="sm"
onClick={() => {
onClose?.();
router.push("/page/workspace/chats/new?mode=skill");
}}
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
title="在对话中描述需求,由 AI 帮你创建一个新技能"
>
<PlusIcon className="size-4" />
{t.settings.skills.createSkill}
</Button>
</div>
</header>
<TagSearchBar
@@ -736,7 +750,7 @@ export function SkillRow({
{t.settings.skills.badgeFromOthers}
</Badge>
)}
{isOwned && skill.published && (
{(isOwned || isAdmin) && !isBuiltin && skill.published && (
<Badge
variant="outline"
className="border-sky-500/30 text-sky-700 dark:text-sky-300 text-xs"
@@ -746,6 +760,16 @@ export function SkillRow({
{t.settings.skills.badgePublished}
</Badge>
)}
{(isOwned || isAdmin) && !isBuiltin && !skill.published && (
<Badge
variant="outline"
className="border-zinc-400/40 text-zinc-500 dark:text-zinc-400 text-xs"
title={t.settings.skills.badgeUnpublishedTitle}
>
<EyeOffIcon className="size-3" />
{t.settings.skills.badgeUnpublished}
</Badge>
)}
{isCustom && !isBuiltin && skill.source === "agent" && (
<Badge
variant="outline"
@@ -1,6 +1,6 @@
"use client";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { ChevronLeft, ChevronRight, Trophy } from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
@@ -86,6 +86,20 @@ export function WorkspaceHeader({ className }: { className?: string }) {
) : (
titleBlock
)}
{/* 用户排行榜入口:紧挨左上角的应用名,新标签打开免登录的公开排行榜页。 */}
<Button
type="button"
variant="ghost"
size="sm"
onClick={() =>
window.open("#/public/leaderboard", "_blank", "noopener")
}
title="打开用户排行榜公开页"
className="text-muted-foreground hover:text-sidebar-foreground h-8 shrink-0 gap-1 px-1.5 text-xs font-medium"
>
<Trophy className="size-4" />
<span>排行榜</span>
</Button>
<SidebarCollapseButton />
</div>
)}
@@ -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")}