This commit is contained in:
吉鑫升 committed 2026-06-04 14:28:22 +08:00
commit 9704eff9f7
42 files changed
+1973 -10517

No files matched your search

@@ -0,0 +1,96 @@
"use client";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/** Compute the page-number window to render, inserting -1 sentinels for gaps.
* Always shows first/last and a window around the current page. */
function buildPageItems(current: number, totalPages: number): number[] {
if (totalPages <= 7) {
return Array.from({ length: totalPages }, (_, i) => i + 1);
}
const items = new Set<number>([1, totalPages, current]);
for (const d of [1, 2]) {
if (current - d >= 1) items.add(current - d);
if (current + d <= totalPages) items.add(current + d);
}
const sorted = [...items].sort((a, b) => a - b);
const out: number[] = [];
let prev = 0;
for (const p of sorted) {
if (prev && p - prev > 1) out.push(-1); // gap sentinel
out.push(p);
prev = p;
}
return out;
}
export interface PaginationProps {
page: number;
pageSize: number;
total: number;
onPageChange: (page: number) => void;
className?: string;
}
/** Controlled, compact pagination control. Renders nothing when a single page. */
export function Pagination({
page,
pageSize,
total,
onPageChange,
className,
}: PaginationProps) {
const totalPages = Math.max(1, Math.ceil(total / Math.max(pageSize, 1)));
if (totalPages <= 1) return null;
const items = buildPageItems(page, totalPages);
return (
<nav
className={cn("flex items-center justify-center gap-1", className)}
aria-label="分页"
>
<Button
variant="outline"
size="icon-sm"
disabled={page <= 1}
onClick={() => onPageChange(page - 1)}
aria-label="上一页"
>
<ChevronLeftIcon className="h-4 w-4" />
</Button>
{items.map((p, idx) =>
p === -1 ? (
<span
key={`gap-${idx}`}
className="text-muted-foreground px-1 text-sm select-none"
>
…
</span>
) : (
<Button
key={p}
variant={p === page ? "default" : "outline"}
size="icon-sm"
onClick={() => onPageChange(p)}
aria-current={p === page ? "page" : undefined}
>
{p}
</Button>
),
)}
<Button
variant="outline"
size="icon-sm"
disabled={page >= totalPages}
onClick={() => onPageChange(page + 1)}
aria-label="下一页"
>
<ChevronRightIcon className="h-4 w-4" />
</Button>
</nav>
);
}
+30 -4
View File
@@ -22,10 +22,31 @@ function ResizablePanelGroup({
);
}
// react-resizable-panels v4 changed size semantics: a bare *number* is now
// interpreted as PIXELS, while a unit-less *string* is a percentage. Every call
// site in this app passes sizes as percentages (the v2/v3 convention), so a
// value like `maxSize={60}` would otherwise pin a panel to 60px and freeze the
// layout/drag. Normalize numbers to "<n>%" to preserve the intended percentage.
const asPercent = (v: number | string | undefined) =>
typeof v === "number" ? `${v}%` : v;
function ResizablePanel({
defaultSize,
minSize,
maxSize,
collapsedSize,
...props
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
return (
<ResizablePrimitive.Panel
data-slot="resizable-panel"
defaultSize={asPercent(defaultSize)}
minSize={asPercent(minSize)}
maxSize={asPercent(maxSize)}
collapsedSize={asPercent(collapsedSize)}
{...props}
/>
);
}
function ResizableHandle({
@@ -39,14 +60,19 @@ function ResizableHandle({
<ResizablePrimitive.Separator
data-slot="resizable-handle"
className={cn(
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
// Thin visible divider, but a generous invisible hit area on both sides
// (after:w-4 → 16px) so the handle is easy to grab and drag. Hovering /
// dragging tints the divider so it's obvious it's interactive.
"bg-border hover:bg-primary/60 active:bg-primary relative flex w-px items-center justify-center transition-colors",
"after:absolute after:inset-y-0 after:left-1/2 after:w-4 after:-translate-x-1/2 after:cursor-col-resize",
"focus-visible:ring-ring focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden",
className,
)}
{...props}
>
{withHandle && (
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
<GripVerticalIcon className="size-2.5" />
<div className="bg-border z-10 flex h-8 w-4 items-center justify-center rounded-sm border shadow-sm">
<GripVerticalIcon className="size-3.5" />
</div>
)}
</ResizablePrimitive.Separator>
@@ -15,7 +15,14 @@ import {
Trash2Icon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import {
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
@@ -63,6 +70,115 @@ interface AgentCardProps {
agent: Agent;
}
interface BadgeItem {
key: string;
node: ReactNode;
}
// Minimum number of skill/tool badges to always render before collapsing the
// remainder into the "+N" chip.
const MIN_VISIBLE_BADGES = 3;
/** Render skill/tool-group badges clamped to at most two rows. Overflow is
* collapsed into a clickable "+N" chip that opens a dialog listing the full
* badge set (the visible rows stay as-is — only the chip is interactive).
*
* Badge widths are variable, so the cutoff is measured rather than assumed: an
* off-screen mirror of the full badge set is laid out at the real container
* width, and we keep only the badges that land within the first two rows
* (reserving one slot for the "+N" chip). A ResizeObserver recomputes when the
* responsive grid changes the card width.
*/
function ClampedBadgeRow({ items }: { items: BadgeItem[] }) {
const measureRef = useRef<HTMLDivElement>(null);
const [visible, setVisible] = useState(items.length);
const [dialogOpen, setDialogOpen] = useState(false);
const sig = items.map((i) => i.key).join("|");
useLayoutEffect(() => {
const el = measureRef.current;
if (!el) return;
const compute = () => {
const kids = Array.from(el.children) as HTMLElement[];
if (kids.length === 0) {
setVisible(0);
return;
}
const top0 = kids[0].offsetTop;
const rowH = kids[0].offsetHeight;
// +2px fudge so the second row's badges (which may sit a hair lower due
// to line-box rounding) are not falsely treated as a third row.
const maxBottom = top0 + rowH * 2 + 2;
let count = 0;
for (const k of kids) {
if (k.offsetTop + k.offsetHeight <= maxBottom) count += 1;
else break;
}
// Reserve one slot for the "+N" chip when anything overflows so the chip
// itself never spills onto a third row.
if (count < kids.length && count > 0) count -= 1;
// Always surface a few badges before collapsing into "+N", even when the
// card is narrow enough that two rows barely fit anything (otherwise a
// skinny column could show just "+N" with no skills at all). Keeps at
// least one badge hidden so the chip still makes sense.
if (count < kids.length) {
count = Math.max(count, Math.min(MIN_VISIBLE_BADGES, kids.length - 1));
}
setVisible(count);
};
compute();
const ro = new ResizeObserver(compute);
ro.observe(el);
return () => ro.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sig]);
const hidden = items.length - visible;
const showChip = hidden > 0;
const shown = items.slice(0, visible);
return (
<div className="relative">
{/* Off-screen full-width mirror used only for measuring row breaks. */}
<div
ref={measureRef}
aria-hidden
className="pointer-events-none invisible absolute inset-x-0 top-0 flex flex-wrap gap-1"
>
{items.map((i) => i.node)}
</div>
<div className="flex flex-wrap gap-1">
{shown.map((i) => i.node)}
{showChip && (
<Badge
variant="secondary"
className="hover:bg-secondary/70 cursor-pointer text-xs"
title="查看全部"
onClick={(e) => {
e.stopPropagation();
setDialogOpen(true);
}}
>
+{hidden}
</Badge>
)}
</div>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>全部技能与工具</DialogTitle>
<DialogDescription>共 {items.length} 项</DialogDescription>
</DialogHeader>
<div className="flex max-h-[60vh] flex-wrap gap-1.5 overflow-y-auto py-1">
{items.map((i) => i.node)}
</div>
</DialogContent>
</Dialog>
</div>
);
}
export function AgentCard({ agent }: AgentCardProps) {
const { t } = useI18n();
const router = useRouter();
@@ -397,31 +513,39 @@ export function AgentCard({ agent }: AgentCardProps) {
{(agent.tool_groups?.length ?? agent.skills?.length ?? 0) > 0 && (
<CardContent className="pt-0 pb-3">
<div className="flex flex-wrap gap-1">
{agent.tool_groups?.map((group) => (
<Badge
key={`tg:${group}`}
variant="outline"
className="text-xs"
>
{desensitize(group)}
</Badge>
))}
{agent.skills?.map((skill) => (
<Badge
key={`sk:${skill}`}
variant="secondary"
className="hover:bg-secondary/70 cursor-pointer text-xs"
title={t.settings.skills.viewDetailAction}
onClick={(e) => {
e.stopPropagation();
setDetailSkillName(skill);
}}
>
{desensitize(skill)}
</Badge>
))}
</div>
<ClampedBadgeRow
items={[
...(agent.tool_groups ?? []).map((group) => ({
key: `tg:${group}`,
node: (
<Badge
key={`tg:${group}`}
variant="outline"
className="text-xs"
>
{desensitize(group)}
</Badge>
),
})),
...(agent.skills ?? []).map((skill) => ({
key: `sk:${skill}`,
node: (
<Badge
key={`sk:${skill}`}
variant="secondary"
className="hover:bg-secondary/70 cursor-pointer text-xs"
title={t.settings.skills.viewDetailAction}
onClick={(e) => {
e.stopPropagation();
setDetailSkillName(skill);
}}
>
{desensitize(skill)}
</Badge>
),
})),
]}
/>
</CardContent>
)}
@@ -2,22 +2,23 @@
import { BotIcon, LockIcon, PlusIcon, ShieldIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Pagination } from "@/components/ui/pagination";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar";
import { useAgents, usePrivateAgents } from "@/core/agents";
import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents";
import type { Agent } from "@/core/agents";
import { getStoredAuth } from "@/core/auth";
import { useI18n } from "@/core/i18n/hooks";
import { usePrivateSquareStatus } from "@/core/system-settings/hooks";
import { desensitize } from "@/lib/desensitize";
import { AgentCard } from "./agent-card";
const PAGE_SIZE = 12;
// Within a single tab the verified password is kept in sessionStorage so a
// refresh / route navigation does not re-prompt. Cleared on tab close, so the
// password never persists beyond the browsing session.
@@ -31,19 +32,19 @@ export function AgentGallery() {
);
const [search, setSearch] = useState("");
const [tagIds, setTagIds] = useState<string[]>([]);
// Tag filtering stays server-side; name search must run on the *desensitized*
// form because that's what the user sees on the card. If we sent the search
// string to the backend it would compare against the raw stored name and
// miss every desensitized hit (e.g. typing "TS分析" wouldn't match the
// stored "态势分析").
const { agents, isLoading } = useAgents({ tagIds });
// Per-tab 1-based page index, preserved while switching tabs.
const [pages, setPages] = useState<{ all: number; mine: number; private: number }>(
{ all: 1, mine: 1, private: 1 },
);
const needle = search.trim().toLowerCase();
const matchesSearch = (a: Agent) =>
!needle || desensitize(a.name).toLowerCase().includes(needle);
const storedAuth = useMemo(() => getStoredAuth(), []);
const currentUserId = storedAuth?.user_id ?? null;
// Search + tag filtering are both server-side now. The backend mirrors the
// frontend's desensitize map, so typing the displayed abbreviation (e.g.
// "TS") still matches the stored raw name (e.g. "态势分析"). Whenever the
// filters change, every tab returns to its first page.
const tagKey = tagIds.join(",");
useEffect(() => {
setPages({ all: 1, mine: 1, private: 1 });
}, [search, tagKey]);
const { data: privateStatus } = usePrivateSquareStatus();
const privateFeatureAvailable = !!privateStatus?.enabled;
@@ -56,11 +57,35 @@ export function AgentGallery() {
});
const [passwordInput, setPasswordInput] = useState("");
// Only the active tab fetches. "广场" maps to the server "square" scope
// (built-in/published, never private), "我的" to "mine" (owned + favorited).
const mainScope = activeTab === "mine" ? "mine" : "square";
const mainPage = activeTab === "mine" ? pages.mine : pages.all;
const {
agents: mainAgents,
total: mainTotal,
isLoading: mainLoading,
} = useAgentsPaginated({
scope: mainScope,
search,
tagIds,
page: mainPage,
pageSize: PAGE_SIZE,
enabled: activeTab !== "private",
});
const {
agents: privateAgents,
total: privateTotal,
isLoading: isPrivateLoading,
error: privateError,
} = usePrivateAgents(privatePassword);
} = usePrivateAgentsPaginated(privatePassword, {
search,
tagIds,
page: pages.private,
pageSize: PAGE_SIZE,
enabled: activeTab === "private",
});
// If the server reports the stored password no longer works (likely the
// admin rotated it), drop it from session storage and re-prompt.
@@ -72,49 +97,10 @@ export function AgentGallery() {
}
}, [privateError, privatePassword]);
// The "广场" tab must never surface private-square agents, even to their
// own owner — moving an agent into the private square is supposed to hide
// it from the public square entirely. (The backend listing endpoint
// already filters them out for non-owners; this extra clause covers the
// owner's own private agents, which still come back in the unified list
// because owners always see their own.)
const allAgents = useMemo(
() =>
agents.filter(
(a) => (a.builtin || a.published) && !a.is_private && matchesSearch(a),
),
// matchesSearch closes over `needle`; depending on `search` is sufficient
// and avoids re-running on every render via the function reference.
// eslint-disable-next-line react-hooks/exhaustive-deps
[agents, search],
);
const activeTotal = activeTab === "private" ? privateTotal : mainTotal;
// "我的" shows the user's own agents plus any agent they've favorited (收藏)
// from the square — favorited public agents have a different user_id but a
// truthy is_favorite flag.
const myAgents = useMemo(
() =>
agents.filter(
(a) =>
((a.user_id !== null && a.user_id === currentUserId) ||
a.is_favorite) &&
matchesSearch(a),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[agents, currentUserId, search],
);
const filteredPrivateAgents = useMemo(() => {
const wanted = new Set(tagIds);
return privateAgents.filter((a) => {
if (!matchesSearch(a)) return false;
if (wanted.size > 0) {
if (!(a.tags ?? []).some((tg) => wanted.has(tg.id))) return false;
}
return true;
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [privateAgents, search, tagIds]);
const setTabPage = (tab: "all" | "mine" | "private", page: number) =>
setPages((prev) => ({ ...prev, [tab]: page }));
const handleNewAgent = () => {
router.push("/page/workspace/agents/new");
@@ -136,7 +122,7 @@ export function AgentGallery() {
setPrivatePassword(null);
};
const renderGrid = (list: typeof agents) => (
const renderGrid = (list: Agent[]) => (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{list.map((agent) => (
<AgentCard key={agent.id} agent={agent} />
@@ -144,6 +130,42 @@ export function AgentGallery() {
</div>
);
/** Loading / empty / (grid + pagination) for one paginated tab. */
const renderListBody = (opts: {
list: Agent[];
total: number;
isLoading: boolean;
tab: "all" | "mine" | "private";
emptyDescription: string;
showNewButton?: boolean;
}) => {
const { list, total, isLoading, 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) {
return (
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
{t.common.loading}
</div>
);
}
if (list.length === 0) {
return renderEmpty(emptyDescription, showNewButton);
}
return (
<div className="flex flex-col gap-4">
{renderGrid(list)}
<Pagination
page={pages[tab]}
pageSize={PAGE_SIZE}
total={total}
onPageChange={(p) => setTabPage(tab, p)}
className="pt-2"
/>
</div>
);
};
const renderEmpty = (description: string, showNewButton = false) => (
<div className="flex h-64 flex-col items-center justify-center gap-3 text-center">
<div className="bg-muted flex h-14 w-14 items-center justify-center rounded-full dark:bg-[#022248]">
@@ -225,19 +247,13 @@ export function AgentGallery() {
);
}
if (isPrivateLoading) {
return (
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
{t.common.loading}
</div>
);
}
if (filteredPrivateAgents.length === 0) {
return renderEmpty("私密广场暂时还没有智能体。");
}
return renderGrid(filteredPrivateAgents);
return renderListBody({
list: privateAgents,
total: privateTotal,
isLoading: isPrivateLoading,
tab: "private",
emptyDescription: "私密广场暂时还没有智能体。",
});
};
return (
@@ -276,17 +292,22 @@ export function AgentGallery() {
</TabsTrigger>
)}
</TabsList>
{activeTab === "private" && privatePassword && (
<Button
variant="outline"
size="sm"
onClick={handleLockPrivate}
title="锁定私密广场,下次需要重新输入密码"
>
<LockIcon className="mr-1.5 h-3.5 w-3.5" />
锁定
</Button>
)}
<div className="flex items-center gap-3">
<span className="text-muted-foreground text-sm whitespace-nowrap">
共 {activeTotal} 个
</span>
{activeTab === "private" && privatePassword && (
<Button
variant="outline"
size="sm"
onClick={handleLockPrivate}
title="锁定私密广场,下次需要重新输入密码"
>
<LockIcon className="mr-1.5 h-3.5 w-3.5" />
锁定
</Button>
)}
</div>
</div>
<TagSearchBar
targetType="agent"
@@ -297,27 +318,24 @@ export function AgentGallery() {
</div>
<TabsContent value="all" className="flex-1 overflow-y-auto p-6 mt-0">
{isLoading ? (
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
{t.common.loading}
</div>
) : allAgents.length === 0 ? (
renderEmpty(t.agents.emptyDescription)
) : (
renderGrid(allAgents)
)}
{renderListBody({
list: mainAgents,
total: mainTotal,
isLoading: mainLoading,
tab: "all",
emptyDescription: t.agents.emptyDescription,
})}
</TabsContent>
<TabsContent value="mine" className="flex-1 overflow-y-auto p-6 mt-0">
{isLoading ? (
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
{t.common.loading}
</div>
) : myAgents.length === 0 ? (
renderEmpty(t.agents.emptyDescription, true)
) : (
renderGrid(myAgents)
)}
{renderListBody({
list: mainAgents,
total: mainTotal,
isLoading: mainLoading,
tab: "mine",
emptyDescription: t.agents.emptyDescription,
showNewButton: true,
})}
</TabsContent>
{privateFeatureAvailable && (
@@ -19,15 +19,32 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useAgents } from "@/core/agents/hooks";
import {
useCreateCustomPrompt,
useCustomPrompts,
useDeleteCustomPrompt,
useUpdateCustomPrompt,
} from "@/core/custom-prompts";
import {
useUpdateUserPreferences,
useUserPreferences,
} from "@/core/user-preferences";
import { desensitize } from "@/lib/desensitize";
import { cn } from "@/lib/utils";
/** Sentinel select value for "no agent association" (global prompt). */
const NO_AGENT = "__global__";
/**
* Bar above the chat input showing the user's saved prompts as centered,
* clickable chips. When there are too many to fit, they become a horizontal
@@ -38,11 +55,21 @@ import { cn } from "@/lib/utils";
export function CustomPromptBar({
onInsert,
className,
currentAgentId,
}: {
onInsert: (content: string) => void;
className?: string;
/**
* The agent currently selected for this chat (or null on the general
* new-chat page). Agent-associated prompts only show when their ``agent_id``
* matches; un-associated (global) prompts always show.
*/
currentAgentId?: string | null;
}) {
const prompts = useCustomPrompts();
const allPrompts = useCustomPrompts();
const prompts = allPrompts.filter(
(p) => !p.agent_id || p.agent_id === currentAgentId,
);
const [manageOpen, setManageOpen] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -153,16 +180,24 @@ function ManagePromptsDialog({
const createPrompt = useCreateCustomPrompt();
const updatePrompt = useUpdateCustomPrompt();
const deletePrompt = useDeleteCustomPrompt();
const { agents } = useAgents();
const preferences = useUserPreferences();
const updatePreferences = useUpdateUserPreferences();
const [editingId, setEditingId] = useState<string | null>(null);
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [agentId, setAgentId] = useState<string>(NO_AGENT);
const saving = createPrompt.isPending || updatePrompt.isPending;
const agentNameById = (id?: string | null) =>
id ? agents.find((a) => a.id === id)?.name ?? null : null;
const resetForm = () => {
setEditingId(null);
setTitle("");
setContent("");
setAgentId(NO_AGENT);
};
const handleSubmit = async () => {
@@ -171,15 +206,20 @@ function ManagePromptsDialog({
toast.error("提示词内容不能为空");
return;
}
const boundAgentId = agentId === NO_AGENT ? null : agentId;
try {
if (editingId) {
await updatePrompt.mutateAsync({
id: editingId,
input: { title: trimmedTitle, content },
input: { title: trimmedTitle, content, agent_id: boundAgentId },
});
toast.success("提示词已更新");
} else {
await createPrompt.mutateAsync({ title: trimmedTitle, content });
await createPrompt.mutateAsync({
title: trimmedTitle,
content,
agent_id: boundAgentId,
});
toast.success("提示词已添加");
}
resetForm();
@@ -194,6 +234,15 @@ function ManagePromptsDialog({
setEditingId(id);
setTitle(target.title);
setContent(target.content);
setAgentId(target.agent_id || NO_AGENT);
};
const handleToggleHideAdmin = async (next: boolean) => {
try {
await updatePreferences.mutateAsync({ hide_admin_prompt_prefix: next });
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
};
const handleDelete = async (id: string) => {
@@ -221,6 +270,20 @@ function ManagePromptsDialog({
</DialogDescription>
</DialogHeader>
<div className="flex items-start justify-between gap-3 rounded-md border p-3">
<div className="min-w-0">
<p className="text-sm font-medium">只用我自己的提示词</p>
<p className="text-muted-foreground mt-0.5 text-xs">
开启后,输入框不再显示管理员配置的提示词(提示词前缀)开关,本账号仅使用自己保存的提示词。
</p>
</div>
<Switch
checked={preferences.hide_admin_prompt_prefix}
disabled={updatePreferences.isPending}
onCheckedChange={(v) => void handleToggleHideAdmin(v)}
/>
</div>
<div className="space-y-3 rounded-md border p-3">
<Input
value={title}
@@ -233,6 +296,28 @@ function ManagePromptsDialog({
placeholder="提示词内容"
className="min-h-28"
/>
<div className="flex flex-col gap-1">
<p className="text-muted-foreground text-xs">关联智能体(可选)</p>
<Select value={agentId} onValueChange={setAgentId}>
<SelectTrigger className="w-full min-w-0 max-w-full overflow-hidden [&>span]:min-w-0 [&>span]:flex-1 [&>span]:truncate">
<SelectValue placeholder="不关联(所有对话可见)" />
</SelectTrigger>
<SelectContent
position="popper"
className="w-[var(--radix-select-trigger-width)] max-w-[var(--radix-select-trigger-width)]"
>
<SelectItem value={NO_AGENT}>不关联(所有对话可见)</SelectItem>
{agents.map((agent) => (
<SelectItem key={agent.id} value={agent.id}>
<span className="block truncate">{desensitize(agent.name)}</span>
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-muted-foreground text-xs">
关联后,仅在选中该智能体的对话里显示此提示词。
</p>
</div>
<div className="flex justify-end gap-2">
{editingId && (
<Button variant="outline" size="sm" onClick={resetForm} disabled={saving}>
@@ -260,6 +345,11 @@ function ManagePromptsDialog({
<p className="truncate text-sm font-medium">
{prompt.title || "未命名提示词"}
</p>
{prompt.agent_id && (
<p className="mt-0.5 truncate text-[11px] text-sky-600 dark:text-sky-400">
仅 {desensitize(agentNameById(prompt.agent_id) || "未知智能体")} 可见
</p>
)}
<p className="text-muted-foreground mt-0.5 line-clamp-2 text-xs whitespace-pre-wrap">
{prompt.content}
</p>
@@ -131,6 +131,7 @@ export function InputBox({
onStop,
promptPrefix,
agentSelector,
assistantId,
...props
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
assistantId?: string | null;
@@ -564,6 +565,7 @@ export function InputBox({
{isNewThread && (
<CustomPromptBar
className="px-1"
currentAgentId={agentSelector?.selectedAgentId ?? assistantId ?? null}
onInsert={(content) => {
const current = textInput.value?.trim() ?? "";
textInput.setInput(current ? `${current}\n${content}` : content);
@@ -473,6 +473,16 @@ const CATEGORY_COLORS: Record<string, string> = {
correction: "bg-red-100 text-red-700",
};
/** 事实分类的中文标签。 */
const CATEGORY_LABELS: Record<string, string> = {
preference: "偏好",
knowledge: "知识",
context: "背景",
behavior: "行为",
goal: "目标",
correction: "纠正",
};
/** V1 记忆只读视图:展示 memory.json 的全部字段,Tab 布局。 */
function MemoryV1View({
memory,
@@ -494,8 +504,9 @@ function MemoryV1View({
V1 模式:记忆由系统在对话结束后自动提取,无需手动管理。
</div>
<Tabs defaultValue="facts">
<Tabs defaultValue="profile">
<TabsList>
<TabsTrigger value="profile">用户画像 &amp; 历史</TabsTrigger>
<TabsTrigger value="facts">
事实记录
{memory.facts.length > 0 && (
@@ -504,55 +515,8 @@ function MemoryV1View({
</span>
)}
</TabsTrigger>
<TabsTrigger value="profile">用户画像 &amp; 历史</TabsTrigger>
</TabsList>
{/* 事实记录 Tab */}
<TabsContent value="facts" className="mt-3">
<div className="rounded-lg border p-4 space-y-3 dark:border-[#213D5E] dark:bg-[#022248]">
<div className="flex items-center justify-between">
<h3 className="text-base font-medium">事实记录</h3>
<span className="text-xs text-muted-foreground">{memory.memory_usage}</span>
</div>
{memory.facts.length === 0 ? (
<div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground ">
暂无事实记录,对话后系统会自动提取。
</div>
) : (
<div className="space-y-2">
{memory.facts.map((fact) => (
<div key={fact.id} className="rounded-md border p-3 space-y-1.5">
<div className="flex items-center gap-2">
<span
className={`rounded px-1.5 py-0.5 text-xs font-medium ${
CATEGORY_COLORS[fact.category] ?? "bg-gray-100 text-gray-700"
}`}
>
{fact.category}
</span>
<div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full bg-primary"
style={{ width: `${Math.round(fact.confidence * 100)}%` }}
/>
</div>
<span className="text-xs text-muted-foreground shrink-0">
{Math.round(fact.confidence * 100)}%
</span>
</div>
<p className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{desensitize(fact.content)}</p>
{fact.sourceError && (
<p className="rounded bg-red-50 px-2 py-1 text-xs text-red-600 dark:bg-[#311629] dark:text-[#EE212C]">
避免:{desensitize(fact.sourceError)}
</p>
)}
</div>
))}
</div>
)}
</div>
</TabsContent>
{/* 用户画像 & 历史摘要 Tab */}
<TabsContent value="profile" className="mt-3 space-y-4">
{/* 用户画像 (userContext) */}
@@ -593,6 +557,49 @@ function MemoryV1View({
)}
</div>
</TabsContent>
{/* 事实记录 Tab */}
<TabsContent value="facts" className="mt-3">
<div className="rounded-lg border p-4 space-y-3 dark:border-[#213D5E] dark:bg-[#022248]">
<div className="flex items-center justify-between">
<h3 className="text-base font-medium">事实记录</h3>
<span className="text-xs text-muted-foreground">{memory.memory_usage}</span>
</div>
{memory.facts.length === 0 ? (
<div className="rounded-md border border-dashed p-3 text-sm text-muted-foreground ">
暂无事实记录,对话后系统会自动提取。
</div>
) : (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{memory.facts.map((fact) => (
<div
key={fact.id}
className="flex flex-col gap-2 rounded-lg border p-3 shadow-sm dark:border-[#213D5E]"
>
<div className="flex items-center justify-between gap-2">
<span
className={`rounded px-1.5 py-0.5 text-xs font-medium ${
CATEGORY_COLORS[fact.category] ?? "bg-gray-100 text-gray-700"
}`}
>
{CATEGORY_LABELS[fact.category] ?? fact.category}
</span>
<span className="shrink-0 text-xs font-medium text-muted-foreground">
置信度 {Math.round(fact.confidence * 100)}%
</span>
</div>
<p className="text-sm whitespace-pre-wrap [overflow-wrap:anywhere]">{desensitize(fact.content)}</p>
{fact.sourceError && (
<p className="rounded bg-red-50 px-2 py-1 text-xs text-red-600 dark:bg-[#311629] dark:text-[#EE212C]">
避免:{desensitize(fact.sourceError)}
</p>
)}
</div>
))}
</div>
)}
</div>
</TabsContent>
</Tabs>
</div>
);