Merge branch 'ji' of http://192.168.0.200/knowledge-base-bj/deerflow-server into ji
This commit is contained in:
commit
9704eff9f7
42 files changed
+1973
-10517
No files matched your search
Generated
-10140
File diff suppressed because it is too large.
Load diff
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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">用户画像 & 历史</TabsTrigger>
|
||||
<TabsTrigger value="facts">
|
||||
事实记录
|
||||
{memory.facts.length > 0 && (
|
||||
@@ -504,55 +515,8 @@ function MemoryV1View({
|
||||
</span>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="profile">用户画像 & 历史</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>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
Agent,
|
||||
AgentSelectorResponse,
|
||||
CreateAgentRequest,
|
||||
PaginatedAgents,
|
||||
UpdateAgentRequest,
|
||||
} from "./types";
|
||||
|
||||
@@ -23,13 +24,25 @@ export class AgentNameCheckError extends Error {
|
||||
export interface ListAgentsParams {
|
||||
search?: string;
|
||||
tagIds?: string[];
|
||||
/** Pagination scope. Omit for the legacy combined-visibility list. */
|
||||
scope?: "mine" | "square";
|
||||
/** 1-based page index. Providing this (or scope) enables server-side pagination. */
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
|
||||
function buildAgentsQuery(params: ListAgentsParams): string {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.search) qs.set("search", params.search);
|
||||
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
||||
const query = qs.toString();
|
||||
if (params.scope) qs.set("scope", params.scope);
|
||||
if (params.page != null) qs.set("page", String(params.page));
|
||||
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
|
||||
return qs.toString();
|
||||
}
|
||||
|
||||
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
|
||||
const query = buildAgentsQuery(params);
|
||||
const res = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
||||
);
|
||||
@@ -38,6 +51,29 @@ export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]
|
||||
return data.agents;
|
||||
}
|
||||
|
||||
/** Like {@link listAgents} but returns the pagination envelope (total/page). */
|
||||
export async function listAgentsPaginated(
|
||||
params: ListAgentsParams = {},
|
||||
): Promise<PaginatedAgents> {
|
||||
const query = buildAgentsQuery(params);
|
||||
const res = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
|
||||
);
|
||||
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
|
||||
const data = (await res.json()) as {
|
||||
agents: Agent[];
|
||||
total?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
};
|
||||
return {
|
||||
agents: data.agents,
|
||||
total: data.total ?? data.agents.length,
|
||||
page: data.page ?? params.page ?? 1,
|
||||
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listAllAgentsAdmin(): Promise<Agent[]> {
|
||||
const res = await apiFetch(`${getBackendBaseURL()}/api/agents?admin=true`);
|
||||
if (!res.ok) {
|
||||
@@ -152,6 +188,52 @@ export async function listPrivateAgents(password: string): Promise<Agent[]> {
|
||||
return data.agents;
|
||||
}
|
||||
|
||||
export interface ListPrivateAgentsParams {
|
||||
password: string;
|
||||
search?: string;
|
||||
tagIds?: string[];
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
/** Paginated private-square listing (password-gated). */
|
||||
export async function listPrivateAgentsPaginated(
|
||||
params: ListPrivateAgentsParams,
|
||||
): Promise<PaginatedAgents> {
|
||||
const res = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/agents/private-square/list`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
password: params.password,
|
||||
search: params.search || undefined,
|
||||
tag_ids: params.tagIds && params.tagIds.length ? params.tagIds : undefined,
|
||||
page: params.page,
|
||||
page_size: params.pageSize,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||
throw new Error(
|
||||
err.detail ?? `Failed to load private agents: ${res.statusText}`,
|
||||
);
|
||||
}
|
||||
const data = (await res.json()) as {
|
||||
agents: Agent[];
|
||||
total?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
};
|
||||
return {
|
||||
agents: data.agents,
|
||||
total: data.total ?? data.agents.length,
|
||||
page: data.page ?? params.page ?? 1,
|
||||
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
|
||||
};
|
||||
}
|
||||
|
||||
export async function setAgentPrivate(
|
||||
id: string,
|
||||
isPrivate: boolean,
|
||||
|
||||
@@ -13,15 +13,42 @@ import {
|
||||
getAgent,
|
||||
getAgentSelector,
|
||||
listAgents,
|
||||
listAgentsPaginated,
|
||||
listAllAgentsAdmin,
|
||||
listPrivateAgents,
|
||||
listPrivateAgentsPaginated,
|
||||
reorderFeaturedAgents,
|
||||
setAgentFeatured,
|
||||
setAgentPrivate,
|
||||
unfavoriteAgent,
|
||||
updateAgent,
|
||||
} from "./api";
|
||||
import type { Agent, CreateAgentRequest, UpdateAgentRequest } from "./types";
|
||||
import type {
|
||||
Agent,
|
||||
CreateAgentRequest,
|
||||
PaginatedAgents,
|
||||
UpdateAgentRequest,
|
||||
} from "./types";
|
||||
|
||||
/** A cached agent listing is either a plain ``Agent[]`` (legacy ``useAgents``)
|
||||
* or the paginated ``{ agents, total, ... }`` envelope. Mutators patch both. */
|
||||
type CachedAgents = Agent[] | PaginatedAgents | undefined;
|
||||
|
||||
function isPaginated(value: CachedAgents): value is PaginatedAgents {
|
||||
return !!value && !Array.isArray(value) && Array.isArray(value.agents);
|
||||
}
|
||||
|
||||
/** Apply ``map`` to every agent inside whatever listing shape is cached. */
|
||||
function mapCachedAgents(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
map: (a: Agent) => Agent,
|
||||
) {
|
||||
queryClient.setQueriesData<CachedAgents>({ queryKey: ["agents"] }, (old) => {
|
||||
if (Array.isArray(old)) return old.map(map);
|
||||
if (isPaginated(old)) return { ...old, agents: old.agents.map(map) };
|
||||
return old;
|
||||
});
|
||||
}
|
||||
|
||||
/** Patch an updated agent into every cached agent listing immediately so
|
||||
* cards re-render before the background refetch finishes. Without this the
|
||||
@@ -32,13 +59,7 @@ function applyAgentToCache(
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
next: Agent,
|
||||
) {
|
||||
queryClient.setQueriesData<Agent[] | undefined>(
|
||||
{ queryKey: ["agents"] },
|
||||
(old) => {
|
||||
if (!Array.isArray(old)) return old;
|
||||
return old.map((a) => (a.id === next.id ? { ...a, ...next } : a));
|
||||
},
|
||||
);
|
||||
mapCachedAgents(queryClient, (a) => (a.id === next.id ? { ...a, ...next } : a));
|
||||
}
|
||||
|
||||
export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
|
||||
@@ -52,6 +73,42 @@ export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
|
||||
return { agents: data ?? [], isLoading, error };
|
||||
}
|
||||
|
||||
/** Server-side paginated agent listing for one gallery tab (scope). Returns
|
||||
* the page of agents plus the total count for the "共 N 个" header. */
|
||||
export function useAgentsPaginated(params: {
|
||||
scope: "mine" | "square";
|
||||
search?: string;
|
||||
tagIds?: string[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
enabled?: boolean;
|
||||
}) {
|
||||
const { scope, page, pageSize, enabled = true } = params;
|
||||
const search = params.search ?? "";
|
||||
const tagIds = params.tagIds ?? [];
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: [
|
||||
"agents",
|
||||
"paginated",
|
||||
scope,
|
||||
search,
|
||||
[...tagIds].sort(),
|
||||
page,
|
||||
pageSize,
|
||||
],
|
||||
queryFn: () =>
|
||||
listAgentsPaginated({ scope, search, tagIds, page, pageSize }),
|
||||
enabled,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
return {
|
||||
agents: data?.agents ?? [],
|
||||
total: data?.total ?? 0,
|
||||
isLoading,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin-only listing — returns every agent including unpublished agents owned
|
||||
* by other users and private-square entries. Caller must be ``system_role
|
||||
@@ -123,14 +180,8 @@ export function useToggleAgentFavorite() {
|
||||
mutationFn: ({ id, favorite }: { id: string; favorite: boolean }) =>
|
||||
favorite ? favoriteAgent(id) : unfavoriteAgent(id),
|
||||
onMutate: ({ id, favorite }) => {
|
||||
queryClient.setQueriesData<Agent[] | undefined>(
|
||||
{ queryKey: ["agents"] },
|
||||
(old) =>
|
||||
Array.isArray(old)
|
||||
? old.map((a) =>
|
||||
a.id === id ? { ...a, is_favorite: favorite } : a,
|
||||
)
|
||||
: old,
|
||||
mapCachedAgents(queryClient, (a) =>
|
||||
a.id === id ? { ...a, is_favorite: favorite } : a,
|
||||
);
|
||||
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
|
||||
old ? { ...old, is_favorite: favorite } : old,
|
||||
@@ -196,6 +247,54 @@ export function usePrivateAgents(password: string | null) {
|
||||
return { agents: data ?? [], isLoading, error, refetch };
|
||||
}
|
||||
|
||||
/** Paginated variant of {@link usePrivateAgents} — one page of the
|
||||
* password-gated private square plus the total count. */
|
||||
export function usePrivateAgentsPaginated(
|
||||
password: string | null,
|
||||
params: {
|
||||
search?: string;
|
||||
tagIds?: string[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
enabled?: boolean;
|
||||
},
|
||||
) {
|
||||
const { page, pageSize, enabled = true } = params;
|
||||
const search = params.search ?? "";
|
||||
const tagIds = params.tagIds ?? [];
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: [
|
||||
"agents",
|
||||
"private-square",
|
||||
password ?? "",
|
||||
"paginated",
|
||||
search,
|
||||
[...tagIds].sort(),
|
||||
page,
|
||||
pageSize,
|
||||
],
|
||||
queryFn: () =>
|
||||
listPrivateAgentsPaginated({
|
||||
password: password!,
|
||||
search,
|
||||
tagIds,
|
||||
page,
|
||||
pageSize,
|
||||
}),
|
||||
enabled: !!password && enabled,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
return {
|
||||
agents: data?.agents ?? [],
|
||||
total: data?.total ?? 0,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
|
||||
export function useSetAgentPrivate() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
|
||||
@@ -24,6 +24,14 @@ export interface AgentSelectorResponse {
|
||||
agents: Agent[];
|
||||
}
|
||||
|
||||
/** Pagination envelope returned by the server-side paginated agent listings. */
|
||||
export interface PaginatedAgents {
|
||||
agents: Agent[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface CreateAgentRequest {
|
||||
name: string;
|
||||
description?: string;
|
||||
|
||||
@@ -9,6 +9,12 @@ export interface CustomPrompt {
|
||||
title: string;
|
||||
content: string;
|
||||
sort_order?: number;
|
||||
/**
|
||||
* Optional association to a single agent. ``null``/absent = global (shown for
|
||||
* every agent); otherwise the prompt only surfaces when that agent is
|
||||
* selected.
|
||||
*/
|
||||
agent_id?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
@@ -27,6 +33,7 @@ async function listUserPrompts(): Promise<CustomPrompt[]> {
|
||||
async function createUserPrompt(input: {
|
||||
title: string;
|
||||
content: string;
|
||||
agent_id?: string | null;
|
||||
}): Promise<CustomPrompt> {
|
||||
const res = await apiFetch(baseUrl(), {
|
||||
method: "POST",
|
||||
@@ -42,7 +49,7 @@ async function createUserPrompt(input: {
|
||||
|
||||
async function updateUserPrompt(
|
||||
id: string,
|
||||
input: { title?: string; content?: string },
|
||||
input: { title?: string; content?: string; agent_id?: string | null },
|
||||
): Promise<CustomPrompt> {
|
||||
const res = await apiFetch(`${baseUrl()}/${encodeURIComponent(id)}`, {
|
||||
method: "PUT",
|
||||
@@ -93,7 +100,7 @@ export function useUpdateCustomPrompt() {
|
||||
input,
|
||||
}: {
|
||||
id: string;
|
||||
input: { title?: string; content?: string };
|
||||
input: { title?: string; content?: string; agent_id?: string | null };
|
||||
}) => updateUserPrompt(id, input),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: QUERY_KEY });
|
||||
|
||||
@@ -26,6 +26,14 @@ export type HtmlPageConfig = {
|
||||
|
||||
export type ScheduledTaskExecutionContext = {
|
||||
require_markdown?: boolean;
|
||||
/**
|
||||
* The unified "必须生成 HTML" switch. The task form no longer splits "普通任务 /
|
||||
* HTML 页面" into separate kinds — instead ``require_html`` and
|
||||
* ``require_markdown`` are two independent toggles that may both be on. Legacy
|
||||
* tasks created under the old two-tab UI still carry ``task_kind`` and are
|
||||
* treated as HTML tasks by the backend for backward compatibility.
|
||||
*/
|
||||
require_html?: boolean;
|
||||
task_kind?: ScheduledTaskKind;
|
||||
html_config?: HtmlPageConfig;
|
||||
[key: string]: unknown;
|
||||
|
||||
@@ -27,6 +27,12 @@ import type { Skill, SkillState } from "./type";
|
||||
|
||||
import { loadAllSkillsAdmin, loadSkills } from ".";
|
||||
|
||||
// Stable empty fallback. Returning `data ?? []` inline would hand out a fresh
|
||||
// array reference on every render while the query is loading/errored, which
|
||||
// makes downstream `useMemo([skills])` / `useEffect([skills])` consumers churn
|
||||
// forever (observed as a "Maximum update depth exceeded" loop on NewAgentPage).
|
||||
const EMPTY_SKILLS: Skill[] = [];
|
||||
|
||||
export function useSkills(params: { search?: string; tagIds?: string[] } = {}) {
|
||||
const search = params.search ?? "";
|
||||
const tagIds = params.tagIds ?? [];
|
||||
@@ -35,7 +41,7 @@ export function useSkills(params: { search?: string; tagIds?: string[] } = {}) {
|
||||
queryFn: () => loadSkills({ search, tagIds }),
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
return { skills: data ?? [], isLoading, error };
|
||||
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,7 +56,7 @@ export function useAllSkillsAdmin(enabled: boolean) {
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
return { skills: data ?? [], isLoading, error };
|
||||
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
|
||||
}
|
||||
|
||||
export function useSkillContent(skillName: string | null) {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
/** Per-user UI preferences, bound to the account (stored server-side). */
|
||||
export interface UserPreferences {
|
||||
/**
|
||||
* When true, the chat input hides the admin-configured prompt-prefix switch
|
||||
* and never applies the prefix — the user uses only their own prompts.
|
||||
*/
|
||||
hide_admin_prompt_prefix: boolean;
|
||||
}
|
||||
|
||||
const QUERY_KEY = ["user-preferences"] as const;
|
||||
const DEFAULT_PREFS: UserPreferences = { hide_admin_prompt_prefix: false };
|
||||
const baseUrl = () => `${getBackendBaseURL()}/api/user-preferences`;
|
||||
|
||||
async function getUserPreferences(): Promise<UserPreferences> {
|
||||
const res = await apiFetch(baseUrl());
|
||||
if (!res.ok) throw new Error(`Failed to load preferences: ${res.statusText}`);
|
||||
const data = (await res.json()) as Partial<UserPreferences>;
|
||||
return { hide_admin_prompt_prefix: !!data.hide_admin_prompt_prefix };
|
||||
}
|
||||
|
||||
async function updateUserPreferences(
|
||||
input: Partial<UserPreferences>,
|
||||
): Promise<UserPreferences> {
|
||||
const res = await apiFetch(baseUrl(), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||
throw new Error(err.detail ?? `Failed to update preferences: ${res.statusText}`);
|
||||
}
|
||||
const data = (await res.json()) as Partial<UserPreferences>;
|
||||
return { hide_admin_prompt_prefix: !!data.hide_admin_prompt_prefix };
|
||||
}
|
||||
|
||||
/** Reactive current-user preferences (server-backed, follows the account). */
|
||||
export function useUserPreferences(): UserPreferences {
|
||||
const { data } = useQuery({
|
||||
queryKey: QUERY_KEY,
|
||||
queryFn: getUserPreferences,
|
||||
});
|
||||
return data ?? DEFAULT_PREFS;
|
||||
}
|
||||
|
||||
export function useUpdateUserPreferences() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: updateUserPreferences,
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData(QUERY_KEY, data);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -250,6 +250,7 @@ export default function AgentChatPage() {
|
||||
className="w-full"
|
||||
isNewThread={isLandingState}
|
||||
threadId={threadId}
|
||||
assistantId={agent_id}
|
||||
autoFocus={isLandingState}
|
||||
status={
|
||||
thread.error
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { type PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||
import { usePromptPrefixSettings } from "@/core/system-settings/hooks";
|
||||
import { useUserPreferences } from "@/core/user-preferences";
|
||||
import { ArtifactTrigger, useArtifacts } from "@/components/workspace/artifacts";
|
||||
import {
|
||||
ChatBox,
|
||||
@@ -50,6 +51,9 @@ export default function ChatPage() {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const { tokenUsageEnabled } = useModels();
|
||||
const { data: promptPrefixSettings } = usePromptPrefixSettings();
|
||||
// Personal opt-out: when set, hide the admin prompt-prefix switch entirely and
|
||||
// never apply the prefix — the user uses only their own prompts.
|
||||
const { hide_admin_prompt_prefix: hideAdminPrompt } = useUserPreferences();
|
||||
const [promptPrefixOn, setPromptPrefixOn] = useState(false);
|
||||
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
|
||||
const { agents: selectorAgents, isLoading: selectorLoading } =
|
||||
@@ -159,6 +163,7 @@ export default function ChatPage() {
|
||||
isNewThread &&
|
||||
!hasStartedConversation &&
|
||||
promptPrefixOn &&
|
||||
!hideAdminPrompt &&
|
||||
promptPrefixSettings?.enabled === true;
|
||||
setHasStartedConversation(true);
|
||||
window.dispatchEvent(
|
||||
@@ -189,6 +194,7 @@ export default function ChatPage() {
|
||||
hasStartedConversation,
|
||||
promptPrefixOn,
|
||||
promptPrefixSettings,
|
||||
hideAdminPrompt,
|
||||
selectedAgentId,
|
||||
router,
|
||||
settings.context.writing_mode,
|
||||
@@ -217,6 +223,8 @@ export default function ChatPage() {
|
||||
|
||||
const promptPrefixProp = useMemo(() => {
|
||||
if (!promptPrefixSettings?.enabled) return undefined;
|
||||
// Personal opt-out hides the admin prompt-prefix switch entirely.
|
||||
if (hideAdminPrompt) return undefined;
|
||||
// The prefix toggle is offered only on the opening turn of a new thread.
|
||||
if (!isNewThread || hasStartedConversation) return undefined;
|
||||
return {
|
||||
@@ -224,7 +232,13 @@ export default function ChatPage() {
|
||||
on: promptPrefixOn,
|
||||
onToggle: () => setPromptPrefixOn((v) => !v),
|
||||
};
|
||||
}, [promptPrefixSettings, isNewThread, hasStartedConversation, promptPrefixOn]);
|
||||
}, [
|
||||
promptPrefixSettings,
|
||||
hideAdminPrompt,
|
||||
isNewThread,
|
||||
hasStartedConversation,
|
||||
promptPrefixOn,
|
||||
]);
|
||||
|
||||
const messageListPaddingBottom = showFollowups
|
||||
? MESSAGE_LIST_DEFAULT_PADDING_BOTTOM +
|
||||
|
||||
@@ -19,6 +19,11 @@ import {
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
ResizableHandle,
|
||||
ResizablePanel,
|
||||
ResizablePanelGroup,
|
||||
} from "@/components/ui/resizable";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -361,8 +366,19 @@ export default function NewAgentPage() {
|
||||
) : null}
|
||||
</header>
|
||||
|
||||
<main className="grid min-h-0 flex-1 grid-cols-1 md:grid-cols-[minmax(0,1fr)_420px]">
|
||||
<section className="flex min-h-0 flex-col border-r">
|
||||
<ResizablePanelGroup
|
||||
id="new-agent-config-panels"
|
||||
orientation="horizontal"
|
||||
defaultLayout={{ chat: 62, config: 38 }}
|
||||
className="min-h-0 flex-1"
|
||||
>
|
||||
<ResizablePanel
|
||||
id="chat"
|
||||
defaultSize={62}
|
||||
minSize={40}
|
||||
className="min-h-0"
|
||||
>
|
||||
<section className="flex size-full min-h-0 flex-col">
|
||||
<div className="min-h-0 flex-1">
|
||||
<MessageList
|
||||
className="size-full"
|
||||
@@ -428,8 +444,18 @@ export default function NewAgentPage() {
|
||||
</PromptInput>
|
||||
</div>
|
||||
</section>
|
||||
</ResizablePanel>
|
||||
|
||||
<aside className="bg-background min-h-0 overflow-y-auto">
|
||||
<ResizableHandle withHandle />
|
||||
|
||||
<ResizablePanel
|
||||
id="config"
|
||||
defaultSize={38}
|
||||
minSize={24}
|
||||
maxSize={60}
|
||||
className="min-h-0"
|
||||
>
|
||||
<aside className="bg-background size-full min-h-0 overflow-y-auto">
|
||||
<div className="space-y-5 p-4">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold">智能体配置</h2>
|
||||
@@ -606,7 +632,8 @@ export default function NewAgentPage() {
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
</main>
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
</ArtifactsProvider>
|
||||
</ThreadContext.Provider>
|
||||
|
||||
@@ -114,13 +114,15 @@ const emptyForm = {
|
||||
timezone: "Asia/Shanghai",
|
||||
prompt: "",
|
||||
execution_agent_name: "",
|
||||
// Two independent output switches (may both be on): require a Markdown file
|
||||
// and/or render an HTML page. The form no longer splits into "普通任务 / HTML
|
||||
// 页面" tabs.
|
||||
require_markdown: false,
|
||||
// HTML page task fields. ``task_kind`` "agent" keeps the original behavior.
|
||||
// Data gathering is delegated to the agent's own search skills — no explicit
|
||||
// search query / data source. ``html_model_name`` empty means "use the first
|
||||
// available model" — never a hardcoded GLM-5.
|
||||
task_kind: "agent" as "agent" | "html_page",
|
||||
html_page_prompt: "",
|
||||
require_html: false,
|
||||
// HTML-only extra fields, shown when ``require_html`` is on. The main
|
||||
// ``prompt`` above doubles as the page requirement, so there is no separate
|
||||
// page-prompt field. ``html_model_name`` empty means "use the first available
|
||||
// model" — never a hardcoded GLM-5.
|
||||
html_negative_prompt: "",
|
||||
html_reference_favorite_id: "",
|
||||
html_model_name: "",
|
||||
@@ -244,11 +246,15 @@ export default function ScheduledTasksPage() {
|
||||
description: task.description ?? "",
|
||||
schedule: task.schedule_text,
|
||||
timezone: task.timezone,
|
||||
prompt: task.prompt,
|
||||
// The main prompt doubles as the HTML page requirement; legacy HTML tasks
|
||||
// stored that under ``html_config.page_prompt``, so prefer it on edit.
|
||||
prompt: html.page_prompt || task.prompt,
|
||||
execution_agent_name: task.execution_agent_name ?? "",
|
||||
require_markdown: !!task.execution_context?.require_markdown,
|
||||
task_kind: task.execution_context?.task_kind === "html_page" ? "html_page" : "agent",
|
||||
html_page_prompt: html.page_prompt ?? "",
|
||||
// Backward compatible: legacy HTML tasks only carry ``task_kind``.
|
||||
require_html:
|
||||
!!task.execution_context?.require_html ||
|
||||
task.execution_context?.task_kind === "html_page",
|
||||
html_negative_prompt: html.negative_prompt ?? "",
|
||||
html_reference_favorite_id: html.reference_favorite_id ?? "",
|
||||
html_model_name: html.model_name ?? "",
|
||||
@@ -270,20 +276,26 @@ export default function ScheduledTasksPage() {
|
||||
setScheduleConfig(DEFAULT_SCHEDULE_CONFIG);
|
||||
};
|
||||
|
||||
const isHtmlTask = form.task_kind === "html_page";
|
||||
const isHtmlTask = form.require_html;
|
||||
// The model actually shown/used: the user's choice, else the first configured
|
||||
// model. Never a hardcoded GLM-5 — it follows config order and the selection.
|
||||
const effectiveHtmlModel = form.html_model_name || availableModels[0]?.name || "";
|
||||
|
||||
// Build the execution_context for the current form. HTML tasks persist their
|
||||
// config under ``html_config``; regular tasks send an explicit ``agent`` kind
|
||||
// so switching a task back from HTML clears the old config.
|
||||
// Build the execution_context for the current form. ``require_html`` and
|
||||
// ``require_markdown`` are independent toggles (both may be on). HTML tasks
|
||||
// persist their extra config under ``html_config`` and reuse the main prompt
|
||||
// as the page requirement; ``task_kind`` is kept in sync only for backward
|
||||
// compatibility with older readers.
|
||||
const buildExecutionContext = (): ScheduledTaskExecutionContext => {
|
||||
if (!isHtmlTask) return { task_kind: "agent", html_config: undefined };
|
||||
if (!isHtmlTask) {
|
||||
return { require_html: false, task_kind: "agent", html_config: undefined };
|
||||
}
|
||||
return {
|
||||
require_html: true,
|
||||
task_kind: "html_page",
|
||||
html_config: {
|
||||
page_prompt: form.html_page_prompt.trim() || null,
|
||||
// The main prompt doubles as the page requirement.
|
||||
page_prompt: form.prompt.trim() || null,
|
||||
negative_prompt: form.html_negative_prompt.trim() || null,
|
||||
reference_favorite_id: form.html_reference_favorite_id || null,
|
||||
// Send the user's selection; fall back to the first configured model,
|
||||
@@ -297,11 +309,10 @@ export default function ScheduledTasksPage() {
|
||||
try {
|
||||
const cronSchedule = buildCron(scheduleConfig);
|
||||
const executionContext = buildExecutionContext();
|
||||
// HTML tasks may leave the agent prompt empty — fall back to the page
|
||||
// prompt so the (non-null) prompt column always has something useful.
|
||||
const effectivePrompt = isHtmlTask
|
||||
? form.prompt.trim() || form.html_page_prompt.trim() || "生成 HTML 页面"
|
||||
: form.prompt;
|
||||
// The (non-null) prompt column always needs something useful; HTML tasks
|
||||
// may leave it sparse, so fall back to a generic instruction.
|
||||
const effectivePrompt =
|
||||
form.prompt.trim() || (isHtmlTask ? "生成 HTML 页面" : form.prompt);
|
||||
if (creating) {
|
||||
const task = await actions.create.mutateAsync({
|
||||
name: form.name || "定时任务",
|
||||
@@ -309,8 +320,8 @@ export default function ScheduledTasksPage() {
|
||||
schedule: cronSchedule,
|
||||
timezone: form.timezone || "Asia/Shanghai",
|
||||
prompt: effectivePrompt,
|
||||
execution_agent_name: isHtmlTask ? null : form.execution_agent_name || null,
|
||||
require_markdown: isHtmlTask ? false : form.require_markdown,
|
||||
execution_agent_name: form.execution_agent_name || null,
|
||||
require_markdown: form.require_markdown,
|
||||
execution_context: executionContext,
|
||||
});
|
||||
setSelectedTaskId(task.task_id);
|
||||
@@ -324,8 +335,8 @@ export default function ScheduledTasksPage() {
|
||||
schedule: cronSchedule,
|
||||
timezone: form.timezone,
|
||||
prompt: effectivePrompt,
|
||||
execution_agent_name: isHtmlTask ? null : form.execution_agent_name || null,
|
||||
require_markdown: isHtmlTask ? false : form.require_markdown,
|
||||
execution_agent_name: form.execution_agent_name || null,
|
||||
require_markdown: form.require_markdown,
|
||||
execution_context: executionContext,
|
||||
},
|
||||
});
|
||||
@@ -502,7 +513,8 @@ export default function ScheduledTasksPage() {
|
||||
<Globe className="size-3" />已发布
|
||||
</Badge>
|
||||
)}
|
||||
{task.execution_context?.task_kind === "html_page" && (
|
||||
{(task.execution_context?.require_html ||
|
||||
task.execution_context?.task_kind === "html_page") && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="shrink-0 border-sky-500/30 bg-sky-500/10 text-xs text-sky-600 dark:text-sky-400"
|
||||
@@ -953,20 +965,6 @@ export default function ScheduledTasksPage() {
|
||||
}
|
||||
placeholder="任务描述(可选,将显示在公开页标题下方)"
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-muted-foreground text-xs">任务类型</p>
|
||||
<Tabs
|
||||
value={form.task_kind}
|
||||
onValueChange={(v) =>
|
||||
setForm((value) => ({ ...value, task_kind: v as "agent" | "html_page" }))
|
||||
}
|
||||
>
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="agent" className="flex-1">普通任务</TabsTrigger>
|
||||
<TabsTrigger value="html_page" className="flex-1">HTML 页面</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-muted-foreground text-xs">执行频率</p>
|
||||
<ScheduleBuilder value={scheduleConfig} onChange={setScheduleConfig} />
|
||||
@@ -979,77 +977,83 @@ export default function ScheduledTasksPage() {
|
||||
placeholder="时区,例如:Asia/Shanghai"
|
||||
/>
|
||||
|
||||
{!isHtmlTask && (
|
||||
<>
|
||||
<Select
|
||||
value={form.execution_agent_name || "__default__"}
|
||||
onValueChange={(v) =>
|
||||
setForm((value) => ({
|
||||
...value,
|
||||
execution_agent_name: v === "__default__" ? "" : v,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<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="__default__">默认助手(不指定)</SelectItem>
|
||||
{agents.map((agent) => (
|
||||
<SelectItem key={agent.id} value={agent.id}>
|
||||
<span className="block truncate">
|
||||
{desensitize(agent.name)}
|
||||
{agent.description ? ` — ${desensitize(agent.description)}` : ""}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Textarea
|
||||
className="min-h-40"
|
||||
value={form.prompt}
|
||||
onChange={(event) =>
|
||||
setForm((value) => ({ ...value, prompt: event.target.value }))
|
||||
}
|
||||
placeholder="任务 Prompt"
|
||||
/>
|
||||
<div className="flex items-center justify-between rounded-md border p-3">
|
||||
<div className="min-w-0 pr-3">
|
||||
<p className="text-sm font-medium">必须生成 Markdown 文件</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={form.require_markdown}
|
||||
onCheckedChange={(v) =>
|
||||
setForm((value) => ({ ...value, require_markdown: v }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<Select
|
||||
value={form.execution_agent_name || "__default__"}
|
||||
onValueChange={(v) =>
|
||||
setForm((value) => ({
|
||||
...value,
|
||||
execution_agent_name: v === "__default__" ? "" : v,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<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="__default__">默认助手(不指定)</SelectItem>
|
||||
{agents.map((agent) => (
|
||||
<SelectItem key={agent.id} value={agent.id}>
|
||||
<span className="block truncate">
|
||||
{desensitize(agent.name)}
|
||||
{agent.description ? ` — ${desensitize(agent.description)}` : ""}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Textarea
|
||||
className="min-h-40"
|
||||
value={form.prompt}
|
||||
onChange={(event) =>
|
||||
setForm((value) => ({ ...value, prompt: event.target.value }))
|
||||
}
|
||||
placeholder={
|
||||
isHtmlTask
|
||||
? "任务 / 页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页"
|
||||
: "任务 Prompt"
|
||||
}
|
||||
/>
|
||||
<div className="flex items-center justify-between rounded-md border p-3">
|
||||
<div className="min-w-0 pr-3">
|
||||
<p className="text-sm font-medium">必须生成 Markdown 文件</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={form.require_markdown}
|
||||
onCheckedChange={(v) =>
|
||||
setForm((value) => ({ ...value, require_markdown: v }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between rounded-md border p-3">
|
||||
<div className="min-w-0 pr-3">
|
||||
<p className="text-sm font-medium">必须生成 HTML 页面</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
开启后会先用智能体检索整理真实数据,再渲染为完整 HTML 页面(可在执行记录中预览)。可与“必须生成 Markdown”同时开启。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={form.require_html}
|
||||
onCheckedChange={(v) =>
|
||||
setForm((value) => ({ ...value, require_html: v }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isHtmlTask && (
|
||||
<>
|
||||
<Textarea
|
||||
className="min-h-24"
|
||||
value={form.html_page_prompt}
|
||||
onChange={(event) =>
|
||||
setForm((value) => ({ ...value, html_page_prompt: event.target.value }))
|
||||
}
|
||||
placeholder="页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页"
|
||||
/>
|
||||
<Textarea
|
||||
className="min-h-16"
|
||||
value={form.html_negative_prompt}
|
||||
onChange={(event) =>
|
||||
setForm((value) => ({ ...value, html_negative_prompt: event.target.value }))
|
||||
}
|
||||
placeholder="限制条件(可选),例如:不要使用深色背景,不要出现外部链接脚本"
|
||||
placeholder="HTML 限制条件(可选),例如:不要使用深色背景,不要出现外部链接脚本"
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-muted-foreground text-xs">参考收藏页面(可选)</p>
|
||||
@@ -1127,14 +1131,6 @@ export default function ScheduledTasksPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Textarea
|
||||
className="min-h-16"
|
||||
value={form.prompt}
|
||||
onChange={(event) =>
|
||||
setForm((value) => ({ ...value, prompt: event.target.value }))
|
||||
}
|
||||
placeholder="补充说明(可选):进一步约束智能体如何检索数据、页面包含哪些内容"
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
执行流程:智能体运用自身检索技能整理真实数据 → 选定模型渲染为完整 HTML → 自动安全清洗与结构校验 → 可在执行记录中预览。
|
||||
</p>
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
"paths": {
|
||||
"@/env": ["./src/env.ts"],
|
||||
"@/*": ["./src/*"],
|
||||
"@vite/*": ["./src/*"]
|
||||
"@vite/*": ["./src/*"],
|
||||
"next/navigation": ["./src/shims/next-navigation.ts"],
|
||||
"next/link": ["./src/shims/next-link.tsx"]
|
||||
},
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user